Les cookies nous permettent de vous proposer nos services plus facilement. En utilisant nos services, vous nous donnez expressément votre accord pour exploiter ces cookies.En savoir plus OK

Microchip-atmel-42167-atmel-studio_user guide-Manuel

Microchip- atmel-42167-atmel-studio_user guide - Manuel

Voir également :
[TXT] Microchip-AN1476-Com..> 2018-11-13 18:55  499K  
[TXT] Microchip-Atmel-ATUC64L4U-32-bit-Atmel-AVR-Microcontroller-Manuel 2018-11-20 16:26  1.9M  
[TXT] Microchip-CAP1188-8-Channel-Capacitive-Touch-Sensor-with-8-LED-Drivers-Manuel 2018-11-13 19:07  1.4M  
[TXT] Microchip-CAP1203-3-..> 2018-11-13 19:06  1.2M  
[TXT] Microchip-CAP1206-6-..> 2018-11-13 18:58  736K  
[TXT] Microchip-CAP1208-8-..> 2018-11-13 19:01  1.0M  
[TXT] Microchip-CAP1293-3-..> 2018-11-13 18:57  620K  
[TXT] Microchip-CAP1296-6-..> 2018-11-13 19:00  883K  
[TXT] Microchip-CAP1298-8-..> 2018-11-13 19:03  1.1M  
[TXT] Microchip-SEC1110-Sm..> 2018-11-13 18:48  479K  
[TXT] Microchip-SEC1210-Sm..> 2018-11-13 18:52  479K 

Au format texte :

Software Atmel Studio USER GUIDE Preface Atmel® Studio is an Integrated Development Environment (IDE) for writing and debugging AVR® /ARM® applications in Windows® XP/Windows Vista® / Windows 7/8 environments. Atmel Studio provides a project management tool, source file editor, simulator, assembler, and front-end for C/C++, programming, and on-chip debugging. Atmel Studio supports the complete range of Atmel AVR tools. Each new release contains the latest updates for the tools as well as support for new AVR/ARM devices. Atmel Studio has a modular architecture, which allows interaction with 3rd party software vendors. GUI plugins and other modules can be written and hooked to the system. Contact Atmel for more information. Atmel-42167B-Atmel-Studio_User Guide-09/2016 Table of Contents Preface............................................................................................................................ 1 1. Introduction................................................................................................................8 1.1. Features....................................................................................................................................... 8 1.2. New and Noteworthy.................................................................................................................... 8 1.2.1. Atmel Studio 7.0............................................................................................................ 8 1.2.2. Atmel Studio 6.2 Service Pack 2..................................................................................11 1.2.3. Atmel Studio 6.2 Service Pack 1..................................................................................11 1.2.4. Atmel Studio 6.2...........................................................................................................11 1.2.5. Atmel Studio 6.1 Update 2...........................................................................................12 1.2.6. Atmel Studio 6.1 Update 1.1........................................................................................12 1.2.7. Atmel Studio 6.1 Update 1...........................................................................................12 1.2.8. Atmel Studio 6.1.......................................................................................................... 12 1.2.9. Atmel Studio 6.0.......................................................................................................... 12 1.2.10. AVR Studio 5.1.............................................................................................................13 1.3. Installation.................................................................................................................................. 13 1.4. Contact Information.................................................................................................................... 14 2. Getting started......................................................................................................... 16 2.1. Starting Atmel Studio..................................................................................................................16 2.2. Creating a Project.......................................................................................................................17 2.2.1. Introduction.................................................................................................................. 17 2.2.2. Creating a new Project................................................................................................ 17 2.2.3. Choosing a Target Device............................................................................................19 2.2.4. Writing and Compiling Code........................................................................................ 19 3. Project Management................................................................................................22 3.1. Introduction.................................................................................................................................22 3.1.1. The Solution Container................................................................................................ 22 3.1.2. Save and Open Projects..............................................................................................22 3.1.3. Project Output View..................................................................................................... 22 3.1.4. Solution Explorer......................................................................................................... 22 3.1.5. Toolbar Icons............................................................................................................... 23 3.1.6. Hierarchical Display..................................................................................................... 23 3.1.7. Item Management Commands.................................................................................... 23 3.1.8. Project Components.................................................................................................... 23 3.2. GCC Projects..............................................................................................................................25 3.2.1. New Project Wizard..................................................................................................... 25 3.2.2. Starting a New GCC Project for AVR Device...............................................................25 3.2.3. Libraries Options..........................................................................................................29 3.2.4. Starting a New GCC Project for SAM (ARM) Device...................................................33 3.2.5. Code Editing................................................................................................................ 36 3.2.6. Starting a New GCC Static Library Project.................................................................. 37 3.2.7. GCC Project Options and Configuration......................................................................40 3.3. Assembler Projects.....................................................................................................................57 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 2 3.3.1. Create New Assembler Project....................................................................................57 3.3.2. Assembler Options ..................................................................................................... 60 3.4. Import of Projects....................................................................................................................... 62 3.4.1. Introduction.................................................................................................................. 62 3.4.2. Import AVR Studio 4 Project........................................................................................ 62 3.4.3. Import AVR 32 Studio Project...................................................................................... 65 3.4.4. Import Project Template...............................................................................................69 3.5. Debug Object File in Atmel Studio..............................................................................................71 3.5.1. Introduction.................................................................................................................. 71 3.5.2. Atmel Studio Supported Debug Formats..................................................................... 72 3.5.3. Opening Object Debug File in Atmel Studio................................................................ 72 4. Debugging............................................................................................................... 77 4.1. Introduction.................................................................................................................................77 4.1.1. Debug Platform Independent Debug Environment...................................................... 77 4.1.2. Differences Between Platforms....................................................................................77 4.2. Starting a Debug Session...........................................................................................................77 4.3. Ending a Debug Session............................................................................................................77 4.4. Attaching to a Target...................................................................................................................78 4.5. Start without Debugging............................................................................................................. 78 4.5.1. One Click Programming - Program and Run............................................................... 78 4.5.2. Keyboard Shortcut....................................................................................................... 79 4.6. Debug Control............................................................................................................................ 79 4.7. Breakpoints.................................................................................................................................81 4.7.1. General Information on Breakpoints............................................................................ 81 4.7.2. Operations with Breakpoints........................................................................................82 4.7.3. Breakpoint Window......................................................................................................84 4.8. Data Breakpoints........................................................................................................................86 4.8.1. Adding Data Breakpoint...............................................................................................86 4.8.2. Data Breakpoints Window........................................................................................... 87 4.8.3. General Information on Data Breakpoint..................................................................... 98 4.8.4. Data Breakpoint Usage................................................................................................99 4.9. QuickWatch, Watch, Locals, and Autos Windows......................................................................99 4.9.1. Watch Window...........................................................................................................100 4.9.2. Locals Window...........................................................................................................102 4.9.3. Autos Window............................................................................................................103 4.9.4. QuickWatch and Watches..........................................................................................104 4.9.5. Expression Formatting...............................................................................................105 4.10. DataTips................................................................................................................................... 106 4.10.1. Expanding and Editing Information............................................................................107 4.10.2. Making a DataTip Transparent...................................................................................108 4.10.3. Visualizing Complex Data Types............................................................................... 108 4.10.4. Adding Information to a Watch Window.....................................................................108 4.10.5. Importing and Exporting DataTips............................................................................. 108 4.11. Disassembly View ................................................................................................................... 108 4.12. I/O View.................................................................................................................................... 110 4.12.1. About the I/O View..................................................................................................... 110 4.12.2. Using the I/O View Tool.............................................................................................. 111 4.12.3. Editing Values and Bits in Break Mode...................................................................... 111 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 3 4.13. Processor View ........................................................................................................................ 111 4.14. Register View............................................................................................................................112 4.15. Memory View............................................................................................................................112 4.16. Call Stack Window....................................................................................................................113 4.17. Object File Formats.................................................................................................................. 116 4.18. Trace.........................................................................................................................................117 4.18.1. Application Output......................................................................................................117 4.18.2. Program Counter Sampling........................................................................................118 4.18.3. Variable Watching...................................................................................................... 118 4.19. Trace View................................................................................................................................119 4.19.1. Trace View Options....................................................................................................119 4.19.2. Trace View Interpretation...........................................................................................122 5. Programming Dialog..............................................................................................125 5.1. Introduction...............................................................................................................................125 5.2. Interface Settings......................................................................................................................128 5.3. Tool Information........................................................................................................................131 5.4. Board Settings/Tool Settings.................................................................................................... 132 5.4.1. Power Debugger........................................................................................................132 5.4.2. STK600......................................................................................................................132 5.4.3. QT600........................................................................................................................133 5.4.4. STK500......................................................................................................................133 5.5. Card Stack................................................................................................................................134 5.6. Device Information....................................................................................................................135 5.7. Oscillator Calibration................................................................................................................ 136 5.8. Memories..................................................................................................................................137 5.9. Fuse Programming...................................................................................................................139 5.10. Lock Bits...................................................................................................................................140 5.11. Production Signatures.............................................................................................................. 140 5.12. Production Files........................................................................................................................141 5.13. Security.....................................................................................................................................144 5.14. Automatic Firmware Upgrade Detection...................................................................................145 6. Miscellaneous Windows........................................................................................ 146 6.1. Device Pack Manager.............................................................................................................. 146 6.2. User Interface Profile Selection................................................................................................148 6.3. Available Tools View.................................................................................................................149 6.3.1. Introduction................................................................................................................ 149 6.3.2. Tool Actions............................................................................................................... 150 6.3.3. Add a Non-detectable Tool........................................................................................ 150 6.4. Tool Info Window...................................................................................................................... 152 6.4.1. Xplained Pro Kits....................................................................................................... 154 6.4.2. Disable the Tools Info Window...................................................................................154 6.4.3. Manually Showing the Window..................................................................................154 6.5. Firmware Upgrade....................................................................................................................154 6.5.1. Introduction................................................................................................................ 154 6.5.2. Automatic Upgrade.................................................................................................... 154 6.5.3. Manual Upgrade........................................................................................................ 155 6.6. Find and Replace Window........................................................................................................155 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 4 6.7. Export Template Wizard........................................................................................................... 159 6.7.1. Project Template........................................................................................................ 160 6.7.2. Item Template............................................................................................................ 160 6.7.3. Template Parameters.................................................................................................160 6.8. Kit Mode Setting....................................................................................................................... 162 7. Atmel GNU Toolchains...........................................................................................163 7.1. GNU Compiler Collection (GCC)..............................................................................................163 7.2. ARM Compiler and Toolchain Options: GUI ............................................................................ 163 7.3. ARM GNU Toolchain Options...................................................................................................168 7.3.1. ARM/GNU Common Options.....................................................................................168 7.3.2. Compiler Options....................................................................................................... 168 7.3.3. Linker Options............................................................................................................171 7.3.4. Assembler Options.................................................................................................... 172 7.3.5. Preprocessing Assembler Options............................................................................ 172 7.3.6. Archiver Options........................................................................................................ 172 7.4. Binutils......................................................................................................................................173 7.5. AVR Compiler and Toolchain Options: GUI .............................................................................173 7.6. Commonly Used Options..........................................................................................................178 7.6.1. Compiler Options....................................................................................................... 178 7.6.2. Linker Options............................................................................................................181 7.6.3. Assembler Options.................................................................................................... 182 7.7. 8-bit Specific AVR GCC Command Line Options.....................................................................182 7.7.1. AVR C Compiler.........................................................................................................182 7.7.2. AVR C Linker............................................................................................................. 183 7.8. 32-bit Specific AVR GCC Command Line Options...................................................................183 7.8.1. Optimization...............................................................................................................183 7.8.2. Debugging................................................................................................................. 184 7.8.3. AVR32 C Linker......................................................................................................... 185 7.9. Binutils......................................................................................................................................186 8. Extending Atmel Studio......................................................................................... 187 8.1. Extension Manager UI..............................................................................................................187 8.2. Registering at Atmel Extension Gallery....................................................................................188 8.3. Installing New Extensions in Atmel Studio............................................................................... 189 8.4. Visual Assist............................................................................................................................. 192 8.5. Overview of QTouch Composer and Library............................................................................ 193 8.5.1. Installation..................................................................................................................194 8.5.2. Overview of QTouch Project Builder.......................................................................... 194 8.5.3. Overview of QTouch Analyzer................................................................................... 195 8.6. Scripting Extensions.................................................................................................................196 8.6.1. Debug Scripting......................................................................................................... 196 9. Menus and Settings...............................................................................................199 9.1. Customizing Existing Menus and Toolbars...............................................................................199 9.2. Reset Your Settings..................................................................................................................200 9.3. Options Dialog Box...................................................................................................................201 9.3.1. Environment Options................................................................................................. 201 9.3.2. Project Options.......................................................................................................... 218 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 5 9.3.3. Source Control...........................................................................................................221 9.3.4. Text Editor Options.................................................................................................... 221 9.3.5. Debugger................................................................................................................... 237 9.3.6. Atmel Software Framework Settings......................................................................... 238 9.3.7. Builder........................................................................................................................239 9.3.8. Device and Tool Libraries.......................................................................................... 239 9.3.9. Status Management...................................................................................................239 9.3.10. Text Templating..........................................................................................................240 9.3.11. Toolchain....................................................................................................................240 9.3.12. GDB Settings............................................................................................................. 241 9.4. Code Snippet Manager............................................................................................................ 242 9.4.1. Managing Code Snippets.......................................................................................... 242 9.4.2. Code Snippet Manager Layout.................................................................................. 243 9.4.3. Modifying Existing Code Snippets............................................................................. 243 9.5. External Tools...........................................................................................................................244 9.5.1. Add an External Tool to the Tools Menu.................................................................... 244 9.5.2. Pass Variables to External Tools................................................................................245 9.5.3. Initial Directory........................................................................................................... 246 9.5.4. Run Behavior............................................................................................................. 246 9.5.5. Assign a Keyboard Shortcut...................................................................................... 246 9.6. Predefined Keyboard Shortcuts............................................................................................... 246 10. Command Line Utility (CLI)................................................................................... 262 11. Frequently Asked Questions..................................................................................263 11.1. Compatibility with Legacy AVR Software and Third-party Products.........................................265 11.1.1. How do I Import External ELF Files for Debugging?................................................. 265 11.1.2. How do I Reuse My AVR Studio 4 Projects with the New Atmel Studio?.................. 265 11.2. Atmel Studio Interface.............................................................................................................. 266 11.2.1. How can I Start Debugging My Code? What is the Keyboard Shortcut for Debugging? ...................................................................................................................................266 11.2.2. What is a Solution?....................................................................................................266 11.2.3. What is a Project........................................................................................................266 11.2.4. How can I use an External Makefile for my Project?................................................. 266 11.2.5. When Watching a Variable, the Debugger says Optimized away......................266 11.2.6. When Starting a Debug Session, I get an Error Stating that Debug Tool is not Set ...................................................................................................................................267 11.3. Performance Issues..................................................................................................................267 11.3.1. Atmel Studio Takes a Very Long Time to Start on My PC, but Runs Well in a VM Environment. Is there Something I Can do With This?..............................................267 11.3.2. Verification and Programming often Fails with a Serial Port Buffer Overrun Error Message when using STK500................................................................................... 267 11.3.3. I've connected my Tool through a USB Hub, and now I get Error Messages and Inconsistent Results while Programming and Debugging......................................... 267 11.4. Driver and USB Issues............................................................................................................. 267 11.4.1. How do I get my Tool to be Recognized by Atmel Studio?........................................ 267 11.4.2. The Firmware upgrade Process fails or is Unstable on a Virtualized Machine..........268 11.4.3. Debugging never Breaks under a Virtualized Machine..............................................268 11.4.4. No Tool is recognized by Atmel Studio, but the Driver seems to be Working............268 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 6 11.4.5. Firmware Upgrade Fails on VirtualBox...................................................................... 268 11.4.6. Common Jungo USB Errors...................................................................................... 269 11.4.7. Issues with ARM Compatible Tools........................................................................... 270 12. Document Revision History................................................................................... 272 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 7 1. Introduction 1.1. Features Atmel Studio provides a large set of features for project development and debugging. The most notable features are listed below. • Rich code editor for C/C++ and Assembly featuring the powerful Visual Assist extension • Cycle correct simulator with advanced debug functionality • Atmel Software Framework allowing creation of modular applications and providing building blocks for a prototype on any AVR platform • Debugging on actual devices using Debugging Tools • Rich SDK to enable tight integration of customer plugins • Compatible with many Microsoft® Visual Studio® plugins 1.2. New and Noteworthy New features available. 1.2.1. Atmel Studio 7.0 Atmel Studio 7.0.1006 The following changes are done in Atmel Studio 7.0.1006: • New Atmel Start extension that allows the user to create and configure Atmel Start projects within Atmel Studio • Ability to load multiple modules in a debug session (experimental) • AVR 8-bit GCC Toolchain 3.5.3 with upstream versions: – gcc 4.9.2 – Binutils 2.26 – avr-libc 2.0.0 – gdb 7.8 • ARM GCC Toolchain 5.3.1 with upstream versions: – gcc (ARM/embedded-5-branch revision 234589) – Binutils 2.26 – gdb 7.10 Atmel Studio 7.0.1006 contains a fix for the following issues that were present in 7.0.943: • AVRSV-6878: Atmel Studio write the write-once wdt registers on some SAM devices. • AVRSV-7470: SAM Cortex® -M7 devices fails launch occasionally. • AVRSV-7471: Devices with external and internal RAM lists all the RAM as available. • AVRSV-7473: Atmel Studio hangs during startup. • AVRSV-7474: Kits connected to Atmel Studio are not getting enumerated in the QTouch Start Page. • AVRSV-7477: Show all files does not work from solution explorer. • AVRSV-7482: Exception when adding breakpoint on SAM4L. • AVRSV-7486: Debugging may fail in Cortex-M0+ SAM devices at high clock speeds. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 8 Atmel Studio 7.0.943 Atmel Studio 7.0.943 contains a fix for the following issue: • AVRSV-7459: Projects containing files with upper case file names can fail to build. Saving files with upper case file names converts file name to lower case. Atmel Studio 7.0.934 The following changes are done in Atmel Studio 7.0.934: • AVR 8-bit GCC Toolchain 3.5.2 with upstream versions: – gcc 4.9.2 – Binutils 2.26 – avr-libc 2.0.0 – gdb 7.8 • AVR 32-bit GCC Toolchain 3.4.3 with upstream versions: – gcc 4.4.7 – Binutils 2.23.1 – Newlib 1.16.0 • ARM GCC Toolchain 4.9.3 with upstream versions: – gcc (ARM/embedded-4_9-branch revision 224288) – Binutils 2.24 – gdb 7.8.0.20150304-cvs Atmel Studio 7.0.934 resolves the following issues present in Atmel Studio 7.0.790: • AVRSV-7376: Atmel-ICE slow programming. • AVRSV-7379: Unhandled exception when writing fuses or lockbits when Auto Read is turned off. • AVRSV-7396: Some machines shows an error regarding 'Exception in MemoryPressureReliever'. • AVRSV-7400: When in Standard mode, Disable debugWire and Close are not visible in the Debug menu. • AVRSV-7408: When using Atmel Studio in Standard mode, the Set Startup Project menu is missing. Atmel Studio 7.0.790 The following features are added in Atmel Studio 7.0.790: • Support for mass storage mode in embedded debugger (EDBG), enabling drag and drop programming • Introduction of user interface profiles. The user can choose an interface where some of the toolbar buttons and menu items are removed. • Support for importing libraries to previously imported sketches. Added support for Arduino Zero and Zero Pro. • Parallel build turned on by default Atmel Studio 7.0.790 resolves the following issues present in Atmel Studio 7.0.634: • AVRSV-7084: Persist user settings during upgrade. • AVRSV-7014: Some ATmega and ATtiny devices failed to start debugging with the Simulator. • AVRSV-7230: "Show all files" in Solution Explorer not consistent. • AVRSV-7062: Firmware upgrade of Xplained Mini kits not detected. • AVRSV-7164: Reading flash to .bin file created incorrect .bin file. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 9 • AVRSV-7106: Hex files with Unix® or mixed file endings fail to load. • AVRSV-7126: Databreakpoints for ARM should not be limited to RAM. Atmel Studio 7.0.634 This release adds device support for the SAM B11 device family. Atmel Studio 7.0.634 resolves the following issues present in Atmel Studio 7.0.594: • AVRSV-6873: Jungo Driver issue with Windows 10. Note:  If you install this version of Atmel Studio in parallel with an older Studio versions or IAR Embedded Workbench® and are using AVR Dragon™ , AVRISP mkII, JTAGICE mkII, AVR ONE!, STK® 600, or QT600 read How to downgrade to use older Jungo drivers. • AVRSV-6676: Launching debugging fails due to issue with Intel graphics driver. Atmel Studio 7.0.594 Atmel Studio 7.0.594 resolves the following issues present in Atmel Studio 7.0.582: • AVRSV-7008: Opening a 6.2 project in Atmel studio 7.0.582 persists Debug configuration settings for all the other configurations. • AVRSV-6983: Uninstalling Studio extensions does not work in some cases. • AVRSV-7018: Project Creation fails with some culture specific user names. • AVRSV-7019: Help Viewer does not work on 32-bit machines. • Issues with getting tools/debuggers recognized or visible see section 2.4 in ‘Atmel Studio 7.0.594- readme.pdf’ for workarounds. Atmel Studio 7.0.582 • Updated to Visual Studio Isolated Shell 2015 • Integration with Atmel Start. – This tool will help you select and configure software components, drivers, middle-ware, and example projects to tailor your embedded application in a usable and optimized manner • New device support system, CMSIS Pack compliant • Data Visualizer, used for processing and visualizing data • Updated help system, improved context sensitive help • Atmel Software Framework version 3.27.3. ASF is an extensive software library of software stacks and examples. • A major upgrade of the Visual Assist extension to Atmel Studio that assists with reading, writing, refactoring, navigating code fast • Import Arduino Sketch projects into Atmel Studio • Support for Flip-compatible bootloaders in atprogram and programming dialogue. The connected device appears as a tool. • AVR 8-bit GCC Toolchain 3.5.0 with upstream versions1 : – gcc 4.9.2 – Binutils 2.25 – avr-libc 1.8.0svn – gdb 7.8 • AVR 32-bit GCC Toolchain 3.4.3 with upstream versions1 : – gcc 4.4.7 – Binutils 2.23.1 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 10 – Newlib 1.16.0 • ARM GCC Toolchain 4.9.3 with upstream versions1 : – gcc 4.9 (revision 221220) – Binutils 2.24 – gdb 7.8.0.20150304-cvs 1.2.2. Atmel Studio 6.2 Service Pack 2 • Atmel Software Framework 3.21.0 • Added support for the ATSAML21 device family • Added support for the ATSAMV7 device family, based on the ATM Cortex-M7 core 1.2.3. Atmel Studio 6.2 Service Pack 1 • Atmel Software Framework 3.19.0 • AVR 8-bit Toolchain 3.4.5 with upstream versions: – GCC 4.8.1 – Binutils 2.41 – avr-libc 1.8.0svn – gdb 7.8 • AVR 32-bit Toolchain 3.4.2 with upstream versions: – GCC 4.4.7 – Binutils 2.23.1 • ARM GCC Toolchain 4.8.4 with upstream versions: – GCC 4.8.4 – Binutils 2.23.1 – gdb 7.8 • Support for trace buffers for ARM (MTB) and 32-bit AVR UC3 (NanoTrace) • Support for attaching to targets 1.2.4. Atmel Studio 6.2 • Atmel Software Framework 3.17.0 • AVR 8-bit Toolchain 3.4.4 (with upstream GCC 4.8.1) • AVR 32-bit Toolchain 3.4.2 (with upstream GCC 4.4.7) • ARM GCC Toolchain 4.8.3 • Support for Atmel-ICE • Support for Xplained Mini • Support for data breakpoints • Read OSCCAL calibration for tinyAVR® and megaAVR® • Create ELF production files for AVR 8-bit using the programming dialogue • Live Watch 1 For more information, see the readme that is installed as part of the toolchain. 2 For more information, see the readme that is installed as part of the toolchain. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 11 • Non-intrusive trace support for SAM3 and SAM4 family of devices including – Interrupt trace and monitoring – Data trace – FreeRTOS™ awareness – Statistical code profiling • Polled Data trace support for Cortex M0+ • Default debugger for SAM devices is now GDB. GDB does in some scenarios handle debugging of optimized code better. • Support to create a GCC Board project (Atmel board\User board) for ALL the installed versions of ASF • New ASF Board Wizard, to Add or Remove Board Project Template • Improved loading time of New Example Project dialog, by loading only one ASF version by default • IDR events now gets displayed in a separate pane in the output window • LSS file syntax highlighting 1.2.5. Atmel Studio 6.1 Update 2 • Support for SAM D20 devices on the JTAGICE3 • Atmel Software Framework 3.11.0 1.2.6. Atmel Studio 6.1 Update 1.1 • Fix programming of boot section for XMEGA devices introduced in 6.1 update 1 • Fix SAM4LSP32 bare-bone project setup 1.2.7. Atmel Studio 6.1 Update 1 • Atmel Software Framework 3.9.1 • Extension Development Kit (XDK). Support for packaging an Embedded Application project into an Atmel Gallery Extension. • Support for SAM D20 and SAM4N devices • ARM GCC Toolchain 4.7.3 with experimental newlib-nano and multilibs 1.2.8. Atmel Studio 6.1 • Support for Embedded Debugger platform • Support for Xplained Pro kits • Atmel Software Framework 3.8.0 • AVR 8-bit Toolchain 3.4.2 (with upstream GCC 4.7.2) • AVR 32-bit Toolchain 3.4.2 (with upstream GCC 4.4.7) • ARM GCC Toolchain 4.7.3 • CMSIS 3.20 • Updated Visual Assist • Command line utility for firmware upgrade • Stimulus for simulator. Create a stimuli file to write register values while executing simulation. 1.2.9. Atmel Studio 6.0 • Support for Atmel ARM-based MCUs with Atmel SAM-ICE • Atmel Software Framework 3.1.3 • AVR Toolchain 3.4.0 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 12 • ARM Toolchain 3.3.1 • Atmel Software Framework Explorer • Support for QTouch Composer as extension • Updated Visual Assist • New extension gallery 1.2.10. AVR Studio 5.1 • New version of AVR Software Framework (ASF) • Availability and installation of new ASF versions through extension manager, without having to upgrade Studio 5 • Support for side by side versioning of ASF, with the ability to upgrade projects • Syntax highlighting and better debugging support for C++ projects • Support for importing AVR 32 Studio C++ projects • New version of AVR Toolchain • New command line utility (atprogram) with support for all Atmel AVR tools and devices • Enhancements to programming dialog including support for ELF programming • New version of Visual Assist with several enhancements and bugfixes 1.3. Installation Installation instructions. Supported Operating Systems • Windows 7 Service Pack 1 or higher • Windows Server 2008 R2 Service Pack 1 or higher • Windows 8 / 8.1 • Windows Server 2012 and Windows Server 2012 R2 • Windows 10 Supported Architectures • 32-bit (x86) • 64-bit (x64) Hardware Requirements • Computer that has a 1.6GHz or faster processor • RAM – 1GB RAM for x86 – 2GB RAM for x64 – An additional 512MB RAM if running in a Virtual Machine • 6GB of available hard disk space Downloading and Installing • Download the latest Atmel Studio installer • Atmel Studio can be run side by side with older versions of Atmel Studio and AVR Studio® . Uninstallation of previous versions is not required. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 13 • Verify the hardware and software requirements from the "System Requirements" section • Make sure your user have local administrator privileges • Save all your work before starting. The installation might prompt you to restart, if required. • Disconnect all Atmel USB/Serial hardware devices • Double click the installer executable file and follow the installation wizard • Once finished, the installer displays an option to Start Atmel Studio after completion. If you choose to open, then note that Atmel Studio will launch with administrative privileges, since the installer was either launched as administrator or with elevated privileges. 1.4. Contact Information Report any problems you experience with this version of Atmel Studio. We would also like to receive good ideas and requests that can help to improve further development and releases of Atmel Studio. Check out the Atmel Knowledge Base for any issues that you might encounter. From the same page, it is possible to contact Atmel Support through the new support portal which is linked up with your myAtmel account. For the latest updates of Atmel Studio, visit the Atmel web site: www.atmel.com. Reporting Bugs Copy the information from the version dialog (see the figure below) and include it in the email to Atmel. Also, make sure to provide a detailed description of the problem: 1. Describe how to recreate the problem. 2. Attach any test program that causes the problem. 3. Check that the copied version information contains used debug platform and device. The version dialog is opened by the file menu Help → About Atmel Studio. Debug platform and device are only displayed if you are in debug mode. Push the copy button to copy the contents to the clipboard. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 14 Figure 1-1. Atmel Studio About Box Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 15 2. Getting started 2.1. Starting Atmel Studio Atmel Studio is started by clicking on the Atmel Studio 7.0 shortcut in the Start-up menu. Once started, the start page is displayed. From within this page you can create new projects and reopen recently used projects, as well as browse through articles providing tutorials, help and news. The Start page can also be accessed from View → Start Page, or Alt V G . Figure 2-1. The Project Related Section of the Start Page The left section of the start page contains project-related items: • New project - Use this to create a new project. If you are new to the concept of software development with Atmel Studio, refer to the step-by-step guides. The project settings and available options are described in detail in Project Management. • New example project - To take a step-by-step tour of the available Atmel platforms' functionalities using the Atmel Software Framework, click this button. • Open project - Load an existing project, not mentioned on the Recent projects pane. The Recent projects lists the most recently opened projects. Clicking on any of the links will open the project, restoring it and the GUI to its last saved settings. You can select the number of projects you would like to be shown in the Menus and Settings. Discover Atmel Studio Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 16 This section contains links to helpful information about how to use Atmel Studio and related tools. Announcements In the Announcements section you can read the Atmel RSS feed or any other RSS feed. From the Tools > Options... menu, select Start Page > Feeds to configure which RSS feeds that should be seen. In order to turn ON or OFF the feeds, use the Show feeds check-box. 2.2. Creating a Project 2.2.1. Introduction Atmel Studio is based on Visual Studio, and hence the application development process is organized into projects and The Solution Container. The following sections demonstrates how to create a new GCC C executable project and write a simple application. 2.2.2. Creating a new Project On the Start Page discussed in Getting started, click the New Project option. Figure 2-2. Project Options The project wizard appears. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 17 Figure 2-3. Project Wizard About project types Table 2-1. Project Types Category Project templates Description C/C++ GCC C ASF Board Project Select this template to create an AVR 8-bit or AVR/ARM 32- bit ASF Board project. C/C++ GCC C Executable Project Select this template to create an AVR 8-bit or AVR/ARM 32- bit GCC project. C/C++ GCC C Static Library Project Select this template to create an AVR 8-bit or AVR/ARM 32- bit GCC static library(LIB) project. C/C++ GCC C++ Executable Project Select this template to create an AVR 8-bit or AVR/ARM 32- bit C++ project. C/C++ GCC C++ Static Library Project Select this template to create an AVR 8-bit or AVR/ARM 32- bit C++ static library (LIB) project. Assembler Assembler Project Select this template to create an AVR 8-bit Assembler project. Category Project Templates Description Note:  Extensions and plugins to Atmel Studio may provide new project templates. Create a project Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 18 1. In the New Project dialog box, select Installed Templates. This lists the available project types. 2. For this example, create an GCC C Executable Project. 3. In the Name box, type a name for the new project. 4. In the Location box, select a save location. 5. Atmel Studio will suggest a name in the Solution name box. You can override this name if wanted. 6. Leave the Create directory for solution checkbox checked. 7. Click OK. 2.2.3. Choosing a Target Device When a new project is created, the Device Selection dialog is displayed and you will be prompted to select the project target device. Figure 2-4. Device Selection The device selection dialog lists all supported devices for the current project type. To narrow down the selection of devices, select the device family in the Device Family field, or use the Search for Device field to view a filtered list of devices matching your search string. Select a device 1. In the Device Selection dialog, select ATxmega128A1. 2. Click OK. 2.2.4. Writing and Compiling Code Your solution and project has been created. You can now start editing your application. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 19 Figure 2-5. Code Editor Atmel Studio automatically opens the newly created C file in the source editor. If the file is closed at any time, double click on [Project_name].c - in this case GccApplication1.c - to open it in the editor. At this time the C file contains only an include statement for I/O manipulation and a simple main() function. Create and build a simple application 1. Replace the original main function with the following source code: #define MAXINT 200000 int main(void) { unsigned int t=1000, k=0, l=5, pn=2; unsigned int primes[t]; primes[0]=2; primes[1]=3; while (pn < t || primes[pn] < MAXINT) { for ( k = 0; k <= pn; k++) { if (l % primes[k] == 0) { goto otog; } else { if (k == pn) primes[pn++]=l; } } otog: l += 2; } Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 20 return 0; } 2. To compile the project, press F7 key or select Build Solution from the Build menu. Atmel Studio now builds the application. All output from the compiler is listed in the output window. This concludes the introduction to creating code projects in Atmel Studio. All aspects of projects are described in detail in Project Management. The next section will describe how to debug this application using the built-in simulator. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 21 3. Project Management 3.1. Introduction Atmel Studio is an Integrated Development Environment (IDE) for writing and debugging applications for AVR/ARM platforms. Currently as a code writing environment, it supports the included AVR Assembler and any external AVRGCC/ARMGCC compiler in a complete IDE environment. Using Atmel Studio as an IDE gives you several advantages: 1. Editing and debugging in the same application window allows for a faster error tracking. 2. Breakpoints are saved and restored between sessions, even if the code was edited in the meantime. 3. Project item management is made convenient and portable. 3.1.1. The Solution Container With AVR Studio 5, the concept of "solution" is introduced. The solution is a container that may contain several projects. A project cannot exist outside a solution. If you try to open a project file ( .cproj or .asmproj extension) a solution will be created for you. This allow you to keep for example a bootloader project, and several application projects in the same solution. In practice the Solution is stored as an .atsln file. In general, projects that are added to the solution are placed in a separate folder inside the folder that the .atsln file recides in. 3.1.2. Save and Open Projects All projects are saved under a chosen name with the .cproj extension for GCC projects and .asmproj extension for 8-bit assembler projects. The user can reopen a project, either from the file menu, from the recently used projects list, or from the Project menu, under Open project. 3.1.3. Project Output View After building, assembling, or compiling the project, the operation result will be shown in the build output window. If any errors occur, the user can double-click on the message, which will position the marker over the corresponding line in the source window. 3.1.4. Solution Explorer Solution Explorer allows you to view items and perform item management tasks in a solution or a project. It also allows you to use the Atmel Studio editors to work on files outside the context of a solution or project. By default it appears on the right side of the Atmel Studio GUI. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 22 Figure 3-1. The Solution Explorer Pane 3.1.5. Toolbar Icons Buttons specific to the item selected in the tree view appear on the Solution Explorer. • Displays the appropriate property user interface for the selected item in the tree view. • Shows all project items, including those that have been excluded in the project and those that are hidden. 3.1.6. Hierarchical Display A single solution and all its projects appear in a hierarchical display. This allows you to work on several projects at the same time and at the same time keep track of all projects and items. Most source control system extensions (such as AnkhSVN) will also add icon overlays to the item icons, to signal the up-todate status of the project items that are under revision control. 3.1.7. Item Management Commands Solution Explorer supports a variety of management commands for each project or solution item. Right click on any item to get a menu with the available commands for that particular item. 3.1.8. Project Components A project will contain a set of device specific components. This includes startup code, linker scripts, and other support libraries. Components are small pieces of code or other supporting files that are included in any project. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 23 Figure 3-2. Project Components Components that are included in a project are listed in the Component drop-down. Selecting a component from the drop-down menu shows the component version, the files that the component is contributing with, and the dependencies that the component has. The version of the component can be changed by clicking the Change version button. 3.1.8.1. Change Version Components are versioned when added to the project. To change the version that is used, use this dialog. There are two options when choosing the version of a component Use a specific version Lock the project to a specific version of the component. Use the latest version Choose the most recent version of the component that is available. Figure 3-3. Change Version Components are part of the device packs in Atmel Studio. These device packs are managed using the Device Pack Manager. Related Links Device Pack Manager on page 146 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 24 3.2. GCC Projects 3.2.1. New Project Wizard Select File → New from the menu, and the dialog below will appear. The startup wizard will also have an option to start a new project. Figure 3-4. New Project Project types Currently several project types are available in the Project Type box. AVR board examples - to guide you through the usage of the AVR boards, User board project - if you have created your own product with the AVR tools, and a general AVR GCC project - a board independent project with a GNU compiler. It is also possible to create an AVR Assembler project and a general AVR Solution, which may include any supported source code type. Tip:  Projects can also be created by loading supported object files. If you want to create such a project, you should use the File → Open file menu. Project name and initial file Input the project name. The project main file, which is generated automatically, will be named with the same name by default (ASM or C). If you wish, you can change this name. It is possible to check a box to create a new folder, bearing the project name. This box is unchecked by default. You can choose to create a new solution in the Solution drop-down menu, or to reuse existing code. Input the solution name in the Solution Name field. If you are satisfied with the project name and type, press OK and proceed to the debugging platform selection stage. You can also leave the platform undefined for now, but then the you will have to select the debug platform and device upon starting a debug session. See also Assembler Projects, Object File Formats 3.2.2. Starting a New GCC Project for AVR Device 1. Create a new project by selecting New Project from the Project menu. This will open the Project Wizard. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 25 2. Select C/C++→GCC C Executable Project as a template, then specify a project name, select a location, and write a solution name for the project. A file with the same name as the project will be created and added to the project by default. It will contain an empty main() function. If you want to change the name of the initial file, just edit the main file name afterward. Press OK when you are satisfied with the settings. 3. Select C/C++→GCC C Static Library Project as a template, then specify a project name, select a location, and write a solution name for the project. This creates a Static Library (LIB) project, which is a good way to reuse code. Tip:  See section Starting a New GCC Static Library Project to learn more about Static Library projects. 4. A device selection table will appear. Choose the appropriate target platform for your project. To start you can select the ATxmega128A1 device. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 26 Figure 3-5. Device Selection 5. The project tree will be set up. Notice that the initial file created in step 2 has been added to the project node. Also, the initial file will be opened in the editor. 6. In order to facilitate applications development and verification you can also use the Driver Selection Wizard, invoked from Project → ASF Wizard... Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 27 In the ASF Wizard you can select which Drivers, Components, and Services you would like to use in the project for current build architecture and board. 7. Now, write the following code into the open editor window. #define MAXINT 200000 int main(void) { unsigned int t=1000, k=0, l=5, pn=2; unsigned int primes[t]; primes[0]=2; primes[1]=3; while (pn < t || primes[pn] < MAXINT) { for ( k = 0; k <= pn; k++) { if (l % primes[k] == 0) { goto otog; } else { if (k == pn) primes[pn++]=l; } } otog: l += 2; } return 0; } 8. Build the project. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 28 Figure 3-6. View of a GCC Project after Build Completed Dependencies All the included files are listed here. Double click on any file to open it in the editor. Output Files All output files will be displayed below this item. Libraries All Static Library files, Toolchain Library, and other Library Files will be displayed below this item. Tip:  See section Library Options to know more about Library options. 3.2.3. Libraries Options All Static Library files, Toolchain Library, and other Library Files will be displayed below this item. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 29 Figure 3-7. Libraries 3.2.3.1. Toolchain Libraries The toolchain libraries would be listed here. The Library search path provided by the toolchain would be enumerated to form the library list. 3.2.3.2. Project Libraries The projects available at the current Solution would be enumerated and the static libraries would be listed here. 3.2.3.3. Browse Libraries You can browse for other libraries. 3.2.3.4. How to Add Project Library Tip:  Ensure you have static library projects in the current solution. Right click on Project or Libraries Node in the project to invoke "Add Library" Wizard. Select Project Libraries Tab; here would see the all the static libraries in current solution listed. Select the Static Library which you would like to add. Click OK. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 30 Figure 3-8. View of a Project after Adding Libraries Also you will see that at Project → Project Dependencies Static Library added. Figure 3-9. View of a Project Dependencies after Adding Libraries 3.2.3.5. How to Add Toolchain Library Right click on Project or Libraries Node in the project to invoke "Add Library" Wizard. Select Toolchain Libraries Tab; here you will see the available toolchain libraries for the currently selected toolchain for project. Select the libraries which you like to add. Click OK. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 31 Figure 3-10. View of a Project after Adding Libraries You will also be able to see the new library added in the Toolchain Linker Settings. Figure 3-11. View of a Linker Option after Adding Libraries Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 32 3.2.4. Starting a New GCC Project for SAM (ARM) Device 1. Create a new project by selecting New Project from the Project menu. This will open the Project Wizard. 2. Select C/C++ → GCC C Executable Project as a template, then specify a project name, select a location, and write a solution name for the project. Some start-up files will be added to the project by default, which will contain some device specific functions and libraries. Press OK when you are satisfied with the settings. 3. Select C/C++ → GCC C Static Library Project as a template, then specify a project name, select a location, and write a solution name for the project. This creates a Static Library (LIB) project, which is a good way to reuse code. Tip:  See section Static Library Project to learn more about Static Library projects. 4. A device selection table will appear. Choose the device family as SAM3 or SAM4 and select the target platform for your project. To start you can select the ATSAM3S1A device. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 33 5. The project tree will be set up. Notice that the initial files created in step 2 has been added to the project node. Also, the file containing main() function will be opened in the editor. Here is a list of files that will be created: – A file with the same name as the project will be created and added to the project by default. It will contain the main() function. – A startup file(startup_*.c) will be available at "cmsis\src" directory. It contains the default interrupt handlers for all the peripherals. – A system file(system_*.c) available at "cmsis\src" provides the system level initialization functions that are called on start-up – Linker scripts with appropriate sections based on the device will be created at "cmsis \LinkerScripts" directory in the project folder – In case if you have deleted any files in cmsis folder and want to revert it back or if you have changed the device, just right click the Project and click "CMSIS Update from Atmel" to get the appropriate files. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 34 Note:  It is recommended not to change the contents of the startup_*.c and system_*.c files unless you have no other choice. These startup, system, and linker scripts will not be created for ARM static library projects. 6. In order to facilitate applications development and verification you can also use the Driver Selection Wizard, invoked from Project → ASF Wizard. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 35 In the ASF Wizard you can select which Drivers, Components, and Services you would like to use in the project for current build architecture and board. 7. Now, write the following code into the open editor window: #define MAXINT 200000 int main(void) { unsigned int t=1000, k=0, l=5, pn=2; unsigned int primes[t]; primes[0]=2; primes[1]=3; while (pn < t || primes[pn] < MAXINT) { for ( k = 0; k <= pn; k++) { if (l % primes[k] == 0) { goto otog; } else { if (k == pn) primes[pn++]=l; } } otog: l += 2; } return 0; } 8. Build the project. 3.2.5. Code Editing For the following part of the introduction we will reuse the same code as you have previously seen. #define MAXINT 200000 int main(void) { unsigned int t=1000, k=0, l=5, pn=2; unsigned int primes[t]; primes[0]=2; primes[1]=3; while (pn < t || primes[pn] < MAXINT) { for ( k = 0; k <= pn; k++) { if (l % primes[k] == 0) { goto otog; } else { if (k == pn) primes[pn++]=l; } } otog: l += 2; } return 0; } Atmel Studio has a rich editor that is made even richer by Atmel and third-party plugins. Atmel Studio has an automatic code generation faculty for snippets of C source code. To use it select and right click the part of the code you wish to enclose in a conditional structure (like for,while,if … etc). Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 36 Using the code snippets you can add parts to your core source. In some snippets the variable names and exit conditions are parametric within the IDE, so as if only one instance is changed all instances within the snippet will also change, such is the case of for loop. Table 3-1. Using "Surround With" ⇒ ⇒ 3.2.6. Starting a New GCC Static Library Project 3.2.6.1. Why Static Libraries Static Libraries (LIB) is a good way to reuse code. Rather than re-creating the same routines/functions in all the programs, the user can write them once and reference from the applications that need the functionality. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 37 3.2.6.2. Create New Static Library Project Figure 3-12. New Static Library Project Click OK to create the Static Library project. A default source file with the same name as the project will be added to the solution. You may then write and compile your routines/functions. You can also add new source files or header files into the project. Open the Project Properties on the menu Project → "Your_project_name Properties". This menu item is only available when a Static Library project is open. Select the Build property page. Here you will see that the Artifact Type is selected as Static Library. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 38 Figure 3-13. Static Library Build Properties Compile the project by selecting Build Solution from the Build menu. This creates a Static Library, which can be used by other programs. 3.2.6.3. Static Library Project Options (AVR/GNU Archiver) The AVR/GNU archiver, avr-ar, combines a collection of object files into a single archive file, also known as a library. Open the Project Properties on the menu Project → "Your_project_name Properties". This menu item is only available when a Static Library project is open. In order to configure Static Library options, click on the Toolchain property tab. In the Toolchain property page, you will see AVR/GNU Archiver active and enabled. You may also see that the AVR/GNU Linker is disabled for a static library project. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 39 Figure 3-14. AVR/GNU Archiver Setup Dialog, Command Line Shown You can set the AVR/GNU Archiver flags at the Archiver Flags textbox in the above General options. Now, save the project and compile by selecting Build Solution from the Build menu. 3.2.7. GCC Project Options and Configuration Project options and configuration can be set up by either right clicking on the Solution Explorer → Project Properties, or by pressing Alt Enter . This will call up the Project properties window, it has seven tabs: If a tab supports properties that are configuration specific, then the tab has two slide-down menus: The Configuration field defines the project configurations to modify. By default, two configurations are provided in each project - Debug and Release. The Platform field is set to AVR. If a tab supports configuration independent properties, then the Configuration and Platform fields are disabled. Note:  Use the "Save All ( Ctrl Shift S )" from the File menu or toolbar to update the changes in the project file whenever changes are made. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 40 3.2.7.1. Build Options Figure 3-15. Build Configuration In the Build tab page, you can configure whether you want to use an external Makefile for your project. In that case, just tick the Use External Makefile check box and browse to select the correct path of make file. Build Commandline will be provided to the external makefile when build is invoked for the project. The default build target is "all". Clean Commandline will be provided to the external makefile when clean is invoked for the project. The default clean target is "clean". Besides the external make file configuration, you can also specify the type of application to build. The options are Executable or Static Library, which can be selected using the Artifact Type combo box. Note:  Custom makefile must fulfill those conditions: 1. Target name must equal project name. 2. Makefile and target must exist in the same folder (can be referenced with NTFS links too). Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 41 3.2.7.2. Build Events Figure 3-16. Build Events Options The Build events tab contains a list of scheduled events for each configuration, launched by the prebuild and post-build scripts. These events can be added, deleted, or modified by clicking either the Edit pre-build... or Edit post-build... buttons. Upon clicking these buttons, you should manually add your commands in the following dialog. As of the current release it is possible to use environment variables and values declared within them as a link with other available applications. In order to use that function press the Show Macros button. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 42 Figure 3-17. Build Event Editor Macros Expands the edit box to display the list of macros/environment variables to insert in the command line edit box. Macro Table List the available macros/environment variables and its value. You can select only one macro at a time to insert into the command line edit box. MSBuild also provides a set of reserved properties that store information about the project file and the MSBuild binaries. These properties may also be listed in the edit box. See Macros/environment variables below for a description which are specific to Atmel Studio. Table 3-2. Atmel Studio Build Macro Table Macro Description $(AVRSTUDIO_EXE_PATH) The installation directory of Atmel Studio (defined with drive and path) $(SolutionDir) The directory of the solution (defined with drive and path) $(SolutionPath) The absolute path name of the solution (defined with drive, path, base name, and file extension) $(SolutionFileName) The file name of the solution $(SolutionName) The base name of the solution $(SolutionExt) The file extension of the solution. It includes the '.' before the file extension. $(Configuration) The name of the current project configuration, for example, "Debug" $(Platform) The name of the currently targeted platform, for example, "AVR" $(DevEnvDir) The installation directory of Atmel Studio (defined with drive and path) $(ProjectVersion) The version of the project Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 43 Macro Description $(ProjectGuid) A unique identifier of the project $(avrdevice) The name of the currently selected device $(avrdeviceseries) The series of the selected device. Used internally by the Atmel Studio. $(OutputType) Defines if the current project is an Executable or a Static Library type $(Language) Language of the current project; for example, C, CPP, or Assembler $(OutputFileName) The file name of the primary output file for the build (defined as base file name) $(OutputFileExtension) The file extension of the primary output file for the build. It includes the '.' before the file extension $(OutputDirectory) The absolute path of the output file directory $(AssemblyName) The assembly name of the primary output for the build $(Name) The base name of the project $(RootNamespace) The base name of the project $(ToolchainName) The name of the toolchain $(ToolchainFlavour) The name of the toolchain's compiler Macro Description Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 44 3.2.7.3. Compiler and Toolchain Options Figure 3-18. Compiler and Toolchain Options AVR GNU C Compiler Options Table 3-3. AVR GNU C compiler Options Option Description General options -mcall-prologues Use subroutines for functions prologues and epilogues -mno-interrupts Change stack pointer without disabling interrupts -funsigned-char Default char type is unsigned -funsigned-bitfield Default bit field is unsigned Preprocessor options -nostdinc Do not search system directories -F Preprocess only Symbols options Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 45 Option Description There one can define (-D) or undefine (-U) a number of in-source symbols. New symbol declarations can be added, modified, or reordered, using the interface buttons below: • Add a new symbol. This and all following icons are reused with the same meaning in other parts of Atmel Studio interface. • Remove a symbol. • Edit symbol. • Move the symbol up in the parsing order. • Move the symbol down in the parsing order. Include directories Contains all the included header and definition directories, can be modified, using the same interface as symbols. Optimization options Optimization level (drop down menu): -O0, - O1, -O2, -O3, -Os No optimization, optimize for speed (level 1 - 3), optimize for size Other optimization flags (manual input form) Here you should write optimization flags specific for the platform and your requirements -ffunction-sections Prepare functions for garbage collection, if a function is never used, its memory will be scrapped -fpack-struct Pack structure members together -fshort-enums Allocate only as many bytes needed by the enumerated types -mshort-calls Use rjmp/rcall limited range instructions on the >8K devices Debug options Debug level (drop down menu): none, -g1, - g2, -g3 Specifies the level of tracing and debugging code and headers left or inserted in the source code Other debug options (form field) Architecture specific debug options Warning messages output options -Wall All warnings -Werror Escalate warnings to errors -fsyntax-only Check syntax only Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 46 Option Description -pedantic Check conformity to GNU, raise warnings on nonstandard programming practice -pedantic-errors Same as above, plus escalate warnings to errors Miscellaneous options Other flags (form field) Input other project-specific flags -v Verbose -ansi Support ANSI programs -save-temps Do not delete temporary files Option Description AVR GCC Linker Options Table 3-4. AVR GCC Linker Options Option Description -Wl -nostartfiles Do not use standard files -Wl -nodefault Do not use default libraries -Wl -nostdlib No start-up or default libraries -Wl -s Omit all symbol information -Wl -static Link statically Libraries options Libraries -Wl, -l (form field) You can add, prioritize, or edit library names here, using these buttons: , , , , Library search path -Wl,-L (form field) You can add, prioritize or edit path where the linker will search for dynamically linked libraries, same interface as above Optimization options -Wl, -gc-sections Garbage collect unused sections --rodata-writable Put read-only data in writable spaces -mrelax Relax branches Miscellaneous options Other linker flags (form field) Input other project-specific flags Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 47 AVR Assembler Options Table 3-5. AVR Assembler Options Option Description Optimization options Assembler flags (form field) Miscellaneous assembler flags Include path (form field) You can add, prioritize or edit path to the architecture and platform specific included files here -v Announce version in the assembler output Debugging options Debugging level (drop down menu) -Wa -g1, - Wa, -g2, -Wa, -g3 Defines a level of debugging symbol and debugging source insertion 3.2.7.4. Device Options This tab allows you to select and change the device for the current project and is similar to the device selector, see Figure 3-5. Tip:  Click on the Device button on the Device and Debugger toolbar to get to this tab quickly while editing. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 48 3.2.7.5. Tool Options This tab allows you to select and change the debugger platform for the current project. Tip:  Click on the Device button on the Device and Debugger toolbar to get to this tab quickly while editing. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 49 Select tool/debugger from the drop-down list. Current selection is shown. Select Interface from the drop-down list. Current selection is shown. Note:  Only tools and interfaces valid for the current device selection are shown. Further Properties are dependent on tool and interface selected. JTAG If you have selected JTAG as the programming interface, clock speed, use external reset - and daisy chain setting may be available. This depends on the tool and device. JTAG clock JTAG clock is the maximum speed the tool will try to clock the device at. The clock range is different for different tools and devices. If there are restrictions, they will be stated in a message below the clock slider. Clock can be set to Manual (all tools), Auto (SAM-ICE only), or Adaptive (SAM-ICE only). Use external reset If checked, the tool will pull the external reset line low when trying to connect to the device. JTAG daisy chain settings Specify the JTAG daisy chain settings relevant to the device to program. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 50 Target is not part of a daisy chain. Select this option when the target device is not part of a daisy chain. Daisy chain - Manual. Allows you to manually configure the JTAG daisy chain in case you are programming in a system-on-board. • Devices before - specifies the number of devices preceding the target device. • Instruction bits before - specifies the total size of the instruction registers of all devices, preceding the target device. • Devices after - specifies the number of devices following the target device. • Instruction bits after - specifies the total size of the instruction registers of all devices, following the target device. Daisy chain-Auto. Automatically detects the devices in the JTAG daisy chain. Allows you to select the device in the JTAG daisy chain. Auto-detection is supported only for SAM devices. PDI The PDI interface has only one setting – the PDI clock speed. PDI Clock is the maximum speed the tool will try to clock the device at. The clock range is different for different tools and devices. If there are restrictions, they will be stated in a message below the clock slider. The clock can not be adjusted on all tools, so an empty Interface settings page will be presented. Programming and debug settings In the drop-down menu it is possible to specify which parts of memory that should be erased during a programming/debug cycle. • Skip programming - specifies that no programming should occur. The tool will try to attach to the program already in memory. • Erase only program area - specifies that only the program area of memory should be erased. • Erase entire chip - specifies that the entire chip is to be erased. The "Preserve Eeprom" option lets you decide whether EEPROM data should be written when launching a debug session. When this checkbox is checked, EEPROM data in the object file will be written to the device at the start of each debug session. The EESAVE fuse will be set and cleared accordingly. When a device is programmed at the start of a debug session, the default behavior is to erase the content of the device (chip erase, if available). This can be changed by selecting a different option from the drop down box under "Programming settings". Keep timers running in stop mode Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 51 When checked, the timers set in the program will continue to run even when the program breaks at breakpoint or is halted This setting is only enabled for certain tool/interfaces. Override Vector Table Offset Register At reset, load PC and SP from the specified address. Note:  The tool you select on this page is also used with the command Start without Debugging. That is why you also can select tools that do not have debugging capabilities. See Start without Debugging for more information. 3.2.7.6. Advanced Options Setting ToolchainFlavour This section allows you to set the flavour of the toolchain for the current project. Default flavour of the respective toolchain is selected. The toolchain path configured in the flavour is used for building the projects. For configuring and adding new flavours Toolchain. Use GDB This section allows you to select whether GDB has to be used for the current project. The Current GDB Path will be computed by the following 1. The Current GDB Path is taken from 'Tools → Options → Debugger → GDB Settings if configured GDB Settings. 2. Otherwise it is taken from selected Toolchain Flavor if GDB is found there. The Current GDB Path will be overridden when we use the option "Override Current GDB Path" in the "Advanced" project property page. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 52 Note:  The option "Use GDB" is enabled by default for ARM based devices and also the following warning will be shown for AVR 32-bit devices if GDB is enabled. 3.2.7.7. Creating ELF Files with Other Memory Types ELF files that contains data for all memory types can be made with the GCC compiler. The data sections are specified in code as shown in following code examples. Creating ELF Files for tinyAVR, megaAVR, and XMEGA devices This code shows how to add memory sections for tinyAVR, megaAVR, and XMEGA devices (except ATtiny4/5/9/10) . This example is for an ATxmega128A1 device. For other devices, it has to be modified accordingly. #include // Example data for ATxmega128A1 const char eeprdata[] __attribute__ ((section (".eeprom"))) = "Hello EEPROM"; // The order of the fuse values is from low to high. 0xA2 is written to Fuse byte 0, 0x00 to byte 1... const uint8_t fusedata[] __attribute__ ((section (".fuse"))) = {0xA2, 0x00, 0xFF, 0xFF, 0xFF, 0xF5}; Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 53 const uint8_t lockbits[] __attribute__ ((section (".lockbits"))) = {0xFC}; const char userdata[] __attribute__ ((section (".user_signatures"))) = "Hello User Signatures"; // Remember to set the following Toolchain project options, // under AVR/GNU -> Miscellaneous: // // -Wl,--section-start,.user_signatures=0x00850000 int main(void) { while(1) { // TODO:: Please write your application code } } Linker setup for User Signature section The User Signatures section must have a specific Linker Setup, as shown below. This is necessary to get the correct address offset for the user signature section in the elf file. Other memory sections gets the correct address automatically. Figure 3-19. Linker Setup for User Signature Section Creating ELF Files for ATtiny4/5/9/10 This code shows how to add memory sections for ATtiny10. #include typedef struct _tagConfig { unsigned char f1; } Config; typedef struct _tagLock { unsigned char f1; } Lock; Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 54 typedef struct _tagSig { unsigned char f1; unsigned char f2; unsigned char f3; } Signature; Config __config __attribute__((section(".config"))) = { f1 : 0xfb, // Set CKOUT }; Lock __lock __attribute__((section(".lock"))) = { f1 : 0xfc, // Further programming and verification disabled }; Signature __sig __attribute__((section(".signature"))) = { f1 : 0x03, f2 : 0x90, f3 : 0x1e, }; int main(void) { while(1) { // TODO:: Write your application code } } Creating ELF Files for UC3 The example below shows how to add data for the user page in UC3 devices. #include const char userdata[] __attribute__((section(".userpage"))) = "Hello Page"; int main(void) { while(1) { //TODO:: Write your application code } } Project Properties If the memory sections are defined but not referenced in the application code, the "Garbage collect unused sections" option in Project Properties → Linker → Optimization must be unchecked. Otherwise the linker will not include the sections in the .elf file. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 55 Figure 3-20. Project Properties Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 56 3.3. Assembler Projects 3.3.1. Create New Assembler Project Figure 3-21. New Assembler Project After pressing OK, you are asked to select your microcontroller. You can try out the Assembler build and code debugging, using a simple LED-chaser code, given below. It should fit any AVR 8-bit microcontroller, simply change the port (in this case E) to your hardware. start: nop ldi R16, 0xff sts PORTE_DIR, r16 ldi r17, 0x80 output: sts PORTE_OUT, r17 rol r17 ldi r16, 0x00 delay: ldi r18, 0x00 delay1: inc r18 brne delay1 inc r16 brne delay break rjmp output Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 57 When a new project is created or an old project is loaded, the project view will be displayed with all the project files. Files can be added, created, or removed from the project list using the context menu in the Solution explorer window. Figure 3-22. View of an Assembler Project All the source files will be listed at the end of the list. Double click on any file to open it in the editor. All custom include files will be listed directly under the project name item, unless you create a new folder in the project. Figure 3-23. View of an Assembler Project after Build Completed Dependencies: All include files are listed here. Double click on any file to open it in the editor. Labels: All labels in your assembler program are listed here. Double click on any item to show its location in the source. A marker will point to the correct line. Output Files: All output files will be displayed below this item. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 58 Figure 3-24. File Context Menu Table 3-6. File Context Menu Menu text Shortcut Description Open Right click O Open the selected file Open With... Right click n Open selected file with another editor or tool Cut Ctrl X Cut the file from current category Copy Ctrl C Copy the file from current category Remove DEL Remove the selected file from the project Rename F2 Rename the selected file Set As EntryFile Set the selected file as entry file Properties Alt ENTER Current file properties Menu text Shortcut Description All the interface views are docked by default. You can switch between docked and undocked views by dragging windows around to a desirable location, or by dragging and dropping a window on a quick docking menu of the Visual Studio IDE. The quick docking menu will appear every time you start dragging an interface view or window. 3.3.1.1. Project Context Menu Several build commands are available from the menu and the toolbars. There is also a context menu for the project: Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 59 Figure 3-25. Project Context Menu Table 3-7. Project Context Menu Menu text Shortcut Description Build Right click+u Build the selected project Rebuild Right click e Will clean the project and build it Clean Right click n Clean up and erase artifacts Add Ctrl Shift A / Shift Alt A (existing item) Add new files or existing files to the project Set as StartUp Project Right click + a Will set up to automatically open current project at start up Cut Ctrl X Cut project to paste it as a sub-project to another solution Remove Del Remove project or sub-project under cursor Rename F2 Rename current project Unload Project Right click l Unload active project files from the IDE Properties Alt Enter Project properties 3.3.2. Assembler Options Open the options window on the menu Project → "Your_project_name Properties". This menu item is only available when an assembler project is open. After opening the Project properties window, you will see six tabs, in order to configure assembler options click on the Toolchain. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 60 Figure 3-26. Assembler Setup Dialog, Command Line Shown Figure 3-27. Assembler Setup Dialog, General Options Shown 3.3.2.1. Description of the Various Settings Configuration menu allows to choose which stages of project maturity are going to be affected by the modifications to the project properties. By default Debug is the initial stage and initially active configuration. Following options are available: 1. Debug. 2. Release. 3. All configurations. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 61 Platform menu shows compatible target platforms available for prototyping. Hex Output format The following file formats can be selected as additional output format: 1. Intel Hex. 2. Generic Hex. 3. Motorola Hex (S-record). Wrap relative jumps The AVR RJMP/RCALL instructions allow a 12-bit PC-relative offset, corresponding to ±2k words. For devices having 4k words (8kB) or less FLASH program memory, the Wrap option causes the assembler's offset calculation to wrap around over the addressable program memory range, enabling the entire program memory to be addressed using these instructions. For devices with more than 4k words of program memory, using this option may cause unpredictable results and it should be turned OFF. If it is left ON, the assembler will produce a warning when wrap takes effect: Attention:  Wrap rjmp/rcall illegal for device > 4k words - Turn off wrap option and use jmp/call. This diagnostic is given as a warning and not an error to retain compatibility with earlier versions of the assembler, but should be treated as an error by the user. The JMP/CALL 2-word instructions take 22-bit absolute addresses and should be used instead. Unsupported Instructions. By default, this option is set to give a warning when the assembler finds unsupported instructions for the actual device. Optionally, you can output an error. Include Paths (-I). Additional include paths can be set here, when using third party modules or your own IP. Assembler's default include path:\Atmel\AVR Tools\AvrAssembler2\Appnotes. Other optimization flags can be set to tailor optimization to your specific needs, see Assembler help for more information. 3.4. Import of Projects 3.4.1. Introduction Atmel Studio allow import of projects from several pre-existing project sources. This section details how to import existing projects. 3.4.2. Import AVR Studio 4 Project Click the menu File → Import → AVR Studio 4 Project.. or Ctrl+4. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 62 An Import AVR Studio 4 Project dialog will appear. Type the name of your project or browse to the project location by clicking the Browse button of the APS File location Tab. Atmel Studio will proceed with conversion also updates the progress, warnings, and errors. They will be shown in the Summary window. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 63 Check Show conversion log after this page is closed to view the complete conversion log. Click Finish to access your newly converted project. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 64 Note:  Currently, conversion only adds a project file and solution file if the Solution Folder is the same as the APS File Location. No other files will be modified. 3.4.3. Import AVR 32 Studio Project Click the menu File → Import → AVR Studio 32 Project.. or Ctrl+3. An "Import AVR Studio 32 Project" dialog will appear. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 65 Type the name of your workspace or browse to the workspace location by clicking the ... (Browse button) of the Workspace Tab. Click Find Projects to find all the project files and populate other folders available in the workspace. The Available AVR32 C/C++ Projects tab will be populated with all AVR32 C/C++ Projects that can be imported and it will also display total number of available projects. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 66 The Invalid AVR32 Projects tab will be populated with all Unsupported AVR32 Projects that can not be imported and it will also display total number of non convertible projects along with reason. Atmel Studio will proceed with conversion also updates the progress, warnings, and errors. They will be shown in the Summary window. Check "Show conversion log after this page is closed" to view the complete conversion log. Click Finish to access your newly converted project. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 67 Note:  • The current version of AVR32 Importer supports AVR32 C/C++ Projects • AP7 device family is currently not supported by Atmel Studio • Currently, conversion only adds project files and solution file if the Solution Folder is the same as the Workspace folder. No other files will be modified. • Pre/Post builds settings are not imported • Automatically generate listing (*.lss) files setting is not imported Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 68 3.4.4. Import Project Template A number of predefined project can be imported to Atmel Studio by File → Import → Project Template..or Ctrl+T These templates provide a starting point to begin creating new projects or expanding current projects. Project templates provide the basic files needed for a particular project type, include standard assembly references, and set default project properties and compiler options. In the " Import Project Template " window specify the following: • Specify the location of your project template • Specify the save location. The combo box will show installed templates that are available in the New Project → Installed Templates. Select any template under which you would like to add your template. You can also add your template at the root by selecting in "Add to folder". Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 69 • You can create a separate folder by specifying the name of the folder under the specified "Add to Folder (Optional)", where you want to add your project template. The resulting project template will be added to the existing installed templates and can be accessed from File → New → Project .. or Ctrl+Shift+N. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 70 Note:  "Import Project Template Importer" will work with template created for the same version. 3.5. Debug Object File in Atmel Studio 3.5.1. Introduction Debug session requires you to load an object file which is supported by Atmel Studio. The debug file contains symbolic information for debugging. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 71 3.5.2. Atmel Studio Supported Debug Formats Table 3-8. Object File Formats Supported by Atmel Studio Object file format Extension Description UBROF .d90 UBROF is an IAR proprietary format. The debug output file contains a complete set of debug information and symbols to support all type of watches. UBROF8 and earlier versions are supported. This is the default output format of IAR EW 2.29 and earlier versions. See below how to force IAR EW 3.10 and later versions to generate UBROF8. ELF/DWARF .elf ELF/DWARF debug information is an open standard. The debug format supports a complete set of debug information and symbols to support all type of watches. The version of the format read by Atmel Studio is DWARF2. AVR-GCC versions configured for DWARF2 output can generate this format. AVRCOFF .cof COFF is an open standard intended for 3rd party vendors creating extensions or tools supported by the Atmel Studio. AVR Assembler format .obj The AVR assembler output file format contains source file info for source stepping. It is an Atmel internal format only. The .map file are automatically parsed to get some watch information. Before debugging, make sure you have set up your compiler/assembler to generate a debug file like one of the formats above. 3rd party compiler vendors should output the ELF/DWARF object file format. 3.5.3. Opening Object Debug File in Atmel Studio Steps to create an Object Project • On the File menu, click Open, and then click Open Object File For Debugging. Open Object File For Debugging wizard will appear. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 72 • – In the Select the object file to debug, select your object file to debug. The object file must be supported by Atmel Studio. – In the Project Name, type a name for the project. Atmel Studio will suggest a name, which you can override if wanted. – In the Location, select a save location. Atmel Studio will suggest a name, which you can override if wanted. – Maintain Folder Hierarchy for Source Files option is selected by default which would create a similar folder structure in the Solution Explorer as that of the source project i.e. the project used to create the object file. Otherwise, all the files are added to the root folder of the project file i.e. the user would not see any folder in the Solution explorer. – Add File As Link option is selected by default in which the object project shall refer the files from its original location without a local copy into the project directory. If the option is not selected, Atmel Studio would copy the files into the object project directory. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 73 • Click Next. The Device Selection dialog will appear. – Choose the appropriate target device. The target device should be the same, which was originally chosen to create the object file. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 74 • Click Finish. The object project files re-mapper appears. In this particular dialog you need to remap your original files of the project using, which the elf projects was created. If files are present at their original place, it will show remapped already in dialog. If files are missing, you will have to remap it manually. Check the screen shot below. If the user resolves the parent folder for any original file, all other files in subsequent directory will be remapped recursively. So, it is useful for the user to remap the number of files by just remapping only one. • Now the Object Project is Created. The files that are not remapped properly are shown in solution explorer like "libgcc.S", with warning sign . Press F5 to debug this Project. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 75 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 76 4. Debugging 4.1. Introduction Atmel Studio can be targeted towards the built-in Simulator, or a variety of tools (see Available Tools View), for example AVR ONE!, JTAGICE mkII or JTAGICE3 (bought separately). 4.1.1. Debug Platform Independent Debug Environment Independent of which debug platform is running, the Atmel Studio environment will appear identical. When switching between debug platforms, all environment options are kept for the new platform. Some platforms have unique features, and new functionality/windows will appear. 4.1.2. Differences Between Platforms Although all debug platforms appear identical in the debug environment there will be small differences between them. A real-time emulator will be significantly faster than the simulator for large projects. An emulator will also allow debugging while the system is connected to the actual hardware environment, while the simulator only allow predefined stimulus to be applied. In the simulator, all registers are always potentially available for display, which might not be the case with an emulator. 4.2. Starting a Debug Session To start a debug session and halt, press Alt+F5 or choose Debug → Start Debugging and Break from the menu, alternatively, press the toolbar button as illustrated below: Figure 4-1. Starting a Debug Session To start a debug session and keep executing, press F5 or press the toolbar button with the continue symbol, or choose Debug → Continue from the menu as illustrated below: Figure 4-2. Starting a Debug Session 4.3. Ending a Debug Session To end the debug session use the Stop Debugging button or keyboard shortcut Shift F5 . Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 77 4.4. Attaching to a Target To attach a target, use the Attach to Target option in the Debug menu, or the attach icon in the debug toolbar. This causes Atmel Studio to launch a debug session on the selected target without uploading a new application or causing a reset. Once the debug session is established, the core of the target is halted and the current execution position of the target is mapped to the code in the project. This means that the state of the target is kept and is inspect-able with normal debug techniques, and the program halts in the current position. Full run control and symbolic debugging should be available after a successful attach. Note:  • The code in the project is mapped to the content of the running target, without any possibility to verify the correctness of this mapping. This means that if the project contains code that is not on the target, then the state and run control might not reflect the truth, as variables and functions might have different code locations on the target than in the project. • The ability to activate a debug session without resetting a target is architecture dependent. Not all architectures supports this feature. Attention:  Physically connecting a debug probe to a target might cause the target to reset, as most debug probes needs an electrical connection to the reset line of the device. Normal electrical precautions needs to be taken to avoid this. 4.5. Start without Debugging 4.5.1. One Click Programming - Program and Run The Start without Debugging command is a one-click alternative to the programming dialog. Execute it by selecting Debug → Start without Debugging from the menu, or press the button on the toolbar. Figure 4-3. Start without Debugging This will build the solution (if any changes are made) and program the target device without starting a debug session. Start without Debugging uses the tool and interface settings specified in the project options. This is different from what takes place when using the stand-alone Programming Dialog, which is not related to the project at all. Note:  Programmers and starter kits can also be used with the Start without Debugging command, not only debuggers. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 78 The Start without Debugging command will also program the EEPROM, fuses, lockbits, and user signature (XMEGA only) segments if they are present in the object file. The GCC compiler can generate ELF object format files with such segments. See Creating ELF Files with Other Memory Types for more information. Note:  The user signature is not erased by Start without Debugging. The programmed user signature from the ELF file will be AND-ed with the content in the device. If you want to replace the signatures with what is in the file, you must perform a user signature erase manually. 4.5.2. Keyboard Shortcut By default, there is no keyboard shortcut to this function, but you might want to add one if you use it a lot. To add one, simply click the Tools → Options menu button and go to Environment → Keyboard. Start typing startwithouttdebugging in the Show commands containing input field, and select Debug.StartWithoutDebugging in the list. Then select the Press shortcut keys input field, and press the desired key combination. You can for example press Ctrl+F5. Note that this shortcut is already assigned to the BreakAll command. If you choose to override it, press the Assign button to assign the new keyboard shortcut. Or, you can select an unused key combination. Figure 4-4. Add Keyboard Shortcut 4.6. Debug Control Several commands are available for controlling the debugger. They are available from both the Debug menu and several toolbars. The Atmel Studio Integrated Development Environment (IDE) has two major operating modes; design mode and debug mode. Design mode is when you are editing the source code project, while debug mode is when you debug your project. The IDE adapts to modes, and menus an toolbars changes. Note:  Some debug commands are available in design mode, some in debug mode. • In design mode, the available debug commands are those that will start the debug session, e.g. Start Debugging and Break, Start Debugging, Start without Debugging. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 79 • In debug mode, you will find commands like Break All, Step Out, and Reset. Start Debugging and Break Starts the debugger, and breaks the execution on the first statement of the program. Start Debugging Starts the debugger, and runs the program. In debug mode and stopped, it resumes execution. Start Without Debugging Programs the project without starting debugging. For details, see Start without Debugging. Break All Halts the debugger. Stop Debugging Stops and terminates the debug session, and returns to design mode. Restart Restarts the debugger and reloads the program. Reset Resets the program to the first statement. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 80 Disable debugWire and Close Available when debugging a device using the debugWire interface. The command disables the debugWire interface (enabling the use of the ISP interface) and terminates the debug session. Step Into Executes one instruction. When in disassembly level, one assembly level instruction is executed, otherwise one source level instruction is executed. Step Over Similar to Step Into, Step Over executes one instruction. However, if the instruction contains a function call/subroutine call, the function/subroutine is executed as well. If a user breakpoint is encountered during Step Over, execution is halted. Step Out Continue execution until the current function has completed. If a user breakpoint is encountered during Step Over, execution is halted. If a Step Out command is issued when the program is on the top level, the program will continue executing until it reaches a breakpoint or it is stopped by the user. Quick Watch Adds a Quick Watch for the variable or expression under the cursor. For details, see QuickWatch and Watches. Toggle Breakpoint Toggle the breakpoint status for the instruction where the cursor is placed. Note that this function is only available when the source window or disassembly window is the active view. New Breakpoint Create a new breakpoint at the location of the cursor. For more information, see Breakpoints. Disable All Breakpoints This function clears all set program breakpoints, including breakpoints which have been disabled. Clear All DataTips Clear all marked Data Tips. For more information, see DataTips. Export Data Tips Save all marked Data Tips to a file in Visual Studio Shell format. Import DataTips Load Data Tips from a Visual Studio Shell file. Options and Settings Debug options and settings, see Debugger. 4.7. Breakpoints 4.7.1. General Information on Breakpoints A breakpoint tells the debugger to temporarily suspend execution of a program when a specific condition takes place, e.g. when a certain instruction is about to be executed. Breakpoints provide a powerful tool that enables you to suspend execution where and when you need to. Rather than stepping through your code line by line or instruction by instruction, you can allow your program to run until it hits a breakpoint, and then start to debug. This speeds up the debugging process. 4.7.1.1. Breakpoint Glyphs The source windows and the isassembly window show breakpoint locations by displaying symbols called glyphs in the left margin. The following table describes these glyphs. If you rest the mouse on a breakpoint glyph, a breakpoint tip appears with more information. This information is especially useful for error and warning breakpoints. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 81 Table 4-1. Breakpoint Glyphs Glyph Description Normal breakpoint. The solid glyph indicates that the breakpoint is enabled. The hollow glyph indicates that it is disabled. Advanced breakpoint. Active/disabled. The + sign indicates that the breakpoint has at least one advanced feature (such as condition, hit count, or filter) attached to it. Breakpoint error. The X indicates that the breakpoint could not be set because of an error condition. Breakpoint warning. The exclamation mark indicates that a breakpoint could not be set because of a temporary condition. Usually, this means that the code at the breakpoint or tracepoint location has not been loaded. It can also be seen if you attach to a process and the symbols for that process are not loaded. When the code or symbols are loaded, the breakpoint will be enabled and the glyph will change. 4.7.2. Operations with Breakpoints 4.7.2.1. To Set a Breakpoint 1. In a source window, click a line of executable code where you want to set a breakpoint. On the right-click menu, click Breakpoint, and then click Insert Breakpoint. —or— In a source window, click a line of executable code where you want to set a breakpoint. On the Debug menu, click Toggle Breakpoint. 4.7.2.2. To Set an Address Breakpoint 1. On the Debug menu, point to Windows, and then click Disassembly if the Disassembly window is not already visible. You need to be in a debug session for this option to be visible. 2. In the Disassembly window, click a line of code, and then click Toggle Breakpoint on the Debug menu. —or— Right-click a line of code, and then select Insert Breakpoint . 4.7.2.3. To Edit a Breakpoint Location 1. In the Breakpoints window, right-click a breakpoint, then click Location on the right-click menu. —or— In a source, Disassembly, or Call Stack window, right-click a line that contains a breakpoint glyph, and then click Location from Breakpoints on the right-click menu. Note:  In a source window, you might have to right-click the exact character where the breakpoint is set. This is necessary if the breakpoint is set on a specific character within a line of source code. 4.7.2.4. Hit Count Keeps Track of How Many Times a Breakpoint is Hit By default, execution breaks every time that a breakpoint is hit. You can choose to: Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 82 • Break always (the default) • Break when the hit count equals a specified value • Break when the hit count equals a multiple of a specified value • Break when the hit count is greater than or equal to a specified value If you want to keep track of the number of times a breakpoint is hit but never break execution, you can set the hit count to a very high value so that the breakpoint is never hit. The specified hit count is retained only for the debugging session. When the debugging session ends, the hit count is reset to zero. 4.7.2.5. To Specify a Hit Count 1. In the Breakpoints window, right-click a breakpoint, and then click Hit Count on the right-click menu. —or— In a source, Disassembly, or Call Stack window, right-click a line that contains a breakpoint, and then click Hit Count from the Breakpoints sub menu on the right-click menu. 2. In the Hit Count dialog box, select the behavior you want from the When the breakpoint is hit list. If you choose any setting other than Break always, a text box appears next to the list. Edit the integer that appears in the text box to set the hit count you want. 3. Click OK. 4.7.2.6. To Enable or Disable a Single Breakpoint In a source, Disassembly, or Call Stack window, right-click a line that contains a breakpoint glyph, point to Breakpoint, then click Enable Breakpoint or Disable Breakpoint. —or— In the Breakpoints window, select or clear the check box next to the breakpoint. To enable or disable all breakpoints From the Debug menu, click Enable All Breakpoints. 4.7.2.7. To Delete a Breakpoint In the Breakpoints window, right-click a breakpoint, and then click Delete on the right-click menu. —or— In a source window or a Disassembly window, click the breakpoint glyph. 4.7.2.8. To Delete all Breakpoints From the Debug menu, click Delete All Breakpoints . Confirmation Prompt When you delete all breakpoints, a prompt requesting confirmation of the action might appear, depending on options settings. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 83 4.7.3. Breakpoint Window Figure 4-5. Breakpoint Window You can open the Breakpoints window from the Debug menu. 4.7.3.1. To Open the Breakpoints Window On the Debug menu, point to Windows, and then click Breakpoints. 4.7.3.2. To Go to the Location of a Breakpoint In the Breakpoints window, double-click a breakpoint. —or— In the Breakpoints window, right-click a breakpoint and choose Go To Source Code or Go To Disassembly. —or— Click a breakpoint, and then click the Go To Source Code or Go To Disassembly tool. 4.7.3.3. To Display Additional Columns In the toolbar at the top of the Breakpoints window, click the Columns tool, and then select the name of the column you want to display. 4.7.3.4. To Export all Breakpoints that Match the Current Search Criteria In the Breakpoints window toolbar, click the Export all breakpoints matching current search criteria icon. 1. The Save As dialog box appears. 2. In the Save As dialog box, type a name in the File name box. 3. This is the name of the XML file that will contain the exported breakpoints. Note the folder path shown at the top of the dialog box. To save the XML file to a different location, change the folder path shown in that box, or click Browse Folders to browse for a new location. 4. Click Save. 4.7.3.5. To Export Selected Breakpoints 1. In the Breakpoints window, select the breakpoints you want to export. To select multiple breakpoints, hold down the Ctrl key and click additional breakpoints. 2. Right-click in the breakpoints list, and choose Export selected. 3. The Save As dialog box appears. 4. In the Save As dialog box, type a name in the File name box. This is the name of the XML file that will contain the exported breakpoints. The folder path is shown at the top of the dialog box. To save the XML file to a different location, change the folder path shown in that box, or click Browse Folders to browse for a new location. 5. Click Save. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 84 4.7.3.6. To Import Breakpoints 1. In the Breakpoints window toolbar, click the Import breakpoints from a file icon. 2. The Open dialog box appears. 3. In the Open dialog box, browse to the directory where your file is located, and then type the file name or select the file from the file list. 4. Click OK. 4.7.3.7. To View Breakpoints that Match a Specified String In the Search box, perform one of the following actions: 1. Type your search string in the Search box and press ENTER. —or— 2. Click the Search drop-down list and select a string from the list of previous search strings. To limit the search to a specified column, click the In Column drop-down list and then click the name of the column that you want to search in. 4.7.3.8. To View all Breakpoints after a Search In the Search box, select and delete the search string and then press ENTER. 4.7.3.9. Breakpoint Labels In Atmel Studio, you can use labels to help keep track of your breakpoints. A label is a name that you can attach to a breakpoint or a group of breakpoints. You can create a name for a label or you can choose from among a list of existing labels. You can attach multiple labels to each breakpoint. Labels are useful when you want to mark a group of breakpoints that are related in some way. After you have labeled the breakpoints, you can use the search function in the Breakpoints window to find all breakpoints that have a specified label. The search function searches all columns of information that are visible in the Breakpoints window. To make your labels easy to search for, avoid using label names that might conflict with strings that appear in another column. For example, if you have a source file that is named "Program.c", "Program.c" will appear in the name of any breakpoint set in that file. If you use "Prog" as a label name, all breakpoints set in Program.c will appear when you search for breakpoints labeled "Prog". 4.7.3.10. To Label Breakpoints 1. In the Breakpoints window, select one or more breakpoints. 2. To select multiple breakpoints, use the Ctrl key when selecting breakpoints. 3. Right-click the selected breakpoints, and then click Edit labels. 4. The Edit breakpoint labels dialog box appears. 5. Select one or more labels in the Choose among existing labels box. —or— Type a new label name in the Type a new label box, and then click Add. 4.7.3.11. To Search for Breakpoints that have a Specified Label 1. In the Breakpoints window toolbar, click the In Column box and select Labels from the drop-down list. 2. In the Search box, type the name of the label you want to search for and press Enter. 4.7.3.12. To Remove Labels from Breakpoints 1. In the Breakpoints window, select one or more breakpoints. Press Ctrl left-click to select multiple breakpoints. 2. Right-click the selected breakpoints, and then click Edit labels. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 85 3. The Edit breakpoint labels dialog box appears. 4. In the Choose among existing labels box, clear the checkboxes for labels that you want to remove from the selected breakpoints. 4.7.3.13. To Sort the Breakpoint List by Label 1. In the Breakpoints window, right-click the breakpoint list. 2. Point to Sort by and then click Label. (Optional) To change the sort order, right-click the breakpoint list again, point to Sort by, and then click Sort Ascending or Sort Descending. 4.8. Data Breakpoints Data breakpoints allow you to break execution when the value stored at a specified memory location is accessed (read/write). In general, Data Breakpoint hardware module listens on the data address and data value lines between the CPU and the data cache and can halt the CPU, if the address and/or value meets a stored compare value. Unlike program breakpoints, data breakpoints halt on the next instruction after the load/store instruction that caused the breakpoint has completed. 4.8.1. Adding Data Breakpoint Adding Data Breakpoint using code editor context menu You can add Data breakpoint from code editor. Select the variable in code editor and select Breakpoint → Add Databreakpoint from context menu. This adds data breakpoint for a given variable address. Default access mode is write and default mask is none. You can invoke the same command using short cut key Ctrl + Shift + R . Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 86 Figure 4-6. Adding Data Breakpoint from the Context Menu Adding Data Breakpoint from Debug menu You can add new Data breakpoint from Debug → New Breakpoint → New Data Breakpoint. This opens the Data Breakpoint Configuration window. Adding Data Breakpoint from Data Breakpoints tool window You can add new Data breakpoint using the New button in Data Breakpoints tool window. This opens the Data Breakpoint Configuration window. Note:  You can add or modify Data breakpoint only in debug mode. 4.8.2. Data Breakpoints Window 4.8.2.1. Data Breakpoints Tool Window The Data Breakpoint window provides the options to set data breakpoint and lists the added data breakpoints. Enable this window by choosing Debug → Windows → Data Breakpoints. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 87 Figure 4-7. Data Breakpoint Window Data Breakpoints toolbar has following elements: • - provides the data breakpoint configuration window to add a new data breakpoint. • - provides the data breakpoint configuration window to edit the selected data breakpoint. • - removes the selected data breakpoint. You can invoke the same command using the Delete key. • - removes the all data breakpoints. • - enable or disable all the data breakpoints. Data Breakpoints window displays several columns related to breakpoint configuration. Some of the columns are dynamically hidden based on the breakpoints configuration. E.g.: if none of the breakpoints has Mask configured, then Mask related columns are not displayed. Name column has three parts: • Check box - Use Check box to enable or disable breakpoint. • Icon - Glyph to represent the current state of the breakpoint. The following table describes these glyphs. If you rest the mouse on a breakpoint glyph, a breakpoint tip appears with more information. This information is especially useful for error and warning breakpoints. • Text - Displays the configured location expression for breakpoint. Table 4-2. Breakpoint Icons Icon Description Normal breakpoint. The solid glyph indicates that the breakpoint is enabled. The hollow glyph indicates that it is disabled. Advanced breakpoint. Active/disabled. The + sign indicates that the breakpoint has hit count attached to it. Tracepoint. Active/disabled. Hitting this point performs a specified action but doesn't break program execution. Advanced tracepoint. Active/disabled. The + sign indicates that the tracepoint has hit count attached to it. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 88 Icon Description Breakpoint or tracepoint error. The X indicates that the breakpoint or tracepoint couldn't be set because of an error condition. Check Message column for more details on error message. Breakpoint or tracepoint is set but with warning. Check Message column for more details on warning message. 4.8.2.2. Data Breakpoint Configuration Window for Mega This window provides configuration options related to data breakpoint for ATmega devices. Address mask is optional. Location You can enter a specific address in RAM (e.g.: 0x8004) directly or an expression that evaluates to an address in RAM (e.g.: &x). Make sure the expression you enter represents the address of the data to monitor. Note:  Data breakpoints on local variables can result in false hits due to reuse of stack memory. Suggestion to declare it as static for debugging purpose. Access Mode You can configure the breakpoint to break on specific Access Mode. Three types of access modes are supported. • Read - Program breaks on read at specified location. • Write (Default) - Program breaks on write at specified location. • Read/Write - Program breaks on read or write at specified location. Address Mask Address Mask on Mega Data Breakpoints is optional. Use address mask to break on more than one address or a range of address on particular access. Mask Mask value to mask the Location address to define more than one address or range of address. Bits with value 1 in the mask are significant bits and 0 are don't care bits. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 89 In general for a given address A and mask M, an address B successfully matches when: (A) & (M) == (B) & (M), where A is resolved address for the expression entered in Location, M is mask value entered in Mask and B is any address in RAM. Masked Address This is a read only field which shows the range of matching addresses on which program can break. The masked address is shown in the binary format for simplicity. 'X' represents don't care bits, remaining bits are expected to match. E.g. 0b000000010XX000XX means it can break as per access mode, at addresses which has all bits as per this string except X bits. In this case 0th, 1st, 5th, and 6th bit (lsb) can be anything since these bits are don't care (X). Note:  ATmega devices don't support Data Masks. 4.8.2.3. Data Breakpoint Configuration Window for XMEGA This window provides configuration options related to data breakpoint for XMEGA devices. Location You can enter a specific address in RAM (e.g.: 0x8004) directly or an expression that evaluates to an address in RAM (e.g.: &x). Make sure the expression you enter represents the address of the data to monitor. Note:  Data breakpoints on local variables can result in false hits due to reuse of stack memory. Suggestion to declare it as static for debugging purpose. Access Mode You can configure the breakpoint to break on specific Access Mode. Three types of access modes are supported. • Read - Program breaks on read at specified location. • Write (Default) - Program breaks on write at specified location. • Read/Write - Program breaks on read or write at specified location. Data Match Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 90 Use the Data Match option to configure Data Breakpoint to compare the data at specified location based on one of the following conditions: • Location content is equal to the value • Location content is greater than the value • Location content is less than or equal to the value • Location content is within the range • Location content is outside the range • Bits of the location is equal to the value Note:  Bit Mask: It is an 8-bit value where bits with '1' are significant and the bits with '0' are don't care. In general for a given value V and bit mask M, the break event is triggered when the value in the location field VL satisfies the condition (V) & (M) == (VL) & (M) For example, using Value = 0xA0 and Bit Mask = 0xF0 will trigger a break event when the location field has any of the values between0xA0 to 0xAF. Note:  Condition Value field has to be of 1 byte. 4.8.2.4. Data Breakpoint Configuration Window for UC3 This window provides configuration options related to data breakpoint for UC3 devices. Location You can enter a specific address in RAM (e.g.: 0x8004) directly or an expression that evaluates to an address in RAM (e.g.: &x). Make sure the expression you enter represents the address of the data to monitor. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 91 Note:  Data breakpoints on local variables can result in false hits due to reuse of stack memory. Suggestion to declare it as static for debugging purpose. Access Mode You can configure the breakpoint to break on specific Access Mode. Three types of access modes are supported. • Read - Program breaks on read at specified location. • Write (Default) - Program breaks on write at specified location. • Read/Write - Program breaks on read or write at specified location. Access Size You can configure the breakpoint to break on specific Access Size. Four types of access size are supported. • Any Access (Default) - Program breaks on any access size at specified location. • Byte Access - Program breaks on Byte access at specified location. • HalfWord Access - Program breaks on HalfWord access at specified location. • Word Access - Program breaks on Word access at specified location. Example for setting access size Configuration: Code: 1: int word = 0; 2: short *halfWord = (short*)&word; 3: Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 92 4: int main(void) 5: { 6: word = 0xAABBCCFF; 7: *halfWord = 0xDDEE; 8: } For the above configuration and code, program breaks at line eight after halfWord access. Data Match Use the Data Match option to configure Data Breakpoint to compare the data at specified location with a 32-bit value. Break event is triggered on a successful match. Value 32-bit (4-byte) value to compare with data at Location address. The value can be decimal or hexadecimal (e.g.: 100 or 0x64). Based on Access Size, respective bytes are used for data comparison. For example, if you select "HalfWord Access" as Access Size and enter 0xAABBCCDD as Value, then only the last two bytes (0xCCDD) are used for data comparison. You could further refine the Value by specifying Mask. Mask (Byte) Each check box controls the significance of respective byte in the Value field. Select appropriate check box to mask specific byte in the Value field. The number of check boxes displayed is decided based on Access Size. Four check boxes (one per byte) are displayed for "Any" and "Word Access", two check boxes for "HalfWord Access" and one check box for "Byte Access". Match Value A read only field, which displays masked value based on Access Size, Value, and Mask (Byte) field. Masked byte is represented as 'XX', which means that byte is insignificant in data comparison. 4.8.2.5. Data Breakpoint Configuration Window for SAM Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 93 Provides the configuration options related to data breakpoint for SAM devices. Address mask and Data match are optional. Location You can enter a specific address (e.g.: 0x8004) directly or an expression that evaluates to an address (e.g.: &x). Make sure the expression you enter represents the address of the data to monitor. Note:  Data breakpoints on local variables can result in false hits due to reuse of stack memory. Suggestion to declare it as static for debugging purpose. Access Mode You can configure the breakpoint to break on a specific Access Mode. Three types of access modes are supported. • Read - Program breaks on read at specified location. • Write (Default) - Program breaks on write at specified location. • Read/Write - Program breaks on read or write at specified location. Address Mask Use this setting to define range of addresses to monitor for access. Byte Count You can enter a number of address locations to monitor starting at Location address. The actual range of monitored address can be wider than the expected range. E.g.: if the Location is 0x23FA and the Byte Count is 5, then the actual range of the monitored address is [0x23F8 to 0x23FF]. The way actual range is computed is by calculating the number of least significant bits that has to be masked in the Location address (0x23FA) in order to cover the expected range [0x23FA to 0x23FA + 5]. In this case the number of bits to be masked is three. As a result the actual range [0x23F8 to 0x23FF] is wider than the expected range [0x23FA to 0x23FF]. Mask Size This is a read only field, which displays the number of least significant bits masked in the Location address. Mask Size is calculated based on the Byte Count and Location addresses. Address Range This is a read only field, which displays the actual range of address monitored for access. Range is closed interval including both minimum and maximum address. Data Match Use the Data Match option to configure Data Breakpoint to compare the data at specified location with a 32-bit value. Break event is triggered on a successful match. Value 32-bit (4-byte) value to compare with data at the Location address. The value can be decimal or hexadecimal (e.g.: 100 or 0x64). You could further refine the Value by specifying Mask. Mask You can use Mask to extract appropriate bytes from Value to use for data comparison. E.g.: if the Value is 0xAABBCCDD and Mask is HalfWord, then last two bytes (0xCCDD) is extracted from Value and used for data comparison. This means data comparison would succeed for the following matches 0xXXXXCCDD, 0xXXCCDDXX, and 0xCCDDXXXX, where X is a don't care hexadecimal digit (0 to F). Three types of Mask's are supported. • Byte - Last byte extracted from Value is used for data comparison. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 94 • HalfWord - Last two bytes extracted from Value is used for data comparison. • Word (Default) - Whole four bytes from Value is used for data comparison. Match Value This is a read only field which displays match values. Data Match Example Byte matching example • Location = 0x200008D4 • Value = 0x0000CCAA • Mask = Byte The program breaks when Location0x200008D4 has any of the following values: • 0xXXXXXXAA • 0xXXXXAAXX • 0xXXAAXXXX • 0xAAXXXXXX HalfWord matching example • Location = 0x200008D4 • Value = 0x0000CCAA • Mask = HalfWord The program breaks when Location0x200008D4 has any of the following values: • 0xXXXXCCAA • 0xXXCCAAXX • 0xCCAAXXXX Word matching example • Location = 0x200008D4 • Value = 0x0000CCAA • Mask = Word The program breaks when Location 0x200008D4 has the following value: • 0x00000CCAA Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 95 4.8.2.6. Data Breakpoint Configuration Window for Simulator Tool The above configuration window is displayed for any device architecture when a simulator tool is selected. Location You can enter a specific address in RAM (e.g.: 0x8004) directly or an expression that evaluates to an address in RAM (e.g.: &x). Make sure the expression you enter represents the address of the data to monitor. Note:  Data breakpoints on local variables can result in false hits due to reuse of stack memory. Suggestion to declare it as static for debugging purpose. Access Mode You can configure the breakpoint to break on specific Access Mode. Three types of access modes are supported. • Read - Program breaks on read at specified location. • Write (Default) - Program breaks on write at specified location. • Read/Write - Program breaks on read or write at specified location. Byte Count You can enter number of address locations to monitor starting at Location address. Note:  • Simulator supports unlimited number of data breakpoints 4.8.2.7. How to: Specify a Data Breakpoint Hit Count Hit count The number of times the value stored in the specified memory location is accessed (read/write). To specify a hit count To specify or edit the Hit Count property, you must open the Hit Count Dialog Box. In Data Breakpoints window, select a breakpoint row, and then choose Hit Count on the context menu. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 96 Figure 4-8. Hit Count Dialog Box To set or modify a hit count property, use the following controls: • When the breakpoint is hit: This setting determines how the breakpoint should behave when it is hit. You can choose to: • Break always (the default) • Break when the hit count equals a specified value • Break when the hit count equals a multiple of a specified value • Break when the hit count is greater or equal to a specified value • Current hit count: This value shows the number of times the data breakpoint has been hit. A read/ write data for a variable will be converted into multiple instructions, resulting in several memory access. So the data breakpoint hits multiple times for the same variable and the hit count will be updated accordingly. • Reset: This button resets the value shown for the Current hit count to 0. If you choose any option other than the default in When the breakpoint is hit list control, an edit box appears next to it. Edit the value in this edit box to set the hit count value. For example, you might choose break when hit count is equal to and enter 5. This causes execution to stop the 5th time the breakpoint is hit, not on any other hit. 4.8.2.8. When Breakpoint is Hit Dialog Box With this dialog box you can print a message in the output window when a data breakpoint is hit. To open the When Breakpoint Is Hit Dialog Box, go to the Data Breakpoints window, select a breakpoint row, and then choose When Hit on the context menu. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 97 Specify the message • You can use any of the keywords that are described on the When Breakpoint Is Hit dialog box. E.g.: Process Id : $PID. • You can also specify expressions in the message by placing it in the curly braces, such as sum={a +b} Specify the breakpoint behavior To break execution when the breakpoint is hit, clear the Continue Execution check box. When Continue Execution is checked, execution is not halted. In both cases, the message is printed. 4.8.3. General Information on Data Breakpoint • Data Breakpoint can be edited/added only in debug mode • Local variables must always be qualified with the function name. This is also the case if the user wants to add a variable from the function that the program has stopped in. Data breakpoints on local variables can result in false hits due to reuse of stack memory. Tip:  Declare local variables as static and provide the static variable's address in the location field, the address of the static variable is fixed during compilation/linking. • Global variables are initialized with default values during the start up, the valid data breakpoint for global variables will hit in the disassembly or initialization code during the start up Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 98 • There can be several instructions to perform read/write data for a variable, for example 'int' data type can have two individual byte read/write instructions so the data breakpoint hits twice for the same variable • Data breakpoint event can occur when the bus access happens for the specific address • Maximum number of data breakpoint supported: (this may vary based on specific device/family refer data sheet) Architecture Maximum Data breakpoint supported ATmega • Two without Data Mask (OR) • One without Data Mask and one with Data Mask XMEGA • Two without Data Mask (OR) • One without Data Mask and one with Data Mask (OR) • Two with Data Mask UC3 • Two without Data Mask (OR) • One without Data Mask and one with Data Mask (OR) • Two with Data Mask SAM Device dependent refer data sheet Tiny Does not support data breakpoint Most of the devices conforms to the above limit. Note:  ATmega and SAM device uses multiple hardware resources when a data breakpoint with data mask is set. Hence, using data mask can reduce the number of data breakpoint that can be set. 4.8.4. Data Breakpoint Usage 4.8.4.1. Stack Overflow Detection Using Data Breakpoint You can decide on maximum stack size for the your application and calculate the approximate end address for the stack. In the end address set the data breakpoint for address range by applying address mask and access type as Read/Write. Note:  The above method may cause false break when heap memory tries to access the specified stack end address. 4.9. QuickWatch, Watch, Locals, and Autos Windows The Atmel Studio debugger provides several windows, collectively known as variable windows, for displaying variable information while you are debugging. Each variable window has a grid with three columns: Name, Value, and Type. The Name column shows the names of variables added automatically in the Auto and Locals windows. In the Watch window, the Name column is where you can add your own variables or expressions. See how to watch an expression in the Debugger. The Value and Type columns display the value and data type of the corresponding variable or expression result. You can edit the value of a variable in the Value column. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 99 The variable windows, Autos, Locals, and Watch, display the values of certain variables during a debugging session. The QuickWatch dialog box can also display variables. When the debugger is in break mode, you can use the variable windows to edit the values of most variables that appear in these locations. Note:  Editing floating-point values can result in minor inaccuracies because of decimal-to-binary conversion of fractional components. Even a seemingly harmless edit can result in changes to some of the least significant bits in the floating-point variable. When an expression is evaluated in the Watch window, you might see a refresh icon. This indicates an error or out-of-date value. For more information, see How to: Refresh Watch Values. If you want to, you can enter an expression for a value. The debugger will evaluate the expression and replace it with the resulting value. The debugger accepts most valid language expressions in a Watch window. For more information, see Expression Formatting. If you are programming in native code, you might sometimes have to qualify the context of a variable name or an expression that contains a variable name. The context means the function, source file, and module where a variable is located. If you have to do this, you can use the context operator syntax. For more information, see Context Operator (C/C++ Language Expressions). Evaluating some expressions can change the value of a variable or otherwise affect the state of your program. For example, evaluating the following expression changes the value of var1 and var2: var1 = var2++ var1 = var2++ Expressions that change data are said to have side effects, which can produce unexpected results if you are not aware of them. Therefore, make sure you understand the effect of an expression before you execute it. To edit a value in a variable window 1. The debugger must be in break mode. 2. If the variable is an array or an object, a tree control appears next to the name in the Name box. In the Name column, expand the variable, if necessary, to find the element whose value you want to edit. 3. In the row you want to change, double-click the Value column. 4. Type the new value. 5. Press ENTER. To display a variable window On the Debug menu, choose Windows, then choose the name of the variable window you want to display (Autos, Locals, Watch, or Watch1 through Watch4). You cannot access these menu items or display these windows in design mode. To display these menu items, the debugger must be running or in break mode. 4.9.1. Watch Window Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 100 The Watch window and QuickWatch dialog box are places where you can enter variable names and expressions that you want to watch during a debugging session. The QuickWatch dialog box enables you to examine a single variable or expression at a time. It is useful for taking a quick look at one value or a larger data structure. The Watch window can store several variables and expressions that you want to view over the course of the debugging session. Atmel Studio has multiple Watch windows, which are numbered Watch1 through Watch4. A variable name is the simplest expression you can enter. If you are debugging native code, you can use register names as well as variable names. The debugger can accept much more complex expressions than that, however. For example, you could enter the following expression to find the average value of three variables: (var1 + var2 + var3) / 3 The debugger accepts most valid language expressions in a Watch window. For more information, see Expression Formatting. If you are programming in native code, you may sometimes need to qualify the context of a variable name or an expression containing a variable name. The context means the function, source file, and module where a variable is located. If you have to do this, you can use the context operator syntax. Expressions that Affect the State of Your Program Evaluating some expressions can change the value of a variable or otherwise affect the state of your program. For example, evaluating the following expression changes the value of var1: var1 = var2 Expressions that change data are said to have side effects. If you enter an expression that has a side effect into the Watch window, the side effect will occur every time the expression is evaluated by the Watch window. This can produce unexpected results if you are unaware that the expression has side effects. An expression that is known to have side effects is only evaluated one time, when you first enter it. Subsequent evaluations are disabled. You can manually override this behavior by clicking an update icon that appears next to the value. Unexpected side effects are frequently the result of function evaluation. For example, you could enter the following function call into the Watch window: PrintFunc1(var1) Func1(var1) If you call a function from the Watch window or QuickWatch, the function you are calling might change data, creating a side effect. One way to avoid possible unexpected side effects from function evaluation is Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 101 to turn OFF automatic function evaluation in the Options dialog box. This disables automatic evaluation of newer language features, such as properties. However, it is safer. Note:  When you examine an expression in the Watch window, you might see an update icon, which resembles two green arrows, circling in opposite directions within a green circle. This is especially likely if you have turned OFF automatic function evaluation. The update icon indicates an error or out-of-date value. The Atmel Studio debugger automatically expands common data types to show their most important elements. You add expansions for custom data types. For more information, see Displaying Custom Data Types and Visualizers. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Menus and Settings. To evaluate an expression in the Watch window 1. In the Watch window, click an empty row in the Name column. The debugger must be in break mode at this point. Type or paste the variable name or expression you want to watch. —or— Drag a variable to a row in the Watch window. 2. Press ENTER. 3. The result appears in the Value column. If you type the name of an array or object variable, a tree control appears next to the name in the Name column. Expand or collapse the variable in the Name column. 4. The expression remains in the Watch window until you remove it. To evaluate an expression in QuickWatch 1. In the QuickWatch dialog box, type or paste the variable, register, or expression into the Expression text box. 2. Click Reevaluate or press ENTER. 3. The value appears in the Current value box. 4. If you type the name of an array or object variable in the Expression box, a tree control appears next to the name in the Current value box. Expand or collapse the variable in the Name column. To reevaluate a previous expression in QuickWatch 1. In the QuickWatch dialog box, click the down arrow that appears to the right of the Expression box. 2. Choose one of the previous expressions from the drop-down list. 3. Click Reevaluate. 4.9.2. Locals Window Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 102 The Locals window displays variables local to the current context. 4.9.2.1. To Display the Locals Window From the Debug menu, choose Windows and click Locals. (The debugger must be running or in break mode.) 4.9.2.2. To Choose an Alternative Context The default context is the function containing the current execution location. You can choose an alternate context to display in the Locals window: • Use the Debug Location toolbar to select the desired function, thread, or program • Double click on an item in the Call Stack or Threads window To view or modify information in the Locals window, the debugger must be in break mode. If you choose Continue, some information may appear in the Locals window while your program executes, but it will not be current until the next time your program breaks (in other words, it hits a breakpoint or you choose Break All from the Debug menu). 4.9.2.3. To Modify the Value of a Variable in the Locals Window 1. The debugger must be in break mode. 2. In the Locals window, select the value you want to edit by double-clicking on it or by using the TAB key. 3. Type the new value, and press ENTER. Attention:  Editing floating-point values can result in minor inaccuracies because of decimal-to-binary conversion of fractional components. Even a seemingly harmless edit can result in changes to some of the least significant bits in the floating-point variable. Setting Numeric Format You can set the numeric format used in the debugger windows to decimal or hexadecimal. Right click inside the Locals window, and check/uncheck the Hexadecimal display menu item. 4.9.3. Autos Window The Autos window displays variables used in the current statement and the previous statement. The current statement is the statement at the current execution location (the statement that will be executed next if execution continues). The debugger identifies these variables for you automatically, hence the window name. Structure and array variables have a tree control that you can use to display or hide the elements. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 103 To display the Autos window From the Debug menu, choose Windows and click Autos. (The debugger must be running or in break mode.) 4.9.3.1. To Modify the Value of a Variable in the Autos Window 1. The debugger must be in break mode. 2. Display the Autos window, if necessary. 3. In the Value column, double-click the value you want to change. -orSingle-click to select the line, then press the TAB key. 4. Type the new value, and press ENTER. Attention:  Editing floating-point values can result in minor inaccuracies because of decimal-to-binary conversion of fractional components. Even a seemingly harmless edit can result in changes to some of the least significant bits in the floating-point variable. 4.9.3.2. Setting Numeric Format You can set the numeric format used in the debugger windows to decimal or hexadecimal. Right click inside the Autos window, and check/uncheck the Hexadecimal display menu item. 4.9.4. QuickWatch and Watches While debugging you might want to track a value of a variable or an expression. To do so you can right click at the expression under cursor and select Add a Watch or Quickwatch. The QuickWatch dialog box lets you examine and evaluate variables and expressions. Because QuickWatch is a modal dialog box, you have to close it before you can continue to debug. You can also edit the value of a variable in QuickWatch. For more information on how to watch a variable, see Watch Window. Some users might wonder why QuickWatch is useful. Why not add the variable or expression to the Watch window? That is possible, but if you just want to do a quick scratch calculation that involves one or Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 104 more variables, you do not want to clutter the Watch window with such calculations. That is when the QuickWatch dialog box is especially useful. Another feature of the QuickWatch dialog box is that it is resizeable. If you want to examine the members of a large object, it is frequently easier to expand and examine the tree QuickWatch than it is in the Watch, Locals, or Autos window. The QuickWatch dialog box does not allow you to view more than one variable or expression at a time. Also, because QuickWatch is a modal dialog box, you cannot perform operations such as stepping through your code while QuickWatch is open. If you want to do these things, use the Watch window instead. Some expressions have side effects that change the value of a variable or otherwise change the state of your program when they are executed. Evaluating an expression in the QuickWatch dialog box will have the same effect as executed the expression in your code. This can produce unexpected results if you do not consider the side effects of the expression. Note:  In Atmel Studio, you can view a variable's value by placing the cursor over the variable. A small box called a DataTip appears and shows the value. To open the QuickWatch dialog box While in break mode, choose QuickWatch on the Debug menu. To open the QuickWatch dialog box with a variable added While in break mode, right-click a variable name in the source window name and choose QuickWatch. This automatically places the variable into the QuickWatch dialog box. To add a QuickWatch expression to the Watch window In the QuickWatch dialog box, click Add Watch. Whatever expression that was displayed in the QuickWatch dialog box is added to the list of expressions in the Watch window. The expression will normally be added to the Watch1 window. 4.9.5. Expression Formatting The Atmel Studio debugger includes expression evaluators that work when you enter an expression in the QuickWatch and Watches, Memory View, Watch Window, or Immediate window. The expression evaluators are also at work in the Breakpoints window and many other places in the debugger. General Syntax: Val, formatString Format Specifier for values The following tables show the format specifiers recognized by the debugger. Table 4-3. Debug Format Specifiers for Values Specifier Format Expression Value displayed d,i signed decimal integer 0xF000F065, d -268373915 u unsigned decimal integer 0x0065, u 101 b unsigned binary number 0xaa,b2 0b10101010 o unsigned octal integer 0xF065, o 0170145 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 105 Specifier Format Expression Value displayed x,X Hexadecimal integer 61541, x 0x0000F065 1,2,4,8 As a suffix specifying number of bytes for: d, i, u, o, x, X. 00406042,x2 0x0c22 s String 0x2000, s "Hello World" f signed floating point (3./2.), f 1.500000 e signed scientific notation (3./2.), e 1.500000e+000 g signed floating point or signed scientific notation, whichever is shorter (3./2.), g 1.5 c Single character 0x0065, c 101 'e' Size Specifier for Pointers as Arrays If you have a pointer to an object you want to view as an array, you can use an integer to specify the number of array elements: ptr,10 or array,20 Memory type specifier The following memory type specifiers will force the memory reference to a specific memory type. To be used in the memory window in the address field, you should have a pointer to an object you want to view as an array. You can use an integer to specify the number of the array elements: Table 4-4. Debug Memory Type Specifiers Specifier Expression Value displayed flash or program Program memory 0,flash data Data memory 0x2000,data sram SRAM 0x100,sram reg or registers registers 1,reg io, eeprom, fusebytes, lockbytes, signature, usersign, prodsign Memory types with same names 4.10. DataTips DataTips provide a convenient way to view information about variables in your program during debugging. DataTips work only in break mode and only with variables that are in the current scope of execution. In Atmel Studio, DataTips can be pinned to a specific location in a source file, or they can float on top of all Atmel Studio windows. To display a DataTip (in break mode only) 1. In a source window, place the mouse pointer over any variable in the current scope. A DataTip appears. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 106 2. The DataTip disappears when you remove the mouse pointer. To pin the DataTip so that it remains open, click the Pin to source icon, or – Right-click on a variable, then click Pin to source The pinned DataTip closes when the debugging session ends. To unpin a DataTip and make it float • In a pinned DataTip, click the Unpin from source icon The pin icon changes to the unpinned position. The DataTip now floats above any open windows. The floating DataTip closes when the debugging session ends. To repin a floating DataTip • In a DataTip, click the pin icon The pin icon changes to the pinned position. If the DataTip is outside a source window, the pin icon is disabled and the DataTip cannot be pinned. To close a DataTip • Place the mouse pointer over a DataTip, and then click the Close icon To close all DataTips • On the Debug menu, click Clear All DataTips To close all DataTips for a specific file • On the Debug menu, click Clear All DataTips Pinned to File 4.10.1. Expanding and Editing Information You can use DataTips to expand an array, a structure, or an object to view its members. You can also edit the value of a variable from a DataTip. To expand a variable to see its elements: • In a DataTip, put the mouse pointer over the + sign that comes before the variable name The variable expands to show its elements in tree form. When the variable is expanded, you can use the arrow keys on your keyboard to move up and down. Alternatively, you can use the mouse. To edit the value of a variable using a DataTip 1. In a DataTip, click the value. This is disabled for read-only values. 2. Type a new value and press ENTER. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 107 4.10.2. Making a DataTip Transparent If you want to see the code that is behind a DataTip, you can make the DataTip temporarily transparent. This does not apply to DataTips that are pinned or floating. To make a DataTip transparent • In a DataTip, press CTRL The DataTip will remain transparent as long as you hold down the CTRL key. 4.10.3. Visualizing Complex Data Types If a magnifying glass icon appears next to a variable name in a DataTip, one or more Visualizers are available for variables of that data type. You can use a visualizer to display the information in a more meaningful, usually graphical, manner. To view the contents of a variable using a visualizer • Click the magnifying glass icon to select the default visualizer for the data type -orClick the pop-up arrow next to the visualizer to select from a list of appropriate visualizers for the data type. A visualizer displays the information. 4.10.4. Adding Information to a Watch Window If you want to continue to watch a variable, you can add the variable to the Watch window from a DataTip. To add a variable to the Watch window • Right-click a DataTip, and then click Add Watch The variable is added to the Watch window. If you are using an edition that supports multiple Watch windows, the variable is added to Watch 1. 4.10.5. Importing and Exporting DataTips You can export DataTips to an XML file, which can be shared with a colleague or edited using a text editor. To Export DataTips 1. On the Debug menu, click Export DataTips. The Export DataTips dialog box appears. 2. Use standard file techniques to navigate to the location where you want to save the XML file, type a name for the file in the File name box, and then click OK. To Import DataTips 1. On the Debug menu, click Import DataTips. The Import DataTips dialog box appears. 2. Use the dialog box to find the XML file that you want to open and click OK. 4.11. Disassembly View The Disassembly window is only available when debugging. When any supported high level language is used, the source window is automatically displayed and the disassembly window is OFF. Enable it by choosing Debug → Windows → Disassembly or Ctrl Alt D during a debugging session. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 108 The disassembly window shows your program code disassembled. Program execution and AVR instructions can be followed in this view. By right clicking inside the Disassembly window you will be able to set breakpoints, run to the position of the cursor, or go to the source code. You cannot modify the source code from the Disassembly window. In addition to assembly instructions, the Disassembly window can show the following optional information: • Memory address where each instruction is located. For native applications, this is the actual memory address. • Source code from which the assembly code derives • Code bytes byte representations of the actual machine • Symbol names for the memory addresses • Line numbers corresponding to the source code Assembly-language instructions consist of mnemonics, which are abbreviations for instruction names, and symbols that represent variables, registers, and constants. Each machine-language instruction is represented by one assembly-language mnemonic, usually followed by one or more variables, registers, or constants. Because assembly code relies heavily on processor registers or, in the case of managed code, common language runtime registers, you will often find it useful to use the Disassembly window in conjunction with the Registers window, which allows you to examine register contents. Note:  You may see inconsistencies in instructions that work on explicit addresses. This stems from the historic difference between the AVR Assembler and Assembly Language and the GCC Assembler and the assembly used on bigger computer systems. You might therefore encounter disassemblies that look like the one below. 13: asm volatile ("JMP 0x0001778A"); 0000007D 0c.94.c5.bb JMP 0x0000BBC5 Jump > Here the assembly instruction JMP 0x0001778A is being assembled by the GCC Assembler, and disassembled using the built-in disassembler in Atmel Studio, which resolves the jump to 0x0000BBC5, which is exactly half of the address in the initial assembly. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 109 It should be noted that the addresses are always of the same dimension as the line addresses shown in the disassembly, so the code is functionally similar. 4.12. I/O View 4.12.1. About the I/O View The purpose of the I/O View is to provide an overview of the registers of the target device for the current project. It serves as a quick reference during design, and is capable of displaying register values when the project is in debug mode. The view supports both 32- and 8-bit devices equally. The default view of the tool window is a vertically split window with peripheral groups in the top section, and registers in the bottom section. Each peripheral typically has a set of defined settings and value enumerations, which can be displayed by expanding a register in the peripheral view (top section). The register view (bottom section) will display all registers which belong to a selected peripheral group. If no peripheral is selected, the view is empty. Each register can also be expanded to display the pre-defined value groupings which belongs to the register. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 110 4.12.2. Using the I/O View Tool The I/O View is confined to a single tool window in the development environment. There can only be one instance of the I/O view at a time. To open the window, select Debug → Windows → I/O View. When in design mode, the I/O View will be disabled for inputs. It is still possible to change the layout or filters, and to navigate the view, but no values can be set or read. To read or change a value in the registers, AVR Studio must be in debug break mode (execution paused). In this mode, all the controls of the I/O View will be enabled and values can be read and updated in the view. In addition to simply displaying the value of a register, the I/O View will display each bit in the register in a separate column. Bits which are set will have a dark color by default, and cleared bits will have no color (default white). To change a bit, simply click it, and the value will be toggled. 4.12.3. Editing Values and Bits in Break Mode When the project is in debug break mode, any value can be changed by clicking the value field and writing a new value. Some values and bits cannot be modified as they are read-only, and some bits may be write-only. See the documentation for each device for more information. When a bit or value is set, it is immediately read back from the device, ensuring that the I/O View only displays actual values from the device. If a new value is set, but the I/O view does not update as expected, the register might be writeonly or simply not accessible. When a register has changed since last time it was displayed, it will indicate so with a red colored value and bits in the display. If a bit has been set since last time, it will be solid red. If it has been cleared it will simply have a red border. This feature can be toggled on or off in the toolbar. 4.13. Processor View Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 111 Debug → Processor View. The processor view offers a simulated or direct view of the current target device MPU or MCU. On the picture above you can see a partial list of the simulated device's ATxmega128U1 registers. The program counter shows the address of the instruction being executed, the stack pointer shows the application's current stack pointer value. The X,Y, and Z registers are temporary pointers that can be used in indirect passing or retrieving arguments or objects to and from functions. Cycle counter counts the cycles elapsed from the simulation’s start. Status register or SREG shows the currently set flags. Further on you will be able to toggle a setting for displaying the flag names. The stop watch field allows you to make rudimentary profiling of your application. It is influenced by the frequency set in the Frequency field, which defines target MCU/MPU frequency, in case when the prototyping board is connected. Each register can be displayed in hexadecimal, decimal, octal, and binary (flag) format by right-clicking and choosing Display in binary, etc., or Display in.... Each field can also be modified, as shown in the below image. If a field is a status or flags register, composed of a number of the one-bit flags, you can toggle individual flags by clicking on them - . The processor view is only active in the debug mode. 4.14. Register View Debug → Windows → Register View or Ctrl Alt G. The register view offers a simple way to see the data and system registers of your target or simulated device. You cannot modify the registers' contents from the Register view. 4.15. Memory View Debug → Windows → Memory view, or Ctrl Alt M n where n is the memory's number. The memory view gives you an outline of the memory. It is possible to select among the attached memories to see all the Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 112 segments by switching between them in a Segment drop-down menu on top of the memory view. You can also specify the starting address for the memory view window in the Address form field on top of the memory view. In order to specify the address you can use either a normal hexadecimal entry or an expression. See Expression Formatting. The Columns drop-down menu allows you to specify how many byte-aligned memory columns you wish to see at one time, most often this should be left at Auto setting, but if you have to manually check a fixed-length type values and you know how many words or bytes those values occupy, you could align the memory view so that each row will correspond to a desired number of values. 4.16. Call Stack Window Note:  Call Stack Window is currently only supported for 32-bit devices. Call stack shows the hierarchical information of callers of the current method. By default, the Call Stack window displays the name of each function. To display Call Stack, Click the menu, Debug → Windows → Call Stack. Along with function name, optional information such as module name, line number, etc. may also be displayed. The display of this optional information can be turned ON or OFF. To switch ON/OFF the optional information displayed, Right-click the Call Stack window and select or deselect Show Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 113 Stack frame of the current execution pointer is indicated by an yellow arrow. By default, this is the frame whose information appears in the source, Disassembly, Locals, Watch, and Auto windows. The stack frame context can also be changed to be another frame displayed in the Call Stack window. Warning:  Call Stack may not show all the call frames with Optimization levels -O1 and higher. To switch to another stack frame 1. In the Call Stack window, right-click the frame whose code and data you want to view. 2. Select Switch to Frame. A green arrow with a curly tail indicates the changed stack context. The execution pointer remains in the original frame, which is still marked with the yellow arrow. If you select Step or Continue from the Debug menu, the execution will be continued from the yellow arrow, not the frame you selected. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 114 To view the source/disassembly code for a function on the call stack 1. In the Call Stack window, right-click the function whose source code you want to see and select Go To Source Code. 2. In the Call Stack window, right-click the function whose disassembly code you want to see and select Go To Disassembly. To set a breakpoint on the exit point of a function call In the Call Stack window, right-click the stack frame to which you would like to add the breakpoint. Select "BreakPoint → Insert Breakpoint" to add the breakpoint. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 115 4.17. Object File Formats While Atmel Studio uses ELF/DWARF as the preferred object file-/debug info-format, You may debug other formats. Several object file formats from various compiler vendors are supported. You can open and debug these files, but you may not be able to edit the code from within Atmel Studio. Using your own editor to edit code and Atmel Studio to debug (use the reload button), you will still have a powerful code/ debug environment. All external debug sessions require you to load an object file supported by Atmel Studio. An object file for debugging usually contains symbolic information which is not included in a release file. The debug information enables Atmel Studio to give extended possibilities when debugging, e.g. Source file stepping and breakpoints set in high level language like C. Precompiled object files can be opened by using the menu command Open file → Open Object File for Debugging. See section Debug Object File in Atmel Studio for more info. Table 4-5. Object File Formats Supported by Atmel Studio Object file format Extension Description UBROF .d90 UBROF is an IAR proprietary format. The debug output file contains a complete set of debug information and symbols to support all type of watches. UBROF8 and earlier versions are supported. This is the default output format of IAR EW 2.29 and earlier versions. See below how to force IAR EW 3.10 and later versions to generate UBROF8. ELF/DWARF .elf ELF/DWARF debug information is an open standard. The debug format supports a complete set of debug information and symbols to support all types of watches. The version of the format read by Atmel Studio is DWARF2. AVR-GCC versions configured for DWARF2 output can generate this format. AVRCOFF .cof COFF is an open standard intended for 3rd party vendors creating extensions or tools supported by the Atmel Studio. AVR Assembler format .obj The AVR assembler output file format contains source file info for source stepping. It is an Atmel internal format only. The .map file are automatically parsed to get some watch information. Before debugging, make sure you have set up your external compiler/assembler to generate an object file with debug information in one of the formats above. 3 rd party compiler vendors should output the ELF/DWARF object file format to ensure support in Atmel Studio. Optionally you could provide an extension to have both debugging and compile support. See Contact Information for more information. Tip:  How to generate AVR-compatible ELF file in IARW32: In the Project options → Output format dialog choose elf/dwarf, and in the Project options → Format variant select ARM-compatible "-yes". Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 116 Tip:  How to force IAR EW 3.10 and later versions to generate UBROF8: By default IAR EW 3.10 and later versions output UBROF9. Currently, Atmel Studio cannot read this format. To force the debug format to UBROF8 open the project options dialog and change the Output format setting to ubrof 8 (forced). Note that the default file name extension is changed from '.d90' to '.dbg' when selecting this option. To keep the '.d90' extension, click the Override default check button and change the extension. 4.18. Trace In Atmel Studio, trace is provided on a plug-in basis. This means that different plugins separate from the core of Atmel Studio will be the provider of the different graphics view to visualize trace. In the realm of trace, there are some terminology that describe the different trace sources that a device and tool combination supports. These high level source names are mapped to different architecture specific trace sources. The following sections will describe some of the high level trace sources that might be available, and how it is mapped to the target architecture. Only a high level description of the different sources will be given, as the device specific details are available in the respective datasheet. Note:  The architecture for discovering trace capabilities in Atmel Studio is based on what the chip itself reports. This means that a debug session needs to be running so that the capabilities can be probed. This means that when activating a trace source, Atmel Studio might fail if the device does not support the source that was asked for during launch. 4.18.1. Application Output Application output is a common name for a technique that provides what is known as a stimuli port. This implies some mean for the application running on the device to output data to a debugger that is connected. 4.18.1.1. ITM ITM is an optional part of the debug system on ARM cores. The module provides a set of registers that an application can write data to, that will be streamed out to the debugger. 4.18.1.2. IDR Events When the application program writes a byte of data to the OCDR register of an AVR device while being debugged, the debugger reads this value out and displays it as IDR events in the output window as shown in the figure below. The OCDR register is polled at a given interval, so writing to it at a higher frequency than the one specified for the debugger will not yield reliable results. The datasheet of the device will explain how to check that a given value has been read. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 117 Figure 4-9. IDR Events Note that the Output window does not have the “IDR Messages” drop down if no IDR events have been sent from the debugger. 4.18.2. Program Counter Sampling This trace source involves some sort of sample system that reads out the program counter of the device periodically. This can then be used to graph where execution time is being spent, based on some statistical average. 4.18.2.1. ARM Implementations There are two ways of sampling the program counter on an ARM Cortex core. The first is using an optional module in the debug system that emits the program counter to the debugger without any impact on the core itself. The program counter is emitted on the SWO pin. As not all Cortex implementation can emit the program counter, Atmel Studio also supports doing a periodical readout of the program counter while to core is running. This is possible as most Cortex devices supports readout of memory while the core is running, with a small impact on the running application as the debug system needs to access the memory bus. 4.18.2.2. AVR 32-bit Implementation Reading the program counter on the AVR 32-bit core is possible in the same way as mentioned in ARM Implementations, as the core supports live readout of memory while the core is running. 4.18.3. Variable Watching Watching variables are usually covered by data breakpoints, see Data Breakpoints. However, on some systems it is also possible to make a data breakpoint emit the information to the debugger without halting the core, meaning that it is possible to watch variables in applications that for instance has some sort of external timing requirement that a data breakpoint would cause to fail. 4.18.3.1. ARM Implementations Data breakpoints on a Cortex core can be changed to emit a trace packet if the debug system implements the needed modules. This means that it is possible to get information about reads or writes to a specific memory location without an interference with the execution on the core. As a fallback to this, it is also possible to read a memory location at a given interval while the core is executing. This will not be any specific event data, but means that if the core supports live memory readout, it is possible to sample some parts of the memory. This has a minor impact on the execution, as the debug system needs to have access to the memory bus. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 118 4.18.3.2. AVR 32-bit Implementation The AVR 32-bit core also supports live readout of memory locations. This means that Atmel Studio can poll a memory location while to core is executing, giving a statistical view of how the variable is changing over time. 4.19. Trace View The Trace View allows you to record the program counter trace when a target is running. The program counter branches are mapped with the respective source line information. It also contains coverage and statistics for the source lines executed. To open the Trace View, go to Debug → Windows → Trace View. To use the functionality of the Trace View, a project has to be opened in Atmel Studio. Figure 4-10. Opening Trace View From the Menu 4.19.1. Trace View Options The Trace View toolbar has the following elements: • - Starts the program trace • - Stops the program trace • - Clears the program trace • - Toggles the highlighting of source code • - Configures the device to record the program trace • - Finds the exception record in the Trace Stack view • - Exports coverage statistics into an xml/xslt report 4.19.1.1. Starting the Program Trace The Program Trace can be started by clicking the play button in the Trace View Window. The start button is enabled during debug. Trace can be started and stopped any number of times in a debug session. Starting a new trace session clears all trace information of the previous trace session. Note:  A region of SRAM has to be allocated to let the device record the trace. Refer to Trace View Settings for more information. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 119 Figure 4-11. Trace View Window 4.19.1.2. Stop Trace Trace can be stopped in run or debug mode. The trace session will be ended automatically without user intervention when the debugging session ends. 4.19.1.3. Clear Trace The clear button clears the trace in the Trace View Window. New trace information will be logged in the same tool window with continuous sequence number. Clear can be done any number of times within a trace session. Once cleared the trace data cannot be recovered. 4.19.1.4. Highlight Source Code Highlight is a toggle button which toggles between highlighting and non-highlighting of the source code. The source code that are covered are highlighted with a green color and remaining source lines with a red color representing the uncovered source code for the current execution. Figure 4-12. Code Highlight Note:  Only the compilable lines are taken into consideration. For example, lines with comments and variable declaration are ignored. 4.19.1.5. Trace View Settings The device has to be configured to record the trace information in SRAM. The allocated size for recording the program trace can be configured from this setting. The memory can be allocated in: • Source code, allocating a global array • Linker scripts, reserving an amount of the memory map Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 120 Select the memory size to be allocated for recording the program trace. Copy the snippet of code displayed in configuration window by clicking on the CopyToClipBoard button and paste into your source code. Follow the instructions given in the dialog to enable the tracing capability. Figure 4-13. Trace Settings Window Through Source Code Note:  If both the linker script and the source code is configured for trace, the linker script settings takes the higher precedence over source code settings. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 121 Figure 4-14. Trace Settings Window through Linker Script 4.19.2. Trace View Interpretation The Trace View window contains the following items: • Trace Stack View • Coverage View 4.19.2.1. Trace Stack View Trace Stack View is populated with program trace information while the target is in a running or debugging state. Trace Stack View contains a sequence number, source and destination address, and a repeat count. A new program trace record is shown when a branching instruction happens on the target, for example as a function call or a return from a function. • Sequence Number - Number that keeps track of the order of the record. This number is reset for every trace session. This number will be continued without break when trace is cleared using clear button from the toolbar. • Source - Represents the instruction/source line from which the branch happened. For example, in a function call, Source is the source line from where the function is being called. • Destination - Represents the instruction/source line to which the branching happened. For example, in a function call, Destination is the source code of the starting line of the function. • Repeat Count - Represents the number of times the same source and destination combination occurred consecutively. For example, if there is a delay which is logging the same packets, it will be grouped together and number of times record occurrence is termed as repeat count Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 122 The source and destination contains instruction address, function name, source file name, and line number. If the source line cannot be mapped only the instruction address is given. Double click on the source or destination navigates the cursor in the editor to the appropriate line. Navigation keys Up, Down, Left, Right, and Tab can be used to locate the source/disassembly view for the trace records. The program trace that is shown in the TraceStack view are cut down to the latest 20000 records by default. The threshold value can be changed using the slider. The program trace records are highlighted with a yellow color when the branching instruction was not an expected one. Unexpected branches usually happens due to some exception, and the entry and exit of the exception handler is highlighted with yellow color. The branching inside the exception are not highlighted. Figure 4-15. Exception Record Tip:  The next and previous exception records can be easily navigated to by using the up and down arrow buttons in the trace view window tool bar. There are some exceptional cases where some program traces could be missed. In that case there will be a packet with red color which represents that there are some discontinuation of the program trace information in the sequence. Since the number of missed packets are unknown, the sequence number shown in the Trace Stack view will be continued without any break except adding a red colored packet with a sequence number for it. Note:  The disassembly view is not supported when navigation keys are used, but it is supported when the record is double clicked using mouse. 4.19.2.2. Coverage View The coverage view shows statistics on the source covered as part of the current target execution. All the files and functions are listed in the coverage view with the information of number of lines covered or uncovered against the total number of lines in the source file. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 123 Figure 4-16. Code Coverage Note:  Only the compilable lines are taken into consideration for the statistics. For example, lines with comments and variable declaration are not taken into account. A coverage report can be exported. Click the export icon in the trace view toolbar to invoke the export operation. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 124 5. Programming Dialog 5.1. Introduction The Device Programming window (also known as the programming dialog), gives you the most low-level control of the debugging and programming tools. With it, you can program the device's different memories, fuses, and lockbits, erase memories, and write user signatures. It can also adjust some of the starter kit properties such as voltage and clock generators. Note:  If you are editing a code project in Atmel Studio and want to see the results of a compilation by downloading the code into the device, take a look at the Start without Debugging command. It is a sort of one-click programming alternative to the programming dialog. See section Start without Debugging for more information. The programming dialog is accessible from a button on the standard toolbar or the menu Tools → Device Programming. Figure 5-1. Device Programming Icon Figure 5-2. Opening Device Programming Dialog Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 125 Figure 5-3. Device Programming The programming dialog contains the following options and tabs: Top status bar Tool You can choose which tool you want to use from this drop-down menu. Only tools connected to the machine are listed. Also, if a tool is used in a debug session, it will not be listed. Several tools of the same type can be connected at the same time. In order to identify them, the serial number will be shown below the tool name in the list. When a tool is selected, the name (and serial number) will be shown in the title bar of the Device Programming dialog. Note:  The Simulator will only offer limited support for the programming dialog features. The Simulator has no persistent memory, so you will not be able to make permanent changes to any simulated devices. Device As soon as a tool is selected, the device list will show all devices supported by that tool. There are two ways to select a device: • Select from the list Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 126 Click on the arrow. This will reveal the list of supported devices. Click to select. • Select by typing. In this example, we will select the ATxmega128A3: 2.1. Double-click in the text field to select the text already present. 2.2. Start typing some part of the device's name, in this example 128A. The list updates while you type, showing all devices containing what is typed. 2.3. Press the Arrow Down keyboard button to move the selection into the list. Use the up and down keys to navigate. Press ENTER to make a selection. 2.4. The ATxmega128A3 is now selected. Note:  A red border around the device selector indicates that the text entered is not a valid device name. Continue typing until the device name is complete, or select from the list. Interface When a tool and a device is selected, the interface list will show the available interfaces. Only interfaces available on both the tool and the device will appear in this menu. Select the interface to use to program the AVR. Apply button When tool, device, and interface is selected, press the Apply button to make the selections take effect. This will establish connection to the tool. The list on the left side of the window will be updated with the relevant pages for the selected tool. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 127 If a different tool, device, or interface is selected, the Apply button must be pressed again, to make the new selections take effect. Device ID Press the Read button to read the signature bytes from the device. The device's unique tag will appear in this field, and can be used for tool compatibility checking and to obtain help either from customer support or from the people at AVR Freaks® . Target voltage All tools are capable of measuring the target's operating voltage. Press the refresh button to make a new measurement. A warning message will appear if the measured voltage is outside the operating range for the selected device, and the target voltage box will turn red. 5.2. Interface Settings The programming interfaces have different settings. Some interfaces have no settings at all, some interfaces settings are only available on some tools. This section will describe all settings, but they are not available for all tools and devices. JTAG If you have selected JTAG as the programming interface, clock speed, use external reset and daisy chain setting may be available. This depends on the tool and device. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 128 JTAG Clock JTAG clock is the maximum speed the tool will try to clock the device at. The clock range is different for different tools and devices. If there are restrictions, they will be stated in a message below the clock slider. Use external reset If checked the tool will pull the external reset line low when trying to connect to the device. JTAG Daisy chain settings Specify the JTAG daisy chain settings relevant to the device to program. Target is not part of a daisy chain. Select this option when the target device is not part of a daisy chain. Daisy chain-Manual. Allows you to manually configure the JTAG daisy chain in case you are programming in a system-on-board. • Devices before - specifies the number of devices preceding the target device. • Instruction bits before - specifies the total size of the instruction registers of all devices, preceding the target device. • Devices after - specifies the number of devices following the target device. • Instruction bits after - specifies the total size of the instruction registers of all devices, following the target device. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 129 Daisy chain-Auto. Automatically detects the devices in the JTAG daisy chain. Allows you to select the device in the JTAG daisy chain. Auto-detection is supported only for SAM devices. To accept the changes and configure the tool, press the Set button. PDI The PDI interface has only one setting – the PDI clock speed. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 130 PDI Clock is the maximum speed the tool will try to clock the device at. The clock range is different for different tools and devices. If there are restrictions, they will be stated in a message below the clock slider. To apply the changes and configure the tool, press the Set button. The clock cannot be adjusted on all tools, so an empty Interface settings page will be presented. 5.3. Tool Information Figure 5-4. Tool Info The Tool information page contains a number of useful tool parameters. Tool Name denotes the common name for the connected tool. Debug Host is the debug session's host IP address for the remote debugging case. If the tool is connected to your machine, then the loopback interface IP (127.0.0.1) will show. Debug Port is the port opened specifically for the remote debugging access to the debugging tool. The port is automatically assigned when Atmel Studio starts, and is usually 4711. Serial number - tool serial number. Connection - Microsoft Driver Framework Method's name used to connect the Tool on your PC. xxx version - Firmware, hardware and FPGA file versions are listed here. Using the link on the bottom of the dialog you can access extensive information on your tool online. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 131 5.4. Board Settings/Tool Settings Some tools (Power Debugger, STK500, STK600, QT600) have on-board voltage and clock generators. They can be controlled from the Board settings/Tool settings page. 5.4.1. Power Debugger The Power Debugger has a single voltage source and two channels of voltage/current measurement. Figure 5-5. Power Debugger Tool Settings The voltage output (VOUT) is adjusted by the slider, or by typing a voltage in the Generated text boxes below the slider. After adjusting the set-point, press the Write button to apply the changes. The value is then sent to the tool, and the measured value is read back. Press the Read button to read both the set-point (Generated) and the Measured values from the Power Debugger. Note:  There may be slight differences between the Generated and the Measured voltages. The output voltage range is 1.6V to 5.5V. The Channel A and Channel B measurements are snapshots of analog readings taken by the Power Debugger. The tool is optimized for real-time monitoring of voltage and current, and this snapshot is thus approximate. It does not perform calibration compensation, and readings are locked in the highest-current range. For best results, use the Atmel Data Visualizer. Note:  When no load is connected to a measurement channel, non-zero measurements can be expected. 5.4.2. STK600 The STK600 has three voltage sources and one clock generator. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 132 Figure 5-6. STK600 Board Settings The set-points of the three voltage sources (VTG, ARef0, and ARef1) are adjusted by the means of three sliders. It is also possible to type a voltage in the Generated text boxes below the sliders. When you drag the sliders, the text boxes will update. And when you type a value in the text box, the slider will move. After adjusting the set-points, press the Write button to apply the changes. The values are sent to the tool, and measure values are read back. Measurements are shown in the Measured row, and shown as blue columns as part of the slider controls. The measured values cannot be edited. Press the Read button to read both the set-point (Generated) and the Measured values from the STK600. Note:  What is the difference between the Generated and the Measured voltages? The generated voltage is the setting on the adjustable power supply, the measured voltage is the readout from the builtin volt meter. If the measured value is different from the generated voltage, this may indicate that the target circuitry draws a lot of current from the generator. Note:  If the VTARGET jumper on STK600 is not mounted, the measured voltage will be 0, unless an external voltage is applied to the VTARGET net. The Clock generator is also adjusted by dragging the slider or typing into the text box below. Press the Write button to apply the new value. 5.4.3. QT600 The QT600 has only one setting, the VTarget voltage. This voltage can be set to five fixed voltages: 0, 1.8, 2.7, 3.3, and 5V. Press the Write button to apply the changes. The actual VTarget value is read back automatically when pressing the Write button. It is also possible to read it back manually using the Read button. 5.4.4. STK500 STK500 has settings similar to the STK600, but only one Aref voltage and combined generated/measured values. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 133 5.5. Card Stack The STK600 uses a combination of routing and socket cards to let all AVR devices to be mounted. Given the device, only certain combinations of routing and socket cards are valid. The Card stack page has information about this. Figure 5-7. Card Stack The card stack page tells which cards are mounted on the STK600 and if they support the selected device. If they do match, a list of devices supported by that card combination is listed. If the mounted cards do not match, a list of suggested card combinations will be listed. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 134 5.6. Device Information Figure 5-8. Device Information The device information page contains basic information on the selected device. When the page is accessed, it will try to read the JTAG (or device) signature from the connected device. In the upper part of the dialog you can see the device name, its signature, the JTAG part identification number, and the device revision (extracted from the JTAG signature). In the lower part of the dialog you see the device variants and characteristics of each variant. Acceptable voltage range, followed by maximum operating clock speed, and the sizes of on-chip memories. The two links on the bottom of the dialog offer you to see a slightly more detailed device information in the purchase catalog online, or to download a complete datasheet of the target device. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 135 5.7. Oscillator Calibration Figure 5-9. Oscillator Calibration Oscillator Calibration Byte(s) for ATtiny and ATmega parts From the Advanced tab you can read the Oscillator Calibration Byte(s) for ATtiny and ATmega parts. The oscillator calibration byte is a value that can be written to the OSCCAL register found in selected devices, in order to tune the internal RC Oscillator to run as close to a chosen clock frequency as possible. Program The oscillator calibration byte is stored in the device during manufacturing and can not be erased or altered by the user. It is automatically transferred to the OSCCAL register during device start-up, or set during program initialization, depending on the device. On devices where the application sets it during program initialization, it must be transferred to FLASH or EEPROM first, using the programming dialog or the command line tools. Reading and Writing the Oscillator Calibration Byte for ATtiny and ATmega parts The calibration value is read from the storage in the device and shown in the Value text box by pressing the Read button. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 136 The calibration byte is programmed into FLASH or EEPROM memory by pressing the Write button. Memory type and address must be specified first. 5.8. Memories Figure 5-10. Memories Programming From the Memories tab you can access all the programmable memories on the target device. Memory is erased by first selecting the memory type and then clicking on the Erase button. Selecting Erase Chip will erase the entire contents of the device, including FLASH, EEPROM (unless the EESAVE fuse is programmed), and lock-bits, but not Userpages if the device contains this. Program To program a file into the device's Flash memory, write the full path and file name in the combo box in the flash section. Or, select the file by pressing the browse button (...). Now, press the Program button to program the file into the memory. If the Erase device before programming check box is checked, a chip erase operation will be performed before the programming operation starts. If the Verify device after programming check box is checked, the content will be verified after the programming operation is done. Some devices can also be programmed through a flashloader. This is mainly an advanced technique, but it will usually give a significant speedup in the programming speed. For devices where this is supported, a Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 137 checkbox will be shown named Program flash from RAM. If this box is checked, the base address of the location of the flashloader needs to be given. Verify To verify the flash content of the device, first select the file you want to verify against. Then press the Verify button. Read The contents of the Flash memory can be read out in Intel® hexadecimal file format, using the Read button. Pressing the Read button will bring up a dialog offering you to specify where the file will be saved. EEPROM The device's EEPROM memory can be programmed in a similar way. User Signatures The XMEGA device's User Signature memory can be programmed the same way. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 138 5.9. Fuse Programming Figure 5-11. Fuse Programming The Fuses page presents the fuses of the selected device. Press the Read button to read the current value of the fuses, and the Program button to write the current fuse setting to the device. Fuse settings are presented as check boxes or as drop down lists. Detailed information on which fuses are available in the different programming modes and their functions can be found in the device datasheet. Note that the selected fuse setting is not affected by erasing the device with a chip-erase cycle (i.e. pressing the Chip Erase button on the Memories page). Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 139 Fuse values can also be written directly into the fuse registers in the lower pane as hexadecimal values. Auto read If this check box is checked, the fuse settings will be read from the device each time you enter the fuse page. Verify after programming When this check box is checked, the settings will be verified after a programming operation is completed. The appearance of the fuse glyph describes whether the fuse information is up to date compared to the state of the device. the fuse value is up to date. i.e the same state as in the device. the fuse has been modified by the user and it is not yet programmed into the device. the fuse state is unknown, it has not been read from the device, nor modified by the user. 5.10. Lock Bits The lock bit page is similar to the fuse page. For usage, see section Fuse Programming. 5.11. Production Signatures The production signature page is only visible for AVR XMEGA devices and shows factory programmed data in the production signature row. It contains calibration data for functions such as oscillators and analog modules. The production signature row can not be written or erased. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 140 Figure 5-12. Production Signatures 5.12. Production Files The ELF production file format can hold the contents of both Flash, EEPROM, and User Signatures (XMEGA devices only) as well as the Fuse- Lockbit configuration in one single file. The format is based on the Executable and Linkable Format (ELF). The production file format is currently supported for tinyAVR, megaAVR, and XMEGA. See Creating ELF Files with Other Memory Types for description on how to configure the project in order to generate such files. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 141 Figure 5-13. Production Files Programming Program device from ELF production file: To program your device from an ELF file, you must first select a source file by typing its full path into the combo box, or by pressing the browse button . Depending on the contents of your file, check boxes for the different memory segments will be activated. It is possible to select one or several of the memory segments that the ELF production file contains. You can then program and verify the device with the content of these segments in one single operation. Select which memory segments you want to program ticking off the corresponding check boxes. Select the Erase memory before programming check box, if you want an erase operation to be performed before the programming operation. Note:  The erase memory operation will depend on the device selection. For tinyAVR and megaAVR, both Flash, EEPROM, and lockbits will be erased (chip erase) independent of which memories are selected, while for XMEGA only the selected memories will be erased. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 142 Select the Verify device after programming check box, if you want the contents to be verified after the programming operation is done. Select the Verify Device ID check box, if you want to verify the device id stored in the file (signature bytes) with the connected device. Now, press the Program button to program the file into the memory. You can verify the contents of the device against an ELF file by pressing the Verify button. The verification will only verify the contents of the selected memory segments. Figure 5-14. Production Files Creation Save to ELF production file: Prior to creating the ELF file, specify the input file path for FLASH, EEPROM, and Usersignature on the production file tab. Then configure the Fuse and Lockbits on the corresponding tab and program it. The Fuse and Lockbits, which are programmed in the device will be taken as input while creating ELF file. Back on the production file tab, press the "Save" button" to generate the ELF file. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 143 You must specify which segments are to be present in the production ELF file by ticking the corresponding check boxes. 5.13. Security The security bit allows the entire chip to be locked from external JTAG or other debug access for code security. Once set, the only way to clear the security bit is through the Chip Erase command. Figure 5-15. Security Page To check the state of the security bit, press the Read button on the Security page of the programming dialog. The value should now read Cleared or Set. Set meaning that the security bit is set, and Cleared meaning that it is not set. If the Auto Read check box is ticked off, the Read operation will be performed automatically when the Security page is opened. To set the security bit, simply press the Set button on the Security page of the programming dialog. Now the device is locked for all further JTAG or aWire access except for the Chip Erase command. Locked device When the security bit is set, the device is locked for most external debug access. Attempts to program or read any memories or fuses, will cause an error message to appear. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 144 Figure 5-16. Security Bit Error To unset the security bit, issue the Chip Erase command. This can be done from the Memories page, see Memories. 5.14. Automatic Firmware Upgrade Detection As mentioned in the Firmware Upgrade section, you may encounter a dialog stating that your tool's firmware is out of date when you open the Device Programming dialog. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 145 6. Miscellaneous Windows 6.1. Device Pack Manager The Device Pack Manager is used to manage the devices supported by Atmel Studio. The Device Pack Manager is launched from Tools → Device Pack Manager. Figure 6-1. Device Pack Manager Menu Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 146 Figure 6-2. Device Pack Manager The Device Pack Manager consists of two panes. The left pane shows the list of packs that are installed. The right pane shows the devices that are provided by the pack selected in the left pane. Packs can have any of the following statuses: Up to date Pack is already up to date and latest. Update Available New update is available. Not Installed Pack is not installed, but can be downloaded. Actions Install selected packs Download and install all packs that have been selected using the check-boxes besides the version. Install all updates Download and install all available updates. Browse pack file Install an already downloaded pack file. Uninstall Uninstalls all packs that have been selected using the check-boxes besides the version. Check for Updates Check for new and updated packs. Search The search box can be used to search after a specific pack, or a device in any of the packs. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 147 Reset cache Resetting the cache will re-index all installed packs. This does not uninstall or remove anything. It is in the Advanced menu. Note:  After installing, updating, or removing packs, Atmel Studio has to be restarted before the changes becomes visible. 6.2. User Interface Profile Selection Different user interface profiles targeted for different use is available in Atmel Studio. The user interface profile controls the visibility of menus, window layouts, toolbars, context menus, and other elements of Atmel Studio. The following modes are available: Standard The default profile. Includes the most used windows and menus. Advanced The profile used in previous versions of Atmel Studio. This profile includes advanced debugging and re-factoring tools. Figure 6-3. Profile Selection The profile selection window is shown the first time Atmel Studio is started. Selecting a profile in the list will show a description of the profile. Clicking the Apply button applies the profile to Atmel Studio. The profile can be changed at any time by navigating to Tools → Select Profile, or by clicking the profile name that is displayed in the top right corner of Atmel Studio. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 148 Figure 6-4. Selected Profile When switching profiles, any changes done to the active profile is saved. Going back to the previous profile will restore the changes as well as the profile. Using the Reset option discards any changes saved to the profile and restores it to the default profile. 6.3. Available Tools View 6.3.1. Introduction The Available Tools view (View → Available Atmel Tools) contains a list of all connected tools such as programmers, debuggers and starter kits. The Simulator is always present. Other tools will show up when they are connected to the PC. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 149 6.3.2. Tool Actions The following actions can be selected by right clicking tools in the Available Tools view: Device Programming Opens the Device Programming window with the tool preselected. Self test Some tools are capable of performing a self test. Follow the displayed instructions. Add target Adds a tool to the list of available tools that is not auto-detectable. See Add a Non-detectable Tool for more information. Upgrade Starts the firmware upgrade tool with the selected tool. Show Info Window Shows the Tool Info window. Not all tools supports this feature. See Tool Info Window for more information. 6.3.3. Add a Non-detectable Tool The STK500 does not have a USB connection, and cannot be automatically detected by Atmel Studio. So it must be added to the list of available tools before it can be used by the Device Programming window. To add an STK500, right click inside the Available Tools view, select Add target and select the STK500 as the tool and the COM port your STK500 will be connected to. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 150 Press the Apply button, and the STK500 will be displayed in the list of available tools. Note:  An STK500 that has been added will be visible in the Available Tools view event even if no STK500 is connected to the specified COM port. If you want to remove STK500 from the list, you can right click on it and select Remove from the context menu. 6.3.3.1. Add J-Link over IP In the Add target dialog, it is possible to add a remote Segger J-Link debug probe. Both using a debug probe with built-in ethernet such as the J-Link PRO3 and any other Segger probe by using the J-Link Remote Server software4 . Figure 6-5. Add J-Link over IP To add a debug probe that is connected to a J-Link Remote Server, choose Connect by hostname and enter the IP address or the hostname of the computer running the J-Link Remote Server. If the J-Link 3 See https://www.segger.com/jlink-pro.html 4 See https://www.segger.com/jlink-remoteserver.html Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 151 Remote server is running on a non-standard port5 then the port also needs to be entered. If the J-Link Remote Server is running on the default port, the port can be left empty. To add a debug probe that has built-in ethernet, choose Connect by serial number in the Add target dialog, and enter the serial number of the debug probe. 6.4. Tool Info Window The Tools Info window shows information about connected tools. At the moment, only the Xplained Pro series is supported. 5 The standard port of the J-Link Remote Server is port 19020 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 152 Figure 6-6. The Tool Info Window When a tool is connected, the window will open. It has a short description about the tool, an image of the tool, and a section of links to then user guide, relevant datasheets on the internet, etc. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 153 There is also a table with technical details about the tool, such as firmware version, serial number, etc. 6.4.1. Xplained Pro Kits The Xplained Pro family of boards supports a range of expansion boards. When an Xplained Pro board is connected, the Tool Info window will show a list on the left side of the window, containing the main board, and all connected expansions. Click on the main board and the expansion to see details about the different boards. 6.4.2. Disable the Tools Info Window By deselecting the Show page on connect check box, the window will not automatically open when Atmel Studio is open and you connect the kit. This feature works on a per-tool basis, which means you can select for every tool you have, if they should show the Tool Info window when connected. 6.4.3. Manually Showing the Window If you want to see the Tool Info window again after it has been closed, you can right-click on the tool in the Available Tools view, and select Show Info Window. Figure 6-7. Show Tool Info Window See also Available Tools View. 6.5. Firmware Upgrade 6.5.1. Introduction Atmel Studio will include the latest firmware for all Atmel tools. New firmware may provide support for new devices and bugfixes. 6.5.2. Automatic Upgrade Atmel Studio will automatically upgrade the tool's firmware when needed. A potential firmware upgrade is triggered once you start using a tool. Examples: the first time you launch a debug session or the first time you select the tool in the Device Programming dialog. The tool cannot be used by Atmel Studio if the user chooses not to upgrade. You can also check for firmware upgrades by using the Available Tools view (View → Available Atmel Tools). Right click on a tool and select Upgrade. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 154 For a description on how to do manual upgrade, downgrade and upgrade with a custom firmware image, see Manual Upgrade. 6.5.3. Manual Upgrade Atmel Studio includes a command line utility called atfw.exe which can be used to do manual upgrade of most Atmel tools. atfw.exe is installed in the atbackend subfolder. atfw.exe can be used to: • Perform upgrade from a script • Upgrade using a custom firmware file • Read out firmware version For details on how to upgrade using this utility, execute atfw.exe -h. Note:  If a tool is locked in firmware upgrade mode, and normal reset does not restore normal operation, a forced firmware upgrade should reset the tool to a working state. To do a firmware upgrade on a tool already in upgrade mode, invoke atfw the same way as normal firmware upgrade. Some warnings may be displayed as the tool is unable to switch the tool to upgrade mode, but should proceed with the upgrade. If a tool listing is done, the tool will have a name that is related to the mode it is in. atfw should however be invoked with the tool name as it is presented to the user in normal operation. 6.6. Find and Replace Window You can use the Find and Replace window to search for text strings, expressions, or entity names within the code of your documents. To access this window, from the Edit menu, click Find and Replace, and then select one of the options listed. The Find and Replace window contains a toolbar with two drop-downs, one for find operations and one for replace operations. When you select an operation, the corresponding options for the operation are displayed. You can search and replace in one or more files or an entire solution for text, code, or symbols. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 155 Figure 6-8. Find and Replace Quick Find allows you to search the code of one or more open documents for a string or expression. The selection moves from match to match, allowing you to review each match in its surrounding context. Note:  The matches found are not listed in the Find Results window. You can use any of the following methods to display Quick Find in the Find and Replace window. To display Quick Find 1. On the Edit menu, expand Find and Replace. 2. Choose Quick Find. -orIf the Find and Replace window is already open, on the toolbar, click the triangular View button on the left drop-down and then choose Quick Find. Quick Find can search through a document either forward or backward from the insertion point. The search automatically continues past the end or start of the document into the unsearched portion. A message appears when the entire document has been searched. Find what These controls allow you to specify the string or expression that will be matched. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 156 Reuse one of the last 20 search strings by selecting it from this drop-down list, or type a new text string or expression to find. Table 6-1. Quick Find Option Description [string with wildcards] If you want to use wildcards such as asterisks (*) and question marks (?) in your search string, select the Use check box under Find options and then choose Wildcards. [regular expression] To instruct the search engine to expect regular expressions, select the Use check box under Find options and then choose Regular expressions. Expression Builder This triangular button next to the Find what field becomes available when the Use check box is selected in Find options and Regular Expressions appears in the drop-down list. Click this button to display a list of wildcards or regular expressions, depending upon the Use option selected. Choosing any item from this list adds it into the Find what string. Find Next Click this button to find the next instance of the Find what string within the search scope chosen in Look in. Bookmark All Click this button to display blue bookmarks at the left edge of the code editor to indicate each line where an instance of the Find what string occurs. Look in The option chosen from the Look in drop-down list determines whether Quick Find searches only in currently active files. Look in Select a predefined search scope from this list. Table 6-2. Look in Scopes Option Description Selection This option is available when text is selected in the code editor. Searches only the selected text in the currently active document. The name of this option indicates the location of the insertion point in the code editor. Searches within the current procedure, module, paragraph, or code block. Current Document This option is available when a document is open in an editor. Searches only the active document for the Find what string. Current Window This option is available when a searchable tool window, such as the View in Browser window, has focus. Searches all content displayed in this window for the Find what string. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 157 Option Description All Open Documents Searches all files currently open for editing as if they were one document. When the starting point of the search is reached in the current file, the search automatically moves to the next file and continues until the last open file has been searched for the Find what string. Current Project Searches all files in the current project as if they were one document. When the starting point of the search is reached in one file, the search continues in the next until the last file in the project has been searched. Find options You can expand or collapse the Find options section. The following options can be selected or cleared: Match case Only displays instances of the Find what string that are matched both by content and by case. For example, a search for "MyObject" with Match case selected will return "MyObject" but not "myobject" or "MYOBJECT". Match whole word Only displays instances of the Find what string that are matched in complete words. For example, a search for "MyObject" will return "MyObject" but not "CMyObject" or "MyObjectC". Search up When selected, files are searched from the insertion point to the top of the file. Search hidden text When selected, the search will also include concealed and collapsed text, such as the metadata of a design-time control; a hidden region of an outlined document; or a collapsed class or method. Use Indicates how to interpret special characters entered in the Find what or Replace with text boxes. The options include: Table 6-3. Search with Special Characters Option Description Wildcards Special characters such as asterisks (*) and question marks (?) represent one or more characters. For a list, see Wildcards (Visual Studio). Regular Expressions Special notations define patterns of text to match. For a list, see Regular Expressions (Visual Studio). Toolbar A toolbar, with two drop-downs, appears at the top of the Find and Replace window. These drop-downs allow you to choose the type of search or replace you intend to perform and changes the options displayed in the window to match. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 158 Table 6-4. Find and Replace Toolbar Drop-down View menu Find (left drop-down) Quick Find Find in Files Find Symbol Replace (right drop-down) Quick Replace Replace in Files Figure 6-9. Find Results Figure 6-10. Find Symbol Results 6.7. Export Template Wizard Atmel Studio project and item templates provide reusable and customizable project and item stubs that accelerate the development process because users do not have to create new projects and items from scratch. Note:  This functionality is inherited from Microsoft Visual Studio® and the documentation from Microsoft goes beyond what is mentioned in this section. See MSDN for in-depth information. Open the Export Template Wizard by clicking File → Export Template.... This opens the Export Template Wizard shown in the figure below. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 159 Figure 6-11. Export Template Wizard... 6.7.1. Project Template A Project template is a template that contains a whole project. This template can be redistributed to other users to ease setup of a default project. The code, which is to be template, can contain parameters that are substituted on creation. See Default Template Parameters for information on this. The template wizard is mostly self explanatory, and on completion the created template will be available in the File → File → New Project... dialog. 6.7.2. Item Template An Item template is a template that contains a single file or collection of files. The code which is to be templated can contain parameters that are substituted on creation. See Default Template Parameters for information on this. The template wizard is mostly self explanatory, and on completion the created template will be available as a file type when files are added to the project. 6.7.3. Template Parameters All templates support parameter substitution to enable replacement of key parameters, such as class names and namespaces, when the template is instantiated. These parameters are replaced by the template wizard that runs in the background when a user clicks OK in the New Project or Add New Item dialog boxes. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 160 6.7.3.1. Declaring and Enabling Template Parameters Template parameters are declared in the format $parameter$. 6.7.3.2. Default Template Parameters The table below lists the reserved template parameters that can be used by any template. Note:  Template parameters are case-sensitive. Table 6-5. Template Parameters Parameter Description $itemname$ The name provided by the user in the Add New Item dialog box $machinename$ The current computer name $projectname$ The name provided by the user in the New Project dialog box $registeredorganization$ The registry key value from HKLM\Software\Microsoft\Windows NT \CurrentVersion\RegisteredOrganization $safeitemname$ The name provided by the user in the Add New Item dialog box, with all unsafe characters and spaces removed $safeprojectname$ The name provided by the user in the New Project dialog box, with all unsafe characters and spaces removed $time$ The current time in the format DD/MM/YYYY 00:00:00 $userdomain$ The current user domain $username$ The current user name $year$ The current year in the format YYYY $guid[1-10]$ A GUID used to replace the project GUID in a project file. You can specify up to 10 unique GUIDs (for example, guid1) 6.7.3.3. Custom Template Parameters You can use the CustomParameter element in your .vstemplate file to add new parameters to a template. 1. Locate the TemplateContent element in the .vstemplate file for the template. 2. Add a CustomParameters element and one or more CustomParameter child elements as children of the TemplateContent element. Figure 6-12. Adding Custom Parameters ... 3. Use the parameter in one or more of the code files in the template as shown in Default Template Parameters. More information on this can be found on MSDN. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 161 6.8. Kit Mode Setting Some kits operate with different modes. This window can be used to change the mode. Figure 6-13. Kit Mode Settings Some examples of the choices that can be made are listed in the following table. Select mode Persistent Resulting mode Mass Storage Yes Auto, enumerating as a Mass Storage Device kit DGI Auto, enumerating as a DGI kit Mass Storage No Mass Storage, enumerating once as a Mass Storage Device kit before returning to the previous mode DGI DGI, enumerating once as a DGI kit before return to the previous mode Note:  When the persistent mode is used, the kit will reboot into Auto mode, since the persistent choice changes the kit default. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 162 7. Atmel GNU Toolchains Atmel GNU Toolchains are a set of standalone command line programs used to create applications for Atmel SAM and Atmel AVR microcontrollers. 7.1. GNU Compiler Collection (GCC) The GNU Compiler Collection is used by Atmel Studio at the build stage. The architecture specific versions of the GNU Compiler Collection supports c-code compilation, assembly and linking of C and C+ +. The AVR GNU compiler collection is distributed under the terms of the GNU General Public License, http://www.gnu.org/licenses/gpl.html. A copy of this license is also found in the installation folder of Atmel Studio . 7.2. ARM Compiler and Toolchain Options: GUI To get help about ARM GCC Toolchain, you can do the following: • For general information about GCC, visit the official GNU GCC web site • Alternatively, you can write arm-none-eabi-gcc --help and see the explanation of some of the parameters in the command output This section illustrates the GUI options that are available for the ARM GNU Toolchain in Atmel Studio. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 163 Figure 7-1. ARM GNU Toolchain Properties Table 7-1. ARM GNU Common Options Option Description Thumb(-mthumb)/Arm(-marm) Switch between Arm and Thumb processor mode Table 7-2. ARM GNU C Compiler Options Option Description Preprocessor options -nostdinc Do not search system include directories -E Preprocess only; Do not compile, Assemble or link Symbols options Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 164 Option Description There one can define (-D) or undefine (-U) a number of in-source symbols. New symbol declarations can be added, modified, or reordered, using the interface buttons below: • Add a new symbol. This and all following icons are reused with the same meaning in other parts of Atmel Studio interface. • Remove a symbol. • Edit symbol. • Move the symbol up in the parsing order. • Move the symbol down in the parsing order. Include directories Default Include Path Enabling this option will add the include path that are specific for the selected SAM device Contains all the included header and definition directories, can be modified, using the same interface as symbols Optimization options Optimization level (drop down menu): -O0, - O1, -O2, -O3, -Os No optimization, optimize for speed (level 1 - 3), optimize for size Other optimization flags (manual input form) Here you should write optimization flags specific for the platform and your requirements -ffunction-sections Place each function into its own section -funsafe-math-optimizations Enable unsafe match optimizations -ffast-math Enable fast math -fpic Generate position independent code Debug options Debug level (drop down menu): none, -g1, - g2, -g3 Specifies the level of tracing and debugging code and headers left or inserted in the source code Other debug options (form field) Architecture specific debug options Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 165 Option Description -pg Generate gprof information -p Generate prof information Warning messages output options -Wall All warnings -Werror Treat all warnings as errors -fsyntax-only Check syntax only -pedantic Check conformity to GNU, raise warnings on nonstandard programming practice -pedantic-errors Same as above, plus escalate warnings to errors -w Inhibits all warnings Miscellaneous options Other flags (form field) Input other project-specific flags -v Verbose (Display the programs invoked by the compiler) -ansi Support ANSI programs -save-temps Do not delete intermediate files Option Description Table 7-3. ARM GCC Linker Options Option Description -Wl -nostartfiles Do not use standard files -Wl -nodefault Do not use default libraries -Wl -nostdlib No start-up or default libraries -Wl -s Omit all symbol information -Wl -static Link statically -Map Generates Map file Libraries options Libraries -Wl, -l (form field) You can add, prioritize or edit library names here, using those buttons: , , , , Library search path -Wl, -L (form field) You can add, prioritize or edit path where the linker will search for dynamically linked libraries, same interface as above Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 166 Option Description Optimization options -Wl, -gc-sections Garbage collect unused sections -funsafe-math-optimizations Enable unsafe math optimizations -ffast-math Enable fast math -fpic Generate position independent code Miscellaneous options Other linker flags (form field) Input other project-specific flags Option Description Linker Scripts • In "linker->miscellaneous->linker flags" ($LinkerScript_FLASH) is added by default. It will be replaced with the appropriate (device_name)_flash.ld file during Build. Similarly ($LinkerScript_SRAM) will be replaced with the appropriate (device_name)_sram.ld file. • You can always override the default flash linker scripts by replacing ($LinkerScript_FLASH) or ($LinkerScript_SRAM) with your custom linker script option - T"custom_linker_script.ld". Note:  These device specific linker scripts will be available in the "ProjectFolder/Linkerscripts" directory. In case of changing the device after project creation, Atmel Studio will automatically add the correct linker scripts for the selected device. ARM Assembler Options Table 7-4. Arm Assembler Options Option Description Optimization options Assembler flags (form field) Miscellaneous assembler flags Include path (form field) You can add, prioritize or edit path to the architecture and platform specific included files here -v Announce version in the assembler output -W Suppress Warnings Debugging options Debugging level (drop down menu) None , (-g). Enable debugging symbols and debugging source insertion Option Description ARM Preprocessing Assembler Options Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 167 Table 7-5. ARM Preprocessing Assembler Options Option Description Optimization options Assembler flags (form field) Miscellaneous assembler flags Include path (form field) You can add, prioritize or edit path to the architecture and platform specific included files here -v Announce version in the assembler output -W Suppress Warnings Debugging options Debugging level (drop down menu) None , -Wa -g. Enables debugging symbols and debugging source insertion Option Description 7.3. ARM GNU Toolchain Options 7.3.1. ARM/GNU Common Options • Thumb(-mthumb)/Arm(-marm) Allows you to select the processor mode. 7.3.2. Compiler Options 7.3.2.1. Preprocessor • -nostdinc Do not search the standard system directories for header files. Only the directories you have specified with -I options (and the directory of the current file, if appropriate) are searched. • -E Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output. Input files which don't require preprocessing are ignored. 7.3.2.2. Symbols • -D • -D name Predefine name as a macro, with definition 1. Eg: • -D name=value Predefine name as a macro, with definition value. The contents of definition are tokenized and processed as if they appeared during translation phase three in a #define directive. In particular, the definition will be truncated by embedded newline characters. • -U Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 168 Cancel any previous definition of name, either built in or provided with a -D option. -D and -U options are processed in the order they are given on the command line. All -imacros file and - include file options are processed after all -D and -U options. 7.3.2.3. Directories • -I dir Add the directory dir to the list of directories to be searched for header files. Directories named by -I are searched before the standard system include directories. If the directory dir is a standard system include directory, the option is ignored to ensure that the default search order for system directories and the special treatment of system headers are not defeated . 7.3.2.4. Optimization • There is a general switch ‘-O’ which specifies the level of optimization used when generating the code: – -Os Signal that the generated code should be optimized for code size. The compiler will not care about the execution performance of the generated code. – -O0 No optimization. GCC will generate code that is easy to debug but slower and larger than with the incremental optimization levels outlined below. – -O1 or -O This will optimize the code for both speed and size. Most statements will be executed in the same order as in the C/C++ code and most variables can be found in the generated code. This makes the code quite suitable for debugging. This is default. – -O2 Turn on most optimizations in GCC except for some optimizations that might drastically increase code size. This also enables instruction scheduling, which allows instructions to be shuffled around to minimize CPU stall cycles because of data hazards and dependencies, for CPU architectures that might benefit from this. Overall this option makes the code quite small and fast, but hard to debug. – -O3 Turn on some extra performance optimizations that might drastically increase code size but increase performance compared to the -O2 and -O1 optimization levels. This includes performing function inlining • Other optimization options – -ffunction-sections – -fdata-sections Place each function or data item into its own section in the output file if the target supports arbitrary sections. The name of the function or the name of the data item determines the section's name in the output file. Only use these options when there are significant benefits from doing so. When you specify these options, the assembler and linker will create larger object and executable files and will also be slower. – -funroll-loops Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 169 Perform loop unrolling when iteration count is known. If code size is not a concern then some extra performance might be obtained by making gcc unroll loops by using the ‘-funroll-loops’’ switch in addition to the ‘-O3’ switch. 7.3.2.5. Debugging • -g level (Debugging level) • -g1 It produces minimal information, enough for making backtraces in parts of the program that you don't plan to debug. This includes descriptions of functions and external variables, but no information about local variables and no line numbers. • -g2 It is the default debugging level. • -g3 It includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use -g3. 7.3.2.6. Warnings • -Wall Show all warnings. • -Werror Show warnings as errors. • -fsyntax-only Check the code for syntax errors, but don't do anything beyond that. • -pedantic Issue all the warnings demanded by strict ISO C, reject all programs that use forbidden extensions, and some other programs that do not follow ISO C. Valid ISO C programs should compile properly with or without this option (though a rare few will require -ansi or a -std option specifying the required version of ISO C). However, without this option, certain GNU extensions and traditional C features are supported as well. With this option, they are rejected. • -pedantic-errors Pedantic warnings are produced as errors. • -w Inhibit all warning messages. 7.3.2.7. Miscellaneous • -v Verbose option. It prints (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler driver program and of the preprocessor and the compiler proper. • -ansi Support ANSI programs. This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code). For the C compiler, it disables recognition of C++ style // comments as well as the inline keyword. The -ansi option does not cause non-ISO programs to be rejected gratuitously. For that, -pedantic is required in addition to -ansi. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 170 7.3.3. Linker Options 7.3.3.1. General • -Wl,option Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. You can use this syntax to pass an argument to the option. For example, `-Wl,- Map,output.map' passes `-Map output.map' to the linker. • -Wl, -nostartfiles Do not use the standard system startup files when linking. The standard system libraries are used normally, unless -nostdlib or -nodefaultlibs is used. • -Wl,-nodefault Do not use the standard system libraries when linking. Only the libraries you specify will be passed to the linker, options specifying linkage of the system libraries, such as -static-libgcc or - shared-libgcc, will be ignored. The standard start-up files are used normally, unless - nostartfiles is used. The compiler may generate calls to memcmp, memset, memcpy and memmove. These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified. • -Wl,-nostdlib Do not use the standard system start-up files or libraries when linking. One of the standard libraries bypassed by -nostdlib and -nodefaultlibs is libgcc.a, a library of internal subroutines that GCC uses to overcome shortcomings of particular machines, or special needs for some languages. In most cases, you need libgcc.a even when you want to avoid other standard libraries. In other words, when you specify -nostdlib or -nodefaultlibs you should usually specify -lgcc as well. This ensures that you have no unresolved references to internal GCC library subroutines. • -Wl,-s Remove all symbol table and relocation information from the executable. • -Wl,-static On systems that support dynamic linking, this prevents linking with the shared libraries. On other systems, this option has no effect. • -Wl,-Map Generates Map file. 7.3.3.2. Libraries • -Wl,-llibrary Search the library named library when linking. It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. The linker searches a standard list of directories for the library, which is actually a file named liblibrary.a. The linker then uses this file as if it had been specified precisely by name. • -Wl, Ldir Add directory dir to the list of directories to be searched for -l. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 171 7.3.3.3. Optimization • -Wl, --gc-sections Garbage collect unused sections. Enable garbage collection of unused input sections. It is ignored on targets that do not support this option. The default behavior (of not performing this garbage collection) can be restored by specifying `--no-gc-sections' on the command line. `--gc-sections' decides which input sections are used by examining symbols and relocations. The section containing the entry symbol and all sections containing symbols undefined on the command-line will be kept, as will sections containing symbols referenced by dynamic objects. • -funsafe-math-optimizations Enable unsafe math optimizations. • -ffast-math Enable fast math • -fpic Generate position independent code. 7.3.4. Assembler Options • -I Use this option to add a path to the list of directories as searches for files specified in .include directives (see .include). You may use -I as many times as necessary to include a variety of paths. The current working directory is always searched first; after that, as searches any `-I' directories in the same order as they were specified (left to right) on the command line. • -v Announce version. • Debugging(-g) Use this option to enable the debug level. 7.3.5. Preprocessing Assembler Options • -I Use this option to add a path to the list of directories as searches for files specified in .include directives (see .include). You may use -I as many times as necessary to include a variety of paths. The current working directory is always searched first; after that, as searches any `-I' directories in the same order as they were specified (left to right) on the command line. • -v Announce version. • Debugging(Wa,-g) Use this option to enable the debug level. 7.3.6. Archiver Options • -r Replace existing or insert new file(s) into the archive. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 172 7.4. Binutils The following ARM GNU Binutils are available: • arm-none-eabi-ld - GNU linker. • arm-none-eabi-as - GNU assembler. • arm-none-eabi-addr2line - Converts addresses into filenames and line numbers. • arm-none-eabi-ar - A utility for creating, modifying and extracting from archives. • arm-none-eabi-c++filt - Filter to demangle encoded C++ symbols. • arm-none-eabi-nm - Lists symbols from object files. • arm-none-eabi-objcopy - Copies and translates object files. • arm-none-eabi-objdump - Displays information from object files. • arm-none-eabi-ranlib - Generates an index to the contents of an archive. • arm-none-eabi-readelf - Displays information from any ELF format object file. • arm-none-eabi-size - Lists the section sizes of an object or archive file. • arm-none-eabi-strings - Lists printable strings from files. • arm-none-eabi-strip - Discards symbols. For more information about each util, use the built in help command: --help. 7.5. AVR Compiler and Toolchain Options: GUI To get help about AVR GNU toolchain, you can do the following: • For information about avr32-gcc usage in Atmel Studio and general parameters consult the GCC Project Options and Configuration section • The API reference for the AVR libc implementation can be found here The API Alphabetical index can be consulted here • For general information about GCC, visit the official GNU GCC web site • Alternatively you can write avr32-gcc --help and see explanations on some of the parameters in the command output This section illustrates the GUI options that are available for the AVR GNU toolchain from the Atmel Studio frontend. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 173 Figure 7-2. AVR GNU Toolchain Options AVR GNU C Compiler Options Table 7-6. AVR GNU C Compiler Options Option Description General options -mcall-prologues Use subroutines for functions prologues and epilogues -mno-interrupts Change stack pointer without disabling interrupts -funsigned-char Default char type is unsigned -funsigned-bitfield Default bit field is unsigned Preprocessor options -nostdinc Do not search system directories -E Preprocess only Symbols options Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 174 Option Description There one can define (-D) or undefine (-U) a number of in-source symbols. New symbol declarations can be added, modified, or reordered, using the interface buttons below: • Add a new symbol. This and all following icons are reused with the same meaning in other parts of Atmel Studio interface. • Remove a symbol. • Edit symbol. • Move the symbol up in the parsing order. • Move the symbol down in the parsing order. Include directories Contains all the included header and definition directories, can be modified, using the same interface as symbols. Optimization options Optimization level (drop down menu): -O0, - O1, -O2, -O3, -Os No optimization, optimize for speed (level 1 - 3), optimize for size Other optimization flags (manual input form) Here you should write optimization flags specific for the platform and your requirements -ffunction-sections Prepare functions for garbage collection, if a function is never used, its memory will be scrapped -fpack-struct Pack structure members together -fshort-enums Allocate only as many bytes needed by the enumerated types -mshort-calls Use rjmp/rcall limited range instructions on the >8K devices Debug options Debug level (drop down menu): none, -g1, - g2, -g3 Specifies the level of tracing and debugging code and headers left or inserted in the source code Other debug options (form field) Architecture specific debug options Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 175 Option Description Warning messages output options -Wall All warnings -Werror Escalate warnings to errors -fsyntax-only Check syntax only -pedantic Check conformity to GNU, raise warnings on nonstandard programming practice -pedantic-errors Same as above, plus escalate warnings to errors Miscellaneous options Other flags (form field) Input other project-specific flags -v Verbose -ansi Support ANSI programs -save-temps Do not delete temporary files AVR GCC Linker Options Table 7-7. AVR GCC Linker Options Option Description -Wl -nostartfiles Do not use standard files -Wl -nodefault Do not use default libraries -Wl -nostdlib No start-up or default libraries -Wl -s Omit all symbol information -Wl -static Link statically Libraries options Libraries -Wl, -l (form field) You can add, prioritize or edit library names here, using those buttons: , , , , Library search path -Wl,-L (form field) You can add, prioritize or edit path where the linker will search for dynamically linked libraries, same interface as above Optimization options -Wl, -gc-sections Garbage collect unused sections --rodata-writable Put read-only data in writable spaces -mrelax Relax branches Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 176 Option Description Miscellaneous options Other linker flags (form field) Input other project-specific flags Memory Settings Displays a dialog where it is possible to configure memory segments. (Syntax for specifying segment values: =
, for example boot=0xff) The address must be given as a hexadecimal number prefixed with 0x. It is interpreted as a word address for flash memory and a byte addresse for SRAM and EEPROM memory. Figure 7-3. Memory settings Notes about the AVR port of gcc The AVR is a Harvard architecture CPU. This means that it separates instruction memory and data memory. The gcc was originally designed to support Von Neumann architectures which define a single storage structure to hold both instructions and data. This dichotomy is solved by a series of nifty tricks in the AVR port of gcc, of which three should be noted: • The .text segment starts at 0x0 • The .data segment starts at 0x800000 • The .eeprom segment starts at 0x810000 These peculiarities have been abstracted away by the GUI , but users will see the truth when building projects with relocated segments. A relocation definition for flash will be passed to the GNU linker via avr-gcc as the option: • -Wl,-section-start=bootloader=0x1fc00 Note that the address has been multiplied by 2 to get the byte address. A relocation definition for the .data section will be passed as: Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 177 • -Wl,-section-start=anewdatasegment=0x800 AVR Assembler Options Table 7-8. AVR Assembler Options Option Description Optimization options Assembler flags (form field) Miscellaneous assembler flags Include path (form field) You can add, prioritize or edit path to the architecture and platform specific included files here -v Announce version in the assembler output Debugging options Debugging (drop down menu) None, -Wa -g Enables debugging symbol and debugging source insertion 7.6. Commonly Used Options 7.6.1. Compiler Options 7.6.1.1. General • -funsigned-char Each kind of machine has a default for what char should be. It is either like unsigned char by default or like signed char by default. This option says that the default char type is unsigned. • -funsigned-bitfields These options control whether a bit-field is signed or unsigned, when the declaration does not use either signed or unsigned. This options says that the default bitfield type is unsigned. 7.6.1.2. Preprocessor • -nostdinc Do not search the standard system directories for header files. Only the directories you have specified with -I options (and the directory of the current file, if appropriate) are searched. • -E Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output. Input files which don't require preprocessing are ignored. 7.6.1.3. Symbols • -D • -D name Predefine name as a macro, with definition 1. E.g.: • -D name=value Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 178 Predefine name as a macro, with definition value. The contents of definition are tokenized and processed as if they appeared during translation phase three in a #define directive. In particular, the definition will be truncated by embedded newline characters. • -U Cancel any previous definition of name, either built in or provided with a -D option. -D and -U options are processed in the order they are given on the command line. All -imacros file and - include file options are processed after all -D and -U options. 7.6.1.4. Directories • -I dir Add the directory dir to the list of directories to be searched for header files. Directories named by -I are searched before the standard system include directories. If the directory dir is a standard system include directory, the option is ignored to ensure that the default search order for system directories and the special treatment of system headers are not defeated . 7.6.1.5. Optimization • There is a general switch ‘-O’ which specifies the level of optimization used when generating the code: – -Os Signal that the generated code should be optimized for code size. The compiler will not care about the execution performance of the generated code. – -O0 No optimization. This is the default. GCC will generate code that is easy to debug but slower and larger than with the incremental optimization levels outlined below. – -O1 or -O This will optimize the code for both speed and size. Most statements will be executed in the same order as in the C/C++ code and most variables can be found in the generated code. This makes the code quite suitable for debugging. – -O2 Turn on most optimizations in GCC except for some optimizations that might drastically increase code size. This also enables instruction scheduling, which allows instructions to be shuffled around to minimize CPU stall cycles because of data hazards and dependencies, for CPU architectures that might benefit from this. Overall this option makes the code quite small and fast, but hard to debug. – -O3 Turn on some extra performance optimizations that might drastically increase code size but increase performance compared to the -O2 and -O1 optimization levels. This includes performing function inlining • Other optimization options – -ffunction-sections – -fdata-sections Place each function or data item into its own section in the output file if the target supports arbitrary sections. The name of the function or the name of the data item determines the section's name in the output file. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 179 Only use these options when there are significant benefits from doing so. When you specify these options, the assembler and linker will create larger object and executable files and will also be slower. – -funroll-loops If code size is not a concern then some extra performance might be obtained by making gcc unroll loops by using the ‘-funroll-loops’’ switch in addition to the ‘-O3’ switch. 7.6.1.6. Debugging • -g level (Debugging level) • -g1 It produces minimal information, enough for making back-traces in parts of the program that you don't plan to debug. This includes descriptions of functions and external variables, but no information about local variables and no line numbers. • -g2 It is the default debugging level. • -g3 It includes extra information, such as all the macro definitions present in the program. Some debuggers support macro expansion when you use -g3. 7.6.1.7. Warnings • -Wall Show all warnings. • -Werror Show warnings as errors. • -fsyntax-only Check the code for syntax errors, but don't do anything beyond that. • -pedantic Issue all the warnings demanded by strict ISO C, reject all programs that use forbidden extensions, and some other programs that do not follow ISO C. Valid ISO C programs should compile properly with or without this option (though a rare few will require -ansi or a -std option specifying the required version of ISO C). However, without this option, certain GNU extensions and traditional C features are supported as well. With this option, they are rejected. • -pedantic-errors Pedantic warnings are produced as errors. • -w Inhibit all warning messages. 7.6.1.8. Miscellaneous • -v Verbose option. It prints (on standard error output) the commands executed to run the stages of compilation. Also print the version number of the compiler driver program and of the preprocessor and the compiler proper. • -ansi Support ANSI programs. This turns off certain features of GCC that are incompatible with ISO C90 (when compiling C code). For the C compiler, it disables recognition of C++ style // comments as Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 180 well as the inline keyword. The -ansi option does not cause non-ISO programs to be rejected gratuitously. For that, -pedantic is required in addition to -ansi. 7.6.2. Linker Options 7.6.2.1. General • -Wl,option Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. You can use this syntax to pass an argument to the option. For example, `-Wl,- Map,output.map' passes `-Map output.map' to the linker. • -Wl, -nostartfiles Do not use the standard system startup files when linking. The standard system libraries are used normally, unless -nostdlib or -nodefaultlibs is used. • -Wl,-nodefault Do not use the standard system libraries when linking. Only the libraries you specify will be passed to the linker, options specifying linkage of the system libraries, such as -static-libgcc or - shared-libgcc, will be ignored. The standard start-up files are normally used, unless - nostartfiles is used. The compiler may generate calls to memcmp, memset, memcpy, and memmove. These entries are usually resolved by entries in libc. These entry points should be supplied through some other mechanism when this option is specified. • -Wl,-nostdlib Do not use the standard system start-up files or libraries when linking. One of the standard libraries bypassed by -nostdlib and -nodefaultlibs is libgcc.a, a library of internal subroutines that GCC uses to overcome shortcomings of particular machines, or special needs for some languages. In most cases, you need libgcc.a even when you want to avoid other standard libraries. In other words, when you specify -nostdlib or -nodefaultlibs you should usually specify -lgcc as well. This ensures that you have no unresolved references to internal GCC library subroutines. • -Wl,-s Remove all symbol table and relocation information from the executable. • -Wl,-static On systems that support dynamic linking, this prevents linking with the shared libraries. On other systems, this option has no effect. 7.6.2.2. Libraries • -Wl,-llibrary Search the library named library when linking. It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. The linker searches a standard list of directories for the library, which is actually a file named liblibrary.a. The linker then uses this file as if it had been specified precisely by name. • -Wl, Ldir Add directory dir to the list of directories to be searched for -l. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 181 7.6.2.3. Optimization • -Wl, --gc-sections Garbage collect unused sections. Enable garbage collection of unused input sections. It is ignored on targets that do not support this option. The default behavior (of not performing this garbage collection) can be restored by specifying `--no-gc-sections' on the command line. `--gc-sections' decides which input sections are used by examining symbols and relocations. The section containing the entry symbol and all sections containing symbols undefined on the command-line will be kept, as will sections containing symbols referenced by dynamic objects. • --rodata-writable Put read-only data in writable data section. 7.6.3. Assembler Options • -I Use this option to add a path to the list of directories as searches for files specified in .include directives (see .include). You may use -I as many times as necessary to include a variety of paths. The current working directory is always searched first; after that, as searches any `-I' directories in the same order as they were specified (left to right) on the command line. • -v Announce version. 7.7. 8-bit Specific AVR GCC Command Line Options This section describes the options specific to AVR 8-bit Toolchain. 7.7.1. AVR C Compiler 7.7.1.1. General • -mcall-prologues Functions prologues/epilogues are expanded as call to appropriate subroutines. Code size will be smaller. • -mno-interrupts Change the stack pointer without disabling interrupts. Generated code is not compatible with hardware interrupts. Code size will be smaller. • -mno-tablejump Do not generate table jump instructions (removed from gcc 4.5.1 coz same as -fno-jump-tables). • -msize Output instruction sizes to the asm file (removed from avr-gcc coz same as using -dp switch which prints the instruction length). 7.7.1.2. Optimization • -fpack-struct Without a value specified, pack all structure members together without holes. When a value is specified (which must be a small power of two), pack structure members according to this value, representing the maximum alignment (that is, objects with default alignment requirements larger than this will be output potentially unaligned at the next fitting location). Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 182 • -fshort-enums Allocate to an enum type only as many bytes as it needs for the declared range of possible values. Specifically, the enum type will be equivalent to the smallest integer type which has enough room. • -mshort-calls Use rjmp/rcall (limited range) on >8K devices. 7.7.1.3. Miscellaneous • -save-temps Do not delete temporary files. Store the usual "temporary" intermediate files permanently; place them in the current directory and name them based on the source file. Thus, compiling foo.c with -c -save-temps would produce files foo.i and foo.s, as well as foo.o. This creates a preprocessed foo.i output file even though the compiler now normally uses an integrated preprocessor. 7.7.2. AVR C Linker 7.7.2.1. Optimization • -mrelax Relax branches. Linker relaxing is enabled in the linker by passing the ‘—relax’ option to the linker. Using GCC as a frontend for the linker, this option is automatically passed to the linker when using ‘-O2’ or ‘-O3’ or explicitly using the ‘-mrelax’ option. When this option is used, GCC outputs pseudo instructions like lda.w, call etc. The linker can then, if the input file is tagged as relaxable, convert a pseudo instruction into the best possible instruction with regards to the final symbol address. 7.8. 32-bit Specific AVR GCC Command Line Options 7.8.1. Optimization • -mfast-float The switch, causes fast, non-ieee compliant versions of some of the optimized AVR 32-bit floatingpoint library functions to be used. This switch is by default enabled if the ‘-ffast-math’ switch is used. • -funsafe-math-optimizations Allow optimizations for floating-point arithmetic that (a) assume that arguments and results are valid and (b) may violate IEEE or ANSI standards. When used at link-time, it may include libraries or start-up files that change the default FPU control word or other similar optimizations. This option is not turned ON by any ‘-O’ option since it can result in incorrect output for programs which depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. Enables ‘- fno-signed-zeros’, ‘-fno-trapping-math’, ‘-fassociative-math’ and ‘-freciprocal-math’. • -ffast-math This option causes the preprocessor macro __FAST_MATH__ to be defined. This option is not turned on by any ‘-O’ option since it can result in incorrect output for programs which depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. It sets ‘-fnomath-errno’, ‘-funsafe-math-optimizations’, ‘-ffinite-math-only’, ‘-fno-rounding-math’, ‘-fno-signalingnans’ and ‘-fcx-limited-range’. • -fpic Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 183 Generate position-independent code (PIC) suitable for use in a shared library, if supported for the target machine. Such code accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not part of GCC; it is part of the operating system). If the GOT size for the linked executable exceeds a machine-specific maximum size, you get an error message from the linker indicating that ‘-fpic’ does not work; in that case, recompile with ‘-fPIC’ instead. (These maximums are 8k on the SPARC and 32k on the m68k and RS/6000. The 386 has no such limit.) Position-independent code requires special support, and therefore works only on certain machines. For the 386, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always positionindependent. When this flag is set, the macros __pic__ and __PIC__ are defined to 1. • -mno-init-got Do not initialize GOT register before using it when compiling PIC code. • -masm-addr-pseudos This option is enabled by default and causes GCC to output the pseudo instructions call and lda.w for calling direct functions and loading symbol addresses respectively. It can be turned OFF by specifying the switch ‘-mno-asm-addr-pseudos’. The advantage of using these pseudo-instructions is that the linker can optimize these instructions at link time if linker relaxing is enabled. The ‘- mrelax’ option can be passed to GCC to signal to the assembler that it should generate a relaxable object file. • -mforce-double-align Force double-word alignment for double-word memory accesses. • -mimm-in-const-pool When GCC needs to move immediate values not suitable for a single move instruction into a register, it has two possible choices; it can put the constant into the code somewhere near the current instruction (the constant pool) and then use a single load instruction to load the value or it can use two immediate instruction for loading the value directly without using a memory load. If a load from the code memory is faster than executing two simple one-cycle immediate instructions, then putting these immediate values into the constant pool will be most optimal for speed. This is often true for MCU architectures implementing an instruction cache, whereas architectures with code executing from internal flash will probably need several cycles for loading values from code memory. By default GCC will use the constant pool for AVR 32-bit products with an instruction cache and two immediate instructions for flash-based MCUs. This can be overridden by using the option ‘-mimm-in-const-pool’ or its negated option ‘-mno-imm-in-const-pool’. • -muse-rodata-sections By default GCC will output read-only data into the code (.text) section. If the code memory is slow it might be more optimal for performance to put read-only data into another faster memory, if available. This can be done by specifying the switch ‘-muse-rodata-section’, which makes GCC put read-only data into the .rodata section. Then the linker file can specify where the content of the .rodata section should be placed. For systems running code from flash this might however mean that the read-only data must be placed in flash and then copied over to another memory at start-up, which means that extra memory usage is required with this scheme. 7.8.2. Debugging • -pg Generate extra code to write profile information suitable for the analysis program gprof. You must use this option when compiling the source files you want data about, and you must also use it when linking. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 184 • -p Generate extra code to write profile information suitable for the analysis program prof. You must use this option when compiling the source files you want data about, and you must also use it when linking. 7.8.3. AVR32 C Linker 7.8.3.1. Optimization • -mfast-float Enable fast floating-point library. Enabled by default if the -funsafe-math-optimizations switch is specified. • -funsafe-math-optimizations Allow optimizations for floating-point arithmetic that (a) assume that arguments and results are valid and (b) may violate IEEE or ANSI standards. When used at link-time, it may include libraries or start-up files that change the default FPU control word or other similar optimizations. This option is not turned on by any ‘-O’ option since it can result in incorrect output for programs which depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. Enables ‘- fno-signed-zeros’, ‘-fno-trapping-math’, ‘-fassociative-math’, and ‘-freciprocal-math’. The default is ‘- fno-unsafe-math-optimizations’. • -ffast-math This option causes the preprocessor macro __FAST_MATH__ to be defined. This option is not turned on by any ‘-O’ option since it can result in incorrect output for programs which depend on an exact implementation of IEEE or ISO rules/specifications for math functions. It may, however, yield faster code for programs that do not require the guarantees of these specifications. It sets ‘-fnomath-errno’, ‘-funsafe-math-optimizations’, ‘-ffinite-math-only’, ‘-fno-rounding-math’, ‘-fno-signalingnans’, and ‘-fcx-limited-range’. • -fpic Generate position-independent code (PIC) suitable for use in a shared library, if supported for the target machine. Such code accesses all constant addresses through a global offset table (GOT). The dynamic loader resolves the GOT entries when the program starts (the dynamic loader is not part of GCC; it is part of the operating system). If the GOT size for the linked executable exceeds a machine-specific maximum size, you get an error message from the linker indicating that ‘-fpic’ does not work; in that case, recompile with ‘-fPIC’ instead. (These maximums are 8k on the SPARC and 32k on the m68k and RS/6000. The 386 has no such limit.) Position-independent code requires special support, and therefore works only on certain machines. For the 386, GCC supports PIC for System V but not for the Sun 386i. Code generated for the IBM RS/6000 is always positionindependent. When this flag is set, the macros __pic__ and __PIC__ are defined to 1. • -Wl,--direct-data Allow direct data references when optimizing. To enable the linker to convert an lda.w into an immediate move instruction, i.e. linker relaxing, the option ‘—direct-data’ must be given to the linker. 7.8.3.2. Miscellaneous • -Xlinker[option] Pass option as an option to the linker. You can use this to supply system-specific linker options which GCC does not know how to recognize. If you want to pass an option that takes a separate argument, you must use -Xlinker twice, once for the option and once for the argument. For example, to pass -assert definitions, you must write `-Xlinker -assert -Xlinker definitions'. It does not Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 185 work to write -Xlinker "-assert definitions", because this passes the entire string as a single argument, which is not what the linker expects. When using the GNU linker, it is usually more convenient to pass arguments to linker options using the option=value syntax than as separate arguments. For example, you can specify `-Xlinker -Map=output.map' rather than `-Xlinker -Map - Xlinker output.map'. Other linkers may not support this syntax for command-line options. 7.9. Binutils The following AVR 32-bit GNU Binutils are available: • avr32-ld- GNU linker. • avr32-as - GNU assembler. • avr32-addr2line - Converts addresses into file-names and line numbers. • avr32-ar - A utility for creating, modifying and extracting from archives. • avr32-c++filt - Filter to demangle encoded C++ symbols. • avr32-nm - Lists symbols from object files. • avr32-objcopy - Copies and translates object files. • avr32-objdump - Displays information from object files. • avr32-ranlib - Generates an index to the contents of an archive. • avr32-readelf - Displays information from any ELF format object file. • avr32-size - Lists the section sizes of an object or archive file. • avr32-strings - Lists printable strings from files. • avr32-strip - Discards symbols. For more information about each util, use the built in help command: avr32- -- help. • For general information about GNU Assembler (GAS), GNU linker and other binutils, visit the official GNU Binutils web site. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 186 8. Extending Atmel Studio Atmel Studio includes a tool named Extension Manager that lets you add, remove, enable, and disable Atmel Studio extensions. To open Extension Manager, on the Tools menu, click Extension Manager. Extension developers are advised to uninstall previous versions of extensions in progress, and uninstall or disable potentially conflicting extensions to prevent conflicts during development. 8.1. Extension Manager UI The Extension Manager window is divided into three panes. The left pane lets you select by group: installed extensions and new extensions from the online gallery. Figure 8-1. Extension Manager The extensions are displayed in the middle pane. You can sort the list by name or author from the combobox above the list. When you select an extension in the middle pane, information about it appears in the right pane. Extension installed by the current user can be uninstalled or disabled, extensions distributed with Atmel Studio cannot be changed. The Extension Manager window also includes a search box. Depending on the selection in the left pane, you can search installed extensions, the online gallery, or available updates. Online Gallery Extension Manager can install extensions from the Atmel Studio Gallery. These extensions may be packages, templates, or other components that add functionality to Atmel Studio. To get started with the extension manager check the Installing New Extensions in Atmel Studio. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 187 Extension Types Extension Manager supports extensions in the VSIX package format, which may include project templates, item templates, toolbox items, Managed Extension Framework (MEF) components, and VSPackages. Extension Manager can also download and install MSI-based extensions, but it cannot enable or disable them. Atmel Studio Gallery contains both VSIX and MSI extensions. Dependency Handling If a user tries to install an extension that has dependencies, the installer verifies that those dependencies are already installed. If they are not installed, Extension Manager shows the user a list of dependencies that must be installed before the extension can be installed. Installing Without Using Extension Manager Extensions that have been packaged in .vsix files may be available in locations other than the Atmel Studio Gallery. Extension Manager cannot detect these files. However, you can install a .vsix file by double-clicking it and then following the setup instructions. When the extension is installed, you can use Extension Manager to enable it, disable it, or remove it. 8.2. Registering at Atmel Extension Gallery In order to download extensions, registering at the Atmel Extension Gallery is required. The first time Updates are accessed or a download is invoked, this login screen is displayed: Figure 8-2. Extension Manager Registration Follow the instructions on the screen. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 188 8.3. Installing New Extensions in Atmel Studio Step 1 Figure 8-3. Extension Manager Opening the extension manager window will show extensions installed. In order to find and install a new extension, click the Available Downloads tab on the left pane. Step 2 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 189 Figure 8-4. Retrieving List of Extensions Updating the available extension list will take some time. Step 3 Figure 8-5. List of Extensions Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 190 A green check mark identifies already installed extensions. Select QTouch Composer and press Download. If you have not previously registered as a user in the Extension Gallery you will be taken to the Registering at Atmel Extension Gallery at this point. . Figure 8-6. Extension Download Progression Download will start as indicated in the status bar of Atmel Studio. If the extension is distributed as a standalone installer you will be asked for location to save the file. Downloading can take several minutes for large files. A dialog with a running bar is displayed during download. Not that download can take a long time for large extensions. Press Cancel to abort the download. Step 4 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 191 Figure 8-7. Extension License A license agreement will appear for you to read, most of the times, when you install a new extension. Read it carefully and install only the extensions you really need as most of the extensions' authors do not take liability in a possible malfunction resulting from installation of mutually incompatible extensions and collateral damages, for example if extension security is breached. Step 5 Once the extension is downloaded a message in the lower status bar will appear. Figure 8-8. Extension Manager Restart Warning Click the Restart Now button to restart the IDE immediately, otherwise if you plan to restart it later - click the Close button. If you have an unsaved project you will be requested to save the changes you made, before restarting. Step 6 Figure 8-9. QTouch Composer Button After restarting Atmel Studio, a new button is added for starting QTouch Composer. 8.4. Visual Assist The Atmel Studio comes with a preinstalled extension - the Visual Assist from WholeTomato Software. The documentation on Visual Assist is available from several sources: • Go to the www.wholetomato.com. Click in the left hand menu to browse documentation by feature. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 192 Figure 8-10. WholeTomato Software Documentation • Jump directly to relevant documentation using hyperlinks in the Visual Assist options dialog Figure 8-11. Visual Assist Options • Click terms in the Glossary 8.5. Overview of QTouch Composer and Library The Atmel QTouch Composer and library allows you to easily and seamlessly develop capacitive touch functionality for your application. This simplifies the design process by tying together the tools required to edit the code in Atmel Studio and tune the touch design. QTouch Composer, formerly called QTouch Studio, is fully integrated in Atmel Studio 6 as an extension. QTouch Library is a software framework extension to Atmel studio, which allows you to add touch functionality on various Atmel devices. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 193 8.5.1. Installation 1. Start Atmel Studio. 2. Go to Tools → Extension Manager → Online Gallery. 3. Select QTouch Library and click “Download” and then install it. 4. Select QTouch Composer and click “Download” and then install it. 5. Click “Restart Now” button in the Extension manager window. 6. After starting Atmel Studio, go to Tools → Extension Manager. Check QTouch library and QTouch composer are listed and status is enabled. 8.5.2. Overview of QTouch Project Builder QTouch Project builder will guide you through all steps from selecting device and touch sensors to automatically generate a complete touch project. 1. Start Atmel Studio. 2. Open the File menu. Click on "New → Project". 3. The “New Project” dialog is opened. Select “GCC C QTouch Executable Project” in the New Project dialog. Enter the following details in the “New Project” dialog and click on the button OK. – Name of the project – Location of the project and solution – Name of the solution Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 194 4. The “QTouch Project Builder” wizard is opened, which will guide through the steps involved in creating a project. Sample QTouch Project creation video here. 8.5.3. Overview of QTouch Analyzer QTouch Analyzer reads and interprets touch data sent from QTouch kit into different views. The Analyzer is separated into Kit View, Kit/Sensor Properties, Sensor Data, Trace View, Power View, and Graph view. When touch kit is connected and Atmel Studio is opened, QTouch Analyzer window opens up and connection information is updated. The Virtual Kit view shows touch events such as button press, wheel, and slider use. The image is updated based on the touch data read from the connected Touch Kit. The Kit/Sensor Properties view allows you to view and modify the kit/sensor configuration options. The Sensor Data View provides touch data information of the currently connected kit. The Graph View displays one or more selected touch data's on a graph. Graph shall display most recent touch data. The data set to show can be selected from the data set list at the right side of the view. The datasets are displayed in tabbed pages representing the Signals, Deltas, References, and Wheel/Slider positions. Each data set selection list follows normal selection convention; click on an item in the list to selected that one item. To select a continuous range of items first click on first item then hold down the SHIFT key and select the last item in the range. Multiple items can also be selected one at a time by holding down the CTRL key prior to selecting the next item in the list. In the last case the items need not be in a continuous range. Using CTRL select method also allows deselection of individual items from a selection of multiple items. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 195 The Trace contains one or more data series with touch data in a chart. The trace keeps all historical data of one single reading session (pressing start and stop reading), and the data can be saved in a separate file and opened again later. 8.6. Scripting Extensions Atmel Studio provides some scripting hooks that can be executed automatically by the IDE. These extensions are mainly written in Python, and will execute for instance when a breakpoint is hit, when an expression is evaluated or when the program is being reset. 8.6.1. Debug Scripting The debug scripting interface is function based and depends on certain, named functions to be defined in a Python® file. The function will then be called when the corresponding event is occurring inside Atmel Studio. Attention:  Error checking is kept at a minimum for the functions exported into the Python environment so that the time used on initialization during normal sessions are kept low. This means that there are many ways to crash Atmel Studio through this interface. To load a Python file, place a file named debughooks.py in the Debug folder of your project, next to the ELF file, or one folder up where the project file is. It is also possible to place this file inside the Atmel Studio installation directory to make the script load for all projects. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 196 Note:  The Python file is loaded and compiled when a project is launched, so changes to the Python file during a debug session will not be active until the next debug session is started. The Python file is running in an IronPython context, with full access to .NET and a Python 2.7 runtime. See http:// ironpython.net/documentation/dotnet/ for more information of the runtime. The functions that Atmel Studio will try to load is shown below with its function signature. def should_process_breakpoint(studio_interface, breakpoint_address, breakpoint_id, obj): """ Called to determine if a breakpoint should cause Atmel Studio to enter debug mode. If this function returns False, Atmel Studio will not break at the breakpoint. """ return True def has_processed_breakpoint(studio_interface, breakpoint_address, breakpoint_id, obj): """ This function is called if Atmel Studio is breaking at a breakpoint. The GUI is now in halted mode. """ pass def on_reset(studio_interface, reset_address): """ This function is called when the target is reset. The address where the reset went to is 'reset_address'. """ pass def on_eval_expr(studio_interface, expression): """ This function is called for each expression that is evaluated in Atmel Studio. This includes the watch window and other windows that show data from the target. Pass the 'expression' string through to evaluate it, or return another expression to be evaluated to override the expression. This override is not visible in the Atmel Studio GUI. """ return expression Note:  Atmel Studio expects all these functions to be available if the script has been found and is loaded correctly. If for instance the should_process_breakpoint is undefined, breakpoints might start to misbehave as the return value of a undefined function is in itself undefined. In the code shown above, the main interface back into the Atmel Studio is the studio_interface object. This object contains some functions to show messages and do target interaction. The Print function in the studio_interface object is used to show text in the output window inside Atmel Studio. The function takes two arguments, the string to print and the name of the tab in the output window. The example below prints all evaluated expression to the “Expressions” tab. def on_eval_expr(studio_interface, expression): studio_interface.Print("Evaluating {}".format(expression), "Expressions") return expression Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 197 Note:  The severity level of text sent through Print is set to INFO, which means that the output may be masked by Atmel Studio. To lower the threshold, go to Tools > Tools, select Status Management, and set the Display Threshold to INFO. The ExecStmt function in the studio_interface object is used to execute statements in the debugger. This can for instance be used to set variables. See MSDN Debugger.ExecuteStatement Method for more information. The WriteMemory and ReadMemory are symmetric functions for reading and writing memory on the target. It is important to use a System.Array[System.Byte] object to pass the data between the script and Atmel Studio. import System def should_process_breakpoint(studio_interface, breakpoint_address, breakpoint_id, obj): vals = System.Array[System.Byte]([1, 2, 3, 4, 5, 6, 7, 8, 9]) studio_interface.WriteMemory(data=vals, adr=0, type="eeprom") ret = studio_interface.ReadMemory(adr=0, type="eeprom", count=9) studio_interface.Print("ret == vals => {!r}".format(ret == vals), "Python") return True The CalcNumericValue is a shorthand for the CalcValue call. It will return the numeric value of the symbol or the provided default value if the function fails to retrieve the value of the symbol. def should_process_breakpoint(studio_interface, breakpoint_address, breakpoint_id, obj): a = studio_interface.CalcNumericValue("a", 0) if a == 0: studio_interface.Print("a was 0 or default", "Value scripts") else: studio_interface.Print("a = {}".format(a), "Value scripts") return True The CalcValue function is used to retrieve information about a symbol in the scope where the target code is running. The return value of this call is a list of information, containing the address of the symbol, symbol information and value. The objects sent in this list contains all known information about a symbol, but the most useful field is the last element which contains the value of the evaluated symbol. def should_process_breakpoint(studio_interface, breakpoint_address, breakpoint_id, obj): a = studio_interface.CalcValue("a") # a now contains all information about the variable a. # It is a list with the following members: # a = [ # , # , # , # '1' ] <-- This is the value of the symbol as a string, here it had the value 1 studio_interface.Print("Value of a = {}".format(a[3]), "Value Scripts") return True Note:  The different objects returned by the CalcValue call contains objects that are either internal, or documented in the Atmel Studio SDK. Use the python dir() command to look at the fields that are exported. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 198 9. Menus and Settings 9.1. Customizing Existing Menus and Toolbars You can add or remove commands on any menu or toolbar, or change the order and grouping of those commands. You can also add toolbars, and change the layout, position, and content of existing toolbars in the integrated development environment (IDE). To add a command to a menu or toolbar 1. On the Tools menu, click Customize. 2. In the Customize dialog box, on the Commands tab, under Choose a menu or tool bar to rearrange, select the menu or tool bar you want to change and then click Add command. 3. In the Add Command dialog box, select a category name on the Categories list and then, on the Commands list, select the command you want to add. 4. Click OK. 5. Click Close. To remove a command from a menu or toolbar 1. On the Tools menu, click Customize. 2. In the Customize dialog box, on the Commands tab, under Choose a menu or toolbar to rearrange, select the menu or toolbar you want to change. 3. Select the command you want to remove, and then click Delete. 4. Click Close. To separate commands on a menu or toolbar 1. On the Tools menu, click Customize. 2. In the Customize dialog box, on the Commands tab, under Choose a menu or toolbar to rearrange, select the menu or toolbar you want to change. 3. Select the command you want to separate from the commands above it. 4. In the Modify Selection list, select Begin a Group. 5. A separator bar appears on the list of commands, above the selected command. 6. Click OK. 7. Click Close. The command appears on the menu or toolbar with a separator before it. To add a new menu 1. On the Tools menu, click Customize. 2. In the Customize dialog box, on the Commands tab, click Add New Menu. The menu appears, named New Menu. 3. In the Modify Selection list, enter the name for the new menu. 4. Click OK. 5. Click Close. The command appears on the menu or toolbar before it. To change the order of menus 1. On the Tools menu, click Customize. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 199 2. In the Customize dialog box, on the Commands tab, under Choose a menu or toolbar to rearrange, select the menu or toolbar you want to move. 3. Select Move Up or Move Down to move the command. 4. Click OK. 5. Click Close. The command appears on the menu or toolbar with a separator before it. To create a toolbar 1. On the Tools menu, click Customize. 2. In the Customize dialog box, on the Toolbars tab, click New. 3. In the New Toolbar dialog box, type a name for the toolbar. 4. Use the steps described earlier in this topic to add commands to the toolbar. Changing Toolbar Layout You can arrange toolbars by dragging them in the main docking area, or by using the Customize dialog box to move them to other docking areas. To arrange toolbars in the main docking area 1. Drag a toolbar by its left edge to move it where you want it. 2. Surrounding toolbars will be automatically rearranged. 3. To change the docking location of a toolbar. 4. On the Tools menu, click Customize. 5. In the Customize dialog box, on the Toolbars tab, on the Modify Selection list, select a dock location. 6. Click Close. For more information about how to improve the usability and accessibility of toolbars, see How to: Set Accessibility Options. Resetting the Main Menu and Shortcut Menus If you change the locations of commands or change command icons, you can reset them to their original configurations. To reset a menu or toolbar 1. On the Tools menu, click Customize. 2. In the Customize dialog box, on the Commands tab, under Choose a menu or toolbar to rearrange, select the menu or toolbar you want to reset. 3. Click Reset all. The selected menu bar, toolbar, or context menu returns to its original configuration. 9.2. Reset Your Settings You can reset the integrated development environment (IDE) to a previous state using the Import and Export Settings wizard. All settings and categories are applied by default; if you want to specify which settings to change, use the option Import selected environment settings. To reset your settings 1. On the Tools menu, click Import and Export Settings. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 200 2. On the Welcome to the Import and Export Settings Wizard page, click Reset all settings, and then click Next. 3. If you want to save your current settings combination, click Yes, save my current settings, specify a file name, and then click Next. —or— If you want to delete your current settings combination, choose No, just reset settings, overwriting my current settings, and then click Next. This option does not delete default settings, which will still be available the next time you use the wizard. 4. In Which collection of settings do you want to reset to, select a settings collection from the list. 5. Click Finish. The Reset Complete page alerts you to any problems encountered during the reset. 9.3. Options Dialog Box The Options dialog box enables you to configure the integrated development environment (IDE) to your needs. For example, you can establish a default save location for your projects, alter the default appearance and behavior of windows, and create shortcuts for commonly used commands. There are also options specific to your development language and platform. You can access Options from the Tools menu. Note:  The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. Layout of the Options dialog box The Options dialog box is divided into two parts: a navigation pane on the left and a display area on the right. The tree control in the navigation pane includes folder nodes, such as Environment, Text Editor, Projects and Solutions, and Source Control. Expand any folder node to list the pages of options that it contains. When you select the node for a particular page, its options appear in the display area. Options for an IDE feature do not appear in the navigation pane until the feature is loaded into memory. Therefore, the same options might not be displayed as you begin a new session that were displayed as you ended the last. When you create a project or run a command that uses a particular application, nodes for relevant options are added to the Options dialog box. These added options will then remain available as long as the IDE feature remains in memory. Note:  Some settings collections scope the number of pages that appear in the navigation pane of the Options dialog box. You can choose to view all possible pages by selecting Show all settings. How options are applied Clicking OK in the Options dialog box saves all settings on all pages. Clicking on Cancel any page cancels all change requests, including any just made on other Options pages. Some changes to option settings, such as those made on Fonts and Colors, Environment, Options Dialog Box, will only take effect after you close and reopen Atmel Studio. 9.3.1. Environment Options The pages in the Environment folder in the Options dialog box let you set how certain elements of the integrated development environment (IDE) display and behave. You can access the Environment pages by clicking Options on the Tools menu, and then clicking Environment. 9.3.1.1. General Environment Settings Items shown in Window menu Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 201 Customizes the number of windows that appear in the Windows list of the Window menu. Type a number between 1 and 24. By default, the number is 10. Items shown in recently used lists Customizes the number of most recently used projects and files that appear on the File menu. Type a number between 1 and 24. By default, the number is 10. This is an easy way to retrieve recently used projects and files. Automatically adjust visual experience based on client performance Specifies whether Atmel Studio sets the adjustment to the visual experience automatically or you set the adjustment explicitly. This adjustment may change the display of colors from gradients to flat colors, or it may restrict the use of animations in menus or pop-up windows. Enable rich client experience Enables the full visual experience of Atmel Studio, including gradients and animations. Clear this option when using Remote Desktop connections or older graphics adapters, because these features may have poor performance in those cases. This option is available only when you clear the Automatically adjust visual experience based on client option. Use hardware graphics acceleration if available Uses hardware graphics acceleration if it is available, rather than software acceleration. Show status bar Displays the status bar. The status bar is located at the bottom of the IDE window and displays information about the progress of ongoing operations. Close button affects active tool window only Specifies that when the Close button is clicked, only the tool window that has focus is closed and not all of the tool windows in the docked set. By default, this option is selected. Auto Hide button affects active tool window only Specifies that when the Auto Hide button is clicked, only the tool window that has focus is hidden automatically and not all of the tool windows in the docked set. By default, this option is not selected. Restore File Associations Registers file types that are typically associated with Atmel Studio. Registration causes Windows to display the correct icons in Windows Explorer, and to recognize Atmel Studio as the correct application for opening these file types. This option can be useful if you have two different versions of Atmel Studio installed on the same computer, and you later uninstall one of the versions. After uninstalling, the icons for Atmel Studio files no longer appear in Windows Explorer. In addition, Windows no longer recognizes Atmel Studio as the default application for editing these files. This option restores those associations. 9.3.1.2. Add-in/Macros Security Add-in Security Settings To enhance security by preventing malicious add-ins from automatically activating, Atmel Studio provides settings in a Tools Options page named Add-in/Macros Security. In addition, this options page allows you to specify the folders in which Atmel Studio searches for .Addin registration files. This enhances security by allowing you to limit the locations where .Addin registration files can be read, helping prevent malicious .Addin files from inadvertently being used. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 202 The settings in the Add-in/Macros Security, Environment, and Options Dialog Box that relate to add-in security are: • Allow add-in components to load. Checked by default. When checked, add-ins are allowed to load in Atmel Studio. When unchecked, add-ins are prohibited from loading in Atmel Studio. • Allow add-in components to load from a URL. Unchecked by default. When checked, add-ins are allowed to be loaded from external Web sites. When unchecked, remote add-ins are prohibited from loading in Atmel Studio. If an add-in cannot load for some reason, then it cannot be loaded from the web. This setting controls only the loading of the add-in DLL. The .Addin registration files must always be located on the local system. Default .Add-In File Search Locations In addition to the security settings, the options page has a list containing folders in which to search for .Addin registration files. By default, the following tokens are included: • %ALLUSERSDOCUMENTS% • %ALLUSERSPROFILE% • %APPDATA% • %VSAPPDATA% • %VSCOMMONAPPDATA% • %VSMYDOCUMENTS% When Atmel Studio begins searching for .AddIn files, it replaces these tokens with the following path strings: Table 9-1. AddIn Files Search Path Tokens Token Path %ALLUSERSDOCUMENTS% %PUBLIC%\Documents %ALLUSERSPROFILE% %ALLUSERSPROFILE% (defined by OS) %APPDATA% %USERPROFILE%\AppData %VSAPPDATA% %USERPROFILE%\AppData\Roaming\Microsoft\AVR Studio 5\ --OR-- %USERPROFILE%\AppData\Local\Microsoft\Atmel Studio 6\ %VSCOMMONAPPDATA% %ProgramData%\Microsoft\Atmel Studio 6\ %VSMYDOCUMENTS% \Atmel Studio 6 Note:  Some of the default paths may resolve to targets that do not exist on your system. You can remove these predefined tokens from the list by highlighting the token and clicking Remove. To add other folders to the search list, click Add and specify a folder in the Browse for Folder dialog box. For more information, see Add-In Registration. 9.3.1.3. AutoRecover Use this page of the Options dialog box to specify whether or not files are automatically backed up. This page also allows you to specify whether or not modified files are restored when the integrated development environment (IDE) shuts down unexpectedly. You can access this dialog box by selecting Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 203 the Tools menu and choosing Options, and then selecting the Environment folder and choosing the AutoRecover page. If this page does not appear in the list, select Show all settings in the Options dialog box. Save AutoRecover information every minutes Use this option to customize how often a file is automatically saved in the editor. For previously saved files, a copy of the file is saved in \...\My Documents\Atmel Studio 6.2\Backup Files \. If the file is new and has not been manually saved, the file is auto-saved using a randomly generated file name. Keep AutoRecover information for days Use this option to specify how long Atmel Studio keeps files created for auto recovery. 9.3.1.4. Find and Replace Use this page of the Options dialog box to control message boxes and other aspects of a find and replace operation. You can access this dialog box from the Tools menu by clicking Options, expanding Environment, and then clicking Find and Replace. If this page does not appear in the list, select Show all settings in the Options dialog box. Display informational messages Select this option to display all Find and Replace informational messages that have the Always show this message option. For example, if you chose not to display the message "Find reached the starting point of the search.", selecting this option would cause this informational message to appear again when you use Find and Replace. If you do not want to see any informational messages for Find and Replace, clear this option. When you have cleared the Always show this message option on some, but not all, Find and Replace informational messages, the Display informational messages check box appears to be filled but not selected. To restore all optional Find and Replace messages, clear this option and then select it again. Note:  This option does not affect any Find and Replace informational messages that do not display the Always show this message option. Display warning messages Select this option to display all cautionary Find and Replace messages that have the Always show this message option. For example, if you chose not to display the Replace All warning message that appears when you attempt to make replacements in files not currently opened for editing, selecting this option would cause this warning message to appear again when you attempt to Replace All. If you do not want to see any cautionary messages for Find and Replace, clear this option. When you have cleared the Always show this message option on some, but not all, Find and Replace warning messages, the Display warning messages check box appears to be filled but not selected. To restore all optional Find and Replace messages, clear this option and then select it again. Note:  This option does not affect any Find and Replace warning messages that do not display the Always show this message option. Automatically populate Find What with text from the editor Select this option to paste the text on either side of the current editor's insertion point into the Find what field when you select any view of the Find and Replace Window window from the Edit menu. Clear this option to use the last search pattern from the previous search as the Find what string. Hide Find and Replace window after a match is located for Quick Find or Quick Replace Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 204 Select this option to automatically close the Find and Replace window when the first match is found for Quick Find. To go to the next match, use the shortcut key for Edit.FindNext, usually F3, or display the Find and Replace window again. 9.3.1.5. Fonts and Colors The Fonts and Colors page of the Options dialog box lets you establish a custom font and color scheme for various user interface elements in the integrated development environment (IDE). You can access this dialog box by clicking Options on the Tools menu, and then selecting the Fonts and Colors page in the Environment folder. If this page does not appear in the list, select Show all settings in the Options dialog box. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Color scheme changes do not take effect during the session in which you make them. You can evaluate color changes by opening another instance of Atmel Studio and producing the conditions under which you expect your changes to apply. Show settings for Lists all of the user interface elements for which you can change font and color schemes. After selecting an item from this list you can customize color settings for the item selected in Display items. Text Editor Changes to font style, size, and color display settings for Text Editor affect the appearance of text in your default text editor. Documents opened in a text editor outside the IDE will not be affected by these settings. For information about changing your default text editor, see How to: Change or Add a Default Editor. Printer Changes to font style, size, and color display settings for Printer affect the appearance of text in printed documents. Note:  As needed, you can select a different default font for printing than that used for display in the text editor. This can be useful when printing code that contains both single-byte and double-byte characters. Statement Completion Changes the font style and size for the text that appears in statement completion pop-up in the editor. Editor Tool tip Changes the font style and size for the text that appears in ToolTips displayed in the editor. Environment Font Changes the font style and size for all IDE user interface elements that do not already have a separate option in Show settings for. For example, this option applies to the Start Page but would not affect the Output window. [All Text Tool Windows] Changes to font style, size, and color display settings for this item affect the appearance of text in tool windows that have output panes in the IDE. For example, Output window, Command window, Immediate window, etc. Note:  Changes to the text of [All Text Tool Windows] items do not take effect during the session in which you make them. You can evaluate such changes by opening another instance of Atmel Studio. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 205 Use Defaults/Use Resets the font and color values of the list item selected in Show settings for. The Use button appears when other display schemes are available for selection. For example, you can choose from two schemes for the Printer. Font (bold type indicates fixed-width fonts) Lists all the fonts installed on your system. When the drop-down menu first appears, the current font for the element selected in the Show settings for field is highlighted. Fixed fonts — which are easier to align in the editor — appear in bold. Size Lists available point sizes for the highlighted font. Changing the size of the font affects all Display items for the Show settings for selection. Display items Lists the items for which you can modify the foreground and background color. Note:  PlainText is the default display item. As such, properties assigned to PlainText will be overridden by properties assigned to other display items. For example, if you assign the color blue to PlainText and the color green to Identifier, all identifiers will appear in green. In this example, Identifier properties override PlainText properties. Some of display items include: Display items Description. Plain Text Text in the editor. Selected Text Text that is included in the current selection when the editor has focus. Inactive Selected Text Text that is included in the current selection when the editor has lost focus. Indicator Margin The margin at the left of the Code Editor where breakpoints and bookmark icons are displayed. Line Numbers Optional numbers that appear next to each line of code. Visible White Space Spaces, tabs and word wrap indicators. Bookmark Lines that have bookmarks. Bookmark is visible only if the indicator margin is disabled. Brace Matching (Highlight) Highlighting that is typically bold formatting for matching braces. Brace Matching (Rectangle) Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 206 Highlighting that is typically a grey rectangle in the background. Breakpoint (Enabled) Specifies the highlight color for statements or lines containing simple breakpoints. This option is applicable only if statement-level breakpoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Breakpoint (Error) Specifies the highlight color for statements or lines containing breakpoints that are in an error state. Applicable only if statement-level breakpoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Breakpoint (Warning) Specifies the highlight color for statements or lines containing breakpoints that are in a warning state. Applicable only if statement-level breakpoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Breakpoint - Advanced (Disabled) Specifies the highlight color for statements or lines containing disabled conditional or hit-counted breakpoints. Applicable only if statement-level breakpoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Breakpoint - Advanced (Enabled) Specifies the highlight color for statements or lines containing conditional or hit-counted breakpoints. Applicable only if statement-level breakpoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Breakpoint - Advanced (Error) Specifies the highlight color for statements or lines containing conditional or hit-counted breakpoints that are in an error state. Applicable only if statement-level breakpoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Breakpoint - Advanced (Warning) Specifies the highlight color for statements or lines containing conditional or hit-counted breakpoints that are in a warning state. Applicable only if statement-level breakpoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Code Snippet Dependent Field A field that will be updated when the current editable field is modified. Code Snippet Field Editable Field when a code snippet is active. Collapsible Text A block of text or code that can be toggled in and out of view within the Code Editor. Comment Code comments. Compiler Error Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 207 Blue squiggles in the editor indicating a compiler error. Coverage Not Touched Area Code that has not been covered by a unit test. Coverage Partially Touched Area Code that has been partially covered by a unit test. Coverage Touched Area Code that has been completely covered by a unit test. Current list location Current line navigated to in a list tool window, such as the Output window or Find Results windows. Current Statement Specifies the highlight color for the source statement or line that indicates the current step position when debugging. Debugger Data Changed The color of text used to display changed data inside the Registers and Memory windows. Definition Window Background The background color of the Code Definition window. Definition Window Current Match The current definition in the Code Definition window. Disassembly File Name The color of text used to display file name breaks inside the Disassembly window. Disassembly Source The color of text used to display source lines inside the Disassembly window. Disassembly Symbol The color of text used to display symbol names inside the Disassembly window. Disassembly Text The color of text used to display op-code and data inside the Disassembly window. Excluded Code that is not to be compiled, per a conditional preprocessor directive such as #if. Identifier Identifiers in code such as the class names, methods names, and variable names. Keyword Keywords for the given language that are reserved. For example: class and namespace. Memory Address The color of text used to display the address column inside the Memory window. Memory Changed The color of text used to display changed data inside the Memory window. Memory Data The color of text used to display data inside the Memory window. Memory Unreadable The color of text used to display unreadable memory areas within the Memory window. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 208 Number A number in code that represents an actual numeric value. Operators such as +, -, and !=. Other Error Other error types not covered by other error squiggles. Currently, this includes rude edits in Edit and Continue. Preprocessor Keyword Keywords used by the preprocessor such as #include. Read-Only Region Code that cannot be edited. For example code displayed in the Code Definition View window or code that cannot be modified during Edit and Continue. Register Data The color of text used to display data inside the Registers window. Register NAT The color of text used to display unrecognized data and objects inside the Registers window. Stale Code Superseded code awaiting an update. In some cases, Edit and Continue cannot apply code changes immediately, but will apply them later as you continue debugging. This occurs if you edit a function that must call the function currently executing, or if you add more than 64 bytes of new variables to a function waiting on the call stack. When this happens, the debugger displays a "Stale Code Warning" dialog box, and the superseded code continues to execute until the function in question finishes and is called again. Edit and Continue applies the code changes at that time. String String literals. Syntax Error Parse errors. Task List Shortcut. If a Task List shortcut is added to a line, and the indicator margin is disabled, the line will be highlighted. Tracepoint (Enabled) Specifies the highlight color for statements or lines containing simple tracepoints. This option is applicable only if statement-level tracepoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Tracepoint (Error) Specifies the highlight color for statements or lines containing tracepoints that are in an error state. This option is applicable only if statement-level tracepoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Tracepoint (Warning) Specifies the highlight color for statements or lines containing tracepoints that are in a warning state. This option is applicable only if statement-level tracepoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Tracepoint - Advanced (Disabled) Specifies the highlight color for statements or lines containing disabled conditional or hit-counted tracepoints. This option is applicable only if statement-level tracepoints are active or the Highlight entire Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 209 source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Tracepoint - Advanced (Enabled) Specifies the highlight color for statements or lines containing conditional or hit-counted tracepoints. This option is applicable only if statement-level tracepoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Tracepoint - Advanced (Error) Specifies the highlight color for statements or lines containing conditional or hit-counted tracepoints that are in an error state. This option is applicable only if statement-level tracepoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Tracepoint - Advanced (Warning) Specifies the highlight color for statements or lines containing conditional or hit-counted tracepoints that are in a warning state. This option is applicable only if statement-level tracepoints are active or the Highlight entire source line for breakpoints or current statement option is selected on General, Debugging, Options Dialog Box. Track Changes after save Lines of code that have been modified since the file was opened but are saved to disk. Track Changes before save Lines of code that have been modified since the file was opened but are not saved to disk. User Types Types defined by users. User Types (Delegates) Type color for delegates. User Types (Enums) Type color used for enums. User Types (Interfaces) Type color for interfaces. User Types (Value types) Type color for value types such as structs in C. Warning Compiler warnings. Warning Lines Path Used for Static Analysis warning lines. XML Attribute Attribute names. XML Attribute Quotes The quote characters for XML attributes. XML Attribute Value Contents of XML attributes. XML Cdata Section Contents of . Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 210 XML Comment The contents of . XML Delimiter XML Syntax delimiters, including <, , ?>, , and [, ]. XML Doc Attribute The value of an XML documentation attribute, such as where the "I" is colorized. XML Doc Comment The comments enclosed in the XML documentation comments. XML Doc Tag The tags in XML documentation comments, such as /// . XML Keyword DTD keywords such as CDATA, IDREF, and NDATA. XML Name Element Names and Processing Instructions target name. XML Processing Instruction Contents of Processing Instructions, not including target name. XML Text Plain Text element content. XSLT Keyword XSLT element names. Item foreground Lists the available colors you can choose for the foreground of the item selected in Display items. Because some items are related, and should therefore maintain a consistent display scheme, changing the foreground color of the text also changes the defaults for elements such as Compiler Error, Keyword, or Operator. Automatic Items can inherit the foreground color from other display items such as Plain Text. Using this option, when you change the color of an inherited display item, the color of the related display items also change automatically. For example, if you selected the Automatic value for Compiler Error and later changed the color of Plain Text to Red, the Compiler Error would also automatically inherit the color Red. Default the color that appears for the item the first time you start AVR Studio 5. Clicking the Use Defaults button resets to this color. Custom Displays the Color dialog box to allow you to set a custom color for the item selected in the Display items list. Note:  Your ability to define custom colors may be limited by the color settings for your computer display. For example, if your computer is set to display 256 colors and you select a custom color from the Color dialog box, the IDE defaults to the closest available Basic color and displays the color black in the Color preview box. Item background Provides a color palette from which you can choose a background color for the item selected in Display items. Because some items are related, and should therefore maintain a consistent display scheme, changing the background color of text also changes the defaults for elements such as Compiler Error, Keyword, or Operator. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 211 Automatic Items can inherit the background color from other display items such as Plain Text. Using this option, when you change the color of an inherited display item, the color of the related display items also change automatically. For example, if you selected the Automatic value for Compiler Error and later changed the color of Plain Text to Red, Compiler Error would also automatically inherit the color Red. Clicking the Use Defaults button resets to this color. Custom Displays the Color dialog box to allow you to set a custom color for the item selected in the Display items list. Bold Select this option to display the text of selected Display items in bold text. Bold text is easier to identify in the editor. Sample Displays a sample of the font style, size, and color scheme for the Show settings for and Display items selected. You can use this box to preview the results as you experiment with different formatting options. 9.3.1.6. Language and International Settings The International Settings page allows you to change the default language when you have more than one language version of the integrated development environment (IDE) installed on your machine. You can access this dialog box by selecting Options from the Tools menu and then choosing International Settings from the Environment folder. If this page does not appear in the list, select Show all settings in the Options dialog box. Any changes you make on this page apply only to the default IDE and do not take effect until the environment is restarted. Language Lists the available languages for the installed product language versions. This option is unavailable unless you have more than one language version installed on your machine. If multiple languages of products or a mixed language installation of products share the environment, the language selection is changed to Same as Microsoft Windows. Caution:  In a system with multiple languages installed, the build tools are not affected by this setting. These tools use the version for last language installed and the tools for the previously installed language are overwritten because the build tools do not use the satellite DLL model. 9.3.1.7. Keyboard Settings The shortcut key combinations in the scheme currently applied, (Default), depend on the settings you have selected as well as any customizations you might have made. For more information about the shortcut keys associated with a settings combination, see Working with Settings. Visual Studio also includes seven other keyboard mapping schemes, each of which differs from the others in the shortcut key combinations assigned by default to various UI elements. For a list of these combinations, organized by mapping scheme, see Pre-defined Keyboard Shortcuts. Commands with shortcut key combinations that are part of the Global scope can be superseded by commands in other scopes depending on the current context of the integrated development environment (IDE). For example, if you are editing a file, commands that are part of the Text Editor scope have precedence over commands in the Global scope that start with the same key combination. For example, if several Global commands have key combinations that start with CTRL + K and the Text Editor also has several commands with key combinations that start with CTRL + K, when you are editing code the Text Editor key combinations will work and the Global key combinations will be ignored. Note:  The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is described in Help depending on your active settings or edition. This Help page Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 212 was written with General Development Settings in mind. To change your settings, from the Tools menu, choose Import and Export Settings. For more information, see Working with Settings. Determine the Shortcut Key Assigned to a Command You can manually search for a command to determine whether or not it has an assigned shortcut key combination. To determine the shortcut key combination for a command 1. On the Tools menu, click Options. 2. Expand the Environment folder and select Keyboard. Note:  If you do not see the Keyboard page, check Show all settings located in the lower left of the Options dialog box. In the Show commands containing box, enter the name of the command without spaces. For example, solutionexplorer. 3. In the list, select the correct command. For example, View.SolutionExplorer. 4. If a shortcut key combination exists for the command, the combination appears in the Shortcut(s) for selected command drop-down list. Create Custom Shortcut Keys You can create new shortcut key combinations for any command or change the shortcut key combination for commands with existing combinations. To create a new shortcut key combination 1. On the Tools menu, click Options. 2. Expand the Environment folder, and select Keyboard. Note:  If you do not see the Keyboard page, check Show all settings located in the lower left corner of the Options dialog box. In the Show commands containing box, enter the name of the command without spaces. For example, solutionexplorer. 3. In the list, select the command you want to assign to a shortcut key combination. 4. On the Use new shortcut in drop-down list, select the feature area in which you want to use the shortcut. For example, you can choose Global if you want the shortcut to work in all contexts. Unless the same shortcut is mapped (as Global) in another editor, you can use it. Otherwise, the editor overrides the shortcut. Note:  The following keys cannot be assigned to a command in Global: PRINT SCRN/SYS RQ, SCROLL LOCK, PAUSE/BREAK, TAB, CAPS LOCK, INSERT, HOME, END, PAGE UP, PAGE DOWN, Windows logo keys, Application key, any of the ARROW keys, or ENTER; NUM LOCK, DEL, or CLEAR on the numeric keypad; or CTRL+ALT+DELETE. 5. Place the cursor in the Press shortcut key(s) box, and then use the keyboard to enter the key combination you intend to use for the command. Note:  Shortcuts can contain the SHIFT, ALT, and/or CTRL keys in combination with letters. Be sure to check the Shortcut currently used by box to see if the key combination is already assigned to another command in the mapping scheme. Press BACKSPACE to delete the key combination, if the combination is already in use, before trying another combination. 6. Click Assign. Note:  Changes made by using the Assign button are not canceled if you click the Cancel button. Exporting and Importing Shortcut Keys Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 213 You can share the shortcut key combinations in the current keyboard mapping scheme by exporting the information to a file so others can import the data. To export shortcut keys only 1. On the Tools menu, choose Import and Export Settings Wizard. 2. Select Export select environment settings and then click Next. 3. Under What settings do you want to export?, clear all categories selected by default. 4. Expand Options and then expand Environment. 5. Select Keyboard and then click Next. 6. For What do you want to name your settings file?, enter a name and then click Finish. To import only shortcut keys 1. On the Tools menu, click Import and Export Settings Wizard. 2. Select Import select environment settings and then click Next. 3. Click No, just import new settings, overwriting my current settings and then click Next. 4. Under My Settings, select the settings file that contains the shortcut keys you want to import, or click Browse to locate the correct settings file. 5. Click Next. 6. Under Which settings do you want to import?, clear all categories. 7. Expand Options and then expand Environment. 8. Select Keyboard and then click Finish. 9.3.1.8. Start-up Page — to Change the Default UI Displayed when You Start Atmel Studio 1. On the Tools menu, chose Options. 2. Expand Environment and then chose Startup. 3. From the At startup drop-down list, chose one of the options. For more information, see Startup, Environment, Options Dialog Box. 4. Click OK. Your changes take affect the next time you start Atmel Studio. Use this page to specify what content or user interface (UI), if any, is displayed when you start Atmel Studio. To access this page, on the Tools menu, click Options, expand Environment, and then click Startup. If this page does not appear in the list in the Options dialog box, select Show all settings. Note:  The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is described in Help depending on your active settings or edition. This Help page was written with General Development settings in mind. To change your settings, on the Tools menu, click Import and Export Settings. At start-up You can specify what you want to view every time you start AVR Studio 5. Open Home Page Displays the default Web page specified by the Home page option in Web Browser, Environment, Options Dialog Box. Load last loaded solution Loads the last saved solution in its previous state. Any files that were open in the solution when it was last closed are opened and displayed when you start Atmel Studio. If no solution is loaded when you exit the product, no solution is loaded when you return. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 214 Show Open Project dialog box Displays the Open Project dialog box when you start Atmel Studio. The dialog box uses the folder set in the Atmel Studio Projects location field of the Projects and Solutions, Environment, Options Dialog Box. Show New Project dialog box Displays the New Project dialog box when you open Atmel Studio. Show empty environment Displays an empty integrated development environment (IDE) when you start Atmel Studio. Show Start Page Displays the Start Page associated with the settings that you have currently applied when you start Atmel Studio. Start Page news channel Specifies the RSS feed used to display content in the Atmel Studio News section of the Start Page. Download content every n minutes Specifies how often the IDE checks for new RSS feed content and product headlines for the Start Page. If this setting is not selected, RSS feed content and product headlines are not downloaded to the Start Page. Customize Start Page If you have custom Start Pages installed, you can specify which Start Page to load. The Customize Start Page drop-down list includes an (Default Start Page) entry to load the default Atmel Studio Start Page, and an entry for each custom Start Page on your system. Any .XAML file in your user start pages directory is considered a custom start page. For more information, see Custom Start Pages. 9.3.1.9. Import and Export Settings Use this page of the Options dialog box to set preferences for saving settings files as well as specifying whether or not to use team settings files stored on a server. You can access this dialog box by selecting Options from the Tools menu and choosing the Import and Export Settings page from the Environment folder. Tip:  If this page does not appear in the list, select Show all setting in the Options dialog box. Note:  The options available in dialog boxes, and the names and locations of menu commands you see, might differ from what is described in Help depending on your active settings or edition. This Help page was written with General Development Settings in mind. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Automatically load and save settings Automatically save my settings to this file: Displays the location and name of the .vssettings file you are currently using. When you close the IDE, any changes you have made, such as moving windows or changing option selections, are saved to the current file. The next time you start the IDE, your settings are loaded. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 215 Team settings Use team settings file: When selected, allows you to navigate to a shared .vssettings file by using the Browse button. This settings file is automatically re-applied each time Atmel Studio detects if a newer version is available. Note:  The location of the team settings file must be specified as a UNC path or local path. URLs and other protocols are not supported paths. 9.3.1.10. Task List This Options page allows you to add, delete, and change the comment tokens that generate Task List reminders. To display these settings, select Options from the Tools menu, expand the Environment folder, and choose Task List. Confirm deletion of tasks When selected, a message box is displayed whenever a User Task is deleted from the Task List, allowing you to confirm the deletion. This option is selected by default. Note:  To delete a Task Comment, use the link to find the comment, and then remove it from your code. Hide full file paths When selected, the File column of the Task List displays only the names of files to be edited, not their full paths. Tokens When you insert a comment into your code whose text begins with a token from the Token List, the Task List displays your comment as new entry whenever the file is opened for editing. You can click this Task List entry to jump directly to the comment line in your code. For more information, see How to: Create Task List Comments. Token List Displays a list of tokens, and allows you to add or remove custom tokens. Comment tokens are case sensitive. Note:  If you do not type the desired token exactly as it appears in the Token List, a comment task will not be displayed in the Task List. Priority Sets the priority of tasks that use the selected token. Task comments that begin with this token are automatically assigned the designated priority in the Task List. Name Enter the token string. This enables the Add button. On Add, this string is included in the Token List, and comments that begin with this name will be displayed in the Task List. Add Enabled when you enter a new Name. Click to add a new token string using the values entered in the Name and Priority fields. Delete Click to delete the selected token from the Token List. You cannot delete the default comment token. Change Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 216 Click to make changes to an existing token using the values entered in the Name and Priority fields. Note:  You cannot rename or delete the default comment token, but you can change its priority level. 9.3.1.11. Web Browser Options Sets options for both the internal Web browser and Internet Explorer. To access this dialog box, click Options on the Tools menu, expand the Environment folder, and select Web Browser. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Attention:  Opening certain files or components from the Web can execute code on your computer. For more information, see Code Access Security. Home page Sets the page displayed when you open the Integrated Development Environment Web Browser. Search page Lets you designate a Search page for the internal Web browser. This location can differ from the search page used by instances of Internet Explorer initiated outside of the integrated development environment (IDE). View Source in Sets the editor used to open a Web page when you choose View Source on the page from the internal Web browser. Source editor Select to view source in the Code and Text Editor. HTML editor Select to view source in the HTML Designer. Use this selection to edit the Web page in one of two views: Design view or the standard text-based Source view. External editor Select to view source in another editor. Specify the path of any editor you choose, for example, Notepad.exe. Internet Explorer Options Click to change options for Internet Explorer in the Internet Properties dialog box. Changes made in this dialog box affect both the internal Web browser and instances of Internet Explorer initiated outside of the Atmel Studio IDE (for example, from the Start menu). 9.3.1.12. Custom Start Pages The Atmel Studio Start Page is a Windows Presentation Foundation (WPF) Extensible Application Markup Language (XAML) page that runs in an Atmel Studio tool window. The Start Page tool window can run Atmel Studio internal commands. When Atmel Studio starts, it opens the current default Start Page. If you have installed a third-party Start Page, you can set that page as the default by using the Options dialog box. Installing and Applying a Custom Start Page Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 217 You can install custom Start Pages by using the Online Gallery section of Extension Manager. You can also install directly from a Web site or local intranet page by locating and opening a .vsix file that contains a custom Start Page, or by copying the Start Page files and pasting them into in the Documents\Atmel Studio\StartPages\ folder on your computer. You can apply a custom Start Page by selecting it in the Options dialog box. Start pages installed by Extension Manager will appear in the Customize Start Page list as [InstalledExtension] Extension Name. Start pages dropped into the \StartPages folder will include a partial file path in the list entry, as shown in the following example. Documents\Atmel Studio 6\StartPages\StartPage.xaml To apply a custom Start Page 1. On the Tools menu, click Options. 2. On the left side of the Options dialog box, expand the Environment node, and then click Startup. 3. In the Customize Start Page list, select the Start Page you want. 4. This list includes every .xaml file in your user Start Pages folder and any installed extensions of type StartPage. 5. Click OK. Troubleshooting It is possible for an error in a third-party Start Page to cause Atmel Studio to crash. If this happens, you can start Atmel Studio in safe mode by adding the /SafeMode switch to the application, i.e. avrstudio5.exe /SafeMode. This prevents the bad Start Page from loading. You can then return to the Options dialog box and reset Atmel Studio to use the default Start Page. 9.3.2. Project Options 9.3.2.1. General Settings Sets the default path of Atmel Studio project folders, and determines the default behavior of the Output window, Task List, and Solution Explorer as projects are developed and built. To access this dialog box, on the Tools menu, click Options, expand Projects and Solutions, and click General. Note:  The options are available in the dialog boxes, and the names and locations of menu commands you see, might differ from what is described in Help depending on your active settings or edition. This Help page was written with the General Development settings in mind. To view or change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Projects location Sets the default location where new projects and solution folders and directories are created. Several dialog boxes also use the location set in this option for folder starting points. For example, the Open Project dialog box uses this location for the My Projects shortcut. User project templates location Sets the default location that is used by the New Project dialog box to create the list of My Templates. For more information, see How to: Locate and Organize Project and Item Templates. User item templates location Sets the default location that is used by the Add New Item dialog box to create the list of My Templates. For more information, see How to: Locate and Organize Project and Item Templates. Always show Error List if build finishes with errors Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 218 Opens the Error List window on build completion, only if a project failed to build. Errors that occur during the build process are displayed. When this option is cleared, the errors still occur but the window does not open when the build is complete. This option is enabled by default. Track Active Item in Solution Explorer When selected, Solution Explorer automatically opens and the active item is selected. The selected item changes as you work with different files in a project or solution, or different components in a designer. When this option is cleared, the selection in Solution Explorer does not change automatically. This option is enabled by default. Show advanced build configurations When selected, the build configuration options appear on the Project Property Pages dialog box and the Solution Property Pages dialog box. When cleared, the build configuration options do not appear on the Project Property Pages dialog box and the Solution Property Pages dialog box for projects that contain one configuration or the two configurations debug and release. If a project has a user-defined configuration, the build configuration options are shown. When deselected, the commands on the Build menu, such as Build Solution, Rebuild Solution, and Clean Solution, are performed on the Release configuration and the commands on the Debug menu, such as Start Debugging and Start Without Debugging, are performed on the Debug configuration. Always show solution When selected, the solution and all commands that act on solutions are always shown in the IDE. When cleared, all projects are created as standalone projects and you do not see the solution in Solution Explorer or commands that act on solutions in the IDE if the solution contains only one project. Save new projects when created When selected, you can specify a location for your project in the New Project dialog box. When cleared, all new projects are created as temporary projects. When you are working with temporary projects, you can create and experiment with a project without having to specify a disk location. Warn user when the project location is not trusted If you attempt to create a new project or open an existing project in a location that is not fully trusted (for example, on a UNC path or an HTTP path), a message is displayed. Use this option to specify whether the message is displayed each time that you attempt to create or open a project in a location that is not fully trusted. Show Output window when build starts Automatically displays the Output Window in the IDE at the outset of solution builds. For more information, see How to: Control the Output Window. This option is enabled by default. Prompt for symbolic renaming when renaming files When selected, displays a message box asking whether or not AVR Studio 5 should also rename all references in the project to the code element. 9.3.2.2. Build and Run Options Determines whether changed files are automatically saved when a project or its solution is built, the maximum number of Visual C++ projects that can build at the same time, and certain default behavior on Run. To access this dialog box, on the Tools menu, click Options, click Projects and Solutions, and then click Build and Run. Save all changes Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 219 Automatically saves changes to the solution file and all project files that were changed since the last build when you press F5, or click Start on the Debug menu or Build on the Build menu. No prompt is given. Items are saved with their current names. By default, this option is enabled. Save changes to open documents only Automatically saves changes to all open documents when you press F5, or click Start on the Debug menu or Build on the Build menu. No prompt is given. Prompt to save all changes When selected, displays a dialog box that asks whether you want to save changes to the solution and project items when you press F5 or click Start on the Debug menu or Build on the Build menu. The Save As dialog box is displayed so that you can assign a name and location to your project. If this option is not selected, the project runs by using the memory image that contains your changes, but the changes are not saved. Don't save any changes When you run your project, the integrated development environment (IDE) runs the code version in the open documents and does not save changes to open documents. Maximum number of parallel project builds Specifies the maximum number of projects that can build at the same time. To optimize the build process, the maximum number of parallel project builds is automatically set to the number of CPUs of your computer. The maximum is 32. For more information, see Multiprocessor Builds. Only build start-up projects and dependencies on Run When selected, pressing F5 or clicking Start on the Debug menu or Build on the Build menu only builds the start-up project and its dependencies. When this option is cleared, pressing F5 builds all projects, dependencies, and solution files. By default, this option is cleared. Always build The message box is not displayed and the out of date project configuration is built. This option is set when you select Do not show this dialog again in the message, and then click Yes. Never build The message box is not displayed and the out of date project configuration is not built. This option is set when you select Do not show this dialog again in the message, and then click No. Prompt to build Displays the message box every time that a project configuration is out of date. Prompt to launch Displays the message box every time that build errors occur. Do not launch The message box is not displayed and the application is not started. This option is set when you select Do not show this dialog again in the message box, and then click No. Launch old version The message box is not displayed and the newly built version of the application is not started. This option is set when you select Do not show this dialog again in the message box, and then click Yes. For new solutions use the currently selected project as the start-up project Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 220 If selected, new solutions use the currently selected project as the start-up project. MSBuild project build output verbosity Sets the verbosity level for the build output. For more information, see the /verbosity switch in MSBuild Command Line Reference. MSBuild project build log file verbosity Sets the verbosity level for the build log file. For more information, see the /verbosity switch in MSBuild Command Line Reference. 9.3.3. Source Control If you have plugins for source control (SVN, ClearCase, Vault, Git, etc.) installed, you should select it from the drop-down list in this section, to activate and use your plugin with the source repository. 9.3.4. Text Editor Options 9.3.4.1. General Settings This dialog box lets you change global settings for the Visual Studio Code and Text Editor. To display this dialog box, click Options on the Tools menu, expand the Text Editor folder, and then click General. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Settings Drag and drop text editing When selected, this enables you to move text by selecting and dragging the text with the mouse to another location within the current document or any other open document. Automatic delimiter highlighting When selected, delimiter characters that separate parameters or item-value pairs, as well as matching braces, are highlighted. Track changes When selected, the code editor's selection margin displays a vertical yellow line to mark code recently changed, and vertical green lines next to unchanged code. Auto-detect UTF-8 encoding without signature By default, the editor detects encoding by searching for byte order marks or charset tags. If neither is found in the current document, the code editor attempts to auto-detect UTF-8 encoding by scanning byte sequences. To disable the auto-detection of encoding, clear this option. Display Selection margin When selected, a vertical margin along the left edge of the editor's text area is displayed. You can click this margin to select an entire line of text, or click and drag to select consecutive lines of text. Selection Margin on / Selection Margin off Indicator margin When selected, a vertical margin outside the left edge of the editor's text area is displayed. When you click in this margin, an icon and ToolTip that are related to the text appear. For example, breakpoint or task list shortcuts appear in the indicator margin. Indicator Margin information does not print. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 221 Vertical scroll bar When selected, a vertical scrollbar which allows you to scroll up and down to view elements that fall outside the viewing area of the Editor is displayed. If vertical scrollbars are not available, you can use the Page Up, Page Down, and cursor keys to scroll. Horizontal scroll bar When selected, a horizontal scrollbar which allows you to scroll from side-to-side to view elements that fall outside the viewing area of the Editor is displayed. If horizontal scrollbars are unavailable, you can use the cursor keys to scroll. 9.3.4.2. File Extensions and Associations There you can specify tool association of the source file extensions. 9.3.4.3. General Language Options This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To open this dialog box, select Options from the Tools menu. Within the Text Editor folder, expand the All Languages sub folder and then select General. Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the General options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the sub folder for that language and select its option pages. A grayed checkmark is displayed when an option has been selected on the General options pages for some programming languages, but not for others. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Statement Completion Auto list members When selected, pop-up lists of available members, properties, values, or methods are displayed by IntelliSense as you type in the editor. Choose any item from the pop-up list to insert the item into your code. Selecting this option enables the Hide advanced members option. For more information, see List Members. Hide advanced members When selected, shortens pop-up statement completion lists by displaying only those items most commonly used. Other items are filtered from the list. Parameter information When selected, the complete syntax for the current declaration or procedure is displayed under the insertion point in the editor, with all of its available parameters. The next parameter you can assign is displayed in bold. For more information, see Parameter Info. Settings Enable virtual space Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 222 When this option is selected and Word wrap is cleared, you can click anywhere beyond the end of a line in the Code Editor, and type. This feature can be used to position comments at a consistent point next to your code. Word wrap When selected, any portion of a line that extends horizontally beyond the viewable editor area is automatically displayed on the next line. Selecting this option enables the Show visual glyphs for word wrap option. Note:  The Virtual Space feature is turned off while Word Wrap is on. Show visual glyphs for word wrap When selected, a return-arrow indicator is displayed where a long line wraps onto a second line. Clear this option if you prefer not to display these indicators. Note:  These reminder arrows are not added to your code, and do not print. They are for reference only. Apply Cut or Copy commands to blank lines when there is no selection This option sets the behavior of the editor when you place the insertion point on a blank line, select nothing, and then Copy or Cut. When this option is selected, the blank line is copied or cut. If you then Paste, a new and blank line is inserted. When this option is cleared, the Cut command removes blank lines. However, the data on the Clipboard is preserved. Therefore, if you then use the Paste command, the content most recently copied onto the Clipboard is pasted. If nothing has been copied previously, nothing is pasted. This setting has no effect on Copy or Cut when a line is not blank. If nothing is selected, the entire line is copied or cut. If you then Paste, the text of the entire line and its endline character are pasted. Tip:  To display indicators for spaces, tabs, and line ends, and thus distinguish indented lines from lines that are entirely blank, select Advanced from the Edit menu and choose View White Space. Display Line numbers When selected, a line number appears next to each line of code. Note:  These line numbers are not added to your code, and do not print. They are for reference only. Enable single-click URL navigation When selected, the mouse cursor changes to a pointing hand as it passes over a URL in the editor. You can click the URL to display the indicated page in your Web browser. Navigation bar When selected, the Navigation bar at the top of the code editor is displayed. Its drop-down Objects and Members lists allow you to choose a particular object in your code, select from its members, and navigates to the declaration of the selected member in the Code Editor. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 223 9.3.4.4. Tabs Dialog This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To display these options, select Options from the Tools menu. Within the Text Editor folder expand the All Languages sub folder, and then choose Tabs. Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the Tabs options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the sub folder for that language and select its option pages. If different settings are selected on the Tabs options pages for particular programming languages, then the message "The indentation settings for individual text formats conflict with each other," is displayed for differing Indenting options; and the message "The tab settings for individual text formats conflict with each other," is displayed for differing Tab options. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Indenting None When selected, new lines are not indented. The insertion point is placed in the first column of a new line. Block When selected, new lines are automatically indented. The insertion point is placed at the same starting point as the preceding line. Smart When selected, new lines are positioned to fit the code context, per other code formatting settings and IntelliSense conventions for your development language. This option is not available for all development languages. For example, lines enclosed between an opening brace ( { ) and a closing brace ( } ) might automatically be indented an extra tab stop from the position of the aligned braces. Tab and indent size Sets the distance in spaces between tab stops and for automatic indentation. The default is four spaces. Tab characters, space characters, or both will be inserted to fill the specified size. Insert spaces When selected, indent operations insert only space characters, not TAB characters. If the Tab and Indent size is set to 5, for example, then five space characters are inserted whenever you press the TAB key or the Increase Indent button on the Formatting toolbar. Keep tabs When selected, each indent operation inserts one TAB character. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 224 9.3.4.5. AVR Assembler Language-specific Settings General Language Options This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To open this dialog box, select Options from the Tools menu. Within the Text Editor folder, expand the All Languages sub folder and then choose General. Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the General options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the sub folder for that language and select its option pages. A grayed checkmark is displayed when an option has been selected on the General options pages for some programming languages, but not for others. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Statement Completion Auto list members When selected, pop-up lists of available members, properties, values, or methods are displayed by IntelliSense as you type in the editor. Choose any item from the pop-up list to insert the item into your code. Selecting this option enables the Hide advanced members option. For more information, see List Members. Hide advanced members When selected it shortens the pop-up statement completion lists by displaying only those items most commonly used. Other items are filtered from the list. Parameter information When selected, the complete syntax for the current declaration or procedure is displayed under the insertion point in the editor, with all of its available parameters. The next parameter you can assign is displayed in bold. For more information, see Parameter Info. Settings Enable virtual space When this option is selected and Word wrap is cleared, you can click anywhere beyond the end of a line in the Code Editor and type. This feature can be used to position comments at a consistent point next to your code. Word wrap When selected, any portion of a line that extends horizontally beyond the viewable editor area is automatically displayed on the next line. Selecting this option enables the Show visual glyphs for word wrap option. Note:  The Virtual Space feature is turned off while Word Wrap is on. Show visual glyphs for word wrap Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 225 When selected, a return-arrow indicator is displayed where a long line wraps onto a second line. Clear this option if you prefer not to display these indicators. Note:  These reminder arrows are not added to your code, and do not print. They are for reference only. Apply Cut or Copy commands to blank lines when there is no selection This option sets the behavior of the editor when you place the insertion point on a blank line, select nothing, and then Copy or Cut. When this option is selected, the blank line is copied or cut. If you then Paste, a new, blank line is inserted. When this option is cleared, the Cut command removes blank lines. However, the data on the Clipboard is preserved. Therefore, if you then use the Paste command, the content most recently copied onto the Clipboard is pasted. If nothing has been copied previously, nothing is pasted. This setting has no effect on Copy or Cut when a line is not blank. If nothing is selected, the entire line is copied or cut. If you then Paste, the text of the entire line and its endline character are pasted. Tip:  To display indicators for spaces, tabs, and line ends, and thus distinguish indented lines from lines that are entirely blank, select Advanced from the Edit menu and choose View White Space. Display Line numbers When selected, a line number appears next to each line of code. Note:  These line numbers are not added to your code, and do not print. They are for reference only. Enable single-click URL navigation When selected, the mouse cursor changes to a pointing hand as it passes over a URL in the editor. You can click the URL to display the indicated page in your Web browser. Navigation bar When selected, displays the Navigation bar at the top of the code editor. Its dropdown Objects and Members lists allow you to choose a particular object in your code, select from its members, and navigates to the declaration of the selected member in the Code Editor. Tabs Dialog This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To display these options, select Options from the Tools menu. Within the Text Editor folder expand the All Languages sub folder, and then choose Tabs. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 226 Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the Tabs options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the sub folder for that language and select its option pages. If different settings are selected on the Tabs options pages for particular programming languages, then the message "The indentation settings for individual text formats conflict with each other," is displayed for differing Indenting options; and the message "The tab settings for individual text formats conflict with each other," is displayed for differing Tab options. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Indenting None When selected, new lines are not indented. The insertion point is placed in the first column of a new line. Block When selected, new lines are automatically indented. The insertion point is placed at the same starting point as the preceding line. Smart When selected, new lines are positioned to fit the code context, per other code formatting settings and IntelliSense conventions for your development language. This option is not available for all development languages. For example, lines enclosed between an opening brace ( { ) and a closing brace ( } ) might automatically be indented an extra tab stop from the position of the aligned braces. Tab and indent size Sets the distance in spaces between tab stops and for automatic indentation. The default is four spaces. Tab characters, space characters, or both will be inserted to fill the specified size. Insert spaces When selected, indent operations insert only space characters, not TAB characters. If the Tab and Indent size is set to 5, for example, then five space characters are inserted whenever you press the TAB key or the Increase Indent button on the Formatting toolbar. Keep tabs When selected, each indent operation inserts one TAB character. 9.3.4.6. AVR GCC Language-specific Settings General Language Options This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To open this dialog box, select Options from the Tools menu. Within the Text Editor folder, expand the All Languages sub folder and then choose General. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 227 Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the General options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the sub folder for that language and select its option pages. A grayed checkmark is displayed when an option has been selected on the General options pages for some programming languages, but not for others. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Statement Completion Auto list members When selected, pop-up lists of available members, properties, values, or methods are displayed by IntelliSense as you type in the editor. Choose any item from the pop-up list to insert the item into your code. Selecting this option enables the Hide advanced members option. For more information, see List Members. Hide advanced members When selected it shortens the pop-up statement completion lists by displaying only those items most commonly used. Other items are filtered from the list. Parameter information When selected, the complete syntax for the current declaration or procedure is displayed under the insertion point in the editor, with all of its available parameters. The next parameter you can assign is displayed in bold. For more information, see Parameter Info. Settings Enable virtual space When this option is selected and Word wrap is cleared, you can click anywhere beyond the end of a line in the Code Editor and type. This feature can be used to position comments at a consistent point next to your code. Word wrap When selected, any portion of a line that extends horizontally beyond the viewable editor area is automatically displayed on the next line. Selecting this option enables the Show visual glyphs for word wrap option. Note:  The Virtual Space feature is turned off while Word Wrap is on. Show visual glyphs for word wrap When selected, a return-arrow indicator is displayed where a long line wraps onto a second line. Clear this option if you prefer not to display these indicators. Note:  These reminder arrows are not added to your code, and do not print. They are for reference only. Apply Cut or Copy commands to blank lines when there is no selection Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 228 This option sets the behavior of the editor when you place the insertion point on a blank line, select nothing, and then Copy or Cut. When this option is selected, the blank line is copied or cut. If you then Paste, a new, blank line is inserted. When this option is cleared, the Cut command removes blank lines. However, the data on the Clipboard is preserved. Therefore, if you then use the Paste command, the content most recently copied onto the Clipboard is pasted. If nothing has been copied previously, nothing is pasted. This setting has no effect on Copy or Cut when a line is not blank. If nothing is selected, the entire line is copied or cut. If you then Paste, the text of the entire line and its endline character are pasted. Tip:  To display indicators for spaces, tabs, and line ends, and thus distinguish indented lines from lines that are entirely blank, select Advanced from the Edit menu and choose View White Space. Display Line numbers When selected, a line number appears next to each line of code. Note:  These line numbers are not added to your code, and do not print. They are for reference only. Enable single-click URL navigation When selected, the mouse cursor changes to a pointing hand as it passes over a URL in the editor. You can click the URL to display the indicated page in your Web browser. Navigation bar When selected, displays the Navigation bar at the top of the code editor. Its drop-down Objects and Members lists allow you to choose a particular object in your code, select from its members, and navigates to the declaration of the selected member in the Code Editor. Tabs Dialog This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To display these options, select Options from the Tools menu. Within the Text Editor folder expand the All Languages subfolder, and then choose Tabs. Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the Tabs options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the subfolder for that language and select its option pages. If different settings are selected on the Tabs options pages for particular programming languages, then the message "The indentation settings for individual text formats conflict with each other," is displayed for differing Indenting options; and the message "The tab settings for individual text formats conflict with each other," is displayed for differing Tab options. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 229 Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Indenting None When selected, new lines are not indented. The insertion point is placed in the first column of a new line. Block When selected, new lines are automatically indented. The insertion point is placed at the same starting point as the preceding line. Smart When selected, new lines are positioned to fit the code context, per other code formatting settings and IntelliSense conventions for your development language. This option is not available for all development languages. For example, lines enclosed between an opening brace ( { ) and a closing brace ( } ) might automatically be indented an extra tab stop from the position of the aligned braces. Tab and indent size Sets the distance in spaces between tab stops and for automatic indentation. The default is four spaces. Tab characters, space characters, or both will be inserted to fill the specified size. Insert spaces When selected, indent operations insert only space characters, not TAB characters. If the Tab and Indent size is set to 5, for example, then five space characters are inserted whenever you press the TAB key or the Increase Indent button on the Formatting toolbar. Keep tabs When selected, each indent operation inserts one TAB character. 9.3.4.7. Plain Text Settings General Language Options This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To open this dialog box, select Options from the Tools menu. Within the Text Editor folder, expand the All Languages subfolder and then choose General. Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the General options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the subfolder for that language and select its option pages. A grayed checkmark is displayed when an option has been selected on the General options pages for some programming languages, but not for others. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 230 Statement Completion Auto list members When selected, pop-up lists of available members, properties, values, or methods are displayed by IntelliSense as you type in the editor. Choose any item from the pop-up list to insert the item into your code. Selecting this option enables the Hide advanced members option. For more information, see List Members. Hide advanced members When selected, it shortens the pop-up statement completion lists by displaying only those items most commonly used. Other items are filtered from the list. Parameter information When selected, the complete syntax for the current declaration or procedure is displayed under the insertion point in the editor, with all of its available parameters. The next parameter you can assign is displayed in bold. For more information, see Parameter Info. Settings Enable virtual space When this option is selected and Word wrap is cleared, you can click anywhere beyond the end of a line in the Code Editor and type. This feature can be used to position comments at a consistent point next to your code. Word wrap When selected, any portion of a line that extends horizontally beyond the viewable editor area is automatically displayed on the next line. Selecting this option enables the Show visual glyphs for word wrap option. Note:  The Virtual Space feature is turned OFF while Word Wrap is ON. Show visual glyphs for word wrap When selected, a return-arrow indicator is displayed where a long line wraps onto a second line. Clear this option if you prefer not to display these indicators. Note:  These reminder arrows are not added to your code, and do not print. They are for reference only. Apply Cut or Copy commands to blank lines when there is no selection This option sets the behavior of the editor when you place the insertion point on a blank line, select nothing, and then Copy or Cut. When this option is selected, the blank line is copied or cut. If you then Paste, a new, blank line is inserted. When this option is cleared, the Cut command removes blank lines. However, the data on the Clipboard is preserved. Therefore, if you then use the Paste command, the content most recently copied onto the Clipboard is pasted. If nothing has been copied previously, nothing is pasted. This setting has no effect on Copy or Cut when a line is not blank. If nothing is selected, the entire line is copied or cut. If you then Paste, the text of the entire line and its endline character are pasted. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 231 Tip:  To display indicators for spaces, tabs, and line ends, and thus distinguish indented lines from lines that are entirely blank, select Advanced from the Edit menu and choose View White Space. Display Line numbers When selected, a line number appears next to each line of code. Note:  These line numbers are not added to your code, and do not print. They are for reference only. Enable single-click URL navigation When selected, the mouse cursor changes to a pointing hand as it passes over a URL in the editor. You can click the URL to display the indicated page in your Web browser. Navigation bar When selected, displays the Navigation bar at the top of the code editor. Its drop-down Objects and Members lists allow you to choose a particular object in your code, select from its members, and navigates to the declaration of the selected member in the Code Editor. Tabs Dialog This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To display these options, select Options from the Tools menu. Within the Text Editor folder expand the All Languages subfolder, and then choose Tabs. Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the Tabs options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the subfolder for that language and select its option pages. If different settings are selected on the Tabs options pages for particular programming languages, then the message "The indentation settings for individual text formats conflict with each other," is displayed for differing Indenting options; and the message "The tab settings for individual text formats conflict with each other," is displayed for differing Tab options. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Indenting None When selected, new lines are not indented. The insertion point is placed in the first column of a new line. Block When selected, new lines are automatically indented. The insertion point is placed at the same starting point as the preceding line. Smart Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 232 When selected, new lines are positioned to fit the code context, per other code formatting settings and IntelliSense conventions for your development language. This option is not available for all development languages. For example, lines enclosed between an opening brace ( { ) and a closing brace ( } ) might automatically be indented an extra tab stop from the position of the aligned braces. Tab and indent size Sets the distance in spaces between tab stops and for automatic indentation. The default is four spaces. Tab characters, space characters, or both will be inserted to fill the specified size. Insert spaces When selected, indent operations insert only space characters, not TAB characters. If the Tab and Indent size is set to 5, for example, then five space characters are inserted whenever you press the TAB key or the Increase Indent button on the Formatting toolbar. Keep tabs When selected, each indent operation inserts one TAB character. 9.3.4.8. XML Settings General Language Options This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To open this dialog box, select Options from the Tools menu. Within the Text Editor folder, expand the All Languages subfolder and then choose General. Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the General options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the subfolder for that language and select its option pages. A grayed checkmark is displayed when an option has been selected on the General options pages for some programming languages, but not for others. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Statement Completion Auto list members When selected, pop-up lists of available members, properties, values, or methods are displayed by IntelliSense as you type in the editor. Choose any item from the pop-up list to insert the item into your code. Selecting this option enables the Hide advanced members option. For more information, see List Members. Hide advanced members When selected, shortens pop-up statement completion lists by displaying only those items most commonly used. Other items are filtered from the list. Parameter information Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 233 When selected, the complete syntax for the current declaration or procedure is displayed under the insertion point in the editor, with all of its available parameters. The next parameter you can assign is displayed in bold. For more information, see Parameter Info. Settings Enable virtual space When this option is selected and Word wrap is cleared, you can click anywhere beyond the end of a line in the Code Editor and type. This feature can be used to position comments at a consistent point next to your code. Word wrap When selected, any portion of a line that extends horizontally beyond the viewable editor area is automatically displayed on the next line. Selecting this option enables the Show visual glyphs for word wrap option. Note:  The Virtual Space feature is turned off while Word Wrap is on. Show visual glyphs for word wrap When selected, a return-arrow indicator is displayed where a long line wraps onto a second line. Clear this option if you prefer not to display these indicators. Note:  These reminder arrows are not added to your code, and do not print. They are for reference only. Apply Cut or Copy commands to blank lines when there is no selection This option sets the behavior of the editor when you place the insertion point on a blank line, select nothing, and then Copy or Cut. When this option is selected, the blank line is copied or cut. If you then Paste, a new, blank line is inserted. When this option is cleared, the Cut command removes blank lines. However, the data on the Clipboard is preserved. Therefore, if you then use the Paste command, the content most recently copied onto the Clipboard is pasted. If nothing has been copied previously, nothing is pasted. This setting has no effect on Copy or Cut when a line is not blank. If nothing is selected, the entire line is copied or cut. If you then Paste, the text of the entire line and its endline character are pasted. Tip:  To display indicators for spaces, tabs, and line ends, and thus distinguish indented lines from lines that are entirely blank, select Advanced from the Edit menu and choose View White Space. Display Line numbers When selected, a line number appears next to each line of code. Note:  These line numbers are not added to your code, and do not print. They are for reference only. Enable single-click URL navigation When selected, the mouse cursor changes to a pointing hand as it passes over a URL in the editor. You can click the URL to display the indicated page in your Web browser. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 234 Navigation bar When selected, displays the Navigation bar at the top of the code editor. Its drop-down Objects and Members lists allow you to choose a particular object in your code, select from its members, and navigates to the declaration of the selected member in the Code Editor. Tabs Dialog This dialog box allows you to change the default behavior of the Code Editor. These settings also apply to other editors based upon the Code Editor, such as the HTML Designer's Source view. To display these options, select Options from the Tools menu. Within the Text Editor folder expand the All Languages subfolder, and then choose Tabs. Caution:  This page sets default options for all development languages. Remember that resetting an option in this dialog will reset the Tabs options in all languages to whatever choices are selected here. To change Text Editor options for just one language, expand the subfolder for that language and select its option pages. If different settings are selected on the Tabs options pages for particular programming languages, then the message "The indentation settings for individual text formats conflict with each other," is displayed for differing Indenting options; and the message "The tab settings for individual text formats conflict with each other," is displayed for differing Tab options. Note:  The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings. Indenting None When selected, new lines are not indented. The insertion point is placed in the first column of a new line. Block When selected, new lines are automatically indented. The insertion point is placed at the same starting point as the preceding line. Smart When selected, new lines are positioned to fit the code context, per other code formatting settings and IntelliSense conventions for your development language. This option is not available for all development languages. For example, lines enclosed between an opening brace ( { ) and a closing brace ( } ) might automatically be indented an extra tab stop from the position of the aligned braces. Tab and indent size Sets the distance in spaces between tab stops and for automatic indentation. The default is four spaces. Tab characters, space characters, or both will be inserted to fill the specified size. Insert spaces When selected, indent operations insert only space characters, not TAB characters. If the Tab and Indent size is set to 5, for example, then five space characters are inserted whenever you press the TAB key or the Increase Indent button on the Formatting toolbar. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 235 Keep tabs When selected, each indent operation inserts one TAB character. XML Formatting Options This dialog box allows you to specify the formatting settings for the XML Editor. You can access the Options dialog box from the Tools menu. Note:  These settings are available when you select the Text Editor folder, the XML folder, and then the Formatting option from the Options dialog box. Attributes Preserve manual attribute formatting Attributes are not reformatted. This is the default. Note:  If the attributes are on multiple lines, the editor indents each line of attributes to match the indentation of the parent element. Align attributes each on their own line Aligns the second and subsequent attributes vertically to match the indentation of the first attribute. The following XML text is an example of how the attributes would be aligned. Auto Reformat On paste from the Clipboard Reformats XML text pasted from the Clipboard. On completion of end tag Reformats the element when the end tag is completed. Mixed Content Preserve mixed content by default Determines whether the editor reformats mixed content. By default, the editor attempts to reformat mixed content, except when the content is found in an xml:space="preserve" scope. If an element contains a mix of text and markup, the contents are considered to be mixed content. The following is an example of an element with mixed content. c:\data\AlphaProject\ test1.txt test2.txt XML Miscellaneous Options This dialog box allows you to change the autocompletion and schema settings for the XML Editor. You can access the Options dialog box from the Tools menu. Note:  These settings are available when you select the Text Editor folder, the XML folder, and then the Miscellaneous option from the Options dialog box. Auto Insert Close tags Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 236 If the autocompletion setting is checked, the editor automatically adds an end tag when you type a right angle bracket (>) to close a start tag, if the tag is not already closed. This is the default behavior. The completion of an empty element does not depend on the autocompletion setting. You can always autocomplete an empty element by typing a backslash (/). Attribute quotes When authoring XML attributes, the editor inserts the =" " characters and positions the caret (^) inside the double quotes. Selected by default. Namespace declarations The editor automatically inserts namespace declarations wherever they are needed. Selected by default. Other markup (Comments, CDATA) Comments, CDATA, DOCTYPE, processing instructions, and other markup are auto-completed. Selected by default. Network Automatically download DTDs and schemas Schemas and document type definitions (DTDs) are automatically downloaded from HTTP locations. This feature uses System.Net with auto-proxy server detection enabled. Selected by default. Outlining Enter outlining mode when files open Turns on the outlining feature when a file is opened. Selected by default. Caching Schemas Specifies the location of the schema cache. The browse button ( ...) opens the Directory Browse dialog box at the current schema cache location. You can select a different directory, or you can select a folder in the dialog, right-click, and choose Open to see what is in the directory. 9.3.5. Debugger 9.3.5.1. Usage In Atmel Studio, you can specify various settings for debugger behavior, including how variables are displayed, whether certain warnings are presented, how breakpoints are set, and how breaking affects running programs. You specify debugger settings in the Options dialog box. To set debugger options On the Tools menu, click Options. In the Options dialog box, open the Debugging folder. In the Debugging folder, choose the category of options you want. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 237 9.3.5.2. AVR Debugger Settings AVR Communication Timeout Shows the timeout delay used for communication with the back-end. If the watchdog detects that timeout is exceeded the back-end is restarted. 20000ms by default. AVR Debugger Path Shows the path to the AVR Debugger. AVR Debugger Port Indicates the Windows Comm API Port number, used by the AVR debugger. 0 by default. RPC transaction times File name to put statistic logging in. This is log data from the communication with the back-end. Empty means no logging. Note that the file must be written to a directory where the user has write permission. E.g. C:/tmp/transactionlog.csv User Tool polling Use internal port polling method for hardware tool discovery, instead of relying on Windows Comm Framework. Must restart Atmel Studio if activated, it may slow down your PC considerably, so use it only if you have errors related to Windows Comm Framework. Disabled by default. 9.3.6. Atmel Software Framework Settings Path of the application used to compare files An application is normally used to compare files in the Atmel Software Framework, as such you must specify a path here. Command line arguments used for file comparison Command line argument macros: • %original - Path of the original Software Framework file. • %mine - Path of the modified file in the local project If the command line for the configured file compare application is FileCompare.exe filepath1 filepath2, specify %original for filepath1 and %mine for filepath2. For example, if configuring WinMerge as the compare application, specify the following command line arguments: %original %mine /s /u. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 238 9.3.7. Builder Figure 9-1. Builder ShellUtils Packages It will list Default, Custom, and installed Shell Utility extensions. ShellUtils Path Based on the package selected the ShellUtils Path will point to the corresponding utilities folder. If you select a custom ShellUtil package then you can configure a custom Shell utilities folder by clicking on ... button. If you select default or installed shell extension package then the path will be read only and point to the package path. Make Configuration You can configure the path to the Make executable by clicking on ... button by default it points to INSTALLDIR\shellUtils\make.exe and you can enable parallel build of projects by checking the box. 9.3.8. Device and Tool Libraries In the Devices sub-menu you can specify the path to custom libraries for your device. In the Tools submenu, you can specify the path to custom tools for your device. 9.3.9. Status Management Contains path to the log files and logging settings. Location Path to the log file. You can change it by clicking and browsing to the desired location. Severity threshold How severe the incident must be in order to generate a log entry. You can choose whether you want to have an output when all operations are successful - OK level, when some unorthodox code is present - Info level, when some operations have been canceled - Cancel setting. If you want to generate output Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 239 only in the case when the code is potentially unstable or erroneous, choose either Warning or Error setting. Component filter Filter messages coming from the source code for standard or custom components in your design. Severity threshold Meaning identical to the Severity threshold for your source code log generation. Use filter Whether the logging process should use a filter to separate components output from your code output. 9.3.10. Text Templating Show security message Display a dialog prompting the user to ensure that the text templates are from a trusted source when a text transformation operation is initiated. 9.3.11. Toolchain Figure 9-2. Toolchain Flavor Configuration Toolchain Toolchain is used to compile, link, and transform the source code to an executable form targeting the AVR devices. By default, AVR Studio has the following Toolchain Type extensions. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 240 Table 9-2. Toolchain Options Toolchain type Language Description AVR Assembler Assembly Used for building 8-Bit Assembler projects Atmel AVR 8-bit C Used for building 8-Bit C/C++ projects C++ Atmel AVR 32-bit C Used for building 32-Bit C/C++ projects C++ Atmel ARM 32-bit C Used for building ARM C/C++ projects C++ 9.3.11.1. Flavor Flavor identifies a particular version of Toolchain extension of a desired Toolchain type. You could have different flavors of same Toolchain type extensions installed for Atmel Studio. Add Flavor 1. Select a Toolchain type for which the new Flavor is to be added. Figure 9-3. Add Toolchain Flavor 2. Enter a new Flavor Name. 3. Configure the Toolchain path for the Flavor. The path should contain desired Toolchain executable, e.g. avr-gcc.exe for Atmel AVR 8-bit. 4. Click the Add button. Set Default Flavor 1. Select a Flavor to set as default. The flavor would be the default for the selected toolchain type. Hence, a new project using the toolchain type, would use the configured Flavor settings. 2. You can view and switch between various Flavors after creating the project through the project properties page shown in Advanced Options. Delete Flavor Pressing the Delete Flavor button deletes the Flavor configuration. Note:  If the customized default flavor is deleted, then the Native flavor will be set as default. Also the projects that were configured with the deleted flavor will be changed to the default flavor of the respective toolchain type when the project is opened the next time. 9.3.12. GDB Settings We can configure architecture specific GDB path in this page. This will override the default toolchain flavor GDB path. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 241 9.4. Code Snippet Manager Code snippets are particularly useful when writing AVR GCC applications. You can use the Code Snippets Manager to add folders to the folder list that the Code Snippet Picker scans for XML .snippet files. Having these building blocks of code at your disposal can facilitate project development. The Code Snippets Manager can be accessed from the Tools menu. 9.4.1. Managing Code Snippets To access the Code Snippets Manager On the Tools menu, click Code Snippets Manager. To add a directory to the Code Snippet Manager 1. In the Language: drop-down list, select the language that you want to add a directory to. 2. Click Add. This opens the Code Snippets Directory window. 3. Select the directory that you want to add to the Code Snippets Manager and click OK. The directory will now be used to search for available code snippets. To remove a directory from the Code Snippet Manager 1. Select the directory that you want to remove. 2. Click Remove. To import a code snippet into the Code Snippet Manager 1. In the Language: drop-down list, select the language that you want to add the code snippet to. 2. Select the existing folder that you want to place the imported code snippet into. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 242 3. Click Import. This opens the Code Snippets Directory window. 4. Select the code snippet file that you want to add to the Code Snippets Manager and click OK. The code snippet is now available for insertion into the code editor. 9.4.2. Code Snippet Manager Layout Language Selects the development language whose code snippet folders are displayed in the folder list. Location Displays the path to the folders in the folder list, or to the code snippet file selected there. Folder list Shows the set of sub-folders, if any, and the code snippet files available for the Language selected. Click any folder to expand it and list its files. Description Displays information on the folder or code snippet file selected in the folder list. When a code snippet file is selected, displays the text from its Author, Description, Shortcut, and Type fields. Add Opens the Code Snippet Directory dialog box. Allows you to navigate to the desired snippets folder on your local drive or server, and include it in the folder list. Remove Removes a selected top-level folder and its contents from the folder list. Does not physically delete the folder. Import Opens the Code Snippet Directory dialog box. Allows you to navigate to the desired snippet on your local drive or server, and add it to an existing code snippet folder. Security Whenever you store a new snippet in a folder accessed by the Code Snippets Manager, you are responsible for ensuring that its code is constructed as securely as the rest of your application. Because using code snippets saves development time, snippets can be reused frequently as you construct applications. You should therefore make sure that model code saved in snippets is designed to address security issues. Development teams should establish procedures to review code snippets for compliance with general security standards. 9.4.3. Modifying Existing Code Snippets IntelliSense Code Snippets are XML files with a .snippet file name extension that can be easily modified using any XML editor, including Atmel Studio. To modify an existing IntelliSense Code Snippet 1. Use the Code Snippets Manager to locate the snippet that you want to modify. 2. Copy the path of the code snippet to the clipboard and click OK. 3. On the File menu, click Open, and click File. 4. Paste the snippet path into the File location box and click OK. 5. Modify the snippet. 6. On the File menu, click Save. You must have write access to the file to save it. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 243 9.5. External Tools You can add items to the Tools menu that allow you to launch external tools from within Visual Studio. For example, you can add an item to the Tools menu to launch utilities such as avrdude or a diffing tool. 9.5.1. Add an External Tool to the Tools Menu You can add a command to the Tools menu to start another application, such as Notepad, from within the integrated development environment (IDE). Figure 9-4. External Tool Dialog The dialog contains a list box where all previously defined external tools are listed. If you have not defined any tool, the list box will be empty. • On the Tools menu, choose External Tools • In the External Tools dialog box, choose Add, and enter a name for the menu option in the Title box Tip:  Type an ampersand before one of the letters in the tool name to create an accelerator key for the command when it appears on the Tools menu. For example, if you use M&y External Tool, the letter 'y' will be the accelerator key. See Assign a Keyboard Shortcut for more information. • In the Command box, enter the path to the file you intend to launch, or choose Browse (...) to navigate to the file. Files types that you can launch include .exe, .bat, .com, .cmd, and .pif. Note:  If the file resides on the system path, you can enter just the file name. If not, enter the full path to the file. • Select Use output window and Close on exit, as appropriate, and then choose OK Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 244 9.5.2. Pass Variables to External Tools You can specify that certain information be passed to a command when it is launched, such as command line switches for console applications. Fill in the Arguments box with the necessary launch arguments, either manually or using the auto-fill button. The auto-fill argument button can provide you with the macros described in the table below. Table 9-3. External Tools Macros Name Argument Description Item Path $(ItemPath) The complete file name of the current source (defined as drive + path + file name); blank if a non-source window is active. Item Directory $(ItemDir) The directory of the current source (defined as drive + path); blank if a non-source window is active. Item File Name $(ItemFilename) The file name of the current source (defined as file name); blank if a non-source window is active. Item Extension $(ItemExt) The file name extension of the current source. Current Line $(CurLine) The current line position of the cursor in the editor. Current Column $(CurCol) The current column position of the cursor in the editor. Current Text $(CurText) The selected text. Target Path $(TargetPath) The complete file name of the item to be built, (defined as drive + path + file name). Target Directory $(TargetDir) The directory of the item to be built. Target Name $(TargetName) The file name of the item to be built. Target Extension $(TargetExt) The file name extension of the item to be built. Binary Directory $(BinDir) The final location of the binary that is being built (defined as drive + path). Project Directory $(ProjectDir) The directory of the current project (defined as drive + path). Project file name $(ProjectFileName) The file name of the current project (defined as drive + path + file name). Solution Directory $(SolutionDir) The directory of the current solution (defined as drive + path). Solution file name $(SolutionFileName) The file name of the current solution (defined as drive + path + file name). Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 245 9.5.3. Initial Directory You can also specify the working directory for the tool or command. For example, if the tool reads file system data from the current directory, the tool requires that certain program components are present in the current directory at start-up. 9.5.4. Run Behavior Underneath the argument boxes you can modify the tool behavior. Use output window - if this box is checked, the tool will output processing information to the Atmel Studio output window, otherwise the output will be suppressed. Close on exit - if the box is checked the tool window, if any will be automatically closed after completing all operations. Prompt for arguments - used for toolchain automation. If the box is checked, external tool will require user intervention to input additional processing parameters, otherwise the tool will be silent. Treat output as Unicode - internationalization option. Some tools have a capacity to output Unicode results for better interpretation. This option allows for correct output rendering if you are using such a tool. 9.5.5. Assign a Keyboard Shortcut To assign a shortcut (accelerator) to a command, add an ampersand (&) in the title of the tool, just before the letter that you want to use as the access key. After the ampersand has been added the accelerator needs to be included as a keyboard shortcut. • On the Tools menu, click Options • Select Keyboard on the Environment page • In the Show commands containing list, type Tools • In the Command names list, locate the appropriate External Command n entry Note:  You can define keyboard shortcuts for up to twenty external tools. External tools are listed as External Command 1-20 in the Command names list. The numbers correspond to the number to the left of the custom external command name on the Tools menu. If the menu command already has a shortcut assigned to it, that information appears in the Shortcuts for selected command list. • Put the cursor in the Press shortcut keys box, and then press the keys you want to assign to the external tool Note:  If the keyboard shortcut is already assigned to another command, the Shortcut currently assigned to list will display that information. • Click Assign 9.6. Predefined Keyboard Shortcuts The Atmel Studio uses the Visual Studio Shell framework from Microsoft Visual Studio 2010 and therefore the integrated development environment (IDE) includes several predefined keyboard shortcut schemes, identical to those in the Visual Studio. When you start Atmel Studio for the first time and select your settings, the associated schemes are automatically set. Thereafter, by using the keyboard options page in the Options dialog box, you can choose from additional schemes and you can also create your own keyboard shortcuts. Designers and Editors, Shared Shortcuts These shortcuts work in both designers and editors. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 246 Command Description General development, web Edit.Copy Copies the selected item to the Clipboard. CTRL+C or CTRL +INSERT Edit.Cut Deletes the selected item from the file and copies it to the Clipboard. CTRL+X or SHIFT +DELETE Edit.CycleClipboardRing Pastes an item from the Clipboard ring to the cursor location in the file. To paste the next item in the Clipboard ring instead, press the shortcut again. CTRL+SHIFT+V Edit.Delete Deletes one character to the right of the cursor. DELETE Edit.Find Displays the Quick tab of the Find and Replace dialog box. CTRL+F Edit.FindAllReferences Displays the list of references for the selected symbol. SHIFT+ALT+F Edit.FindinFiles Displays the In Files tab of the Find and Replace dialog box. CTRL+SHIFT+F Edit.FindNext Finds the next occurrence of the search text. F3 Edit.FindNextSelected Finds the next occurrence of the currently selected text, or the word at the cursor. CTRL+F3 Edit.FindPrevious Finds the previous occurrence of the search text. SHIFT+F3 Edit.FindPreviousSelected Finds the previous occurrence of the currently selected text, or the word at the cursor. CTRL+SHIFT+F3 Edit.FindSymbol Displays the Find Symbol pane of the Find and Replace dialog box. ALT+F12 Edit.GoToFindCombo Puts the cursor in the Find/Command box on the Standard toolbar. CTRL+D Edit.IncrementalSearch Activates incremental search. If incremental search is on, but no input is passed, the previous search query is used. If search input has been found, the next invocation searches for the next occurrence of the input text. CTRL+I Edit.Paste Inserts the Clipboard contents at the cursor. CTRL+V or SHIFT +INSERT Edit.QuickFindSymbol Searches for the selected object or member and displays the matches in the Find Symbol Results window. SHIFT+ALT+F12 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 247 Command Description General development, web Edit.NavigateTo Displays the Navigate To dialog box. CTRL+, Edit.Redo Repeats the most recent action. CTRL+Y or SHIFT+ALT +BACKSPACE or CTRL +SHIFT+Z Edit.Replace Displays the replace options on the Quick tab of the Find and Replace dialog box. CTRL+H Edit.ReplaceinFiles Displays the replace options on the In Files tab of the Find and Replace dialog box. CTRL+SHIFT+H Edit.SelectAll Selects everything in the current document. CTRL+A Edit.StopSearch Stops the current Find in Files operation. ALT+F3, S Edit.Undo Reverses the last editing action. CTRL+Z or ALT +BACKSPACE View.ViewCode For the selected item, opens the corresponding file and puts the cursor in the correct location. CTRL+ALT+0 Text Navigation These shortcuts are for moving around in an open document. Command Description Shortcut Edit.CharLeft Moves the cursor one character to the left. LEFT ARROW Edit.CharRight Moves the cursor one character to the right. RIGHT ARROW Edit.DocumentEnd Moves the cursor to the last line of the document. CTRL+END Edit.DocumentStart Moves the cursor to the first line of the document. CTRL+HOME Edit.GoTo Displays the Go To Line dialog box. CTRL+G Edit.GoToDefinition Navigates to the declaration for the selected symbol in code. ALT+G Edit.GoToNextLocation Moves the cursor to the next item, such as a task in the Task List window or a search match in the Find Results window. Subsequent invocations move to the next item in the list. F8 Edit.GoToPrevLocation Moves the cursor back to the previous item. SHIFT+F8 Edit.IncrementalSearch Starts incremental search. If incremental search is started but you have not typed any characters, recalls the previous pattern. If text has been found, searches for the next occurrence. CTRL+I Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 248 Command Description Shortcut Edit.LineDown Moves the cursor down one line. DOWN ARROW Edit.LineEnd Moves the cursor to the end of the current line. END Edit.LineStart Moves the cursor to the start of the line. HOME Edit.LineUp Moves the cursor up one line. UP ARROW Edit.NextBookmark Moves to the next bookmark in the document. CTRL+K, CTRL +N Edit.NextBookmarkInFolder If the current bookmark is in a folder, moves to the next bookmark in that folder. Bookmarks outside the folder are skipped. If the current bookmark is not in a folder, moves to the next bookmark at the same level. If the Bookmark window contains folders, bookmarks in folders are skipped. CTRL+SHIFT+K, CTRL+SHIFT+N Edit.PageDown Scrolls down one screen in the editor window. PAGE DOWN Edit.PageUp Scrolls up one screen in the editor window. PAGE UP Edit.PreviousBookmark Moves the cursor to the location of the previous bookmark. CTRL+K, CTRL +P Edit.PreviousBookmarkInFolder If the current bookmark is in a folder, moves to the previous bookmark in that folder. Bookmarks outside the folder are skipped. If the current bookmark is not in a folder, moves to the previous bookmark at the same level. If the Bookmark window contains folders, bookmarks in folders are skipped. CTRL+SHIFT+K, CTRL+SHIFT+P Edit.ReverseIncrementalSearch Changes the direction of incremental search to start at the bottom of the file and progress toward the top. CTRL+SHIFT+I Edit.ScrollLineDown Scrolls text down one line. Available in text editors only. CTRL+DOWN ARROW Edit.ScrollLineUp Scrolls text up one line. Available in text editors only. CTRL+UP ARROW Edit.ViewBottom Moves to the last visible line of the active window. CTRL+PAGE DOWN Edit.ViewTop Moves to the first visible line of the active window. CTRL+PAGE UP Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 249 Command Description Shortcut Edit.WordNext Moves the cursor to the right one word. CTRL+RIGHT ARROW Edit.WordPrevious Moves the cursor to the left one word. CTRL+LEFT ARROW View.NavigateBackward Moves to the previously browsed line of code. CTRL+- View.NavigateForward Moves to the next browsed line of code. CTRL+SHIFT+- View.NextError Moves to the next error entry in the Error List window, which automatically scrolls to the affected section of text in the editor. CTRL+SHIFT +F12 View.NextTask Moves to the next task or comment in the Task List window. Visual Assist shortcuts These shortcuts are for Visual Assist. Command Description Shortcut VAssistX.FindReference Find all references to the marked text. SHIFT+ALT+F VAssistX.FindSymbolDialog Opens the symbols dialog listing all symbols in the project. SHIFT+ALT+S VAssistX.GotoImplementation Go to implementation. ALT+G VAssistX.ListMethodsInCurrentFile Opens the list of all methods in the current file. ALT+M VAssistX.OpenCorrespondingFile Opens the corresponding file (i.e. .h/.c). ALT+O VAssistX.OpenFileInSolutionDialog Displays a list of all files in the solution. SHIFT+ALT+O VAssistX.Paste Shows the paste history menu. CTRL+SHIFT+V VAssistX.RefactorContextMenu Shows the refactor context menu. SHIFT+ALT+Q VAssistX.RefactorRename Shows the rename dialog. SHIFT+ALT+R VAssistX.ScopeNext Jump to next scope. ALT+Down Arrow VAssitX.ScopePrevious Jump to previous scope. ALT+Up Arrow Text Selection These shortcuts are for selecting text in an open document. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 250 Command Description Shortcut Edit.CharLeftExtend Moves the cursor one character to the left and extends the current selection. SHIFT+LEFT ARROW Edit.CharLeftExtendColumn Moves the cursor to the left one character, extending the column selection. SHIFT+ALT+LEFT ARROW Edit.CharRightExtend Moves the cursor one character to the right and extends the current selection. SHIFT+RIGHT ARROW Edit.CharRightExtendColumn Moves the cursor to the right one character, extending the column selection. SHIFT+ALT+RIGHT ARROW Edit.DocumentEndExtend Selects the text from the cursor to the last line of the document. CTRL+SHIFT+END Edit.DocumentStartExtend Selects the text from the cursor to the first line of the document. CTRL+SHIFT +HOME Edit.LineDownExtend Extends text selection down one line, starting at the location of the cursor. SHIFT+DOWN ARROW Edit.LineDownExtendColumn Moves the pointer down one line, extending the column selection. SHIFT+ALT+DOWN ARROW Edit.LineEndExtend Selects text from the cursor to the end of the current line. SHIFT+END Edit.LineEndExtendColumn Moves the cursor to the end of the line, extending the column selection. SHIFT+ALT+END Edit.LineStartExtend Selects text from the cursor to the start of the line. SHIFT+HOME Edit.LineStartExtendColumn Moves the cursor to the start of the line, extending the column selection. SHIFT+ALT+HOME Edit.LineUpExtend Selects text up, line by line, starting from the location of the cursor. SHIFT+UP ARROW Edit.LineUpExtendColumn Moves the cursor up one line, extending the column selection. SHIFT+ALT+UP ARROW Edit.PageDownExtend Extends selection down one page. SHIFT+PAGE DOWN Edit.PageUpExtend Extends selection up one page. SHIFT+PAGE UP Edit.SelectCurrentWord Selects the word that contains the cursor or the word to the right of the cursor. CTRL+W Edit.SelectionCancel Cancels the current selection. ESC Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 251 Command Description Shortcut Edit.ViewBottomExtend Moves the cursor and extends the selection to the last line in view. CTRL+SHIFT +PAGE DOWN Edit.ViewTopExtend Extends the selection to the top of the active window. CTRL+SHIFT +PAGE UP Edit.WordNextExtend Extends the selection one word to the right. CTRL+SHIFT +RIGHT ARROW Edit.WordNextExtendColumn Moves the cursor to the right one word, extending the column selection. CTRL+SHIFT+ALT +RIGHT ARROW Edit.WordPreviousExtend Extends the selection one word to the left. CTRL+SHIFT+LEFT ARROW Edit.WordPreviousExtendColumn Moves the cursor to the left one word, extending the column selection. CTRL+SHIFT+ALT +LEFT ARROW Text Viewing These shortcuts are for changing how text is displayed without changing the text itself, for example, by hiding a selected area or by outlining methods. Command Description Shortcut Edit.ClearBookmarks Removes all bookmarks in all open documents. CTRL+K, CTRL+L Edit.CollapseAllOutlining Collapses all regions on the page to show just the outermost groups in the hierarchy; typically the using/imports section and the namespace definition. CTRL+M, CTRL+A Edit.CollapseCurrentRegion Collapses the region that contains the cursor to show just the top line of the region, followed by an ellipsis. Regions are indicated by triangles on the left edge of the document window. CTRL+M, CTRL+S Edit.CollapseTag Hides the selected HTML tag and displays an ellipsis (. . .) instead. You can view the complete tag as a tooltip by putting the mouse pointer over the ellipsis. CTRL+M, CTRL+T Edit.CollapsetoDefinitions Collapses existing regions to provide a high-level view of the types and members in the source file. CTRL+M, CTRL+O Edit.EnableBookmark Enables bookmark usage in current document. Edit.ExpandAllOutlining Expands all collapsed regions on the page. CTRL+M, CTRL+X Edit.ExpandCurrentRegion Expands the current region. Put the cursor on a collapsed region to use this command. CTRL+M, CTRL+E Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 252 Command Description Shortcut Edit.HideSelection Hides the selected text. A signal icon marks the location of the hidden text in the file. CTRL+M, CTRL+H Edit.StopHidingCurrent Removes the outlining information for the currently selected region. CTRL+M, CTRL+U Edit.StopOutlining Removes all outlining information from the whole document. CTRL+M, CTRL+P Edit.ToggleAllOutlining Toggles all previously collapsed outlining regions between collapsed and expanded states. CTRL+M, CTRL+L Edit.ToggleBookmark Sets or removes a bookmark at the current line. CTRL+K, CTRL+K Edit.ToggleOutliningExpansion Toggles the currently selected collapsed region between the collapsed and expanded state. CTRL+M, CTRL+M Edit.ToggleTaskListShortcut Sets or removes a shortcut at the current line. CTRL+K, CTRL+H Edit.ToggleWordWrap Enables or disables word-wrap in an editor. CTRL+E, CTRL+W Edit.ViewWhiteSpace Shows or hides spaces and tab marks. CTRL+R, CTRL+W Text Manipulation These shortcuts are for deleting, moving, or formatting text in an open document. Command Description Shortcut Edit.BreakLine Inserts a new line. ENTER Edit.CharTranspose Swaps the characters on either side of the cursor. For example, AC|BD becomes AB|CD. CTRL+T Edit.CommentSelection Applies comment characters for the current language to the current selection. CTRL+K, CTRL+C Edit.CompleteWord Completes the current word in the completion list. ALT+RIGHT ARROW or CTRL+SPACEBAR Edit.DeleteBackwards Deletes one character to the left of the cursor. BACKSPACE Edit.FormatDocument Formats the current document according to the indentation and code formatting settings specified on the Formatting pane in the Options dialog box, for the current language. CTRL+K, CTRL+D Edit.FormatSelection Formats the current selection according to the indentation and code formatting settings specified on the Formatting pane in the Options dialog box, for the current language. CTRL+K, CTRL+F Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 253 Command Description Shortcut Edit.InsertSnippet Displays the Code Snippet Picker. The selected code snippet will be inserted at the cursor position. CTRL+K, CTRL+X Edit.InsertTab Indents the line of text a specified number of spaces. TAB Edit.LineCut Cuts all selected lines, or the current line if nothing has been selected, to the Clipboard. CTRL+L Edit.LineDelete Deletes all selected lines, or the current line if no selection has been made. CTRL+SHIFT+L Edit.LineOpenAbove Inserts a blank line above the cursor. CTRL+SHIFT+ENTER Edit.LineOpenBelow Inserts a blank line below the cursor. CTRL+ENTER Edit.LineTranspose Moves the line that contains the cursor below the next line. SHIFT+ALT+T Edit.ListMembers Invokes the IntelliSense completion list. CTRL+J Edit.MakeLowercase Changes the selected text to lowercase characters. CTRL+U Edit.MakeUppercase Changes the selected text to uppercase characters. CTRL+SHIFT+U Edit.OvertypeMode Toggles between insert and over-type insertion modes. INSERT Edit.ParameterInfo Displays the name, number, and type of parameters required for the specified method. CTRL+SHIFT +SPACEBAR Edit.SurroundWith Displays the Code Snippet Picker. The selected code snippet will be wrapped around the selected text. CTRL+K, CTRL+S Edit.TabifySelectedLines Replaces spaces with tabs in the selected text. Edit.TabLeft Moves selected lines to the left one tab stop. SHIFT+TAB Edit.UncommentSelection Removes the comment syntax from the current line of code. CTRL+K, CTRL+U Edit.UntabifySelectedLines Replaces tabs with spaces in selected text. Edit.WordDeleteToEnd Deletes the word to the right of the cursor. CTRL+DELETE Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 254 Command Description Shortcut Edit.WordDeleteToStart Deletes the word to the left of the cursor. CTRL+BACKSPACE Edit.WordTranspose Transposes the words on either side of the cursor. For example, |End Sub would be changed to read Sub End|. CTRL+SHIFT+T File and Project Operations These shortcuts are for file and project operations, and can be used anywhere in the IDE. Command Description Shortcut Build.BuildSelection Builds the selected project and its dependencies. Build.BuildSolution Builds all the projects in the solution. F7 Build.Cancel Stops the current build. CTRL+BREAK Build.Compile Creates an object file that contains machine code, linker directives, sections, external references, and function/ data names for the selected file. CTRL+F7 Build.RebuildSolution Rebuilds the solution. CTRL+ALT+F7 File.NewFile Displays the New File dialog box so that you can add a new file to the current project. CTRL+N File.NewProject Displays the New Project dialog box. CTRL+SHIFT+N File.OpenFile Displays the Open File dialog box. CTRL+O File.OpenProject Displays the Open Project dialog box so that you can add existing projects to your solution. CTRL+SHIFT+O File.Print Displays the Print dialog box so that you can select printer settings. CTRL+P File.Rename Lets you modify the name of the item selected in Solution Explorer. F2 File.SaveAll Saves all documents in the current solution and all files in the external files project. CTRL+SHIFT+S File.SaveSelectedItems Saves the selected items in the current project. CTRL+S File.SaveSelectedItemsAs Displays the Save File As dialog box when items are selected in the editor. Project.AddExistingItem Displays the Add Existing Item dialog box, which lets you add an existing file to the current project. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 255 Command Description Shortcut Project.AddNewItem Displays the Add New Item dialog box, which lets you add a new file to the current project. Project.Properties Displays the Project Properties dialog box for the current project in the editing frame. Window Management These shortcuts are for moving, closing, or navigating in tool windows and document windows. Command Description Shortcut View.FullScreen Toggles Full Screen mode ON and OFF. SHIFT+ALT +ENTER Window.ActivateDocumentWindow Closes a menu or dialog box, cancels an operation in progress, or puts focus in the current document window. ESC Window.CloseDocumentWindow Closes the current tab. CTRL+F4 Window.CloseToolWindow Closes the current tool window. SHIFT+ESC Window.Dock Returns a floating tool or document window to its most recent docked location in the IDE. Window.NextDocumentWindow Cycles through the open documents. CTRL+F6 Window.NextDocumentWindowNav Displays the IDE Navigator, with the first document window selected. CTRL+TAB Window.NextPane Moves to the next pane of the current tool or document window. ALT+F6 Window.NextToolWindow Moves to the next tool window. Window.NextToolWindowNav Displays the IDE Navigator, with the first tool window selected. ALT+F7 Window.PreviousDocumentWindow Moves to the previous document in the editor. CTRL+SHIFT+F6 Window.PreviousDocumentWindowNav Displays the IDE Navigator, with the previous document window selected. CTRL+SHIFT +TAB Window.PreviousPane Moves to the previously selected window. SHIFT+ALT+F6 Window.ShowEzMDIFileList Displays a pop-up listing all open documents only. CTRL+ALT +DOWN ARROW Tool Windows Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 256 These shortcuts are for opening tool windows anywhere in the IDE. Command Description Shortcut Tools.CodeSnippetsManager Displays the Code Snippets Manager, which lets you search for and insert code snippets in files. CTRL+K, CTRL+B Tools.GoToCommandLine Puts the pointer in the Find/Command box on the Standard toolbar. CTRL+/ View.BookmarkWindow Displays the Bookmark window. CTRL+K, CTRL+W View.CallHierarchy Displays the Call Hierarchy window. CTRL+ALT+K View.CommandWindow Displays the Command window, where commands can be invoked to make changes to the IDE. CTRL+ALT+A View.EditLabel Lets you change the name of the selected item in Solution Explorer. F2 View.ErrorList Displays the Error List window. CTRL+\, E View.FindSymbolResults Displays the Find Symbol Results window. CTRL+ALT+F12 View.Output Displays the Output window to view status messages at run time. CTRL+ALT+O View.SolutionExplorer Displays Solution Explorer, which lists the projects and files in the current solution. CTRL+ALT+L View.TaskList Displays the Task List window, which displays custom tasks, comments, shortcuts, warnings, and error messages. CTRL+\, T View.WebBrowser Displays the Web Browser window, which lets you view pages on the Internet. CTRL+ALT+R Window.PreviousToolWindow Brings focus to the previous tool-window. Window.PreviousToolWindowNav Displays the IDE Navigator, with the previous tool window selected. SHIFT+ALT+F7 Bookmark Window These shortcuts are for working with bookmarks, either in the Bookmarks window or in the editor. For more information, see . Command Description Shortcut Edit.ClearBookmarks Removes all bookmarks in all open documents. CTRL+K, CTRL+L Edit.EnableBookmark Enables bookmark usage in current document. Edit.NextBookmark Moves to the next bookmark in the document. CTRL+K, CTRL+N Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 257 Command Description Shortcut Edit.NextBookmarkInFolder If the current bookmark is in a folder, moves to the next bookmark in that folder. Bookmarks outside the folder are skipped. If the current bookmark is not in a folder, moves to the next bookmark at the same level. If the Bookmark window contains folders, bookmarks in folders are skipped. CTRL+SHIFT+K, CTRL+SHIFT+N Edit.ToggleBoomark Toggles a bookmark on the current line in the document. CTRL+K, CTRL+K View.BookmarkWindow Displays the Bookmark window. CTRL+K, CTRL +W Edit.PreviousBookmark Moves the cursor to the location of the previous bookmark. CTRL+K, CTRL+P Edit.PreviousBookmarkInFolder If the current bookmark is in a folder, moves to the previous bookmark in that folder. Bookmarks outside the folder are skipped. If the current bookmark is not in a folder, moves to the previous bookmark at the same level. If the Bookmark window contains folders, bookmarks in folders are skipped. CTRL+SHIFT+K, CTRL+SHIFT+P Debugging These shortcuts are for debugging code. Command Description Shortcut Debug.Autos Displays the Auto window, which displays variables used in the current line of code and the previous line of code. CTRL+ALT+V, A Debug.BreakAll Temporarily stops execution of all processes in a debugging session. Available only in Run mode. CTRL+F5 Debug.BreakatFunction Displays the New Breakpoint dialog box. CTRL+B Debug.Breakpoints Displays the Breakpoints dialog box, where you can add, remove, and modify breakpoints. ALT+F9 or CTRL +ALT+B Debug.CallStack Displays the Call Stack window, which displays a list of all active methods or stack frames for the current thread of execution. ALT+7 or CTRL +ALT+C Debug.DeleteAllBreakpoints Clears all the breakpoints in the project. CTRL+SHIFT+F9 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 258 Command Description Shortcut Debug.Disassembly Displays the Disassembly window. CTRL+ALT+D or ALT+8 Debug.EnableBreakpoint Toggles the breakpoint between disabled and enabled. CTRL+F9 Debug.Exceptions Displays the Exceptions dialog box. CTRL+ALT+E Debug.Immediate Displays the Immediate window, where expressions can be evaluated. CTRL+ALT+I Debug.Locals Displays the Locals window, which displays the local variables and their values for each method in the current stack frame. ALT+4 or CTRL +ALT+V, L Debug.Memory1 Displays the Memory 1 window to view large buffers, strings, and other data that do not display clearly in the Watch or Variables windows. CTRL+ALT+M, 1 Debug.Memory2 Displays the Memory 2 window to view large buffers, strings, and other data that do not display clearly in the Watch or Variables windows. CTRL+ALT+M, 2 Debug.Memory3 Displays the Memory 3 window to view large buffers, strings, and other data that do not display clearly in the Watch or Variables windows. CTRL+ALT+M, 3 Debug.Memory4 Displays the Memory 4 window to view large buffers, strings, and other data that do not display clearly in the Watch or Variables windows. CTRL+ALT+M, 4 Debug.Modules Displays the Modules window, which lets you view the .dll or .exe files that are used by the program. In multiprocess debugging, you can right-click and then click Show Modules for all Programs. CTRL+ALT+U Debug.ParallelStacks Opens the Parallel Stacks window. CTRL+SHIFT+D, S Debug.ParallelTasks Opens the Parallel Tasks window. CTRL+SHIFT+D, K Debug.Processes Displays the Processes window. Available in Run mode. CTRL+ALT+Z Debug.QuickWatch Displays the QuickWatch dialog box that has the current value of the selected expression. Available only in Break mode. Use this command to examine the current value of a variable, property, or other expression for which you have not defined a watch expression. CTRL+ALT+Q or SHIFT+F9 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 259 Command Description Shortcut Debug.Registers Displays the Registers window, which displays registers content for debugging native code applications. ALT+5 or CTRL +ALT+G Debug.RunToCursor In Break mode, resumes execution of your code from the current statement to the selected statement. The Current Line of Execution margin indicator appears in the Margin Indicator bar. In Design mode, starts the debugger and executes your code to the pointer location. CTRL+F10 Debug.Start Launches the application under the debugger based off of the settings from the start-up project. When in Break mode, invoking this command will run the application until the next breakpoint. F5 Debug.StepInto Executes code one statement at a time, following execution into method calls. F11 Debug.StepIntoCurrentProcess Available from the Processes window. CTRL+ALT+F11 Debug.StepOver Sets the execution point to the line of code you select. F10 Debug.StopDebugging Stops running the current application under the debugger. CTRL+SHIFT+F5 Debug.Threads Displays the Threads window to view the running threads. CTRL+ALT+H Debug.ToggleBreakpoint Sets or removes a breakpoint at the current line. F9 Debug.Watch1 Displays the Watch window, which displays the values of selected variables or watch expressions. CTRL+ALT+W, 1 Debug.Watch2 Displays the Watch2 window to view the values of selected variables or watch expressions. CTRL+ALT+W, 2 Debug.Watch3 Displays the Watch3 window to view the values of selected variables or watch expressions. CTRL+ALT+W, 3 Debug.Watch4 Displays the Watch4 window to view the values of selected variables or watch expressions. CTRL+ALT+W, 4 Help These shortcuts are for viewing topics in Help and moving among them. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 260 Command Description Shortcut Help.F1Help Displays a topic from Help that corresponds to the user interface that has focus. F1 Help.ManageHelpSettings Displays the Help Library Manager. CTRL+ALT+F1 Help.WindowHelp Displays a topic from Help that corresponds to the user interface that has focus. SHIFT+F1 Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 261 10. Command Line Utility (CLI) Atmel Studio comes with a command line software utility called atprogram.exe. Tip:  You can start a command shell with the PATH set up to run atprogram by clicking on Start > All Programs > Atmel AVR Tools > Atmel Studio 6.2 Command Prompt as shown in the figure below. atprogram.exe can be used to: • Program a .bin .hex or .elf file to a device • Verify that the programming was correct • Read, write, and erase the device memories • Program fuses, lock bits, security bits, user page, and user signature • Program a production file to a device 6 • List out all connected tools • Set interface and interface clock speeds To get help on how to use the utility, execute: atprogram.exe. This will print out the atprogram CLI help text on stdout. 6 The ELF production file format can hold the contents of both Flash, EEPROM and User Signatures (XMEGA devices only) as well as the Fuse- LockBit configuration in one single file. The format is based on the Executable and Linkable Format (ELF). The production file format is currently supported for tinyAVR, megaAVR, and XMEGA. See Creating ELF Files with Other Memory Types for description on how to configure the project in order to generate such files. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 262 11. Frequently Asked Questions Frequently asked questions about Atmel Studio. What is the Atmel USB Driver? The Atmel USB Driver is a cumulative installer that bundles the Jungo USB driver for the AVR tools and the Segger USB Driver for SAM tools. I get an error during installation of the Atmel USB Driver Package. During installation of the Atmel USB Driver Package, you might get the error 0x800b010a - A certificate chain could not be built to a trusted root authority. This means that the certificate that signs the installer could not be validated using the certificate authority built in to Windows. The reason for not being able to validate the certificate is because the certificate chain needs to be updated through Windows Update. Make sure that you have received all updates, so that Windows is able to validate the certificate. If you are not able to update your computer due to the computer being offline or restricted in some way, then the root certificate update can be downloaded from http://support2.microsoft.com/kb/931125. Will Atmel Studio work in parallel with older versions of Atmel Studio, AVR Studio, and AVR32 Studio? Yes, it will work side by side between major and minor versions. Side by side installation with different build numbers are not possible. If you are uninstalling AVR Studio 4.0 or AVR32 Studio be careful when you manually delete folders or registry entries after uninstall, as there might be other keys and folders deployed by Atmel Studio inside the Atmel folder and registry paths. Note that drivers may be incompatible between versions. I have AVR Studio 4 in my PC. When installing Atmel Studio it updated the Jungo USB driver. Will AVR Studio 4 still work? Yes, it will work. If Jungo driver is already present and its version is anything less than the new one, then the installer will update the Jungo driver you already have. The newest Jungo USB driver (version 12) breaks compatibility with older versions. See KB: Downgrading tools for how to switch between Jungo versions. Atmel Studio cannot find any debuggers or programmers when Norton AntiVirus is running. Atmel Studio might not show any connected tools if Norton AntiVirus is running. To make it work make sure Norton AntiVirus allows atprogram.exe to communicate with Atmel Studio by adding atbackend.exe as an exception in the Norton AntiVirus allowed programs. This is the same with any anti-virus program that by default blocks ports. Windows shows a message box with the following message when attempting to run Atmel Studio installer: "Windows cannot access the specified device, path or file. You may not have the appropriate permissions to access the item. " This might be caused by an anti-virus program blocking the installation of the Atmel Studio. We have seen this with the Sophos antivirus package. Temporarily disable the Sophos service running on the machine (or any corresponding anti-virus service), and attempt installation. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 263 Atmel Studio takes a very long time to start, but runs well in a VM environment. The Visual Studio shell (and thus Atmel Studio) does a considerable amount of processing during start-up. Parts of the operations are WPF operations which benefits greatly by updated graphics libraries and drivers. Installing the latest graphics driver may give a performance boost both during normal operation and during start-up. Verification and programming often fails with a serial port buffer overrun error message when using STK500. This is a known issue. Due to DPC latency, serial communication can have buffer overruns on the UART chipset. A workaround which works for most systems is to use an USB to serial adapter. When launching from a guest account, the following error is displayed when starting Atmel Studio: "Exception has been thrown by the target of an invocation". Atmel Studio neither installs under guest account and nor runs under it. Can install and run Atmel Studio from within a Virtual Machine. Yes, with simulator there should be no issues. However with physical devices like debuggers and programmers, the VM must offer support for physical USB and Serial port connections. How can I reduce the startup time of Atmel Studio? • Make sure you have uninstalled unwanted extensions • Disable Allow Add-in components to load: 2.1. Go to Tools, Options, Add-in/Macro Security. 2.2. Then uncheck the Allow Add-in components to load option. • Disable the start-up page: 3.1. Go to Tools, Options, Environment, Startup, At Startup. 3.2. Select the Show empty environment option. How to improve studio performance for any supported version of Windows? • Make sure your system has the latest version of the Windows Automation API • Exclude the following directories and files from your antivirus scanner: – The Atmel Studio installation directory, and all files and folders inside it – %AppData%\Roaming\Atmel directory, and all files and folders inside it – %AppData%\Local\Atmel directory, and all files and folders inside it – Your project directories • Visual Studio Shell requires a lot of swap space. Increase the paging file. Also put the system to maximize performance. Both options are found in the System, Properties, Performance, Settings menu. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 264 Should I install the latest Windows Automation API 3.0? Yes, if your OS is any of the following: • Windows Server 2008 How can I make sure my system has the latest Windows Automation API 3.0? Your system has the latest Windows Automation API if you have Windows 7 or Windows 8. Only Windows XP, Windows Vista, Windows Server 2003, and Windows Server 2008 have the old version of the API. Find the UIAutomationCore.dll file in your system (normally found in the windows folder) and compare the version number of that file. The version should be 7.X.X.X. for the new API. The latest API can be found at http://support.microsoft.com/kb/971513. My Project is large and it takes a long time to open. Is there any option to avoid this delay? Visual Assist X parses all the files when we opening the existing project. You could disable this option: 1. Go to VAssistX, Visual Assist X Options, Performance. 2. Uncheck the Parse all files when opening the project. I have the limited RAM size in my system and I work long hours in the same instance of Atmel Studio. After some time, Atmel Studio becomes slow on my system. Press Ctrl+Shift+Alt+F12 twice to force Atmel Studio to garbage collect. Does Atmel Studio perform better on multi-core processors than on singlecore systems? Yes, Atmel Studio performs better on a multi-core system. How can I make my projects build faster? You can enable parallel build Option from Tools, Options, Builder, GNU Make, Make Parallel Execution Of Build. This option will enable the parallel execution feature in the GNU make utility. This option may cause the build log to be displayed unordered. 11.1. Compatibility with Legacy AVR Software and Third-party Products 11.1.1. How do I Import External ELF Files for Debugging? Use the File → Open object file for debugging. 11.1.2. How do I Reuse My AVR Studio 4 Projects with the New Atmel Studio? 1. Click the menu File→Import AVR Studio 4 project. 2. An "Import AVR Studio 4 Project" dialog will appear. 3. Type in the name of your project or browse to the project location by clicking the Browse button of the APFS File location Tab. 4. Name the new solution resulting from the conversion of your project in the Solution Folder Tab. 5. Click Next. 6. Atmel Studio will proceed with conversion. Depending on the complexity and specificity of your project there might be some warnings and errors. They will be shown in the Summary window. 7. Click Finish to access your newly converted project. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 265 11.2. Atmel Studio Interface 11.2.1. How can I Start Debugging My Code? What is the Keyboard Shortcut for Debugging? Unlike the AVR Studio 4 to build your project, without starting debugging, you should press F7. If you need to rebuild your project after a change to the source files, press Ctrl Alt F7 . To Start debugging - press F5. To open the Debugging Interface without running directly, press the Debug→Start Debugging and Break menu button, or press F11. To start a line-by-line debugging press F10, to start an instruction by instruction debugging session - press F11. To run your project without debugging, press the Debug→Start Without Debugging menu button. 11.2.2. What is a Solution? A solution is a structure for organizing projects in Atmel Studio. The solution maintains the state information for projects in .sln (text-based, shared) and .suo (binary, user-specific solution options) files. 11.2.3. What is a Project A project is a logic folder that contains references to all the source files contained in your project, all the included libraries and all the built executables. Projects allow seamless reuse of code and easy automation of the build process for complex applications. 11.2.4. How can I use an External Makefile for my Project? The usage of external makefiles and other project options can be configured in the project properties. Remember that an external makefile has to contain the rules needed by Atmel Studio to work. 11.2.5. When Watching a Variable, the Debugger says Optimized away Most compilers today are what is known as an optimizing compiler. This means that the compiler will employ a number of tricks to reduce the size of your program, or speed it up. Note:  This behavior is usually controlled by the -On switches. The cause of this error is usually trying to debug parts of code that does nothing. Trying to watch the variable a in the following example may cause this behavior. int main() { int a = 0; while (a < 42) { a += 2; } } The reason for a to be optimized away is obvious as the incrementation of a does not affect any other part of our code. This example of a busy wait loop is a prime example of unexpected behavior if you are unaware of this fact. To fix this, either lower the optimization level used during compilation, or preferably declare a as volatile. Other situations where a variable should be declared volatile is if some variable is shared between the code and a ISR7 . For a thorough walk through of this issue, have a look at Cliff Lawsons excellent tutorial on this issue. 7 Interrupt Service Routine Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 266 11.2.6. When Starting a Debug Session, I get an Error Stating that Debug Tool is not Set The reason for this message is that there are no tool capable to debug that are selected for your project. Go to the Tool project pane and change the to a supported tool. If the tool you have selected does support debug, then check that the correct interface is chosen and that the frequency is according to the specification. If the issue persist, try to lower the frequency to a frequency where programming is stable, and then slowly increase the frequency as long as it keeps stable. 11.3. Performance Issues 11.3.1. Atmel Studio Takes a Very Long Time to Start on My PC, but Runs Well in a VM Environment. Is there Something I Can do With This? Visual Studio shell (and thus Atmel Studio) uses WPF as a graphics library and does a lot of processing in the GUI thread. WPF has support for hardware acceleration. Some graphics card drivers does not utilize this well and spend time in kernel space even when no graphics update is required. Installing the latest graphics driver may give a performance boost. 11.3.2. Verification and Programming often Fails with a Serial Port Buffer Overrun Error Message when using STK500 This is a known issue. Interrupt DPC latency for serial communication may be disrupted by other drivers, thus causing buffer overruns on the UART chipset. A workaround which works for most systems is to use a USB to serial adapter. 11.3.3. I've connected my Tool through a USB Hub, and now I get Error Messages and Inconsistent Results while Programming and Debugging Tools and devices should be connected directly to an USB port on your debugging PC. If this is not an option, you may reduce/eliminate problems by: • Disconnect any other USB devices connected to the hub • Switch ports on the USB hub • Set the tool clock frequency low. E.g. Set JTAG Clock < 600kHz. • If Use external reset is an option for your tool/device combination, enable this Note:  The AVR Dragon should be connected through a powered USB hub. This because the power supply on the Dragon can be too weak if the motherboard does not provided enough power. If the Dragon times out or freezes, then the hub might be of to low quality. 11.4. Driver and USB Issues 11.4.1. How do I get my Tool to be Recognized by Atmel Studio? This should happen automatically, but sometimes the Windows driver does not recognize the tool correctly. To correct this, you have to check that the tool is listed under the Jungo item in the device manager in Windows. If your tool is not listed, try to find it under Unknown devices. If it is located there, try to reinstall the driver by double clicking the tool, click the Driver tab and choose Update Driver. Let Windows search for the driver. The driver should be reinstalled and the tool should be displayed under Jungo. Now, the tool should be usable from Atmel Studio. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 267 11.4.2. The Firmware upgrade Process fails or is Unstable on a Virtualized Machine Most tools will perform a reset when asked to switch from normal operation mode to firmware upgrade mode. This forces the tool to re-enumerate on the USB bus, and the virtualization software may not reattach to it making your virtualized system with a disconnected tool. Normal virtualization software supports the idea of USB filters where you set a collection of USB devices you want to automatically attach to a given guest operating system. Check the manual for your virtualization solution to see how this is done, or see the Firmware Upgrade Fails on VirtualBox. 11.4.3. Debugging never Breaks under a Virtualized Machine Some virtualization solutions have a limit on how many USB endpoints it supports. This may become an issue if the number of endpoints is lower than the required number for the tool. Usually this causes programming to work as expected but debug not to work as debug events are transmitted on a higher endpoint number. Check with your virtualization software how many endpoints are available, and on other endpoint specific issues with your virtualization software regarding this. 11.4.4. No Tool is recognized by Atmel Studio, but the Driver seems to be Working On some systems the Jungo driver is known not to activate properly. This can be seen as the WinDriver unit under Jungo in the device manager in Windows is missing. To remedy this, try the following: 1. In your Device Manager, right click on your computer name (the very top item) and choose Add Legacy Hardware. 2. Click next, and choose to install the hardware manually. 3. Choose the Show All Devices item on the top of the list, and click next. 4. Click the Have Disk button. 5. Navigate to the folder Atmel USB which is located under the install directory for Atmel Studio (typical location is C:\Program Files (x86)\Atmel\Atmel USB. 6. Choose the usb32 or usb64 folder depending on the architecture you are running. 7. Inside there should be only one file named windrvr#.inf, where the hash is the revision number for the driver. Double click this, click OK, and the WinDriver should appear in the list. If you get an error message, you probably have chosen the wrong architecture. 8. Click Next until finished. 9. Verify that the WinDriver has appeared under Jungo. The tools should be working straight away, but you may have to restart your machine if you are still having problems. 11.4.5. Firmware Upgrade Fails on VirtualBox When doing a firmware upgrade on any tool, the tool needs to be reconnected in another mode than the one used during regular operation. This causes the tool to be re-enumerated, and can cause the tool to be disconnected from the VirtualBox instance and returned to the host operating system. To make the tool connect automatically to the VirtualBox instance, you need to set up a couple of USB filters. More information on USB filters can be found in the VirtualBox documentation. Make two filters that are similar to the two shown in the figure below. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 268 Figure 11-1. VirtualBox USB Filter Note that the example in the figure above is specific for the JTAGICE mkII. There are one entry for the tool, here the JTAGICE mkII, and one for AVRBLDR, which is the firmware upgrade mode for the tool. The name, serial, Vendor ID, and Product ID may be different for your tool, so change those values accordingly. Note:  This section contains specifics to VirtualBox. The same logic applies to other virtualization software, but the steps may differ. 11.4.6. Common Jungo USB Errors Jungo is the driver stack that is used for older programmers and debuggers, up to the JTAGICE3. Common Jungo USB Error Codes Table 11-1. Common Jungo USB Errors Error Cause Resolution Internal system error USB subsystem malfunctions Reinstall driver and check Driver and USB Issues page Conflict between read and write operations Directional error in data Disconnect and reconnect the tool Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 269 Error Cause Resolution Data mismatch Expected and received/sent data error Make sure that you use the latest driver for your USB controller and the latest firmware for your tool Packet size is zero Sent or received a zero packet Insufficient resources Unable to set up send/receive buffers due to memory limitation Free more memory or try to restart your machine USB descriptor error Error in control data on USB bus Try connection tool to another USB port Wrong unique ID Device not found Wrong unique ID Timeout expired Error Cause Resolution 11.4.7. Issues with ARM Compatible Tools In some rare instances all ARM compatible tools disappears from Atmel Studio. This has been tracked down to different dll load strategies used in different versions of Windows. To check that it is a dll load error, try to read out the chip information using atprogram. This can be done by opening the Atmel Studio command prompt from the Tools menu inside Atmel Studio or from the start menu. In the command prompt, enter the following command and check that it does not fail. atprogram -t -i -d info In the snippet above, replace with the tool name, e.g. atmelice, samice, or edbg. Likewise, replace interface with the used interface and the device with the full device name, e.g. atsam3s4c. Invoking the above command should output information about the memory layout, the supply voltage for the chip, and the fuse settings. If it fails it is likely a driver issue, which is covered by Driver and USB Issues. If atprogram is able to communicate with the device it means that the issue is most likely a wrong version of JLinkArm.dll being loaded due to loader precedence. To check this, use the Procmon tool to check what dll is being loaded. Download the Procmon tool, open it, and configure the filter shown in the figure below. Then start Atmel Studio. A couple of seconds after Atmel Studio has started, one line should become visible showing the path to where the dll is being loaded from. It should be loaded from the atbackend folder inside the Atmel Studio installation directory. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 270 Figure 11-2. Procmon Filter Configuration If the path of the dll is different it means that Atmel Studio has picked up the wrong dll, and this dll is incompatible with the dll shipped with Atmel Studio. An example of this is shown in the figure below. Figure 11-3. Procmon Filter Configuration To solve the above issue, we recommend backing up the dll that is being loaded and then replacing it with the JLinkARM.dll found in the atbackend directory inside the Atmel Studio installation directory. This can be done given the assumption that the dll bundled with Atmel Studio is newer than the one that is being loaded, and the dll is backwards compatible. Note:  Remember to back up the offending JLinkARM.dll before replacing it, as it is not given that it will be compatible with the program that deployed it. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 271 12. Document Revision History Doc Rev. Date Comments 42167B 09/2016 Section "Power Debugger" is added 42167A 07/2016 Initial document release. Atmel Atmel Studio [USER GUIDE] Atmel-42167B-Atmel-Studio_User Guide-09/2016 272 Index A AsmToolchainOptions 3, 60 Atmel Studio 1 AVR Studio 1 C Choose file 201 D Device selection 26, 33 T ToolchainOptions 5, 163, 173 Atmel Corporation 1600 Technology Drive, San Jose, CA 95110 USA T: (+1)(408) 441.0311 F: (+1)(408) 436.4200 | www.atmel.com © 2016 Atmel Corporation. / Rev.: Atmel-42167B-Atmel-Studio_User Guide-09/2016 Atmel® , Atmel logo and combinations thereof, Enabling Unlimited Possibilities® , AVR® , megaAVR® , STK® , tinyAVR® , XMEGA® , and others are registered trademarks or trademarks of Atmel Corporation in U.S. and other countries. ARM® , ARM Connected® logo, Cortex® , and others are the registered trademarks or trademarks of ARM Ltd. Windows® is a registered trademark of Microsoft Corporation in U.S. and or other countries. Other terms and product names may be trademarks of others. DISCLAIMER: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN THE ATMEL TERMS AND CONDITIONS OF SALES LOCATED ON THE ATMEL WEBSITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS AND PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and products descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life. SAFETY-CRITICAL, MILITARY, AND AUTOMOTIVE APPLICATIONS DISCLAIMER: Atmel products are not designed for and will not be used in connection with any applications where the failure of such products would reasonably be expected to result in significant personal injury or death (“Safety-Critical Applications”) without an Atmel officer's specific written consent. Safety-Critical Applications include, without limitation, life support devices and systems, equipment or systems for the operation of nuclear facilities and weapons systems. Atmel products are not designed nor intended for use in military or aerospace applications or environments unless specifically designated by Atmel as military-grade. Atmel products are not designed nor intended for use in automotive applications unless specifically designated by Atmel as automotive-grade.

Atmel-8291C-AVR-XMEGA B -09/2014 This document contains complete and detailed description of all modules included in the Atmel®AVR®XMEGA® B microcontroller family. The Atmel AVR XMEGA B is a family of lowpower, high-performance, and peripheral-rich CMOS 8/16-bit microcontrollers based on the AVR enhanced RISC architecture with integrated LCD controller. The available Atmel AVR XMEGA B modules described in this manual are: z Atmel AVR CPU z Memories z DMAC - Direct memory access controller z Event system z System clock and clock options z Power management and sleep modes z System control and reset z WDT - Watchdog timer z Interrupts and programmable multilevel interrupt controller z PORT - I/O ports z TC - 16-bit timer/counters z AWeX - Advanced waveform extension z Hi-Res - High resolution extension z RTC - Real-time counter z USB - Universal serial bus interface z TWI - Two-wire serial interface z SPI - Serial peripheral interface z USART - Universal synchronous and asynchronous serial receiver and transmitter z IRCOM - Infrared communication module z AES and DES cryptographic engine z CRC - Cyclic redundancy check z LCD - Liquid Crystal Display controller z ADC - Analog-to-digital converter z AC - Analog comparator z IEEE 1149.1 JTAG interface z PDI - Program and debug interface z Memory programming z Peripheral address map z Register summary z Interrupt vector summary z Instruction set summary 8-bit Atmel XMEGA B Microcontroller XMEGA B MANUAL XMEGA B [MANUAL] 2 Atmel-8291C-AVR-XMEGA B -09/2014 1. About the Manual This document contains in-depth documentation of all peripherals and modules available for the Atmel AVR XMEGA B microcontroller family. All features are documented on a functional level and described in a general sense. All peripherals and modules described in this manual may not be present in all Atmel AVR XMEGA B devices. For all device-specific information such as characterization data, memory sizes, modules, peripherals available and their absolute memory addresses, refer to the device datasheets. When several instances of a peripheral exists in one device, each instance will have a unique name. For example each port module (PORT) have unique name, such as PORTA, PORTB, etc. Register and bit names are unique within one module instance. For more details on applied use and code examples for peripherals and modules, refer to the Atmel AVR XMEGA specific application notes available from http://www.atmel.com/avr. 1.1 Reading the Manual The main sections describe the various modules and peripherals. Each section contains a short feature list and overview describing the module. The remaining section describes the features and functions in more detail. The register description sections list all registers and describe each register, bit and flag with their function. This includes details on how to set up and enable various features in the module. When multiple bits are needed for a configuration setting, these are grouped together in a bit group. The possible bit group configurations are listed for all bit groups together with their associated Group Configuration and a short description. The Group Configuration refers to the defined configuration name used in the Atmel AVR XMEGA assembler header files and application note source code. The register summary sections list the internal register map for each module type. The interrupt vector summary sections list the interrupt vectors and offset address for each module type. 1.2 Resources A comprehensive set of development tools, application notes, and datasheets are available for download from http://www.atmel.com/avr. 1.3 Recommended Reading z Atmel AVR XMEGA B device datasheets z AVR XMEGA application notes This manual contains general modules and peripheral descriptions. The AVR XMEGA B device datasheets contains the device-specific information. The XMEGA application notes and Atmel Software Framework contain example code and show applied use of the modules and peripherals. For new users, it is recommended to read the AVR1000 - Getting Started Writing C Code for Atmel XMEGA. XMEGA B [MANUAL] 3 Atmel-8291C-AVR-XMEGA B -09/2014 2. Overview The AVR XMEGA B microcontrollers is a family of low-power, high-performance, and peripheral-rich CMOS 8/16-bit microcontrollers based on the AVR enhanced RISC architecture. By executing powerful instructions in a single clock cycle, the Atmel AVR XMEGA B devices achieve throughputs approaching one million instructions per second (MIPS) per megahertz, allowing the system designer to optimize power consumption versus processing speed. The AVR CPU combines a rich instruction set with 32 general purpose working registers. All 32 registers are directly connected to the arithmetic logic unit (ALU), allowing two independent registers to be accessed in a single instruction, executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs many times faster than conventional single-accumulator or CISC based microcontrollers. The Atmel AVR XMEGA B devices provide the following features: in-system programmable flash with read-while-write capabilities; internal EEPROM and SRAM; two-channel DMA controller; four-channel event system and programmable multilevel interrupt controller; up to 53 general purpose I/O lines; 16-bit real-time counter (RTC); up to three flexible 16-bit timer/counters with capture, compare and PWM modes; up to two USARTs; one I2 C and SMBUS compatible two-wire serial interface (TWI); one full-speed USB 2.0 interface; one serial peripheral interface (SPI); one LCD controller supporting display capacity up to 4 Common and up to 40 Segment terminals; CRC module; AES and DES cryptographic engine; up to two 8-channel, 12-bit ADCs with programmable gain; up to four analog comparators with window mode; programmable watchdog timer with separate internal oscillator; accurate internal oscillators with PLL and prescaler; and programmable brown-out detection. The program and debug interface (PDI), a fast, two-pin interface for programming and debugging, is available. Selected devices also have an IEEE std. 1149.1 compliant JTAG interface, and this can also be used for on-chip debug and programming. The Atmel AVR XMEGA devices have five software selectable power saving modes. The idle mode stops the CPU while allowing the SRAM, DMA controller, event system, interrupt controller, and all peripherals to continue functioning. The power-down mode saves the SRAM and register contents, but stops the oscillators, disabling all other functions until the next TWI, USB resume, or pin-change interrupt, or reset. In power-save mode, the asynchronous real-time counter continues to run, allowing the application to maintain a timer base while the rest of the device is sleeping. In this mode, the LCD controller is allowed to refresh data to the panel. In standby mode, the external crystal oscillator keeps running while the rest of the device is sleeping. This allows very fast startup from the external crystal, combined with low power consumption. In extended standby mode, both the main oscillator and the asynchronous timer continue to run. In this mode, the LCD controller is allowed to refresh data to the panel. To further reduce power consumption, the peripheral clock to each individual peripheral can optionally be stopped in active mode and idle sleep mode. The devices are manufactured using Atmel high-density, nonvolatile memory technology. The program flash memory can be reprogrammed in-system through the PDI or JTAG interfaces. A boot loader running in the device can use any interface to download the application program to the flash memory. The boot loader software in the boot flash section will continue to run while the application flash section is updated, providing true read-while-write operation. By combining an 8/16-bit RISC CPU with In-system, self-programmable flash, the Atmel AVR XMEGA is a powerful microcontroller family that provides a highly flexible and cost effective solution for many embedded applications. The Atmel AVR XMEGA B devices are supported with a full suite of program and system development tools, including C compilers, macro assemblers, program debugger/simulators, programmers, and evaluation kits. XMEGA B [MANUAL] 4 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 2-1. Atmel AVR XMEGA B block diagram. In Table 2-1 on page 5 a feature summary for the XMEGA B family is shown, split into one feature summary column for each sub-family. Each sub-family has identical feature set, but different memory options, refer to their device datasheet for ordering codes and memory options. Power Supervision POR/BOD & RESET PORT A (8) PORT B (8) EVENT ROUTING NETWORK DMA Controller BUS Matrix SRAM ADCA ACA ADCB ACB OCD PORT M (8) PDI SEG[31..24] / PM[0..7] SEG[0..23] COM[0..3] PA[0..7] PB[0..7]/ JTAG Watchdog Timer Watchdog Oscillator Interrupt Controller DATA BUS Prog/Debug Controller VCC GND PORT R (2) PR[0..1] Oscillator Control Real Time Counter Event System Controller JTAG PDI_DATA RESET / PDI_CLK PORT B Sleep Controller DES CRC IRCOM PORT G (8) SEG[39..32] / PG[0..7] LCD POWER[0..4] PORT C (8) PC[0..7] TCC0:1 USARTC0 SPIC TWIC PD[0..2] PE[0..7] PORT D (3) TCE0 USARTE0 PORT E (8) USB EVENT ROUTING NETWORK AES Int. Refs. AREFA AREFB Tempref VCC/10 CPU NVM Controller Flash EEPROM DATA BUS LCD TOSC1 TOSC2 To Clock Generator XTAL2 / TOSC2 XTAL1 / TOSC1 Oscillator Circuits/ Clock Generation (Alternate) Digital function Analog function / Oscillators Programming, debug, test External clock / Crystal pins General Purpose I/O Ground Power LCD XMEGA B [MANUAL] 5 Atmel-8291C-AVR-XMEGA B -09/2014 Table 2-1. XMEGA B feature summary overview. Feature Details / sub-family B1 B3 Pins, I/O Total 100 64 Programmable I/O pins 53 36 Memory Program memory (KB) 64 - 128 64 - 128 Boot memory (KB) 4 - 8 4 - 8 SRAM (KB) 4 - 8 4 - 8 EEPROM 2 2 - 4 General purpose registers 16 16 Package TQFP 100A 64A QFN /VQFN – 64M2 BGA 100C1/100C2 – QTouch Sense channels 56 56 DMA Controller Channels 2 2 Event System Channels 4 4 QDEC 1 1 Crystal Oscillator 0.4 - 16MHz XOSC Yes Yes 32.768 kHz TOSC Yes Yes Internal Oscillator 2MHz calibrated Yes Yes 32MHz calibrated Yes Yes 128MHz PLL Yes Yes 32.768kHz calibrated Yes Yes 32kHz ULP Yes Yes Timer / Counter TC0 - 16-bit, 4 CC 2 1 TC1 - 16-bit, 2 CC 1 1 TC2 - 2x 8-bit 2 1 Hi-Res 1 1 AWeX 1 1 RTC 1 1 RTC32 Serial Communication USB full-speed device 1 1 USART 2 1 SPI 1 1 TWI 1 1 XMEGA B [MANUAL] 6 Atmel-8291C-AVR-XMEGA B -09/2014 Crypto /CRC AES-128 Yes Yes DES Yes Yes CRC-16 Yes Yes CRC-32 Yes Yes Liquid Crystal Display Controller (LCD) Segments 40 25 Common terminals 4 4 Analog to Digital Converter (ADC) 2 1 Resolution (bits) 12 12 Sampling speed (kbps) 300 300 Input channels per ADC 16 8 Conversion channels 1 1 Analog Comparator (AC) 4 2 Program and Debug Interface PDI Yes Yes JTAG Yes Yes Boundary scan Yes Yes Feature Details / sub-family B1 B3 XMEGA B [MANUAL] 7 Atmel-8291C-AVR-XMEGA B -09/2014 3. Atmel AVR CPU 3.1 Features z 8/16-bit, high-performance Atmel AVR RISC CPU z 142 instructions z Hardware multiplier z 32x8-bit registers directly connected to the ALU z Stack in RAM z Stack pointer accessible in I/O memory space z Direct addressing of up to 16MB of program memory and 16MB of data memory z True 16/24-bit access to 16/24-bit I/O registers z Efficient support for 8-, 16-, and 32-bit arithmetic z Configuration change protection of system-critical features 3.2 Overview All Atmel AVR XMEGA devices use the 8/16-bit AVR CPU. The main function of the CPU is to execute the code and perform all calculations. The CPU is able to access memories, perform calculations, control peripherals, and execute the program in the flash memory. Interrupt handling is described in a separate section, “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. 3.3 Architectural Overview In order to maximize performance and parallelism, the AVR CPU uses a Harvard architecture with separate memories and buses for program and data. Instructions in the program memory are executed with single-level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory. This enables instructions to be executed on every clock cycle. For a summary of all AVR instructions, refer to “Instruction Set Summary” on page 395. For details of all AVR instructions, refer to http://www.atmel.com/avr. Figure 3-1. Block diagram of the AVR CPU architecture. XMEGA B [MANUAL] 8 Atmel-8291C-AVR-XMEGA B -09/2014 The arithmetic logic unit (ALU) supports arithmetic and logic operations between registers or between a constant and a register. Single-register operations can also be executed in the ALU. After an arithmetic operation, the status register is updated to reflect information about the result of the operation. The ALU is directly connected to the fast-access register file. The 32 x 8-bit general purpose working registers all have single clock cycle access time allowing single-cycle arithmetic logic unit operation between registers or between a register and an immediate. Six of the 32 registers can be used as three 16-bit address pointers for program and data space addressing, enabling efficient address calculations. The memory spaces are linear. The data memory space and the program memory space are two different memory spaces. The data memory space is divided into I/O registers, SRAM, and external RAM. In addition, the EEPROM can be memory mapped in the data memory. All I/O status and control registers reside in the lowest 4KB addresses of the data memory. This is referred to as the I/O memory space. The lowest 64 addresses can be accessed directly, or as the data space locations from 0x00 to 0x3F. The rest is the extended I/O memory space, ranging from 0x0040 to 0x0FFF. I/O registers here must be accessed as data space locations using load (LD/LDS/LDD) and store (ST/STS/STD) instructions. The SRAM holds data. Code execution from SRAM is not supported. It can easily be accessed through the five different addressing modes supported in the AVR architecture. The first SRAM address is 0x2000. Data addresses 0x1000 to 0x1FFF are reserved for memory mapping of EEPROM. The program memory is divided in two sections, the application program section and the boot program section. Both sections have dedicated lock bits for write and read/write protection. The SPM instruction that is used for selfprogramming of the application flash memory must reside in the boot program section. The application section contains an application table section with separate lock bits for write and read/write protection. The application table section can be used for save storing of nonvolatile data in the program memory. 3.4 ALU - Arithmetic Logic Unit The arithmetic logic unit supports arithmetic and logic operations between registers or between a constant and a register. Single-register operations can also be executed. The ALU operates in direct connection with all 32 general purpose registers. In a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed and the result is stored in the register file. After an arithmetic or logic operation, the status register is updated to reflect information about the result of the operation. ALU operations are divided into three main categories – arithmetic, logical, and bit functions. Both 8- and 16-bit arithmetic is supported, and the instruction set allows for efficient implementation of 32-bit arithmetic. The hardware multiplier supports signed and unsigned multiplication and fractional format. 3.4.1 Hardware Multiplier The multiplier is capable of multiplying two 8-bit numbers into a 16-bit result. The hardware multiplier supports different variations of signed and unsigned integer and fractional numbers: z Multiplication of unsigned integers z Multiplication of signed integers z Multiplication of a signed integer with an unsigned integer z Multiplication of unsigned fractional numbers z Multiplication of signed fractional numbers z Multiplication of a signed fractional number with an unsigned one A multiplication takes two CPU clock cycles. XMEGA B [MANUAL] 9 Atmel-8291C-AVR-XMEGA B -09/2014 3.5 Program Flow After reset, the CPU starts to execute instructions from the lowest address in the flash program memory ‘0.’ The program counter (PC) addresses the next instruction to be fetched. Program flow is provided by conditional and unconditional jump and call instructions capable of addressing the whole address space directly. Most AVR instructions use a 16-bit word format, while a limited number use a 32-bit format. During interrupts and subroutine calls, the return address PC is stored on the stack. The stack is allocated in the general data SRAM, and consequently the stack size is only limited by the total SRAM size and the usage of the SRAM. After reset, the stack pointer (SP) points to the highest address in the internal SRAM. The SP is read/write accessible in the I/O memory space, enabling easy implementation of multiple stacks or stack areas. The data SRAM can easily be accessed through the five different addressing modes supported in the AVR CPU. 3.6 Instruction Execution Timing The AVR CPU is clocked by the CPU clock, clkCPU. No internal clock division is used. Figure 3-2 on page 9 shows the parallel instruction fetches and instruction executions enabled by the Harvard architecture and the fast-access register file concept. This is the basic pipelining concept used to obtain up to 1MIPS/MHz performance with high power efficiency. Figure 3-2. The parallel instruction fetches and instruction executions. Figure 3-3 on page 9 shows the internal timing concept for the register file. In a single clock cycle, an ALU operation using two register operands is executed and the result is stored back to the destination register. Figure 3-3. Single Cycle ALU Operation clk 1st Instruction Fetch 1st Instruction Execute 2nd Instruction Fetch 2nd Instruction Execute 3rd Instruction Fetch 3rd Instruction Execute 4th Instruction Fetch T1 T2 T3 T4 CPU Total Execution Time Register Operands Fetch ALU Operation Execute Result Write Back T1 T2 T3 T4 clkCPU XMEGA B [MANUAL] 10 Atmel-8291C-AVR-XMEGA B -09/2014 3.7 Status Register The status register (SREG) contains information about the result of the most recently executed arithmetic or logic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the status register is updated after all ALU operations, as specified in the instruction set reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. The status register is not automatically stored when entering an interrupt routine nor restored when returning from an interrupt. This must be handled by software. The status register is accessible in the I/O memory space. 3.8 Stack and Stack Pointer The stack is used for storing return addresses after interrupts and subroutine calls. It can also be used for storing temporary data. The stack pointer (SP) register always points to the top of the stack. It is implemented as two 8-bit registers that are accessible in the I/O memory space. Data are pushed and popped from the stack using the PUSH and POP instructions. The stack grows from a higher memory location to a lower memory location. This implies that pushing data onto the stack decreases the SP, and popping data off the stack increases the SP. The SP is automatically loaded after reset, and the initial value is the highest address of the internal SRAM. If the SP is changed, it must be set to point above address 0x2000, and it must be defined before any subroutine calls are executed or before interrupts are enabled. During interrupts or subroutine calls, the return address is automatically pushed on the stack. The return address can be two or three bytes, depending on program memory size of the device. For devices with 128KB or less of program memory, the return address is two bytes, and hence the stack pointer is decremented/incremented by two. For devices with more than 128KB of program memory, the return address is three bytes, and hence the SP is decremented/incremented by three. The return address is popped off the stack when returning from interrupts using the RETI instruction, and from subroutine calls using the RET instruction. The SP is decremented by one when data are pushed on the stack with the PUSH instruction, and incremented by one when data is popped off the stack using the POP instruction. To prevent corruption when updating the stack pointer from software, a write to SPL will automatically disable interrupts for up to four instructions or until the next I/O memory write. 3.9 Register File The register file consists of 32 x 8-bit general purpose working registers with single clock cycle access time. The register file supports the following input/output schemes: z One 8-bit output operand and one 8-bit result input z Two 8-bit output operands and one 8-bit result input z Two 8-bit output operands and one 16-bit result input z One 16-bit output operand and one 16-bit result input Six of the 32 registers can be used as three 16-bit address register pointers for data space addressing, enabling efficient address calculations. One of these address pointers can also be used as an address pointer for lookup tables in flash program memory. XMEGA B [MANUAL] 11 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 3-4. AVR CPU general purpose working registers. The register file is located in a separate address space, and so the registers are not accessible as data memory. 3.9.1 The X-, Y-, and Z- Registers Registers R26..R31 have added functions besides their general-purpose usage. These registers can form 16-bit address pointers for addressing data memory. These three address registers are called the X-register, Y-register, and Z-register. The Z-register can also be used as an address pointer to read from and/or write to the flash program memory, signature rows, fuses, and lock bits. Figure 3-5. The X-, Y- and Z-registers. 7 0 Addr. R0 0x00 R1 0x01 R2 0x02 … R13 0x0D General R14 0x0E Purpose R15 0x0F Working R16 0x10 Registers R17 0x11 … R26 0x1A X-register Low Byte R27 0x1B X-register High Byte R28 0x1C Y-register Low Byte R29 0x1D Y-register High Byte R30 0x1E Z-register Low Byte R31 0x1F Z-register High Byte Bit (individually) 7 R27 0 7 R26 0 X-register XH XL Bit (X-register) 15 8 7 0 Bit (individually) 7 R29 0 7 R28 0 Y-register YH YL Bit (Y-register) 15 8 7 0 Bit (individually) 7 R31 0 7 R30 0 Z-register ZH ZL Bit (Z-register) 15 8 7 0 XMEGA B [MANUAL] 12 Atmel-8291C-AVR-XMEGA B -09/2014 The lowest register address holds the least-significant byte (LSB), and the highest register address holds the mostsignificant byte (MSB). In the different addressing modes, these address registers function as fixed displacement, automatic increment, and automatic decrement (see the instruction set reference for details). 3.10 RAMP and Extended Indirect Registers In order to access program memory or data memory above 64KB, the address pointer must be larger than 16 bits. This is done by concatenating one register to one of the X-, Y-, or Z-registers. This register then holds the most-significant byte (MSB) in a 24-bit address or address pointer. These registers are available only on devices with external bus interface and/or more than 64KB of program or data memory space. For these devices, only the number of bits required to address the whole program and data memory space in the device is implemented in the registers. 3.10.1 RAMPX, RAMPY and RAMPZ Registers The RAMPX, RAMPY and RAMPZ registers are concatenated with the X-, Y-, and Z-registers, respectively, to enable indirect addressing of the whole data memory space above 64KB and up to 16MB. Figure 3-6. The combined RAMPX + X, RAMPY + Y and RAMPZ + Z registers. When reading (ELPM) and writing (SPM) program memory locations above the first 128KB of the program memory, RAMPZ is concatenated with the Z-register to form the 24-bit address. LPM is not affected by the RAMPZ setting. 3.10.2 RAMPD Register This register is concatenated with the operand to enable direct addressing of the whole data memory space above 64KB. Together, RAMPD and the operand will form a 24-bit address. Figure 3-7. The combined RAMPD + K register. Bit (Individually) 7 0 7 0 7 0 RAMPX XH XL Bit (X-pointer) 23 16 15 8 7 0 Bit (Individually) 7 0 7 0 7 0 RAMPY YH YL Bit (Y-pointer) 23 16 15 8 7 0 Bit (Individually) 7 0 7 0 7 0 RAMPZ ZH ZL Bit (Z-pointer) 23 16 15 8 7 0 Bit (Individually) 7 0 15 0 RAMPD K Bit (D-pointer) 23 16 15 0 XMEGA B [MANUAL] 13 Atmel-8291C-AVR-XMEGA B -09/2014 3.10.3 EIND - Extended Indirect Register EIND is concatenated with the Z-register to enable indirect jump and call to locations above the first 128KB (64K words) of the program memory. Figure 3-8. The combined EIND + Z register. 3.11 Accessing 16-bit Registers The AVR data bus is 8 bits wide, and so accessing 16-bit registers requires atomic operations. These registers must be byte-accessed using two read or write operations. 16-bit registers are connected to the 8-bit bus and a temporary register using a 16-bit bus. For a write operation, the low byte of the 16-bit register must be written before the high byte. The low byte is then written into the temporary register. When the high byte of the 16-bit register is written, the temporary register is copied into the low byte of the 16-bit register in the same clock cycle. For a read operation, the low byte of the 16-bit register must be read before the high byte. When the low byte register is read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. When the high byte is read, it is then read from the temporary register. This ensures that the low and high bytes of 16-bit registers are always accessed simultaneously when reading or writing the register. Interrupts can corrupt the timed sequence if an interrupt is triggered and accesses the same 16-bit register during an atomic 16-bit read/write operation. To prevent this, interrupts can be disabled when writing or reading 16-bit registers. The temporary registers can also be read and written directly from user software. 3.11.1 Accessing 24- and 32-bit Registers For 24- and 32-bit registers, the read and write access is done in the same way as described for 16-bit registers, except there are two temporary registers for 24-bit registers and three for 32-bit registers. The least-significant byte must be written first when doing a write, and read first when doing a read. 3.12 Configuration Change Protection System critical I/O register settings are protected from accidental modification. The SPM instruction is protected from accidental execution, and the LPM instruction is protected when reading the fuses and signature row. This is handled globally by the configuration change protection (CCP) register. Changes to the protected I/O registers or bits, or execution of protected instructions, are only possible after the CPU writes a signature to the CCP register. The different signatures are described in the register description. There are two modes of operation: one for protected I/O registers, and one for the protected instructions, SPM/LPM. 3.12.1 Sequence for write operation to protected I/O registers 1. The application code writes the signature that enable change of protected I/O registers to the CCP register. 2. Within four instruction cycles, the application code must write the appropriate data to the protected register. Most protected registers also contain a write enable/change enable bit. This bit must be written to one in the same operation as the data are written. The protected change is immediately disabled if the CPU performs write operations to the I/O register or data memory or if the SPM, LPM, or SLEEP instruction is executed. Bit (Individually) 7 0 7 0 7 0 EIND ZH ZL Bit (D-pointer) 23 16 15 8 7 0 XMEGA B [MANUAL] 14 Atmel-8291C-AVR-XMEGA B -09/2014 3.12.2 Sequence for execution of protected SPM/LPM 1. The application code writes the signature for the execution of protected SPM/LPM to the CCP register. 2. Within four instruction cycles, the application code must execute the appropriate instruction. The protected change is immediately disabled if the CPU performs write operations to the data memory or if the SLEEP instruction is executed. Once the correct signature is written by the CPU, interrupts will be ignored for the duration of the configuration change enable period. Any interrupt request (including non-maskable interrupts) during the CCP period will set the corresponding interrupt flag as normal, and the request is kept pending. After the CCP period is completed, any pending interrupts are executed according to their level and priority. DMA requests are still handled, but do not influence the protected configuration change enable period. A signature written by DMA is ignored. 3.13 Fuse Lock For some system-critical features, it is possible to program a fuse to disable all changes to the associated I/O control registers. If this is done, it will not be possible to change the registers from the user software, and the fuse can only be reprogrammed using an external programmer. Details on this are described in the datasheet module where this feature is available. XMEGA B [MANUAL] 15 Atmel-8291C-AVR-XMEGA B -09/2014 3.14 Register Descriptions 3.14.1 CCP – Configuration Change Protection register z Bit 7:0 – CCP[7:0]: Configuration Change Protection The CCP register must be written with the correct signature to enable change of the protected I/O register or execution of the protected instruction for a maximum period of four CPU instruction cycles. All interrupts are ignored during these cycles. After these cycles, interrupts will automatically be handled again by the CPU, and any pending interrupts will be executed according to their level and priority. When the protected I/O register signature is written, CCP[0] will read as one as long as the protected feature is enabled. Similarly when the protected SPM/LPM signature is written, CCP[1] will read as one as long as the protected feature is enabled. CCP[7:2] will always read as zero. Table 3-1 shows the signature for the various modes. Table 3-1. Modes of CPU change protection. 3.14.2 RAMPD – Extended Direct Addressing register This register is concatenated with the operand for direct addressing (LDS/STS) of the whole data memory space on devices with more than 64KB of data memory. This register is not available if the data memory, including external memory, is less than 64KB. z Bit 7:0 – RAMPD[7:0]: Extended Direct Addressing bits These bits hold the MSB of the 24-bit address created by RAMPD and the 16-bit operand. Only the number of bits required to address the available data memory is implemented for each device. Unused bits will always read as zero. Bit 7 6 5 4 3 2 1 0 +0x04 CCP[7:0] Read/Write W W W W W W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Signature Group Configuration Description 0x9D SPM Protected SPM/LPM 0xD8 IOREG Protected IO register Bit 7 6 5 4 3 2 1 0 +0x08 RAMPD[7:0] 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 XMEGA B [MANUAL] 16 Atmel-8291C-AVR-XMEGA B -09/2014 3.14.3 RAMPX – Extended X-Pointer register This register is concatenated with the X-register for indirect addressing (LD/LDD/ST/STD) of the whole data memory space on devices with more than 64KB of data memory. This register is not available if the data memory, including external memory, is less than 64KB. z Bit 7:0 – RAMPX[7:0]: Extended X-pointer Address bits These bits hold the MSB of the 24-bit address created by RAMPX and the 16-bit X-register. Only the number of bits required to address the available data memory is implemented for each device. Unused bits will always read as zero. 3.14.4 RAMPY – Extended Y-Pointer register This register is concatenated with the Y-register for indirect addressing (LD/LDD/ST/STD) of the whole data memory space on devices with more than 64KB of data memory. This register is not available if the data memory, including external memory, is less than 64KB. z Bit 7:0 – RAMPY[7:0]: Extended Y-pointer Address bits These bits hold the MSB of the 24-bit address created by RAMPY and the 16-bit Y-register. Only the number of bits required to address the available data memory is implemented for each device. Unused bits will always read as zero. 3.14.5 RAMPZ – Extended Z-Pointer register This register is concatenated with the Z-register for indirect addressing (LD/LDD/ST/STD) of the whole data memory space on devices with more than 64KB of data memory. RAMPZ is concatenated with the Z-register when reading (ELPM) program memory locations above the first 64KB and writing (SPM) program memory locations above the first 128KB of the program memory. This register is not available if the data memory, including external memory and program memory in the device, is less than 64KB. z Bit 7:0 – RAMPZ[7:0]: Extended Z-pointer Address bits These bits hold the MSB of the 24-bit address created by RAMPZ and the 16-bit Z-register. Only the number of bits required to address the available data and program memory is implemented for each device. Unused bits will always read as zero. Bit 7 6 5 4 3 2 1 0 +0x09 RAMPX[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0A RAMPY[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 000000 Bit 7 6 5 4 3 2 1 0 +0x0B RAMPZ[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 17 Atmel-8291C-AVR-XMEGA B -09/2014 3.14.6 EIND – Extended Indirect register This register is concatenated with the Z-register for enabling extended indirect jump (EIJMP) and call (EICALL) to the whole program memory space on devices with more than 128KB of program memory. The register should be used for jumps to addresses below 128KB if ECALL/EIJMP are used, and it will not be used if CALL and IJMP commands are used. For jump or call to addresses below 128KB, this register is not used. This register is not available if the program memory in the device is less than 128KB. z Bit 7:0 – EIND[7:0]: Extended Indirect Address bits These bits hold the MSB of the 24-bit address created by EIND and the 16-bit Z-register. Only the number of bits required to access the available program memory is implemented for each device. Unused bits will always read as zero. 3.14.7 SPL – Stack Pointer Register Low The SPH and SPL register pair represent the 16-bit SP value. The SP holds the stack pointer that points to the top of the stack. After reset, the stack pointer points to the highest internal SRAM address. To prevent corruption when updating the stack pointer from software, a write to SPL will automatically disable interrupts for the next four instructions or until the next I/O memory write. Only the number of bits required to address the available data memory, including external memory, up to 64KB is implemented for each device. Unused bits will always read as zero. Note: 1. Refer to specific device datasheets for exact initial values. z Bit 7:0 – SP[7:0]: Stack Pointer Register Low These bits hold the LSB of the 16-bit stack pointer (SP). 3.14.8 SPH – Stack Pointer Register High Note: 1. Refer to specific device datasheets for exact initial values. z Bit 7:0 – SP[15:8]: Stack Pointer Register High These bits hold the MSB of the 16-bit stack pointer (SP). Bit 7 6 5 4 3 2 1 0 +0x0C EIND[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0D SP[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value(1) 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 Bit 7 6 5 4 3 2 1 0 +0x0E SP[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value(1) 0/1 0/1 0/1 0/1 0/1 0/1 0/1 0/1 XMEGA B [MANUAL] 18 Atmel-8291C-AVR-XMEGA B -09/2014 3.14.9 SREG – Status Register The status register (SREG) contains information about the result of the most recently executed arithmetic or logic instruction. z Bit 7 – I: Global Interrupt Enable The global interrupt enable bit must be set for interrupts to be enabled. If the global interrupt enable register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. This bit is not cleared by hardware after an interrupt has occurred. This bit can be set and cleared by the application with the SEI and CLI instructions, as described in “Instruction Set Description.” Changing the I flag through the I/O-register result in a onecycle wait state on the access. z Bit 6 – T: Bit Copy Storage The bit copy instructions bit load (BLD) and bit store (BST) use the T bit as source or destination for the operated bit. A bit from a register in the register file can be copied into this bit by the BST instruction, and this bit can be copied into a bit in a register in the register file by the BLD instruction. z Bit 5 – H: Half Carry Flag The half carry flag (H) indicates a half carry in some arithmetic operations. Half carry Is useful in BCD arithmetic. See “Instruction Set Description” for detailed information. z Bit 4 – S: Sign Bit, S = N ⊕ V The sign bit is always an exclusive or between the negative flag, N, and the two’s complement overflow flag, V. See “Instruction Set Description” for detailed information. z Bit 3 – V: Two’s Complement Overflow Flag The two’s complement overflow flag (V) supports two’s complement arithmetic. See “Instruction Set Description” for detailed information. z Bit 2 – N: Negative Flag The negative flag (N) indicates a negative result in an arithmetic or logic operation. See “Instruction Set Description” for detailed information. z Bit 1 – Z: Zero Flag The zero flag (Z) indicates a zero result in an arithmetic or logic operation. See “Instruction Set Description” for detailed information. z Bit 0 – C: Carry Flag The carry flag (C) indicates a carry in an arithmetic or logic operation. See “Instruction Set Description” for detailed information. Bit 7 6 5 4 3 2 1 0 +0x0F I THSVNZC 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 XMEGA B [MANUAL] 19 Atmel-8291C-AVR-XMEGA B -09/2014 3.15 Register Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 Reserved – – – – – – – – +0x01 Reserved – – – – – – – – +0x02 Reserved – – – – – – – – +0x03 Reserved – – – – – – – – +0x04 CCP CCP[7:0] 15 +0x05 Reserved – – – – – – – – +0x06 Reserved – – – – – – – – +0x07 Reserved – – – – – – – – +0x08 RAMPD RAMPD[7:0] 15 +0x09 RAMPX RAMPX[7:0] 16 +0x0A RAMPY RAMPY[7:0] 16 +0x0B RAMPZ RAMPZ[7:0] 16 +0x0C EIND EIND[7:0] 17 +0x0D SPL SPL[7:0] 17 +0x0E SPH SPH[7:0] 17 +0x0F SREG I T H S V N Z C 18 XMEGA B [MANUAL] 20 Atmel-8291C-AVR-XMEGA B -09/2014 4. Memories 4.1 Features z Flash program memory z One linear address space z In-system programmable z Self-programming and boot loader support z Application section for application code z Application table section for application code or data storage z Boot section for application code or bootloader code z Separate read/write protection lock bits for all sections z Built in fast CRC check of a selectable flash program memory section z Data memory z One linear address space z Single-cycle access from CPU z SRAM z EEPROM z Byte and page accessible z Optional memory mapping for direct load and store z I/O memory z Configuration and status registers for all peripherals and modules z 4 bit-accessible general purpose registers for global variables or flags z Bus arbitration z Safe and deterministic handling of priority between CPU, DMA controller, and other bus masters z Separate buses for SRAM, EEPROM, I/O memory, and external memory access z Simultaneous bus access for CPU and DMA controller z Production signature row memory for factory programmed data z ID for each microcontroller device type z Serial number for each device z Calibration bytes for factory calibrated peripherals z User signature row z One flash page in size z Can be read and written from software z Content is kept after chip erase 4.2 Overview This section describes the different memory sections. The AVR architecture has two main memory spaces, the program memory and the data memory. Executable code can reside only in the program memory, while data can be stored in the program memory and the data memory. The data memory includes the internal SRAM, and EEPROM for nonvolatile data storage. All memory spaces are linear and require no memory bank switching. Nonvolatile memory (NVM) spaces can be locked for further write and read/write operations. This prevents unrestricted access to the application software. A separate memory section contains the fuse bytes. These are used for configuring important system functions, and can only be written by an external programmer. 4.3 Flash Program Memory All XMEGA devices contain on-chip, in-system reprogrammable flash memory for program storage. The flash memory can be accessed for read and write from an external programmer through the PDI or from application software running in the device. XMEGA B [MANUAL] 21 Atmel-8291C-AVR-XMEGA B -09/2014 All AVR CPU instructions are 16 or 32 bits wide, and each flash location is 16 bits wide. The flash memory is organized in two main sections, the application section and the boot loader section, as shown in Figure 4-1 on page 21. The sizes of the different sections are fixed, but device-dependent. These two sections have separate lock bits, and can have different levels of protection. The store program memory (SPM) instruction, which is used to write to the flash from the application software, will only operate when executed from the boot loader section. The application section contains an application table section with separate lock settings. This enables safe storage of nonvolatile data in the program memory. Figure 4-1. Flash memory sections. 4.3.1 Application Section The Application section is the section of the flash that is used for storing the executable application code. The protection level for the application section can be selected by the boot lock bits for this section. The application section can not store any boot loader code since the SPM instruction cannot be executed from the application section. 4.3.2 Application Table Section The application table section is a part of the application section of the flash memory that can be used for storing data. The size is identical to the boot loader section. The protection level for the application table section can be selected by the boot lock bits for this section. The possibilities for different protection levels on the application section and the application table section enable safe parameter storage in the program memory. If this section is not used for data, application code can reside here. 4.3.3 Boot Loader Section While the application section is used for storing the application code, the boot loader software must be located in the boot loader section because the SPM instruction can only initiate programming when executing from this section. The SPM instruction can access the entire flash, including the boot loader section itself. The protection level for the boot loader section can be selected by the boot loader lock bits. If this section is not used for boot loader software, application code can be stored here. Application Flash Section 0x000000 End Application Start Boot Loader Flashend Application Table Flash Section Boot Loader Flash Section XMEGA B [MANUAL] 22 Atmel-8291C-AVR-XMEGA B -09/2014 4.3.4 Production Signature Row The production signature row is a separate memory section for factory programmed data. It contains calibration data for functions such as oscillators and analog modules. Some of the calibration values will be automatically loaded to the corresponding module or peripheral unit during reset. Other values must be loaded from the signature row and written to the corresponding peripheral registers from software. For details on calibration conditions such as temperature, voltage references, etc., refer to the device datasheet. The production signature row also contains an ID that identifies each microcontroller device type and a serial number for each manufactured device. The serial number consists of the production lot number, wafer number, and wafer coordinates for the device. The production signature row cannot be written or erased, but it can be read from application software and external programmers. For accessing the production signature row, refer to “NVM Flash Commands” on page 380. 4.3.5 User Signature Row The user signature row is a separate memory section that is fully accessible (read and write) from application software and external programmers. It is one flash page in size, and is meant for static user parameter storage, such as calibration data, custom serial number, identification numbers, random number seeds, etc. This section is not erased by chip erase commands that erase the flash, and requires a dedicated erase command. This ensures parameter storage during multiple program/erase operations and on-chip debug sessions. 4.4 Fuses and Lockbits The fuses are used to configure important system functions, and can only be written from an external programmer. The application software can read the fuses. The fuses are used to configure reset sources such as brownout detector, watchdog and startup configuration. The lock bits are used to set protection levels for the different flash sections (i.e., if read and/or write access should be blocked). Lock bits can be written by external programmers and application software, but only to stricter protection levels. Chip erase is the only way to erase the lock bits. To ensure that flash contents are protected even during chip erase, the lock bits are erased after the rest of the flash memory has been erased. An unprogrammed fuse or lock bit will have the value one, while a programmed fuse or lock bit will have the value zero. Both fuses and lock bits are reprogrammable like the flash program memory. For some fuse bytes, leaving them unprogrammed (0xFF) will result in invalid settings. The user must ensure that the fuse bytes are programmed to values which give valid settings. Refer to the detailed description of the individual fuse bytes for further information. 4.5 Data Memory The data memory contains the I/O memory, internal SRAM, optionally memory mapped and EEPROM. The data memory is organized as one continuous memory section, as shown in Figure 4-2 on page 23. XMEGA B [MANUAL] 23 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 4-2. Data memory map. I/O memory, EEPROM, and SRAM will always have the same start addresses for all XMEGA devices. 4.6 Internal SRAM The internal SRAM always starts at hexadecimal address 0x2000. SRAM is accessed by the CPU using the load (LD/LDS/LDD) and store (ST/STS/STD) instructions. 4.7 EEPROM All XMEGA devices have EEPROM for nonvolatile data storage. It is addressable in a separate data space (default) or memory mapped and accessed in normal data space. The EEPROM supports both byte and page access. Memory mapped EEPROM allows highly efficient EEPROM reading and EEPROM buffer loading. When doing this, EEPROM is accessible using load and store instructions. Memory mapped EEPROM will always start at hexadecimal address 0x1000. 4.8 I/O Memory The status and configuration registers for peripherals and modules, including the CPU, are addressable through I/O memory locations. All I/O locations can be accessed by the load (LD/LDS/LDD) and store (ST/STS/STD) instructions, which are used to transfer data between the 32 registers in the register file and the I/O memory. The IN and OUT instructions can address I/O memory locations in the range of 0x00 to 0x3F directly. In the address range 0x00 - 0x1F, single-cycle instructions for manipulation and checking of individual bits are available. 4.8.1 General Purpose I/O Registers The lowest 4 I/O memory addresses are reserved as general purpose I/O registers. These registers can be used for storing global variables and flags, as they are directly bit-accessible using the SBI, CBI, SBIS, and SBIC instructions. 4.9 Data Memory and Bus Arbitration Since the data memory is organized as four separate sets of memories, the different bus masters (CPU, DMA controller read and DMA controller write, etc.) can access different memory sections at the same time. See Figure 4-3 on page 24. I/O Memory (Up to 4 KB) EEPROM (Up to 4 KB) Internal SRAM 0x0000 0x1000 0x2000 Start/End Address Data Memory XMEGA B [MANUAL] 24 Atmel-8291C-AVR-XMEGA B -09/2014 The USB module acts as a bus master, and is connected directly to internal SRAM through a pseudo-dual-port (PDP) interface. Figure 4-3. Bus access. 4.9.1 Bus Priority When several masters request access to the same bus, the bus priority is in the following order (from higher to lower priority): 1. Bus Master with ongoing access. 2. Bus Master with ongoing burst. z Alternating DMA controller read and DMA controller write when they access the same data memory section. 3. Bus Master requesting burst access. z CPU has priority. 4. Bus Master requesting bus access. z CPU has priority. 4.10 Memory Timing Read and write access to the I/O memory takes one CPU clock cycle. A write to SRAM takes one cycle, and a read from SRAM takes two cycles. For burst read (DMA), new data are available every cycle. EEPROM page load (write) takes one cycle, and three cycles are required for read. For burst read, new data are available every second cycle. Refer to the instruction summary for more details on instructions and instruction timing. 4.11 Device ID and Revision Each device has a three-byte device ID. This ID identifies Atmel as the manufacturer of the device and the device type. A separate register contains the revision number of the device. Peripherals and system modules Bus matrix DMA CPU RAM OCD USART SPI Timer / Counter TWI USB Interrupt Controller Power Management SRAM External Programming AVR core PDI CH0 ADC AC Crypto modules Event System Controller Oscillator Control CH1 Non-Volatile Memory EEPROM Flash CRC Real Time Counter I/O NVM Controller XMEGA B [MANUAL] 25 Atmel-8291C-AVR-XMEGA B -09/2014 4.12 I/O Memory Protection Some features in the device are regarded as critical for safety in some applications. Due to this, it is possible to lock the I/O register related to the clock system, the event system, and the advanced waveform extensions. As long as the lock is enabled, all related I/O registers are locked and they can not be written from the application software. The lock registers themselves are protected by the configuration change protection mechanism. For details, refer to “Configuration Change Protection” on page 13. XMEGA B [MANUAL] 26 Atmel-8291C-AVR-XMEGA B -09/2014 4.13 Register Description – NVM Controller 4.13.1 ADDR0 – Address register 0 The ADDR0, ADDR1, and ADDR2 registers represent the 24-bit value, ADDR. This is used for addressing all NVM sections for read, write, and CRC operations. z Bit 7:0 – ADDR[7:0]: Address Byte 0 This register gives the address low byte when accessing NVM locations. 4.13.2 ADDR1 – Address register 1 z Bit 7:0 – ADDR[15:8]: Address Byte 1 This register gives the address high byte when accessing NVM locations. 4.13.3 ADDR2 – Address register 2 z Bit 7:0 – ADDR[23:16]: Address Byte 2 This register gives the address extended byte when accessing NVM locations. 4.13.4 DATA0 – Data register 0 The DATA0, DATA1, and DATA registers represent the 24-bit value, DATA. This holds data during NVM read, write, and CRC access. z Bit 7:0 – DATA[7:0]: Data Byte 0 This register gives the data value byte 0 when accessing NVM locations. Bit 7 6 5 4 3 2 1 0 +0x00 ADDR[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1 1 1 1 1 1 1 Bit 7 6 5 4 3 2 1 0 +0x01 ADDR[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x02 ADDR[23:16] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x04 DATA[7:0] 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 XMEGA B [MANUAL] 27 Atmel-8291C-AVR-XMEGA B -09/2014 4.13.5 DATA1 – Data register 1 z Bit 7:0 – DATA[15:8]: Data Byte 1 This register gives the data value byte 1 when accessing NVM locations. 4.13.6 DATA2 – Data register 2 z Bit 7:0 – DATA[23:16]: Data Byte 2 This register gives the data value byte 2 when accessing NVM locations. 4.13.7 CMD – Command register z Bit 7 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 6:0 – CMD[6:0]: Command These bits define the programming commands for the flash. Bit 6 is only set for external programming commands. See “Memory Programming” on page 375” for programming commands. 4.13.8 CTRLA – Control register A z Bit 7:1 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 0 – CMDEX: Command Execute Setting this bit will execute the command in the CMD register. This bit is protected by the configuration change protection (CCP) mechanism. Refer to “Configuration Change Protection” on page 13 for details on the CCP. Bit 7 6 5 4 3 2 1 0 +0x05 DATA[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x06 DATA[23:16] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0A – CMD[6:0] Read/Write R R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0B – – – – – – – CMDEX Read/Write R RRRRRRS Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 28 Atmel-8291C-AVR-XMEGA B -09/2014 4.13.9 CTRLB – Control register B z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3 – EEMAPEN: EEPROM Data Memory Mapping Enable Setting this bit enables data memory mapping of the EEPROM section. The EEPROM can then be accessed using load and store instructions. z Bit 2 – FPRM: Flash Power Reduction Mode Setting this bit enables power saving for the flash memory. If code is running from the application section, the boot loader section will be turned off, and vice versa. If access to the section that is turned off is required, the CPU will be halted for a time equal to the start-up time from the idle sleep mode. z Bit 1 – EPRM: EEPROM Power Reduction Mode Setting this bit enables power saving for the EEPROM. The EEPROM will then be turned off in a manner equal to entering sleep mode. If access is required, the bus master will be halted for a time equal to the start-up time from idle sleep mode. z Bit 0 – SPMLOCK: SPM Locked This bit can be written to prevent all further self-programming. The bit is cleared at reset, and cannot be cleared from software. This bit is protected by the configuration change protection (CCP) mechanism. Refer to “Configuration Change Protection” on page 13 for details on the CCP. 4.13.10 INTCTRL – Interrupt Control register z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:2 – SPMLVL[1:0]: SPM Ready Interrupt Level These bits enable the interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. This is a level interrupt that will be triggered only when the NVMBUSY flag in the STATUS register is set to zero. Thus, the interrupt should not be enabled before triggering an NVM command, as the NVMBUSY flag will not be set before the NVM command is triggered. The interrupt should be disabled in the interrupt handler. z Bit 1:0 – EELVL[1:0]: EEPROM Ready Interrupt Level These bits enable the EEPROM ready interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. This is a level interrupt that will be triggered only when the NVMBUSY flag in the STATUS register is set to zero. Thus, the interrupt should not be enabled before triggering an NVM command, as the NVMBUSY flag will not be set before the NVM command is triggered. The interrupt should be disabled in the interrupt handler. Bit 7 6 5 4 3 2 1 0 +0x0C – – – – EEMAPEN FPRM EPRM SPMLOCK Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0D – – – – SPMLVL[1:0] EELVL[1:0] Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 29 Atmel-8291C-AVR-XMEGA B -09/2014 4.13.11 STATUS – Status register z Bit 7 – NVMBUSY: Nonvolatile Memory Busy The NVMBUSY flag indicates if the NVM (Flash, EEPROM, lock bit) is being programmed. Once an operation is started, this flag is set and remains set until the operation is completed. The NVMBUSY flag is automatically cleared when the operation is finished. z Bit 6 – FBUSY: Flash Busy The FBUSY flag indicates if a flash programming operation is initiated. Once an operation is started, the FBUSY flag is set and the application section cannot be accessed. The FBUSY flag is automatically cleared when the operation is finished. z Bit 5:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1 – EELOAD: EEPROM Page Buffer Active Loading The EELOAD flag indicates that the temporary EEPROM page buffer has been loaded with one or more data bytes. It remains set until an EEPROM page write or a page buffer flush operation is executed. For more details, see “Flash and EEPROM Programming Sequences” on page 377. z Bit 0 – FLOAD: Flash Page Buffer Active Loading The FLOAD flag indicates that the temporary flash page buffer has been loaded with one or more data bytes. It remains set until an application page write, boot page write, or page buffer flush operation is executed. For more details, see “Flash and EEPROM Programming Sequences” on page 377. 4.13.12 LOCKBITS – Lock Bit register This register is a mapping of the NVM lock bits into the I/O memory space, which enables direct read access from the application software. Refer to “LOCKBITS – Lock Bit register” on page 33 for a description. Bit 7 6 5 4 3 2 1 0 +0x04 NVMBUSY FBUSY – – – – EELOAD FLOAD Read/Write R R RRRR R R Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x07 BLBB[1:0] BLBA[1:0] BLBAT[1:0] LB[1:0] Read/Write R R R RRRRR Initial Value 11111111 XMEGA B [MANUAL] 30 Atmel-8291C-AVR-XMEGA B -09/2014 4.14 Register Descriptions – Fuses and Lock Bits 4.14.1 FUSEBYTE1 – Fuse Byte1 z Bit 7:4 – WDWPER[3:0]: Watchdog Window Timeout Period These fuse bits are used to set initial value of the closed window for the Watchdog Timer in Window Mode. During reset these fuse bits are automatically written to the WPER bits Watchdog Window Mode Control Register. Refer to “WINCTRL – Window Mode Control register” on page 113 for details. z Bit 3:0 – WDPER[3:0]: Watchdog Timeout Period These fuse bits are used to set the initial value of the watchdog timeout period. During reset these fuse bits are automatically written to the PER bits in the watchdog control register. Refer to “CTRL – Control register” on page 112 for details. 4.14.2 FUSEBYTE2 – Fuse Byte2 z Bit 7 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to one when this register is written. z Bit 6 – BOOTRST: Boot Loader Section Reset Vector This fuse can be programmed so the reset vector is pointing to the first address in the boot loader flash section. The device will then start executing from the boot loader flash section after reset. Table 4-1. Boot reset fuse. z Bit 5 – TOSCSEL: 32.768kHz Timer Oscillator Pin Selection This fuse is used to select the pin location for the 32.768kHz timer oscillator (TOSC). This fuse is available only on devices where XTAL and TOSC pins by default are shared. Bit 7 6 5 4 3 2 1 0 +0x01 WDWPER[3:0] WDPER[3:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x02 – BOOTRST TOSCSEL – – – BODPD[1:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1 1 1 1 1 1 1 BOOSTRST Reset address 0 Reset vector = Boot loader reset 1 Reset vector = Application reset (address 0x0000) XMEGA B [MANUAL] 31 Atmel-8291C-AVR-XMEGA B -09/2014 Table 4-2. TOSCSEL fuse. Note: 1. See the device datasheet for alternate TOSC position. z Bit 4:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to one when this register is written. z Bit 1:0 – BODPD[1:0]: BOD Operation in Power-down Mode These fuse bits set the BOD operation mode in all sleep modes except idle mode. For details on the BOD and BOD operation modes, refer to “Brownout Detection” on page 104. Table 4-3. BOD operation modes in sleep modes. 4.14.3 FUSEBYTE4 – Fuse Byte4 z Bit 7:5 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to one when this register is written. z Bit: 4 – RSTDISBL: External Reset Disable This fuse can be programmed to disable the external reset pin functionality. When this is done, pulling the reset pin low will not cause an external reset. A reset is required before this bit will be read correctly after it is changed. z Bit 3:2 – STARTUPTIME[1:0]: Start-up time These fuse bits can be used to set at a programmable timeout period from when all reset sources are released until the internal reset is released from the delay counter. A reset is required before these bits will be read correctly after they are changed. The delay is timed from the 1kHz output of the ULP oscillator. Refer to “Reset Sequence” on page 103 for details. TOSCSEL Group configuration Description 0 ALTERNATE(1) TOSC1/2 on separate pins 1 XTAL TOSC1/2 shared with XTAL BODPD[1:0] Description 00 Reserved 01 BOD enabled in sampled mode 10 BOD enabled continuously 11 BOD disabled Bit 7 6 5 4 3 2 1 0 +0x04 – – – RSTDISBL STARTUPTIME[1:0] WDLOCK – Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1 1 1 1 1 1 1 XMEGA B [MANUAL] 32 Atmel-8291C-AVR-XMEGA B -09/2014 Table 4-4. Start-up time z Bit 1 – WDLOCK: Watchdog Timer Lock The WDLOCK fuse can be programmed to lock the watchdog timer configuration. When this fuse is programmed, the watchdog timer configuration cannot be changed, and the ENABLE bit in the watchdog CTRL register is automatically set at reset and cannot be cleared from the application software. The WEN bit in the watchdog WINCTRL register is not set automatically, and needs to be set from software. A reset is required before this bit will be read correctly after it is changed. Table 4-5. Watchdog timer lock z Bit 0 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to one when this register is written. 4.14.4 FUSEBYTE5 – Fuse Byte 5 z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to one when this register is written. z Bit 5:4 – BODACT[1:0]: BOD Operation in Active Mode These fuse bits set the BOD operation mode when the device is in active and idle modes. For details on the BOD and BOD operation modes. Refer to “Brownout Detection” on page 104. Table 4-6. BOD operation modes in active and idle modes STARTUPTIME[1:0 1kHz ULP oscillator cycles 00 64 01 4 10 Reserved 11 0 WDLOCK Description 0 Watchdog timer locked for modifications 1 Watchdog timer not locked Bit 7 6 5 4 3 2 1 0 +0x05 – – BODACT[1:0] EESAVE BODLEVEL[2:0] Read/Write R R R/W R/W R/W R/W R/W R/W Initial Value 1 1 – – – – – – BODACT[1:0] Description 00 Reserved 01 BOD enabled in sampled mode 10 BOD enabled continuously 11 BOD disabled XMEGA B [MANUAL] 33 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 3 – EESAVE: EEPROM is Preserved through the Chip Erase A chip erase command will normally erase the flash, EEPROM, and internal SRAM. If this fuse is programmed, the EEPROM is not erased during chip erase. This is useful if EEPROM is used to store data independently of the software revision. Table 4-7. EEPROM preserved through chip erase Changes to the EESAVE fuse bit take effect immediately after the write timeout elapses. Hence, it is possible to update EESAVE and perform a chip erase according to the new setting of EESAVE without leaving and reentering programming mode. z Bit 2:0 – BODLEVEL[2:0]: Brownout Detection Voltage Level These fuse bits sets the BOD voltage level. Refer to “Reset System” on page 102 for details. For BOD level nominal values, see Table 9-2 on page 105. 4.14.5 LOCKBITS – Lock Bit register z Bit 7:6 – BLBB[1:0]: Boot Lock Bit Boot Loader Section These lock bits control the software security level for accessing the boot loader section. The BLBB bits can only be written to a more strict locking. Resetting the BLBB bits is possible by executing a chip erase command. Table 4-8. Boot lock bit for the boot loader section EESAVE Description 0 EEPROM is preserved during chip erase 1 EEPROM is erased during chip erase Bit 7 6 5 4 3 2 1 0 +0x07 BLBB[1:0] BLBA[1:0] BLBAT[1:0] LB[1:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1 1 1 1 1 1 1 BLBB[1:0] Group Configuration Description 11 NOLOCK No lock – no restrictions for SPM and (E)LPM accessing the boot loader section. 10 WLOCK Write lock – SPM is not allowed to write the boot loader section. 01 RLOCK Read lock – (E)LPM executing from the application section is not allowed to read from the boot loader section. If the interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. 00 RWLOCK Read and write lock – SPM is not allowed to write to the boot loader section, and (E)LPM executing from the application section is not allowed to read from the boot loader section. If the interrupt vectors are placed in the application section, interrupts are disabled while executing from the boot loader section. XMEGA B [MANUAL] 34 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 5:4 – BLBA[1:0]: Boot Lock Bit Application Section These lock bits control the software security level for accessing the application section according to Table 4-9 on page 34. The BLBA bits can only be written to a more strict locking. Resetting the BLBA bits is possible only by executing a chip erase command. Table 4-9. Boot lock bit for the application section z Bit 3:2 – BLBAT[1:0]: Boot Lock Bit Application Table Section These lock bits control the software security level for accessing the application table section for software access. The BLBAT bits can only be written to a more strict locking. Resetting the BLBAT bits is possible only by executing a chip erase command. Table 4-10. Boot lock bit for the application table section z Bit 1:0 – LB[1:0]: Lock Bits(1) These lock bits control the security level for the flash and EEPROM during external programming. These bits are writable only through an external programming interface. Resetting the lock bits is possible only by executing a chip erase BLBA[1:0] Group Configuration Description 11 NOLOCK No Lock - no restrictions for SPM and (E)LPM accessing the application section. 10 WLOCK Write lock – SPM is not allowed to write the application section. 01 RLOCK Read lock – (E)LPM executing from the boot loader section is not allowed to read from the application section. If the interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 00 RWLOCK Read and write lock – SPM is not allowed to write to the application section, and (E)LPM executing from the boot loader section is not allowed to read from the application section. If the interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. BLBAT[1:0] Group Configuration Description 11 NOLOCK No lock – no restrictions for SPM and (E)LPM accessing the application table section. 10 WLOCK Write lock – SPM is not allowed to write the application table 01 RLOCK Read lock – (E)LPM executing from the boot loader section is not allowed to read from the application table section. If the interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. 00 RWLOCK Read and write lock – SPM is not allowed to write to the application table section, and (E)LPM executing from the boot loader section is not allowed to read from the application table section. If the interrupt vectors are placed in the boot loader section, interrupts are disabled while executing from the application section. XMEGA B [MANUAL] 35 Atmel-8291C-AVR-XMEGA B -09/2014 command. All other access; using the TIF and OCD, is blocked if any of the Lock Bits are written to 0. These bits do not block any software access to the memory. Table 4-11. Lock bit protection mode. Note: 1. Program the Fuse Bits and Boot Lock Bits before programming the Lock Bits. LB[1:0] Group Configuration Description 11 NOLOCK3 No lock – no memory locks enabled. 10 WLOCK Write lock – programming of the flash and EEPROM is disabled for the programming interface. Fuse bits are locked for write from the programming interface. 00 RWLOCK Read and write lock – programming and read/verification of the flash and EEPROM are disabled for the programming interface. The lock bits and fuses are locked for read and write from the programming interface. XMEGA B [MANUAL] 36 Atmel-8291C-AVR-XMEGA B -09/2014 4.15 Register Description – Production Signature Row 4.15.1 RCOSC2M – Internal 2MHz Oscillator Calibration register z Bit 7:0 – RCOSC2M[7:0]: Internal 2MHz Oscillator Calibration Value This byte contains the oscillator calibration value for the internal 2MHz oscillator. Calibration of the oscillator is performed during production test of the device. During reset this value is automatically loaded into calibration register B for the 2MHz DFLL. Refer to “CALB – DFLL Calibration register B” on page 92 for more details. 4.15.2 RCOSC2MA – Internal 2MHz Oscillator Calibration register z Bit 7:0 – RCOSC2MA[7:0]: Internal 2MHz Oscillator Calibration Value This byte contains the oscillator calibration value for the internal 2MHz oscillator. Calibration of the oscillator is performed during production test of the device. During reset this value is automatically loaded into calibration register A for the 2MHz DFLL. Refer to “CALA – DFLL Calibration Register A” on page 92 for more details. 4.15.3 RCOSC32K – Internal 32.768kHz Oscillator Calibration register z Bit 7:0 – RCOSC32K[7:0]: Internal 32.768kHz Oscillator Calibration Value This byte contains the oscillator calibration value for the internal 32.768kHz oscillator. Calibration of the oscillator is performed during production test of the device. During reset this value is automatically loaded into the calibration register for the 32.768kHz oscillator. Refer to “RC32KCAL – 32kHz Oscillator Calibration register” on page 90 for more details. 4.15.4 RCOSC32M – Internal 32MHz Oscillator Calibration register z Bit 7:0 – RCOSC32M[7:0]: Internal 32MHz Oscillator Calibration Value This byte contains the oscillator calibration value for the internal 32MHz oscillator. Calibration of the oscillator is performed during production test of the device. During reset this value is automatically loaded into calibration register B for the 32MHz DFLL. Refer to “CALB – DFLL Calibration register B” on page 92 for more details. Bit 7 6 5 4 3 2 1 0 0x00 RCOSC2M[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x01 RCOSC2MA[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x02 RCOSC32K[7:0] Read/Write RRRR R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x03 RCOSC32M[7:0] Read/Write RRRR R R R R Initial Value x x x x x x x x XMEGA B [MANUAL] 37 Atmel-8291C-AVR-XMEGA B -09/2014 4.15.5 RCOSC32MA – Internal 32MHz RC Oscillator Calibration register z Bit 7:0 – RCOSC32MA[7:0]: Internal 32MHz Oscillator Calibration Value This byte contains the oscillator calibration value for the internal 32MHz oscillator. Calibration of the oscillator is performed during production test of the device. During reset this value is automatically loaded into calibration register A for the 32MHz DFLL. Refer to “CALA – DFLL Calibration Register A” on page 92 for more details. 4.15.6 LOTNUM0 – Lot Number register 0 LOTNUM0, LOTNUM1, LOTNUM2, LOTNUM3, LOTNUM4 and LOTNUM5 contain the lot number for each device. Together with the wafer number and wafer coordinates this gives a serial number for the device. z Bit 7:0 – LOTNUM0[7:0]: Lot Number Byte 0 This byte contains byte 0 of the lot number for the device. 4.15.7 LOTNUM1 – Lot Number register 1 z Bit 7:0 – LOTNUM1[7:0]: Lot Number Byte 1 This byte contains byte 1 of the lot number for the device. 4.15.8 LOTNUM2 – Lot Number Register 2 z Bit 7:0 – LOTNUM2[7:0]: Lot Number Byte 2 This byte contains byte 2 of the lot number for the device. Bit 7 6 5 4 3 2 1 0 0x04 RCOSC32MA[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x08 LOTNUM0[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x09 LOTNUM1[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x0A LOTNUM2[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x XMEGA B [MANUAL] 38 Atmel-8291C-AVR-XMEGA B -09/2014 4.15.9 LOTNUM3 – Lot Number register 3 z Bit 7:0 – LOTNUM3[7:0]: Lot Number Byte 3 This byte contains byte 3 of the lot number for the device. 4.15.10 LOTNUM4 – Lot Number register 4 z Bit 7:0 – LOTNUM4[7:0]: Lot Number Byte 4 This byte contains byte 4 of the lot number for the device. 4.15.11 LOTNUM5 – Lot Number register 5 z Bit 7:0 – LOTNUM5[7:0]: Lot Number Byte 5 This byte contains byte 5 of the lot number for the device. 4.15.12 WAFNUM – Wafer Number register z Bit 7:0 – WAFNUM[7:0]: Wafer Number This byte contains the wafer number for each device. Together with the lot number and wafer coordinates this gives a serial number for the device. Bit 7 6 5 4 3 2 1 0 0x0B LOTNUM3[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x0C LOTNUM4[7:0] Read/Write RRRR R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x0D LOTNUM5[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x10 WAFNUM[7:0] Read/Write R R R R R R R R Initial Value 0 0 0 x x x x x XMEGA B [MANUAL] 39 Atmel-8291C-AVR-XMEGA B -09/2014 4.15.13 COORDX0 – Wafer Coordinate X register 0 COORDX0, COORDX1, COORDY0 and COORDY1 contain the wafer X and Y coordinates for each device. Together with the lot number and wafer number, this gives a serial number for each device. z Bit 7:0 – COORDX0[7:0]: Wafer Coordinate X Byte 0 This byte contains byte 0 of wafer coordinate X for the device. 4.15.14 COORDX1 – Wafer Coordinate X register 1 z Bit 7:0 – COORDX0[7:0]: Wafer Coordinate X Byte 1 This byte contains byte 1 of wafer coordinate X for the device. 4.15.15 COORDY0 – Wafer Coordinate Y register 0 z Bit 7:0 – COORDY0[7:0]: Wafer Coordinate Y Byte 0 This byte contains byte 0 of wafer coordinate Y for the device. 4.15.16 COORDY1 – Wafer Coordinate Y register 1 z Bit 7:0 – COORDY1[7:0]: Wafer Coordinate Y Byte 1 This byte contains byte 1 of wafer coordinate Y for the device. Bit 7 6 5 4 3 2 1 0 0x12 COORDX0[7:0] Read/Write RRRR R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x13 COORDX1[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x14 COORDY0[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x15 COORDY1[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x XMEGA B [MANUAL] 40 Atmel-8291C-AVR-XMEGA B -09/2014 4.15.17 USBCAL0 – USB Calibration register 0 USBCAL0 and USBCAL1 contain the calibration value for the USB pins. Calibration is done during production to enable operation without requiring external components on the USB lines for the device. The calibration bytes are not loaded automatically into the USB calibration registers, and so this must be done from software. z Bit 7:0 – USBCAL0[7:0]: USB Pad Calibration byte 0 This byte contains byte 0 of the USB pin calibration data, and must be loaded into the USB CALL register. 4.15.18 USBCAL1 – USB Pad Calibration register 1 z Bit 7:0 – USBCAL1[7:0]: USB Pad Calibration byte 1 This byte contains byte 1 of the USB pin calibration data, and must be loaded into the USB CALH register. 4.15.19 USBRCOSC – USB RCOSC Calibration z Bit 7:0 – USBRCOSC[7:0]: 48MHz RSCOSC Calibration This byte contains a 48MHz calibration value for the internal 32MHz oscillator. When this calibration value is written to calibration register B for the 32MHz DFLL, the oscillator is calibrated to 48MHz to enable full-speed USB operation from internal oscillator. Note: The COMP2 and COMP1 registers inside the DFLL32M must be set to B71B. 4.15.20 ADCACAL0 – ADCA Calibration register 0 ADCACAL0 and ADCACAL1 contain the calibration value for the analog to digital converter A (ADCA). Calibration is done during production test of the device. The calibration bytes are not loaded automatically into the ADC calibration registers, so this must be done from software. z Bit 7:0 – ADCACAL0[7:0]: ADCA Calibration Byte 0 This byte contains byte 0 of the ADCA calibration data, and must be loaded into the ADCA CALL register. Bit 7 6 5 4 3 2 1 0 0x1A USBCAL0[7:0] Read/Write RRRR R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x1B USBCAL1[7:0] Read/Write RRRR R R R R Initial Value xxxx x x x x Bit 7 6 5 4 3 2 1 0 0x1C USBRCOSC[7:0] Read/Write RRRR R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x20 ADCACAL0[7:0] Read/Write RRRR R R R R Initial Value xxxx x x x x XMEGA B [MANUAL] 41 Atmel-8291C-AVR-XMEGA B -09/2014 4.15.21 ADCACAL1 – ADCA Calibration register 1 z Bit 7:0 – ADCACAL1[7:0]: ADCA Calibration Byte 1 This byte contains byte 1 of the ADCA calibration data, and must be loaded into the ADCA CALH register. 4.15.22 TEMPSENSE0 – Temperature Sensor Calibration register 0 TEMPSENSE0 and TEMPSENSE1 contain the 12-bit ADCA value from a temperature measurement done with the internal temperature sensor. The measurement is done in production test at 85°C and can be used for single- or multipoint temperature sensor calibration. z Bit 7:0 – TEMPSENSE0[7:0]: Temperature Sensor Calibration Byte 0 This byte contains the byte 0 of the temperature measurement. 4.15.23 TEMPSENSE1 – Temperature Sensor Calibration register 1 z Bit 7:0 – TEMPSENSE1[7:0]: Temperature Sensor Calibration Byte 1 This byte contains byte 1 of the temperature measurement. Bit 7 6 5 4 3 2 1 0 0x21 ADCACAL1[7:0] Read/Write RRRR R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x2E TEMPSENSE0[7:0] Read/Write R R R R R R R R Initial Value x x x x x x x x Bit 7 6 5 4 3 2 1 0 0x2F TEMPSENSE1[7:0] Read/Write R R R R R R R R Initial Value 0 0 0 0 x x x x XMEGA B [MANUAL] 42 Atmel-8291C-AVR-XMEGA B -09/2014 4.16 Register Description – General Purpose I/O Memory 4.16.1 GPIORn – General Purpose I/O register n These are general purpose registers that can be used to store data, such as global variables and flags, in the bitaccessible I/O memory space. 4.17 Register Descriptions – MCU Control 4.17.1 DEVID0 – Device ID register 0 DEVID0, DEVID1 and DEVID2 contain the byte identification that identifies each microcontroller device type. For details on the actual ID, refer to the device datasheets. z Bit 7:0 – DEVID0[7:0]: Device ID Byte 0 Byte 0 of the device ID. This byte will always be read as 0x1E. This indicates that the device is manufactured by Atmel. 4.17.2 DEVID1 – Device ID register 1 z Bit 7:0 – DEVID[7:0]: Device ID Byte 1 Byte 1 of the device ID indicates the flash size of the device. 4.17.3 DEVID2 – Device ID register 2 z Bit 7:0 – DEVID2[7:0]: Device ID Byte 2 Byte 2 of the device ID indicates the device number. Bit 7 6 5 4 3 2 1 0 +n GPIORn[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 00000 Bit 7 6 5 4 3 2 1 0 +0x00 DEVID0[7:0] Read/Write R R RRRRRR Initial Value 00011110 Bit 7 6 5 4 3 2 1 0 +0x01 DEVID1[7:0] Read/Write R R RRRRRR Initial Value 1/0 1/0 1/0 1/0 1/0 1/0 1/0 1/0 Bit 7 6 5 4 3 2 1 0 +0x02 DEVID2[7:0] Read/Write R R RRRRRR Initial Value 1/0 1/0 1/0 1/0 1/0 1/0 1/0 1/0 XMEGA B [MANUAL] 43 Atmel-8291C-AVR-XMEGA B -09/2014 4.17.4 REVID – Revision ID z Bit 7:4 – Reserved These bits are unused and reserved for future use. z Bit 3:0 – REVID[3:0]: Revision ID These bits contains the device revision. 0 = A, 1 = B, and so on. 4.17.5 ANAINIT – Analog Initialization register z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1:0 – STARTUPDLYx Setting these bits enables sequential start of the internal components used for the ADC, DAC, and analog comparator with the main input/output connected to that port. When this is done, the internal components such as voltage reference and bias currents are started sequentially when the module is enabled. This reduces the peak current consumption during startup of the module. For maximum effect, the start-up delay should be set so that it is larger than 0.5μs. Table 4-12. Analog start-up delay 4.17.6 EVSYSLOCK – Event System Lock register z Bit 7:1 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. Bit 7 6 5 4 3 2 1 0 +0x03 – – – – REVID[3:0] Read/Write R RRRRRRR Initial Value 0 0 0 0 1/0 1/0 1/0 1/0 Bit 7 6 5 4 3 2 1 0 +0x07 – – – – – – STARTUPDLYA[1:0] Read/Write R R R R R R R/W R/W Initial Value 0 0 0 00000 STARTUPDLYx Group Configuration Description 00 NONE Direct startup 11 2CLK 2 * CLKPER 10 8CLK 8 * CLKPER 11 32CLK 32 * CLKPER Bit 7 6 5 4 3 2 1 0 +0x08 – – – – – – – EVSYS0LOCK Read/Write R R R R R R R R/W Initial Value 0 0 0 0000 0 XMEGA B [MANUAL] 44 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 0 – EVSYS0LOCK: Setting this bit will lock all registers in the event system related to event channels 0 to 3 against further modification. The following registers in the event system are locked: CH0MUX, CH0CTRL, CH1MUX, CH1CTRL, CH2MUX, CH2CTRL, CH3MUX, and CH3CTRL. This bit is protected by the configuration change protection mechanism. For details, refer to “Configuration Change Protection” on page 13. 4.17.7 AWEXLOCK – Advanced Waveform Extension Lock register z Bit 7:1 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 0 – AWEXCLOCK: Advanced Waveform Extension Lock for TCC0 Setting this bit will lock all registers in the AWEXC module for timer/counter C0 for against further modification. This bit is protected by the configuration change protection mechanism. For details, refer to “Configuration Change Protection” on page 13. Bit 7 6 5 4 3 2 1 0 +0x09 – – – – – – – AWEXCLOCK Read/Write R R R R R R R R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 45 Atmel-8291C-AVR-XMEGA B -09/2014 4.18 Register Summary - NVM Controller 4.19 Register Summary - Fuses and Lock Bits 4.20 Register Summary - Production Signature Row Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 ADDR0 Address Byte 0 25 +0x01 ADDR1 Address Byte 1 25 +0x02 ADDR2 Address Byte 2 25 +0x03 Reserved – – – – – – – – +0x04 DATA0 Data Byte 0 26 +0x05 DATA1 Data Byte 1 26 +0x06 DATA2 Data Byte 2 26 +0x07 Reserved – – – – – – – – +0x08 Reserved – – – – – – – – +0x09 Reserved – – – – – – – – +0x0A CMD – CMD[6:0] 26 +0x0B CTRLA – – – – – – – CMDEX 27 +0x0C CTRLB – – – – EEMAPEN FPRM EPRM SPMLOCK 27 +0x0D INTCTRL – – – – SPMLVL[1:0] EELVL[1:0] 28 +0x0E Reserved – – – – – – – – +0x0F STATUS NVMBUSY FBUSY – – – – EELOAD FLOAD 28 +0x10 LOCKBITS BLBB[1:0] BLBA[1:0] BLBAT[1:0] LB[1:0] 29 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 Reserved – – – – – – – – +0x01 FUSEBYTE1 WDWPER3:0] WDPER[3:0] 30 +0x02 FUSEBYTE2 – BOOTRST TOSCSEL – – – BODPD[1:0] 30 +0x03 Reserved – – – – – – – – +0x04 FUSEBYTE4 – – – RSTDISBL STARTUPTIME[1:0] WDLOCK – 31 +0x05 FUSEBYTE5 – – BODACT[1:0] EESAVE BODLEVEL[2:0] 32 +0x06 Reserved – – – – – – – – +0x07 LOCKBITS BLBB[1:0] BLBA[1:0] BLBAT[1:0] LB[1:0] 34 Address Auto Load Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page 0x00 YES RCOSC2M RCOSC2M[7:0] 36 0x01 YES RCOSC2MA RCOSC2MA[7:0] 37 0x02 YES RCOSC32K RCOSC32K[7:0] 36 0x03 YES RCOSC32M RCOSC32M[7:0] 36 0x04 YES RCOSC32MA RCOSC32MA[7:0] 37 0x05 Reserved – – – – – – – – 0x06 Reserved – – – – – – – – 0x07 Reserved – – – – – – – – 0x08 NO LOTNUM0 LOTNUM0[7:0] 37 0x09 NO LOTNUM1 LOTNUM1[7:0] 37 0x0A NO LOTNUM2 LOTNUM2[7:0] 37 0x0B NO LOTNUM3 LOTNUM3[7:0] 38 0x0C NO LOTNUM4 LOTNUM4[7:0] 38 0x0D NO LOTNUM5 LOTNUM5[7:0] 38 0x0E Reserved – – – – – – – – 0x0F Reserved – – – – – – – – 0x10 NO WAFNUM WAFNUM[7:0] 38 0x11 Reserved – – – – – – – – 0x12 NO COORDX0 COORDX0[7:0] 39 0x13 NO COORDX1 COORDX1[7:0] 39 0x14 NO COORDY0 COORDY0[7:0] 39 0x15 NO COORDY1 COORDY1[7:0] 39 0x16 Reserved – – – – – – – – 0x17 Reserved – – – – – – – – 0x18 Reserved – – – – – – – – 0x19 Reserved – – – – – – – – 0x1A USBCAL0 USBCAL0[7:0] 40 0x1B USBCAL1 USBCAL1[7:0] 40 0x1C USBRCOSC USBRCOSC[7:0] 40 XMEGA B [MANUAL] 46 Atmel-8291C-AVR-XMEGA B -09/2014 4.21 Register Summary – General Purpose I/O Registers 4.22 Register Summary – MCU Control 4.23 Interrupt Vector Summary – NVM Controller 0x1D Reserved – – – – – – – – 0x0E Reserved – – – – – – – – 0x1E Reserved – – – – – – – – 0x20 NO ADCACAL0 ADCACAL0[7:0] 40 0x21 NO ADCACAL1 ADCACAL1{7:0] 41 0x22 Reserved – – – – – – – – 0x23 Reserved – – – – – – – – 0x24 Reserved – – – – – – – – 0x25 Reserved – – – – – – – – 0x26 Reserved – – – – – – – – 0x27 Reserved – – – – – – – – 0x28 Reserved – – – – – – – – 0x29 Reserved – – – – – – – – 0x2A Reserved – – – – – – – – 0x2B Reserved – – – – – – – – 0x2C Reserved – – – – – – – – 0x2D Reserved – – – – – – – – 0x2E NO TEMPSENSE0 TEMPSENSE0[7:0] 41 0x2F NO TEMPSENSE1 – – – – TEMPSENSE1[11:8] 41 0x38 Reserved – – – – – – – – 0x39 Reserved – – – – – – – – 0x3A Reserved – – – – – – – – 0x3B Reserved – – – – – – – – 0x3C Reserved – – – – – – – – 0x3D Reserved – – – – – – – – 0x3E Reserved – – – – – – – – Address Auto Load Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 GPIOR0 GPIOR[7:0] 42 +0x01 GPIOR1 GPIOR[7:0] 42 +0x02 GPIOR2 GPIOR[7:0] 42 +0x03 GPIOR3 GPIOR[7:0] 42 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 DEVID0 DEVID0[7:0] 42 +0x01 DEVID1 DEVID1[7:0] 42 +0x02 DEVID2 DEVID2[7:0] 42 +0x03 REVID – – – – REVID[3:0] 43 +0x04 Reserved – – – – – – – – +0x05 Reserved – – – – – – – – +0x06 Reserved – – – – – – – – +0x07 ANAINIT – – – – STARTUPDLYB[1:0] STARTUPDLYA[1:0] 43 +0x08 EVSYSLOCK – – – – – – – EVSYS0LOC 43 +0x09 AWEXLOCK – – – – – – – AWEXCLOCK 44 +0x0A Reserved – – – – – – – – +0x0B Reserved – – – – – – – – Offset Source Interrupt Description 0x00 EE_vect Nonvolatile memory EEPROM interrupt vector 0x02 SPM_vect Nonvolatile memory SPM interrupt vector XMEGA B [MANUAL] 47 8291C–AVR–09/2014 5. DMAC - Direct Memory Access Controller 5.1 Features z Allows high speed data transfers with minimal CPU intervention z from data memory to data memory z from data memory to peripheral z from peripheral to data memory z from peripheral to peripheral z Two DMA channels with separate z transfer triggers z interrupt vectors z addressing modes z Programmable channel priority z From 1 byte to 16MB of data in a single transaction z Up to 64KB block transfers with repeat z 1, 2, 4, or 8 byte burst transfers z Multiple addressing modes z Static z Incremental z Decremental z Optional reload of source and destination addresses at the end of each z Burst z Block z Transaction z Optional interrupt on end of transaction z Optional connection to CRC generator for CRC on DMA data 5.2 Overview The two-channel direct memory access (DMA) controller can transfer data between memories and peripherals, and thus offload these tasks from the CPU. It enables high data transfer rates with minimum CPU intervention, and frees up CPU time. The two DMA channels enable up to two independent and parallel transfers. The DMA controller can move data between SRAM and peripherals, between SRAM locations and directly between peripheral registers. With access to all peripherals, the DMA controller can handle automatic transfer of data to/from communication modules. The DMA controller can also read from memory mapped EEPROM. Data transfers are done in continuous bursts of 1, 2, 4, or 8 bytes. They build block transfers of configurable size from 1 byte to 64KB. A repeat counter can be used to repeat each block transfer for single transactions up to 16MB. Source and destination addressing can be static, incremental or decremental. Automatic reload of source and/or destination addresses can be done after each burst or block transfer, or when a transaction is complete. Application software, peripherals, and events can trigger DMA transfers. The two DMA channels have individual configuration and control settings. This include source, destination, transfer triggers, and transaction sizes. They have individual interrupt settings. Interrupt requests can be generated when a transaction is complete or when the DMA controller detects an error on a DMA channel. To allow for continuous transfers, two channels can be interlinked so that the second takes over the transfer when the first is finished, and vice versa. XMEGA B [MANUAL] 48 8291C–AVR–09/2014 Figure 5-1. DMA Overview. 5.3 DMA Transaction A complete DMA read and write operation between memories and/or peripherals is called a DMA transaction. A transaction is done in data blocks, and the size of the transaction (number of bytes to transfer) is selectable from software and controlled by the block size and repeat counter settings. Each block transfer is divided into smaller bursts. 5.3.1 Block Transfer and Repeat The size of the block transfer is set by the block transfer count register, and can be anything from 1 byte to 64KB. A repeat counter can be enabled to set a number of repeated block transfers before a transaction is complete. The repeat is from 1 to 255, and an unlimited repeat count can be achieved by setting the repeat count to zero. 5.3.2 Burst Transfer Since the AVR CPU and DMA controller use the same data buses, a block transfer is divided into smaller burst transfers. The burst transfer is selectable to 1, 2, 4, or 8 bytes. This means that if the DMA acquires the data bus and a transfer request is pending, it will occupy the bus until all bytes in the burst are transferred. A bus arbiter controls when the DMA controller and the AVR CPU can use the bus. The CPU always has priority, and so as long as the CPU requests access to the bus, any pending burst transfer must wait. The CPU requests bus access when it executes an instruction that writes or reads data to SRAM, I/O memory, EEPROM or the external bus interface. For more details on memory access bus arbitration, refer to “Data Memory” on page 22. Figure 5-2. DMA transaction. R/W Master port Arbitration BUF Bus matrix Arbiter Read Write Slave port Read / Write CTRL DMA Channel 1 DMA trigger / Event DMA Channel 0 SRCADDR TRFCNT DESTADDR TRIGSRC REPCNT Control Logic Enable Burst CTRLA CTRLB XMEGA B [MANUAL] 49 8291C–AVR–09/2014 5.4 Transfer Triggers DMA transfers can be started only when a DMA transfer request is detected. A transfer request can be triggered from software, from an external trigger source (peripheral), or from an event. There are dedicated source trigger selections for each DMA channel. The available trigger sources may vary from device to device, depending on the modules or peripherals that exist in the device. Using a transfer trigger for a module or peripherals that does not exist will have no effect. For a list of all transfer triggers, refer to “TRIGSRC – Trigger Source” on page 57. By default, a trigger starts a block transfer operation. When the block transfer is complete, the channel is automatically disabled. When enabled again, the channel will wait for the next block transfer trigger. It is possible to select the trigger to start a burst transfer instead of a block transfer. This is called a single-shot transfer, and for each trigger only one burst is transferred. When repeat mode is enabled, the next block transfer does not require a transfer trigger. It will start as soon as the previous block is done. If the trigger source generates a transfer request during an ongoing transfer, this will be kept pending, and the transfer can start when the ongoing one is done. Only one pending transfer can be kept, and so if the trigger source generates more transfer requests when one is already pending, these will be lost. 5.5 Addressing The source and destination address for a DMA transfer can either be static or automatically incremented or decremented, with individual selections for source and destination. When address increment or decrement is used, the default behaviour is to update the address after each access. The original source and destination addresses are stored by the DMA controller, and so the source and destination addresses can be individually configured to be reloaded at the following points: z End of each burst transfer z End of each block transfer z End of transaction z Never reloaded 5.6 Priority Between Channels If several channels request a data transfer at the same time, a priority scheme is available to determine which channel is allowed to transfer data. Application software can decide whether one or more channels should have a fixed priority or if a round robin scheme should be used. A round robin scheme means that the channel that last transferred data will have the lowest priority. 5.7 Double Buffering To allow for continuous transfer, two channels can be interlinked so that the second takes over the transfer when the first is finished, and vice versa. This leaves time for the application to process the data transferred by the first channel, prepare fresh data buffers, and set up the channel registers again while the second channel is working. This is referred to as double buffering or chained transfers. When double buffering is enabled for a channel pair, it is important that the two channels are configured with the same repeat count. The block sizes need not be equal, but for most applications they should be, along with the rest of the channel’s operation mode settings. Note that the double buffering channel pairs are limited to channels 0 and 1 as the first pair and channels 2 and 3 as the second pair. However, it is possible to have one pair operate in double buffered mode while the other is left unused or operating independently. 5.8 Transfer Buffers To avoid unnecessary bus loading when doing data transfer between memories with different access timing (for example, I/O register and external memory), the DMA controller has a four-byte buffer. Two bytes will be read from the source address and written to this buffer before a write to the destination is started. XMEGA B [MANUAL] 50 8291C–AVR–09/2014 5.9 Error detection The DMA controller can detect erroneous operation. Error conditions are detected individually for each DMA channel, and the error conditions are: z Write to memory mapped EEPROM locations z Reading EEPROM when the EEPROM is off (sleep entered) z DMA controller or a busy channel is disabled in software during a transfer 5.10 Software Reset Both the DMA controller and a DMA channel can be reset from the user software. When the DMA controller is reset, all registers associated with the DMA controller, including channels, are cleared. A software reset can be done only when the DMA controller is disabled. When a DMA channel is reset, all registers associated with the DMA channel are cleared. A software reset can be done only when the DMA channel is disabled. 5.11 Protection In order to ensure safe operation, some of the channel registers are protected during a transaction. When the DMA channel busy flag (CHnBUSY) is set for a channel, the user can modify only the following registers and bits: z CTRL register z INTFLAGS register z TEMP registers z CHEN, CHRST, TRFREQ, and REPEAT bits of the channel CTRL register z TRIGSRC register 5.12 Interrupts The DMA controller can generate interrupts when an error is detected on a DMA channel or when a transaction is complete for a DMA channel. Each DMA channel has a separate interrupt vector, and there are different interrupt flags for error and transaction complete. If repeat is not enabled, the transaction complete flag is set at the end of the block transfer. If unlimited repeat is enabled, the transaction complete flag is also set at the end of each block transfer. XMEGA B [MANUAL] 51 8291C–AVR–09/2014 5.13 Register Description – DMA Controller 5.13.1 CTRL – Control register z Bit 7 – ENABLE: Enable Setting this bit enables the DMA controller. If the DMA controller is enabled and this bit is written to zero, the ENABLE bit is not cleared before the internal transfer buffer is empty, and the DMA data transfer is aborted. z Bit 6 – RESET: Software Reset Writing a one to RESET will be ignored as long as DMA is enabled (ENABLE = 1). This bit can be set only when the DMA controller is disabled (ENABLE = 0). z Bit 5:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2 – DBUFMODE: Double Buffer Mode This bit enables the double buffer mode. z Bit 1 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bits to zero when this register is written. z Bit 0 – PRIMODE: Channel Priority Mode This bit determines the internal channel priority according to Table 5-1. Table 5-1. Channel priority settings 5.13.2 INTFLAGS – Interrupt Status register z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. Bit 7 6 5 4 3 2 1 0 +0x00 ENABLE RESET – – – DBUFMODE – PRIMODE Read/Write R/W R/W R R R R/W R R/W Initial Value 0 0 0 0 0 0 0 0 PRIMODE Group Configuration Description 0 RR01 Round robin 1 CH01 Channel0 has priority Bit 7 6 5 4 3 2 1 0 +0x03 – – CH1ERRIF CH0ERRIF – – CH1TRNFIF CH0TRNFIF Read/Write R R R/W R/W R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 52 8291C–AVR–09/2014 z Bit 5:4 – CHnERRIF[1:0]: Channel n Error Interrupt Flag If an error condition is detected on DMA channel n, the CHnERRIF flag will be set. Writing a one to this bit location will clear the flag. z Bit 3:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1:0 – CHnTRNFIF[1:0]: Channel n Transaction Complete Interrupt Flag When a transaction on channel n has been completed, the CHnTRFIF flag will be set. If unlimited repeat count is enabled, this flag is read as one after each block transfer. Writing a one to this bit location will clear the flag. 5.13.3 STATUS – Status register z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 5:4 – CHnBUSY[1:0]: Channel Busy When channel n starts a DMA transaction, the CHnBUSY flag will be read as one. This flag is automatically cleared when the DMA channel is disabled, when the channel n transaction complete interrupt flag is set, or if the DMA channel n error interrupt flag is set. z Bit 3:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written z Bit 1:0 – CHnPEND[1:0]: Channel Pending If a block transfer is pending on DMA channel n, the CHnPEND flag will be read as one. This flag is automatically cleared when the block transfer starts or if the transfer is aborted. 5.13.4 TEMPL – Temporary register Low z Bit 7:0 – TEMP[7:0]: Temporary register 0 This register is used when reading 16- and 24-bit registers in the DMA controller. Byte 1 of the 16/24-bit register is stored here when it is written by the CPU. Byte 1 of the 16/24-bit register is stored when byte 0 is read by the CPU. This register can also be read and written from the user software. Reading and writing 16- and 24-bit registers requires special attention. For details, refer to “Accessing 16-bit Registers” on page 13. Bit 7 6 5 4 3 2 1 0 +0x04 – – CH1BUSY CH0BUSY – – CH1PEND CH0PEND Read/Write R R R R R R R R Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x06 TEMP[7:0] 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 XMEGA B [MANUAL] 53 8291C–AVR–09/2014 5.13.5 TEMPH – Temporary Register High z Bit 7:0 – TEMP[15:8]: Temporary Register This register is used when reading and writing 24-bit registers in the DMA controller. Byte 2 of the 24-bit register is stored when it is written by the CPU. Byte 2 of the 24-bit register is stored here when byte 1 is read by the CPU. This register can also be read and written from the user software. Reading and writing 24-bit registers requires special attention. For details, refer to “Accessing 16-bit Registers” on page 13. 5.14 Register Description – DMA Channel 5.14.1 CTRLA – Control register A z Bit 7 – ENABLE: Channel Enable Setting this bit enables the DMA channel. This bit is automatically cleared when the transaction is completed. If the DMA channel is enabled and this bit is written to zero, the CHEN bit is not cleared until the internal transfer buffer is empty and the DMA transfer is aborted. z Bit 6 – RESET: Software Reset Setting this bit will reset the DMA channel. It can only be set when the DMA channel is disabled (CHEN = 0). Writing a one to this bit will be ignored as long as the channel is enabled (CHEN=1). This bit is automatically cleared when reset is completed. z Bit 5 – REPEAT: Repeat Mode Setting this bit enables the repeat mode. In repeat mode, this bit is cleared by hardware at the beginning of the last block transfer. The REPCNT register should be configured before setting the REPEAT bit. z Bit 4 – TRFREQ: Transfer Request Setting this bit requests a data transfer on the DMA channel. This bit is automatically cleared at the beginning of the data transfer. Writing this bit does not have any effect unless the channel is enabled. z Bit 3 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 2 – SINGLE: Single-Shot Data transfer Setting this bit enables the single-shot mode. The channel will then do a burst transfer of BURSTLEN bytes on the transfer trigger. A write to this bit will be ignored while the channel is enabled. Bit 7 6 5 4 3 2 1 0 +0x07 TEMP[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x00 ENABLE RESET REPEAT TRFREQ – SINGLE BURSTLEN[1:0] Read/Write R/W R/W R/W R/W R R/W R/W R/W Initial Value 0 0 000000 XMEGA B [MANUAL] 54 8291C–AVR–09/2014 z Bit 1:0 – BURSTLEN[1:0]: Burst Mode These bits decide the DMA channel burst mode according to Table 5-2 on page 54. These bits cannot be changed if the channel is busy. Table 5-2. DMA channel burst mode Table 5-3. Summary of triggers, transaction complete flag and channel disable according to DMA channel configuration. 5.14.2 CTRLB – Control register B z Bit 7 – CHBUSY: Channel Busy When the DMA channel starts a DMA transaction, the CHBUSY flag will be read as one. This flag is automatically cleared when the DMA channel is disabled, when the channel transaction complete interrupt flag is set or when the channel error interrupt flag is set. BURSTLEN[1:0] Group Configuration Description 00 1BYTE 1 byte burst mode 01 2BYTE 2 bytes burst mode 10 4BYTE 4 bytes burst mode 11 8BYTE 8 bytes burst mode REPEAT SINGLE REPCNT Trigger Flag Set After Channel Disabled After 0 0 0 Block 1 block 1 block 0 0 1 Block 1 block 1 block 0 0 n > 1 Block 1 block 1 block 0 1 0 BURSTLEN 1 block 1 block 0 1 1 BURSTLEN 1 block 1 block 0 1 n > 1 BURSTLEN 1 block 1 block 1 0 0 Block Each block Each block 1 0 1 Transaction 1 block 1 block 1 0 n > 1 Transaction n blocks n blocks 1 1 0 BURSTLEN Each block Never 1 1 1 BURSTLEN 1 block 1 block 1 1 n > 1 BURSTLEN n blocks n blocks Bit 7 6 5 4 3 2 1 0 +0x01 CHBUSY CHPEND ERRIF TRNIF ERRINTLVL[1:0] TRNINTLVL[1:0] Read/Write R R R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 55 8291C–AVR–09/2014 z Bit 6 – CHPEND: Channel Pending If a block transfer is pending on the DMA channel, the CHPEND flag will be read as one. This flag is automatically cleared when the transfer starts or if the transfer is aborted. z Bit 5 – ERRIF: Error Interrupt Flag If an error condition is detected on the DMA channel, the ERRIF flag will be set and the optional interrupt is generated. Since the DMA channel error interrupt shares the interrupt address with the DMA channel n transaction complete interrupt, ERRIF will not be cleared when the interrupt vector is executed. This flag is cleared by writing a one to this location. z Bit 4 – TRNIF: Channel n Transaction Complete Interrupt Flag When a transaction on the DMA channel has been completed, the TRNIF flag will be set and the optional interrupt is generated. When repeat is not enabled, the transaction is complete and TRNIFR is set after the block transfer. When unlimited repeat is enabled, TRNIF is also set after each block transfer. Since the DMA channel transaction n complete interrupt shares the interrupt address with the DMA channel error interrupt, TRNIF will not be cleared when the interrupt vector is executed. This flag is cleared by writing a one to this location. z Bit 3:2 – ERRINTLVL[1:0]: Channel Error Interrupt Level These bits enable the interrupt for DMA channel transfer errors and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger for the conditions when ERRIF is set. z Bit 1:0 – TRNINTLVL[1:0]: Channel Transaction Complete Interrupt Level These bits enable the interrupt for DMA channel transaction completes and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger for the conditions when TRNIF is set. 5.14.3 ADDRCTRL – Address Control register z Bit 7:6 – SRCRELOAD[1:0]: Channel Source Address Reload These bits decide the DMA channel source address reload according to Table 5-4. A write to these bits is ignored while the channel is busy. Table 5-4. DMA channel source address reload settings Bit 7 6 5 4 3 2 1 0 +0x02 SRCRELOAD[1:0] SRCDIR[1:0] DESTRELOAD[1:0] DESTDIR[1:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0000000 SRCRELOAD[1:0] Group Configuration Description 00 NONE No reload performed. 01 BLOCK DMA source address register is reloaded with initial value at end of each block transfer. 10 BURST DMA source address register is reloaded with initial value at end of each burst transfer. 11 TRANSACTION DMA source address register is reloaded with initial value at end of each transaction. XMEGA B [MANUAL] 56 8291C–AVR–09/2014 z Bit 5:4 – SRCDIR[1:0]: Channel Source Address Mode These bits decide the DMA channel source address mode according to Table 5-5. These bits cannot be changed if the channel is busy. Table 5-5. DMA channel source address mode settings. z Bit 3:2 – DESTRELOAD[1:0]: Channel Destination Address Reload These bits decide the DMA channel destination address reload according to Table 5-6. These bits cannot be changed if the channel is busy. Table 5-6. DMA channel destination address reload settings z Bit 1:0 – DESTDIR[1:0]: Channel Destination Address Mode These bits decide the DMA channel destination address mode according to Table 5-7. These bits cannot be changed if the channel is busy. Table 5-7. DMA channel destination address mode settings SRCDIR[1:0] Group Configuration Description 00 FIXED Fixed 01 INC Increment 10 DEC Decrement 11 - Reserved DESTRELOAD[1:0] Group Configuration Description 00 NONE No reload performed. 01 BLOCK DMA channel destination address register is reloaded with initial value at end of each block transfer. 10 BURST DMA channel destination address register is reloaded with initial value at end of each burst transfer. 11 TRANSACTION DMA channel destination address register is reloaded with initial value at end of each transaction. DESTDIR[1:0] Group Configuration Description 00 FIXED Fixed 01 INC Increment 10 DEC Decrement 11 - Reserved XMEGA B [MANUAL] 57 8291C–AVR–09/2014 5.14.4 TRIGSRC – Trigger Source z Bit 7:0 – TRIGSRC[7:0]: Channel Trigger Source Select These bits select which trigger source is used for triggering a transfer on the DMA channel. A zero value means that the trigger source is disabled. For each trigger source, the value to put in the TRIGSRC register is the sum of the module’s or peripheral’s base value and the offset value for the trigger source in the module or peripheral. Table 5-8 on page 57 shows the base value for all modules and peripherals. Table 5-9 on page 58 to Table 5-11 on page 58 shows the offset value for the trigger sources in the different modules and peripheral types. For modules or peripherals which do not exist for a device, the transfer trigger does not exist. Refer to the device datasheet for the list of peripherals available. If the interrupt flag related to the trigger source is cleared or the interrupt level enabled so that an interrupt is triggered, the DMA request will be lost. Since a DMA request can clear the interrupt flag, interrupts can be lost. Note: For most trigger sources, the request is cleared by accessing a register belonging to the peripheral with the request. Refer to the different peripheral chapters for how requests are generated and cleared. Table 5-8. DMA trigger source base values for all modules and peripherals. Bit 7 6 5 4 3 2 1 0 +0x03 TRIGSRC[7:0] 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 TRIGSRC Base Value Group Configuration Description 0x00 OFF Software triggers only 0x01 SYS Event system DMA triggers base value 0x04 AES AES DMA trigger value 0x10 ADCA ADCA DMA trigger value 0x40 TCC0 Timer/counter C0 DMA triggers base value 0x46 TCC1 Timer/counter C1 triggers base value 0x4A SPIC SPI C DMA trigger value 0x4B USARTC0 USART C0 DMA triggers base value 0x60 TCD0 Timer/counter D0 DMA triggers base value 0x6A SPID SPI D DMA triggers value 0x6B USARTD0 USART D0 DMA triggers base value 0x80 TCE0 Timer/counter E0 DMA triggers base value 0x8B USARTE0 USART E0 DMA triggers base value 0xA0 TCF0 Timer/counter F0 DMA triggers base value 0xAB USARTF0 USART F0 DMA triggers base value XMEGA B [MANUAL] 58 8291C–AVR–09/2014 Note: 1. CC channel C and D triggers are available only for timer/counters 0. The group configuration is the “base_offset;” for example, TCC1_CCA for the timer/counter C1 CC channel A the transfer trigger. 5.14.5 TRFCNTL – Channel Block Transfer Count register Low The TRFCNTH and TRFCNTL register pair represents the 16-bit value TRFCNT. TRFCNT defines the number of bytes in a block transfer. The value of TRFCNT is decremented after each byte read by the DMA channel. When TRFCNT reaches zero, the register is reloaded with the last value written to it. z Bit 7:0 – TRFCNT[7:0]: Channel n Block Transfer Count low byte These bits hold the LSB of the 16-bit block transfer count. The default value of this register is 0x1. If a user writes 0x0 to this register and fires a DMA trigger, DMA will be doing 0xFFFF transfers. Table 5-9. DMA trigger source offset values for event system triggers. TRGSRC Offset Value Group Configuration Description +0x00 CH0 Event channel 0 +0x01 CH1 Event channel 1 +0x02 CH2 Event channel 2 Table 5-10. DMA trigger source offset values for timer/ counter triggers. TRGSRC Offset Value Group Configuration Description +0x00 OVF Overflow/underflow +0x01 ERR Error +0x02 CCA Compare or capture channel A +0x03 CCB Compare or capture channel B +0x04 CCC(1) Compare or capture channel C +0x05 CCD(1) Compare or capture channel D Table 5-11. DMA trigger source offset values for USART triggers. TRGSRC Offset Value Group Configuration Description 0x00 RXC Receive complete 0x01 DRE Data register empty Bit 7 6 5 4 3 2 1 0 +0x04 TRFCNT[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 59 8291C–AVR–09/2014 5.14.6 TRFCNTH – Channel Block Transfer Count register High Reading and writing 16-bit values requires special attention. For details, refer to “Accessing 16-bit Registers” on page 13. z Bit 7:0 – TRFCNT[15:8]: Channel n Block Transfer Count high byte These bits hold the MSB of the 16-bit block transfer count. The default value of this register is 0x1. If a user writes 0x0 to this register and fires a DMA trigger, DMA will be doing 0xFFFF transfers. 5.14.7 REPCNT – Repeat Counter register REPCNT counts how many times a block transfer is performed. For each block transfer, this register will be decremented. When repeat mode is enabled (see REPEAT bit in “ADDRCTRL – Address Control register” on page 55), this register is used to control when the transaction is complete. The counter is decremented after each block transfer if the DMA has to serve a limited number of repeated block transfers. When repeat mode is enabled, the channel is disabled when REPCNT reaches zero and the last block transfer is completed. Unlimited repeat is achieved by setting this register to zero. 5.14.8 SRCADDR0 – Source Address 0 SRCADDR0, SRCADDR1, and SRCADDR2 represent the 24-bit value SRCADDR, which is the DMA channel source address. SRCADDR2 is the most significant byte in the register. SRCADDR may be automatically incremented or decremented based on settings in the SRCDIR bits in “ADDRCTRL – Address Control register” on page 55. z Bit 7:0 – SRCADDR[7:0]: Channel Source Address byte 0 These bits hold byte 0 of the 24-bit source address. Bit 7 6 5 4 3 2 1 0 +0x05 TRFCNT[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 00000 Bit 7 6 5 4 3 2 1 0 +0x06 REPCNT[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 000000 Bit 7 6 5 4 3 2 1 0 +0x08 SRCADDR[7:0] 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 XMEGA B [MANUAL] 60 8291C–AVR–09/2014 5.14.9 SRCADDR1 – Channel Source Address 1 z Bit 7:0 – SRCADDR[15:8]: Channel Source Address byte 1 These bits hold byte 1 of the 24-bit source address. 5.14.10 SRCADDR2 – Channel Source Address 2 Reading and writing 24-bit values require special attention. For details, refer to “Accessing 24- and 32-bit Registers” on page 13. z Bit 7:0 – SRCADDR[23:16]: Channel Source Address byte 2 These bits hold byte 2 of the 24-bit source address. 5.14.11 DESTADDR0 – Channel Destination Address 0 DESTADDR0, DESTADDR1, and DESTADDR2 represent the 24-bit value DESTADDR, which is the DMA channel destination address. DESTADDR2 holds the most significant byte in the register. DESTADDR may be automatically incremented or decremented based on settings in the DESTDIR bits in “ADDRCTRL – Address Control register” on page 55. z Bit 7:0 – DESTADDR[7:0]: Channel Destination Address byte 0 These bits hold byte 0 of the 24-bit source address. Bit 7 6 5 4 3 2 1 0 +0x09 SRCADDR[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 00000 Bit 7 6 5 4 3 2 1 0 +0x0A SRCADDR[23:16] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0C DESTADDR[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 61 8291C–AVR–09/2014 5.14.12 DESTADDR1 – Channel Destination Address 1 z Bit 7:0 – DESTADDR[15:8]: Channel Destination Address byte 1 These bits hold byte 1 of the 24-bit source address. 5.14.13 DESTADDR2 – Channel Destination Address 2 Reading and writing 24-bit values require special attention. For details, refer to “Accessing 24- and 32-bit Registers” on page 13. z Bit 7:0 – DESTADDR[23:16]: Channel Destination Address byte 2 These bits hold byte 2 of the 24-bit source address. Bit 7 6 5 4 3 2 1 0 +0x0D DESTADDR[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0E DESTADDR[23:16] 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 XMEGA B [MANUAL] 62 8291C–AVR–09/2014 5.15 Register Summary – DMA Controller 5.16 Register Summary – DMA Channel 5.17 DMA Interrupt Vector Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL ENABLE RESET – – – DBUFMODE – PRIMODE 51 +0x01 Reserved – – – – – – – – +0x02 Reserved – – – – – – – – +0x03 INTFLAGS – – CH1ERRIF CH0ERRIF – – CH1TRNFIF CH0TRNFIF 51 +0x04 STATUS – – CH1BUSY CH0BUSY – – CH1PEND CH0PEND 52 +0x05 Reserved – – – – – – – – +0x06 TEMPL TEMP[7:0] 52 +0x07 TEMPH TEMP[15:8] 53 +0x10 CH0 Offset Offset address for DMA Channel 0 +0x20 CH1 Offset Offset address for DMA Channel 1 +0x30 Reserved – – – – – – – – +0x40 Reserved – – – – – – – – Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRLA ENABLE RESET REPEAT TRFREQ – SINGLE BURSTLEN[1:0] 53 +0x01 CTRLB CHBUSY CHPEND ERRIF TRNIF ERRINTLVL[1:0] TRNINTLVL[1:0] 54 +0x02 ADDCTRL SRCRELOAD[1:0] SRCDIR[1:0] DESTRELOAD[1:0] DESTDIR[1:0] 55 +0x03 TRIGSRC TRIGSRC[7:0] 57 +0x04 TRFCNTL TRFCNT[7:0] 58 +0x05 TRFCNTH TRFCNT[15:8] 59 +0x06 REPCNT REPCNT[7:0] 59 +0x07 Reserved – – – – – – – – +0x08 SRCADDR0 SRCADDR[7:0] 59 +0x09 SRCADDR1 SRCADDR[15:8] 60 +0x0A SRCADDR2 SRCADDR[23:16] 60 +0x0B Reserved – – – – – – – – +0x0C DESTADDR0 DESTADDR[7:0] 60 +0x0D DESTADDR1 DESTADDR[15:8] 61 +0x0E DESTADDR2 DESTADDR[23:16] 61 +0x0F Reserved – – – – – – – – Offset Source Interrupt Description 0x00 CH0_vect DMA controller channel 0 interrupt vector 0x02 CH1_vect DMA controller channel 1 interrupt vector XMEGA B [MANUAL] 63 8291C–AVR–09/2014 6. Event System 6.1 Features z System for direct peripheral-to-peripheral communication and signaling z Peripherals can directly send, receive, and react to peripheral events z CPU and DMA controller independent operation z 100% predictable signal timing z Short and guaranteed response time z Four event channels for up to eight different and parallel signal routings and configurations z Events can be sent and/or used by most peripherals, clock system, and software z Additional functions include z Quadrature decoders z Digital filtering of I/O pin state z Works in active mode and idle sleep mode 6.2 Overview The event system enables direct peripheral-to-peripheral communication and signaling. It allows a change in one peripheral’s state to automatically trigger actions in other peripherals. It is designed to provide a predictable system for short and predictable response times between peripherals. It allows for autonomous peripheral control and interaction without the use of interrupts CPU or DMA controller resources, and is thus a powerful tool for reducing the complexity, size and execution time of application code. It also allows for synchronized timing of actions in several peripheral modules. A change in a peripheral’s state is referred to as an event, and usually corresponds to the peripheral’s interrupt conditions. Events can be directly passed to other peripherals using a dedicated routing network called the event routing network. How events are routed and used by the peripherals is configured in software. Figure 6-1 on page 64 shows a basic diagram of all connected peripherals. The event system can directly connect together analog converters, analog comparators, I/O port pins, the real-time counter, timer/counters, IR communication module (IRCOM) and USB interface. It can also be used to trigger DMA transactions (DMA controller). Events can also be generated from software and the peripheral clock. XMEGA B [MANUAL] 64 8291C–AVR–09/2014 Figure 6-1. Event system overview and connected peripherals. The event routing network consists of four software-configurable multiplexers that control how events are routed and used. These are called event channels, and allow for up to four parallel event configurations and routings. The maximum routing latency is two peripheral clock cycles. The event system works in both active mode and idle sleep mode. 6.3 Events In the context of the event system, an indication that a change of state within a peripheral has occurred is called an event. There are two main types of events: signaling events and data events. Signaling events only indicate a change of state while data events contain additional information about the event. The peripheral from which the event originates is called the event generator. Within each peripheral (for example, a timer/counter), there can be several event sources, such as a timer compare match or timer overflow. The peripheral using the event is called the event user, and the action that is triggered is called the event action. Timer / Counters USB ADC Real Time Counter Port pins CPU / Software DMA Controller IRCOM Event Routing Network Event System Controller clkPER Prescaler AC XMEGA B [MANUAL] 65 8291C–AVR–09/2014 Figure 6-2. Example of event source, generator, user, and action. Events can also be generated manually in software. 6.3.1 Signaling Events Signaling events are the most basic type of event. A signaling event does not contain any information apart from the indication of a change in a peripheral. Most peripherals can only generate and use signaling events. Unless otherwise stated, all occurrences of the word ”event” are to be understood as meaning signaling events. 6.3.2 Data Events Data events differ from signaling events in that they contain information that event users can decode to decide event actions based on the receiver information. Although the event routing network can route all events to all event users, those that are only meant to use signaling events do not have decoding capabilities needed to utilize data events. How event users decode data events is shown in Table 6-1 on page 66. Event users that can utilize data events can also use signaling events. This is configurable, and is described in the datasheet module for each peripheral. 6.3.3 Peripheral Clock Events Each event channel includes a peripheral clock prescaler with a range from 1 (no prescaling) to 32768. This enables configurable periodic event generation based on the peripheral clock. It is possible to periodically trigger events in a peripheral or to periodically trigger synchronized events in several peripherals. Since each event channel include a prescaler, different peripherals can receive triggers with different intervals. 6.3.4 Software Events Events can be generated from software by writing the DATA and STROBE registers. The DATA register must be written first, since writing the STROBE register triggers the operation. The DATA and STROBE registers contain one bit for each event channel. Bit n corresponds to event channel n. It is possible to generate events on several channels at the same time by writing to several bit locations at once. Software-generated events last for one clock cycle and will overwrite events from other event generators on that event channel during that clock cycle. Table 6-1 on page 66 shows the different events, how they can be manually generated, and how they are decoded. Event User Event Routing Network | Compare Match Over-/Underflow Error Timer/Counter Syncsweep Single Conversion ADC Event Generator Event Source Event Action Event Action Selection XMEGA B [MANUAL] 66 8291C–AVR–09/2014 Table 6-1. Manually generated events and decoding of events. 6.4 Event Routing Network The event routing network routes the events between peripherals. It consists of eight multiplexers (CHnMUX), which can each be configured to route any event source to any event users. The output from a multiplexer is referred to as an event channel. For each peripheral, it is selectable if and how incoming events should trigger event actions. Details on configurations can be found in the datasheet for each peripheral. The event routing network is shown in Figure 6-3 on page 67. STROBE DATA Data Event User Signaling Event User 0 0 No event No event 0 1 Data event 01 No event 1 0 Data event 02 Signaling event 1 1 Data event 03 Signaling event XMEGA B [MANUAL] 67 8291C–AVR–09/2014 Figure 6-3. Event routing network. Four multiplexers means that it is possible to route up to four events at the same time. It is also possible to route one event through several multiplexers. Not all XMEGA devices contain all peripherals. This only means that a peripheral is not available for generating or using events. The network configuration itself is compatible between all devices. 6.5 Event Timing An event normally lasts for one peripheral clock cycle, but some event sources, such as a low level on an I/O pin, will generate events continuously. Details on this are described in the datasheet for each peripheral, but unless otherwise stated, an event lasts for one peripheral clock cycle. (48) PORTA PORTB PORTC PORTD PORTE PORTF ADCA TCF0 (6) TCE0 TCD0 TCC0 TCC1 (6) (4) (4) (4) (4) (10) (6) (29) (4) (4) (4) RTC ClkPER (8) (8) (8) (8) (8) (8) CH0MUX[7:0] CH1MUX[7:0] CH2MUX[7:0] CH3MUX[7:0] CH0CTRL[7:0] CH1CTRL[7:0] CH2CTRL[7:0] CH3CTRL[7:0] Event Channel 3 Event Channel 2 Event Channel 1 Event Channel 0 (6) (16) (2) ACA (3) USB (4) XMEGA B [MANUAL] 68 8291C–AVR–09/2014 It takes a maximum of two peripheral clock cycles from when an event is generated until the event actions in other peripherals are triggered. This ensures short and 100% predictable response times, independent of CPU or DMA controller load or software revisions. 6.6 Filtering Each event channel includes a digital filter. When this is enabled, an event must be sampled with the same value for a configurable number of system clock cycles before it is accepted. This is primarily intended for pin change events. 6.7 Quadrature Decoder The event system includes one quadrature decoder (QDEC), which enable the device to decode quadrature input on I/O pins and send data events that a timer/counter can decode to count up, count down, or index/reset. Table 6-2 summarizes which quadrature decoder data events are available, how they are decoded, and how they can be generated. The QDEC and related features, control and status registers are available for event channel 0. Table 6-2. Quadrature decoder data events. 6.7.1 Quadrature Operation A quadrature signal is characterized by having two square waves that are phase shifted 90 degrees relative to each other. Rotational movement can be measured by counting the edges of the two waveforms. The phase relationship between the two square waves determines the direction of rotation. Figure 6-4. Quadrature signals from a rotary encoder. Figure 6-4 shows typical quadrature signals from a rotary encoder. The signals QDPH0 and QDPH90 are the two quadrature signals. When QDPH90 leads QDPH0, the rotation is defined as positive or forward. When QDPH0 leads QDPH90, the rotation is defined as negative or reverse. The concatenation of the two phase signals is called the quadrature state or the phase state. STROBE DATA Data Event User Signaling Event User 0 0 No event No event 0 1 Index/reset No event 1 0 Count down Signaling event 1 1 Count up Signaling event XMEGA B [MANUAL] 69 8291C–AVR–09/2014 In order to know the absolute rotary displacement, a third index signal (QINDX) can be used. This gives an indication once per revolution. 6.7.2 QDEC Setup For a full QDEC setup, the following is required: z Tho or three I/O port pins for quadrature signal input z Two event system channels for quadrature decoding z One timer/counter for up, down, and optional index count The following procedure should be used for QDEC setup: 1. Choose two successive pins on a port as QDEC phase inputs. 2. Set the pin direction for QDPH0 and QDPH90 as input. 3. Set the pin configuration for QDPH0 and QDPH90 to low level sense. 4. Select the QDPH0 pin as a multiplexer input for an event channel, n. 5. Enable quadrature decoding and digital filtering in the event channel. 6. Optional: 1. Set up a QDEC index (QINDX). 2. Select a third pin for QINDX input. 3. Set the pin direction for QINDX as input. 4. Set the pin configuration for QINDX to sense both edges. 5. Select QINDX as a multiplexer input for event channel n+1 6. Set the quadrature index enable bit in event channel n+1. 7. Select the index recognition mode for event channel n+1. 7. Set quadrature decoding as the event action for a timer/counter. 8. Select event channel n as the event source for the timer/counter. z Set the period register of the timer/counter to ('line count' * 4 - 1), the line count of the quadrature encoder. z Enable the timer/counter without clock prescaling. The angle of a quadrature encoder attached to QDPH0, QDPH90 (and QINDX) can now be read directly from the timer/counter count register. If the count register is different from BOTTOM when the index is recognized, the timer/counter error flag is set. Similarly, the error flag is set if the position counter passes BOTTOM without the recognition of the index. XMEGA B [MANUAL] 70 8291C–AVR–09/2014 6.8 Register Description 6.8.1 CHnMUX – Event Channel n Multiplexer register z Bit 7:0 – CHnMUX[7:0]: Channel Multiplexer These bits select the event source according to Table 6-3. This table is valid for all XMEGA devices regardless of whether the peripheral is present or not. Selecting event sources from peripherals that are not present will give the same result as when this register is zero. When this register is zero, no events are routed through. Manually generated events will override CHnMUX and be routed to the event channel even if this register is zero. Table 6-3. CHnMUX[7:0] bit settings. Bit 7 6 5 4 3 2 1 0 CHnMUX[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 CHnMUX[7:4] CHnMUX[3:0] Group Configuration Event Source 0000 0 0 0 0 None (manually generated events only) 0000 0 0 0 1 (Reserved) 0000 0 0 1 X (Reserved) 0000 0 1 X X (Reserved) 0000 1 0 0 0 RTC_OVF RTC overflow 0000 1 0 0 1 RTC_CMP RTC compare match 0000 1 0 1 0 USB start of frame on CH0(2) USB error on CH1(2) USB overflow on CH2(2) USB setup on CH3(2) 0000 1 0 1 X (Reserved) 0000 1 1 X X (Reserved) 0001 0 0 0 0 ACA_CH0 ACA channel 0 0001 0 0 0 1 ACA_CH1 ACA channel 1 0001 0 0 1 0 ACA_WIN ACA window 0001 0 0 1 1 (Reserved) 0001 0 1 X X (Reserved) 0001 1 X X X (Reserved) 0010 0 0 0 0 ADCA_CH0 ADCA 0010 0 0 0 1 (Reserved) 0010 0 0 1 X (Reserved) 0010 0 1 X X (Reserved) XMEGA B [MANUAL] 71 8291C–AVR–09/2014 Notes: 1. The description of how the ports generate events is described in “Port Event” on page 130. 2. The different USB events can be selected for only event channel, 0 to 3. Table 6-4. Timer/counter events 0010 1 X X X (Reserved) 0011 X X X X (Reserved) 0100 X X X X (Reserved) 0101 0 n PORTA_PINn(1) PORTA pin n (n= 0, 1, 2 ... or 7) 0101 1 n PORTB_PINn(1) PORTB pin n (n= 0, 1, 2 ... or 7) 0110 0 n PORTC_PINn(1) PORTC pin n (n= 0, 1, 2 ... or 7) 0110 1 n PORTD_PINn(1) PORTD pin n (n= 0, 1, 2 ... or 7) 0111 0 n PORTE_PINn(1) PORTE pin n (n= 0, 1, 2 ... or 7) 0111 1 n PORTF_PINn(1) PORTF pin n (n= 0, 1, 2 ... or 7) 1000 M PRESCALER_M ClkPER divide by 2M (M=0 to 15) 1001 X X X X (Reserved) 1010 X X X X (Reserved) 1011 X X X X (Reserved) 1100 0 E See Table 6-4 Timer/counter C0 event type E 1100 1 E See Table 6-4 Timer/counter C1 event type E 1101 0 E See Table 6-4 Timer/counter D0 event type E 1111 1 X X X (Reserved) 1110 0 E See Table 6-4 Timer/counter E0 event type E 1111 1 X X X (Reserved) 1111 0 E See Table 6-4 Timer/counter F0 event type E 1111 1 X X X (Reserved) T/C Event E Group Configuration Event Type 0 0 0 TCxn_OVF Over/Underflow (x = C, D, E or F) (n= 0 or 1) 0 0 1 TCxn_ERR Error (x = C, D, E or F) (n= 0 or 1) 0 1 X – (Reserved) 1 0 0 TCxn_CCA Capture or compare A (x = C, D, E or F) (n= 0 or 1) 1 0 1 TCxn_CCB Capture or compare B (x = C, D, E or F) (n= 0 or 1) 1 1 0 TCxn_CCC Capture or compare C (x = C, D, E or F) (n= 0) 1 1 1 TCxn_CCD Capture or compare D (x = C, D, E or F) (n= 0) CHnMUX[7:4] CHnMUX[3:0] Group Configuration Event Source XMEGA B [MANUAL] 72 8291C–AVR–09/2014 6.8.2 CHnCTRL – Event Channel n Control register Note: 1. Only available for CH0CTRL and CH2CTRL. These bits are reserved in CH1CTRL and CH3CTRL. z Bit 7 – Reserved This bit is reserved and will always be read as zero. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 6:5 – QDIRM[1:0]: Quadrature Decode Index Recognition Mode These bits determine the quadrature state for the QDPH0 and QDPH90 signals, where a valid index signal is recognized and the counter index data event is given according to Table 6-5. These bits should only be set when a quadrature encoder with a connected index signal is used.These bits are available only for CH0CTRL and CH2CTRL. Table 6-5. QDIRM bit settings. z Bit 4 – QDIEN: Quadrature Decode Index Enable When this bit is set, the event channel will be used as a QDEC index source, and the index data event will be enabled. This bit is available only for CH0CTRL and CH2CTRL. z Bit 3 – QDEN: Quadrature Decode Enable Setting this bit enables QDEC operation. This bit is available only for CH0CTRL and CH2CTRL. z Bit 2:0 – DIGFILT[2:0]: Digital Filter Coefficient These bits define the length of digital filtering used, according to Table 6-6 on page 72. Events will be passed through to the event channel only when the event source has been active and sampled with the same level for the number of peripheral clock cycles defined by DIGFILT. Bit 7 6 5 4 3 2 1 0 – QDIRM[1:0](1) QDIEN(1) QDEN(1) DIGFILT[2:0] – – – – – DIGFILT[2:0] Read/Write R R/W R/W R/W R/W R/W R/W R Initial Value 0 0 0 0 0 0 0 0 QDIRM[1:0] Index Recognition State 0 0 {QDPH0, QDPH90} = 0b00 0 1 {QDPH0, QDPH90} = 0b01 1 0 {QDPH0, QDPH90} = 0b10 1 1 {QDPH0, QDPH90} = 0b11 Table 6-6. Digital filter coefficient values . DIGFILT[2:0] Group Configuration Description 000 1SAMPLE One sample 001 2SAMPLES Two samples 010 3SAMPLES Three samples XMEGA B [MANUAL] 73 8291C–AVR–09/2014 6.8.3 STROBE – Strobe register If the STROBE register location is written, each event channel will be set according to the STROBE[n] and corresponding DATA[n] bit settings, if any are unequal to zero. A single event lasting for one peripheral clock cycle will be generated. 6.8.4 DATA – Data register This register contains the data value when manually generating a data event. This register must be written before the STROBE register. For details, See ”STROBE – Strobe register” on page 73. 011 4SAMPLES Four samples 100 5SAMPLES Five samples 101 6SAMPLES Six samples 110 7SAMPLES Seven samples 111 8SAMPLES Eight samples Table 6-6. Digital filter coefficient values (Continued). DIGFILT[2:0] Group Configuration Description Bit 7 6 5 4 3 2 1 0 +0x10 STROBE[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x11 DATA[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 74 8291C–AVR–09/2014 6.9 Register Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CH0MUX CH0MUX[7:0] 70 +0x01 CH1MUX CH1MUX[7:0] 70 +0x02 CH2MUX CH2MUX[7:0] 70 +0x03 CH3MUX CH3MUX[7:0] 70 +0x04 Reserved – – – – – – – – +0x05 Reserved – – – – – – – – +0x06 Reserved – – – – – – – – +0x07 Reserved – – – – – – – – +0x08 CH0CTRL – QDIRM[1:0] QDIEN QDEN DIGFILT[2:0] 72 +0x09 CH1CTRL – – – – – DIGFILT[2:0] 72 +0x0A CH2CTRL – QDIRM[1:0] QDIEN QDEN DIGFILT[2:0] 72 +0x0B CH3CTRL – – – – – DIGFILT[2:0] 72 +0x0C Reserved – – – – – – – – +0x0D Reserved – – – – – – – – +0x0E Reserved – – – – – – – – +0x0F Reserved – – – – – – – – +0x10 STROBE STROBE[7:0] 73 +0x11 DATA DATA[7:0] 73 XMEGA B [MANUAL] 75 8291C–AVR–09/2014 7. System Clock and Clock Options 7.1 Features z Fast start-up time z Safe run-time clock switching z Internal oscillators: z 32MHz run-time calibrated and tunable oscillator z 2MHz run-time calibrated oscillator z 32.768kHz calibrated oscillator z 32kHz ultra low power (ULP) oscillator with 1kHz output z External clock options z 0.4MHz - 16MHz crystal oscillator z 32.768kHz crystal oscillator z External clock z PLL with 20MHz - 128MHz output frequency z Internal and external clock options and 1x to 31x multiplication z Lock detector z Clock prescalers with 1x to 2048x division z Fast peripheral clocks running at 2 and 4 times the CPU clock z Automatic run-time calibration of internal oscillators z External oscillator and PLL lock failure detection with optional non-maskable interrupt 7.2 Overview XMEGA devices have a flexible clock system supporting a large number of clock sources. It incorporates both accurate internal oscillators and external crystal oscillator and resonator support. A high-frequency phase locked loop (PLL) and clock prescalers can be used to generate a wide range of clock frequencies. A calibration feature (DFLL) is available, and can be used for automatic run-time calibration of the internal oscillators to remove frequency drift over voltage and temperature. An oscillator failure monitor can be enabled to issue a non-maskable interrupt and switch to the internal oscillator if the external oscillator or PLL fails. When a reset occurs, all clock sources except the 32kHz ultra low power oscillator are disabled. After reset, the device will always start up running from the 2MHz internal oscillator. During normal operation, the system clock source and prescalers can be changed from software at any time. Figure 7-1 on page 76 presents the principal clock system in the XMEGA family of devices. Not all of the clocks need to be active at a given time. The clocks for the CPU and peripherals can be stopped using sleep modes and power reduction registers, as described in “Power Management and Sleep Modes” on page 94. XMEGA B [MANUAL] 76 8291C–AVR–09/2014 Figure 7-1. The clock system, clock sources, and clock distribution. Real Time Counter Peripherals RAM AVR CPU Non-Volatile Memory Watchdog Timer Brown-out Detector System Clock Prescalers USB Prescaler System Clock Multiplexer (SCLKSEL) PLLSRC RTCSRC DIV32 32 kHz Int. ULP 32.768 kHz Int. OSC 32.768 kHz TOSC 2 MHz Int. Osc 32 MHz Int. Osc 0.4 – 16 MHz XTAL DIV32 DIV32 DIV4 XOSCSEL PLL USBSRC TOSC1 TOSC2 XTAL1 XTAL2 clkSYS clkRTC clkPER2 clkPER clkCPU clkPER4 clkUSB XMEGA B [MANUAL] 77 8291C–AVR–09/2014 7.3 Clock Distribution Figure 7-1 on page 76 presents the principal clock distribution system used in XMEGA devices. 7.3.1 System Clock - ClkSYS The system clock is the output from the main system clock selection. This is fed into the prescalers that are used to generate all internal clocks except the asynchronous and USB clocks. 7.3.2 CPU Clock - ClkCPU The CPU clock is routed to the CPU and nonvolatile memory. Halting the CPU clock inhibits the CPU from executing instructions. 7.3.3 Peripheral Clock - ClkPER The majority of peripherals and system modules use the peripheral clock. This includes the DMA controller, event system, interrupt controller, external bus interface and RAM. This clock is always synchronous to the CPU clock, but may run even when the CPU clock is turned off. 7.3.4 Peripheral 2x/4x Clocks - ClkPER2/ClkPER4 Modules that can run at two or four times the CPU clock frequency can use the peripheral 2x and peripheral 4x clocks. 7.3.5 Asynchronous Clock - ClkRTC The asynchronous clock allows the real-time counter (RTC) to be clocked directly from an external 32.768kHz crystal oscillator or the 32 times prescaled output from the internal 32.768kHz oscillator or ULP oscillator. The dedicated clock domain allows operation of this peripheral even when the device is in sleep mode and the rest of the clocks are stopped. 7.3.6 USB Clock - ClkUSB The USB device module requires a 12MHz or 48MHz clock. It has a separate clock source selection in order to avoid system clock source limitations when USB is used. 7.4 Clock Sources The clock sources are divided in two main groups: internal oscillators and external clock sources. Most of the clock sources can be directly enabled and disabled from software, while others are automatically enabled or disabled, depending on peripheral settings. After reset, the device starts up running from the 2MHz internal oscillator. The other clock sources, DFLLs and PLL, are turned off by default. 7.4.1 Internal Oscillators The internal oscillators do not require any external components to run. For details on characteristics and accuracy of the internal oscillators, refer to the device datasheet. 7.4.1.1 32kHz Ultra Low Power Oscillator This oscillator provides an approximate 32kHz clock. The 32kHz ultra low power (ULP) internal oscillator is a very low power clock source, and it is not designed for high accuracy.The oscillator employs a built-in prescaler that provides a 1kHz output, see “RTCCTRL – RTC Control register” on page 85 for details. The oscillator is automatically enabled/disabled when it is used as clock source for any part of the device. This oscillator can be selected as the clock source for the RTC. 7.4.1.2 32.768kHz Calibrated Oscillator This oscillator provides an approximate 32.768kHz clock. It is calibrated during production to provide a default frequency close to its nominal frequency. The calibration register can also be written from software for run-time calibration of the oscillator frequency. The oscillator employs a built-in prescaler, which provides both a 32.768kHz output and a 1.024kHz XMEGA B [MANUAL] 78 8291C–AVR–09/2014 output, see “RTCCTRL – RTC Control register” on page 85 for details. 7.4.1.3 32MHz Run-time Calibrated Oscillator The 32MHz run-time calibrated internal oscillator is a high-frequency oscillator. It is calibrated during production to provide a default frequency close to its nominal frequency. A digital frequency looked loop (DFLL) can be enabled for automatic run-time calibration of the oscillator to compensate for temperature and voltage drift and optimize the oscillator accuracy. This oscillator can also be adjusted and calibrated to any frequency between 30MHz and 55MHz. The production signature row contains 48 MHz calibration values intended used when the oscillator is used a full-speed USB clock source. 7.4.1.4 2MHz Run-time Calibrated Oscillator The 2MHz run-time calibrated internal oscillator is the default system clock source after reset. It is calibrated during production to provide a default frequency close to its nominal frequency. A DFLL can be enabled for automatic run-time calibration of the oscillator to compensate for temperature and voltage drift and optimize the oscillator accuracy. 7.4.2 External Clock Sources The XTAL1 and XTAL2 pins can be used to drive an external oscillator, either a quartz crystal or a ceramic resonator. XTAL1 can be used as input for an external clock signal. The TOSC1 and TOSC2 pins is dedicated to driving a 32.768kHz crystal oscillator. 7.4.2.1 0.4MHz - 16MHz Crystal Oscillator This oscillator can operate in four different modes optimized for different frequency ranges, all within 0.4MHz - 16MHz. Figure 7-2 shows a typical connection of a crystal oscillator or resonator. Figure 7-2. Crystal oscillator connection. Two capacitors, C1 and C2, may be added to match the required load capacitance for the connected crystal. 7.4.2.2 External Clock Input To drive the device from an external clock source, XTAL1 must be driven as shown in Figure 7-3 on page 78. In this mode, XTAL2 can be used as a general I/O pin. Figure 7-3. External clock drive configuration. C1 C2 XTAL2 XTAL1 GND General Purpose I/O XTAL2 XTAL1 External Clock Signal XMEGA B [MANUAL] 79 8291C–AVR–09/2014 7.4.2.3 32.768kHz Crystal Oscillator A 32.768kHz crystal oscillator can be connected between the TOSC1 and TOSC2 pins and enables a dedicated low frequency oscillator input circuit. A typical connection is shown in Figure 7-4 on page 79. A low power mode with reduced voltage swing on TOSC2 is available. This oscillator can be used as a clock source for the system clock and RTC, and as the DFLL reference clock. Figure 7-4. 32.768kHz crystal oscillator connection. Two capacitors, C1 and C2, may be added to match the required load capacitance for the connected crystal. For details on recommended TOSC characteristics and capacitor load, refer to device datasheets. 7.5 System Clock Selection and Prescalers All the calibrated internal oscillators, the external clock sources (XOSC), and the PLL output can be used as the system clock source. The system clock source is selectable from software, and can be changed during normal operation. Built-in hardware protection prevents unsafe clock switching. It is not possible to select a non-stable or disabled oscillator as the clock source, or to disable the oscillator currently used as the system clock source. Each oscillator option has a status flag that can be read from software to check that the oscillator is ready. The system clock is fed into a prescaler block that can divide the clock signal by a factor from 1 to 2048 before it is routed to the CPU and peripherals. The prescaler settings can be changed from software during normal operation. The first stage, prescaler A, can divide by a factor of from 1 to 512. Then, prescalers B and C can be individually configured to either pass the clock through or combine divide it by a factor from 1 to 4. The prescaler guarantees that derived clocks are always in phase, and that no glitches or intermediate frequencies occur when changing the prescaler setting. The prescaler settings are updated in accordance with the rising edge of the slowest clock. Figure 7-5. System clock selection and prescalers. Prescaler A divides the system clock, and the resulting clock is clkPER4. Prescalers B and C can be enabled to divide the clock speed further to enable peripheral modules to run at twice or four times the CPU clock frequency. If Prescalers B and C are not used, all the clocks will run at the same frequency as the output from Prescaler A. The system clock selection and prescaler registers are protected by the configuration change protection mechanism, employing a timed write procedure for changing the system clock and prescaler settings. For details, refer to “Configuration Change Protection” on page 13. C1 C2 TOSC2 TOSC1 GND Prescaler A 1, 2, 4, ... , 512 Prescaler B 1, 2, 4 Prescaler C 1, 2 Internal 2MHz Osc. Internal 32.768kHz Osc. Internal 32MHz Osc. External Oscillator or Clock. ClkCPU Clock Selection ClkPER ClkSYS ClkPER4 ClkPER2 Internal PLL. XMEGA B [MANUAL] 80 8291C–AVR–09/2014 7.6 PLL with 1x-31x Multiplication Factor The built-in phase locked loop (PLL) can be used to generate a high-frequency system clock. The PLL has a userselectable multiplication factor of from 1 to 31. The output frequency, fOUT, is given by the input frequency, fIN, multiplied by the multiplication factor, PLL_FAC. Four different clock sources can be chosen as input to the PLL: z 2MHz internal oscillator z 32MHz internal oscillator divided by 4 z 0.4MHz - 16MHz crystal oscillator z External clock To enable the PLL, the following procedure must be followed: 1. Enable reference clock source. 2. Set the multiplication factor and select the clock reference for the PLL. 3. Wait until the clock reference source is stable. 4. Enable the PLL. Hardware ensures that the PLL configuration cannot be changed when the PLL is in use. The PLL must be disabled before a new configuration can be written. It is not possible to use the PLL before the selected clock source is stable and the PLL has locked. The reference clock source cannot be disabled while the PLL is running. 7.7 DFLL 2MHz and DFLL 32MHz Two built-in digital frequency locked loops (DFLLs) can be used to improve the accuracy of the 2MHz and 32MHz internal oscillators. The DFLL compares the oscillator frequency with a more accurate reference clock to do automatic run-time calibration of the oscillator and compensate for temperature and voltage drift. The choices for the reference clock sources are: z 32.768kHz calibrated internal oscillator z 32.768kHz crystal oscillator connected to the TOSC pins z External clock z USB start of frame The DFLLs divide the oscillator reference clock by 32 to use a 1.024kHz reference. The reference clock is individually selected for each DFLL, as shown on Figure 7-6 on page 81. f OUT f IN = ⋅ PLL_FAC XMEGA B [MANUAL] 81 8291C–AVR–09/2014 Figure 7-6. DFLL reference clock selection. The ideal counter value representing the frequency ratio between the internal oscillator and a 1.024kHz reference clock is loaded into the DFLL oscillator compare register (COMP) during reset. For the 32MHz oscillator, this register can be written from software to make the oscillator run at a different frequency or when the ratio between the reference clock and the oscillator is different (for example when the USB start of frame is used). The 48MHz calibration values must be read from the production signature row and written to the 32MHz CAL register before the DFLL is enabled with USB SOF as reference source. The value that should be written to the COMP register is given by the following formula: When the DFLL is enabled, it controls the ratio between the reference clock frequency and the oscillator frequency. If the internal oscillator runs too fast or too slow, the DFLL will decrement or increment its calibration register value by one to adjust the oscillator frequency. The oscillator is considered running too fast or too slow when the error is more than a half calibration step size. 32.768 kHz Crystal Osc External Clock 32.768 kHz Int. Osc DFLL32M 32 MHz Int. RCOSC DFLL2M 2 MHz Int. RCOSC clkRC32MCREF clkRC2MCREF TOSC1 TOSC2 XTAL1 DIV32 DIV32 XOSCSEL USB Start of Frame XMEGA B [MANUAL] 82 8291C–AVR–09/2014 Figure 7-7. Automatic run-time calibration. The DFLL will stop when entering a sleep mode where the oscillators are stopped. After wake up, the DFLL will continue with the calibration value found before entering sleep. The reset value of the DFLL calibration register can be read from the production signature row. When the DFLL is disabled, the DFLL calibration register can be written from software for manual run-time calibration of the oscillator. 7.8 PLL and External Clock Source Failure Monitor A built-in failure monitor is available for the PLL and external clock source. If the failure monitor is enabled for the PLL and/or the external clock source, and this clock source fails (the PLL looses lock or the external clock source stops) while being used as the system clock, the device will: z Switch to run the system clock from the 2MHz internal oscillator z Reset the oscillator control register and system clock selection register to their default values z Set the failure detection interrupt flag for the failing clock source (PLL or external clock) z Issue a non-maskable interrupt (NMI) If the PLL or external clock source fails when not being used for the system clock, it is automatically disabled, and the system clock will continue to operate normally. No NMI is issued. The failure monitor is meant for external clock sources above 32kHz. It cannot be used for slower external clocks. When the failure monitor is enabled, it will not be disabled until the next reset. The failure monitor is stopped in all sleep modes where the PLL or external clock source are stopped. During wake up from sleep, it is automatically restarted. The PLL and external clock source failure monitor settings are protected by the configuration change protection mechanism, employing a timed write procedure for changing the settings. For details, refer to “Configuration Change Protection” on page 13. DFLL CNT COMP 0 tRCnCREF Frequency OK RCOSC fast, CALA decremented RCOSC slow, CALA incremented clkRCnCREF XMEGA B [MANUAL] 83 8291C–AVR–09/2014 7.9 Register Description – Clock 7.9.1 CTRL – Control register z Bit 7:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2:0 – SCLKSEL[2:0]: System Clock Selection These bits are used to select the source for the system clock. See Table 7-1 for the different selections. Changing the system clock source will take two clock cycles on the old clock source and two more clock cycles on the new clock source. These bits are protected by the configuration change protection mechanism. For details, refer to “Configuration Change Protection” on page 13. SCLKSEL cannot be changed if the new clock source is not stable. The old clock can not be disabled until the clock switching is completed. Table 7-1. System clock selection. 7.9.2 PSCTRL – Prescaler register This register is protected by the configuration change protection mechanism. For details, refer to “Configuration Change Protection” on page 13. z Bit 7 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. Bit 7 6 5 4 3 2 1 0 +0x00 – – – – – SCLKSEL[2:0] Read/Write R R R R R R/W R/W R/W Initial Value 0 0 0 00000 SCLKSEL[2:0] Group Configuration Description 000 RC2MHZ 2MHz internal oscillator 001 RC32MHZ 32MHz internal oscillator 010 RC32KHZ 32.768kHz internal oscillator 011 XOSC External oscillator or clock 100 PLL Phase locked loop 101 – Reserved 110 – Reserved 111 – Reserved Bit 7 6 5 4 3 2 1 0 +0x01 – PSADIV[4:0] PSBCDIV Read/Write R R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 84 8291C–AVR–09/2014 z Bit 6:2 – PSADIV[4:0]: Prescaler A Division Factor These bits define the division ratio of the clock prescaler A according to Table 7-2. These bits can be written at run-time to change the frequency of the ClkPER4 clock relative to the system clock, ClkSYS. Table 7-2. Prescaler A division factor. z Bit 1:0 – PSBCDIV: Prescaler B and C Division Factors These bits define the division ratio of the clock prescalers B and C according to Table 7-3. Prescaler B will set the clock frequency for the ClkPER2 clock relative to the ClkPER4 clock. Prescaler C will set the clock frequency for the ClkPER and ClkCPU clocks relative to the ClkPER2 clock. Refer to Figure 7-5 on page 79 fore more details. Table 7-3. Prescaler B and C division factors. PSADIV[4:0] Group Configuration Description 00000 1 No division 00001 2 Divide by 2 00011 4 Divide by 4 00101 8 Divide by 8 00111 16 Divide by 16 01001 32 Divide by 32 01011 64 Divide by 64 01101 128 Divide by 128 01111 256 Divide by 256 10001 512 Divide by 512 10101 – Reserved 10111 – Reserved 11001 – Reserved 11011 – Reserved 11101 – Reserved 11111 – Reserved PSBCDIV[1:0] Group Configuration Prescaler B division Prescaler C division 00 1_1 No division No division 01 1_2 No division Divide by 2 10 4_1 Divide by 4 No division 11 2_2 Divide by 2 Divide by 2 XMEGA B [MANUAL] 85 8291C–AVR–09/2014 7.9.3 LOCK – Lock register z Bit 7:1 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 0 – LOCK: Clock System Lock When this bit is written to one, the CTRL and PSCTRL registers cannot be changed, and the system clock selection and prescaler settings are protected against all further updates until after the next reset. This bit is protected by the configuration change protection mechanism. For details, refer to “Configuration Change Protection” on page 13. The LOCK bit can be cleared only by a reset. 7.9.4 RTCCTRL – RTC Control register z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:1 – RTCSRC[2:0]: RTC Clock Source These bits select the clock source for the real-time counter according to Table 7-4. Table 7-4. RTC clock source selection. z Bit 0 – RTCEN: RTC Clock Source Enable Setting the RTCEN bit enables the selected RTC clock source for the real-time counter. Bit 7 6 5 4 3 2 1 0 +0x02 – – – – – – – LOCK Read/Write R R R R R R R R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x03 – – – – RTCSRC[2:0] RTCEN Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 RTCSRC[2:0] Group Configuration Description 000 ULP 1kHz from 32kHz internal ULP oscillator 001 TOSC 1.024kHz from 32.768kHz crystal oscillator on TOSC 010 RCOSC 1.024kHz from 32.768kHz internal oscillator 011 — Reserved 100 — Reserved 101 TOSC32 32.768kHz from 32.768kHz crystal oscillator on TOSC 110 RCOSC32 32.768kHz from 32.768kHz internal oscillator 111 EXTCLK External clock from TOSC1 XMEGA B [MANUAL] 86 8291C–AVR–09/2014 7.9.5 USBSCTRL – USB Control register z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 5:3 – USBPSDIV[2:0]: USB Prescaler Division Factor These bits define the division ratio of the USB clock prescaler according to Table 7-5. These bits are locked as long as the USB clock source is enabled. Table 7-5. USB prescaler division factor. z Bit 2:1 – USBSRC[1:0]: USB Clock Source These bits select the clock source for the USB module according to Table 7-6. Table 7-6. USB clock source. Note: 1. The 32MHz internal oscillator must be calibrated to 48MHz before selecting this as source for the USB device module. Refer to “DFLL 2MHz and DFLL 32MHz” on page 80. z Bit 0 – USBSEN: USB Clock Source Enable Setting this bit enables the selected clock source for the USB device module. Bit 7 6 5 4 3 2 1 0 +0x04 – – USBPSDIV[2:0] USBSRC[1:0] USBSEN Read/Write R R R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 USBPSDIV[2:0] Group Configuration Description 000 1 No division 001 2 Divide by 2 010 4 Divide by 4 011 8 Divide by 8 100 16 Divide by 16 101 32 Divide by 32 110 — Reserved 111 — Reserved USBSRC[1:0] Group Configuration Description 00 PLL PLL 01 RC32M 32MHz internal oscillator(1) XMEGA B [MANUAL] 87 8291C–AVR–09/2014 7.10 Register Description – Oscillator 7.10.1 CTRL – Oscillator Control register z Bit 7:5 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 4 – PLLEN: PLL Enable Setting this bit enables the PLL. Before the PLL is enabled, it must be configured with the desired multiplication factor and clock source. See ”STATUS – Oscillator Status register” on page 87. z Bit 3 – XOSCEN: External Oscillator Enable Setting this bit enables the selected external clock source. Refer to “XOSCCTRL – XOSC Control register” on page 88 for details on how to select the external clock source. The external clock source should be allowed time to stabilize before it is selected as the source for the system clock. See ”STATUS – Oscillator Status register” on page 87. z Bit 2 – RC32KEN: 32.768kHz Internal Oscillator Enable Setting this bit enables the 32.768kHz internal oscillator. The oscillator must be stable before it is selected as the source for the system clock. See ”STATUS – Oscillator Status register” on page 87. z Bit 1 – RC32MEN: 32MHz Internal Oscillator Enable Setting this bit will enable the 32MHz internal oscillator. The oscillator must be stable before it is selected as the source for the system clock. See ”STATUS – Oscillator Status register” on page 87. z Bit 0 – RC2MEN: 2MHz Internal Oscillator Enable Setting this bit enables the 2MHz internal oscillator. The oscillator must be stable before it is selected as the source for the system clock. See ”STATUS – Oscillator Status register” on page 87. By default, the 2MHz internal oscillator is enabled and this bit is set. 7.10.2 STATUS – Oscillator Status register z Bit 7:5 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 4 – PLLRDY: PLL Ready This flag is set when the PLL has locked on the selected frequency and is ready to be used as the system clock source. z Bit 3 – XOSCRDY: External Clock Source Ready This flag is set when the external clock source is stable and is ready to be used as the system clock source. z Bit 2 – RC32KRDY: 32.768kHz Internal Oscillator Ready This flag is set when the 32.768kHz internal oscillator is stable and is ready to be used as the system clock source. Bit 7 6 5 4 3 2 1 0 +0x00 – – – PLLEN XOSCEN RC32KEN RC32MEN RC2MEN Read/Write R R R R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 1 Bit 7 6 5 4 3 2 1 0 +0x01 – – – PLLRDY XOSCRDY RC32KRDY RC32MRDY RC2MRDY Read/Write R R R R R R R R Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 88 8291C–AVR–09/2014 z Bit 1 – RC32MRDY: 32MHz Internal Oscillator Ready This flag is set when the 32MHz internal oscillator is stable and is ready to be used as the system clock source. z Bit 0 – RC2MRDY: 2MHz Internal Oscillator Ready This flag is set when the 2MHz internal oscillator is stable and is ready to be used as the system clock source. 7.10.3 XOSCCTRL – XOSC Control register z Bit 7:6 – FRQRANGE[1:0]: 0.4 - 16MHz Crystal Oscillator Frequency Range Select These bits select the frequency range for the connected crystal oscillator according to Table 7-7. Table 7-7. 16MHz crystal oscillator frequency range selection. z Bit 5 – X32KLPM: Crystal Oscillator 32.768kHz Low Power Mode Setting this bit enables the low power mode for the 32.768kHz crystal oscillator. This will reduce the swing on the TOSC2 pin. z Bit 4 – XOSCPWR: Crystal Oscillator Drive Setting this bit will increase the current in the 0.4MHz - 16MHz crystal oscillator and increase the swing on the XTAL2 pin. This allows for driving crystals with higher load or higher frequency than specified by the FRQRANGE bits. z Bit 3:0 – XOSCSEL[3:0]: Crystal Oscillator Selection These bits select the type and start-up time for the crystal or resonator that is connected to the XTAL or TOSC pins. See Table 7-8 on page 89 for crystal selections. If an external clock or external oscillator is selected as the source for the system clock, see “CTRL – Oscillator Control register” on page 87. This configuration cannot be changed. Bit 7 6 5 4 3 2 1 0 +0x02 FRQRANGE[1:0] X32KLPM XOSCPWR XOSCSEL[3:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0000 FRQRANGE[1:0] Group Configuration Typical Frequency Range Recommended Range for Capacitors C1 and C2 (pF) 00 04TO2 0.4MHz - 2MHz 100-300 01 2TO9 2MHz - 9MHz 10-40 10 9TO12 9MHz - 12MHz 10-40 11 12TO16 12MHz - 16MHz 10-30 XMEGA B [MANUAL] 89 8291C–AVR–09/2014 Table 7-8. External oscillator selection and start-up time.. Notes: 1. This option should be used only when frequency stability at startup is not important for the application. The option is not suitable for crystals. 2. This option is intended for use with ceramic resonators. It can also be used when the frequency stability at startup is not important for the application. 3. When the external oscillator is used as the reference for a DFLL, only EXTCLK and 32KHZ can be selected. 7.10.4 XOSCFAIL – XOSC Failure Detection register z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3 – PLLFDIF: PLL Fault Detection Flag If PLL failure detection is enabled, PLLFDIF is set when the PLL looses lock. Writing logic one to this location will clear PLLFDIF. z Bit 2 – PLLFDEN: PLL Fault Detection Enable Setting this bit will enable PLL failure detection. A non-maskable interrupt will be issued when PLLFDIF is set. This bit is protected by the configuration change protection mechanism. Refer to “Configuration Change Protection” on page 13 for details. z Bit 1 – XOSCFDIF: Failure Detection Interrupt Flag If the external clock source oscillator failure monitor is enabled, XOSCFDIF is set when a failure is detected. Writing logic one to this location will clear XOSCFDIF. z Bit 0 – XOSCFDEN: Failure Detection Enable Setting this bit will enable the failure detection monitor, and a non-maskable interrupt will be issued when XOSCFDIF is set. This bit is protected by the configuration change protection mechanism. Refer to “Configuration Change Protection” on page 13 for details. Once enabled, failure detection can only be disabled by a reset. XOSCSEL[3:0] Group Configuration Selected Clock Source Start-up Time 0000 EXTCLK(3) External Clock 6 CLK 0010 32KHZ(3) 32.768kHz TOSC 16K CLK 0011 XTAL_256CLK(1) 0.4MHz - 16MHz XTAL 256 CLK 0111 XTAL_1KCLK(2) 0.4MHz - 16MHz XTAL 1K CLK 1011 XTAL_16KCLK 0.4MHz - 16MHz XTAL 16K CLK Bit 7 6 5 4 3 2 1 0 +0x03 – – – – PLLFDIF PLLFDEN XOSCFDIF XOSCFDEN Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 90 8291C–AVR–09/2014 7.10.5 RC32KCAL – 32kHz Oscillator Calibration register z Bit 7:0 – RC32KCAL[7:0]: 32.768kHz Internal Oscillator Calibration bits This register is used to calibrate the 32.768kHz internal oscillator. A factory-calibrated value is loaded from the signature row of the device and written to this register during reset, giving an oscillator frequency close to 32.768kHz. The register can also be written from software to calibrate the oscillator frequency during normal operation. 7.10.6 PLLCTRL – PLL Control register z Bit 7:6 – PLLSRC[1:0]: Clock Source The PLLSRC bits select the input source for the PLL according to Table 7-9. Table 7-9. PLL clock source. Notes: 1. The 32.768kHz TOSC cannot be selected as the source for the PLL. An external clock must be a minimum 0.4MHz to be used as the source clock. z Bit 5 – PLLDIV: PLL Divided Output Enable Setting this bit will divide the output from the PLL by 2. z Bit 4:0 – PLLFAC[4:0]: Multiplication Factor These bits select the multiplication factor for the PLL. The multiplication factor can be in the range of from 1x to 31x. 7.10.7 DFLLCTRL – DFLL Control register z Bit 7:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. Bit 7 6 5 4 3 2 1 0 +0x04 RC32KCAL[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value x xxxxxxx Bit 7 6 5 4 3 2 1 0 +0x05 PLLSRC[1:0] PLLDIV PLLFAC[4:0] 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 PLLSRC[1:0] Group Configuration PLL Input Source 00 RC2M 2MHz internal oscillator 01 — Reserved 10 RC32M 32MHz internal oscillator 11 XOSC External clock source(1) Bit 7 6 5 4 3 2 1 0 +0x06 – – – – – RC32MCREF[1:0] RC2MCREF Read/Write R R R R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 91 8291C–AVR–09/2014 z Bit 2:1 – RC32MCREF[1:0]: 32MHz Oscillator Calibration Reference These bits are used to select the calibration source for the 32MHz DFLL according to the Table 7-10. These bits will select only which calibration source to use for the DFLL. In addition, the actual clock source that is selected must enabled and configured for the calibration to function. Table 7-10. 32MHz oscillator reference selection. z Bit 0 – RC2MCREF: 2MHz Oscillator Calibration Reference This bit is used to select the calibration source for the 2MHz DFLL. By default, this bit is zero and the 32.768kHz internal oscillator is selected. If this bit is set to one, the 32.768kHz crystal oscillator on TOSC is selected as the reference. This bit will select only which calibration source to use for the DFLL. In addition, the actual clock source that is selected must enabled and configured for the calibration to function. 7.11 Register Description – DFLL32M/DFLL2M 7.11.1 CTRL – DFLL Control register z Bit 7:1 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 0 – ENABLE: DFLL Enable Setting this bit enables the DFLL and auto-calibration of the internal oscillator. The reference clock must be enabled and stable before the DFLL is enabled. After disabling the DFLL, the reference clock can not be disabled before the ENABLE bit is read as zero. RC32MCREF[1:0] Group Configuration Description 00 RC32K 32.768kHz internal oscillator 01 XOSC32 32.768kHz crystal oscillator on TOSC 10 USBSOF USB start of frame 11 – Reserved Bit 7 6 5 4 3 2 1 0 +0x00 – – – – – – – ENABLE Read/Write R R R R R R R R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 92 8291C–AVR–09/2014 7.11.2 CALA – DFLL Calibration Register A The CALA and CALB registers hold the 13-bit DFLL calibration value that is used for automatic run-time calibration of the internal oscillator. When the DFLL is disabled, the calibration registers can be written by software for manual run-time calibration of the oscillator. The oscillators will also be calibrated according to the calibration value in these registers when the DFLL is disabled. z Bit 7 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 6:0 – CALA[6:0]: DFLL Calibration Bits These bits hold the part of the oscillator calibration value that is used for automatic runtime calibration. A factorycalibrated value is loaded from the signature row of the device and written to this register during reset, giving an oscillator frequency approximate to the nominal frequency for the oscillator. The bits cannot be written when the DFLL is enabled. 7.11.3 CALB – DFLL Calibration register B z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 5:0 – CALB[5:0]: DFLL Calibration bits These bits hold the part of the oscillator calibration value that is used to select the oscillator frequency. A factorycalibrated value is loaded from the signature row of the device and written to this register during reset, giving an oscillator frequency approximate to the nominal frequency for the oscillator. These bits are not changed during automatic run-time calibration of the oscillator. The bits cannot be written when the DFLL is enabled. When calibrating to a frequency different from the default, the CALA bits should be set to a middle value to maximize the range for the DFLL. 7.11.4 COMP1 – DFLL Compare register 1 The COMP1 and COMP2 register pair represent the frequency ratio between the oscillator and the reference clock. The initial value for these registers is the ratio between the internal oscillator frequency and a 1.024kHz reference z Bit 7:0 – COMP1[7:0]: Compare value byte 1 These bits hold byte 1 of the 16-bit compare register. Bit 7 6 5 4 3 2 1 0 +0x02 – CALA[6:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 x x x x x x x Bit 7 6 5 4 3 2 1 0 +0x03 – – CALB[5:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 x x x x x x Bit 7 6 5 4 3 2 1 0 +0x05 COMP[7:0] 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 XMEGA B [MANUAL] 93 8291C–AVR–09/2014 7.11.5 COMP2 – DFLL Compare register 2 z Bit 7:0 – COMP2[15:8]: Compare Register value byte 2 These bits hold byte 2 of the 16-bit compare register. Table 7-11. Nominal DFLL32M COMP values for different output frequencies. Bit 7 6 5 4 3 2 1 0 +0x06 COMP[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Oscillator Frequency (MHz) COMP Value (ClkRCnCREF = 1.024kHz) 30.0 0x7270 32.0 0x7A12 34.0 0x81B3 36.0 0x8954 38.0 0x90F5 40.0 0x9896 42.0 0xA037 44.0 0xA7D8 46.0 0xAF79 48.0 0xB71B 50.0 0xBEBC 52.0 0xC65D 54.0 0xCDFE XMEGA B [MANUAL] 94 8291C–AVR–09/2014 7.12 Register Summary - Clock 7.13 Register Summary - Oscillator 7.14 Register Summary - DFLL32M/DFLL2M 7.15 Oscillator Failure Interrupt Vector Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL – – – – – SCLKSEL[2:0] 83 +0x01 PSCTRL – PSADIV[4:0] PSBCDIV[1:0] 83 +0x02 LOCK – – – – – – – LOCK 85 +0x03 RTCCTRL – – – – RTCSRC[2:0] RTCEN 85 +0x04 USBSCTR – – USBPSDIV[2:0] USBSRC[1:0] USBSEN 85 +0x05 Reserved – – – – – – – – +0x06 Reserved – – – – – – – – +0x07 Reserved – – – – – – – – Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL – – – PLLEN XOSCEN RC32KEN R32MEN RC2MEN 87 +0x01 STATUS – – – PLLRDY XOSCRDY RC32KRD R32MRDY RC2MRDY 87 +0x02 XOSCCTR FRQRANGE[1:0] X32KLPM XOSCPW XOSCSEL[3:0] 88 +0x03 XOSCFAIL – – – – PLLFDIF PLLFDEN XOSCFDIF XOSCFDEN 89 +0x04 RC32KCAL RC32KCAL[7:0] 90 +0x05 PLLCTRL PLLSRC[1:0] – PLLFAC[4:0] 90 +0x06 DFLLCTRL – – – – – RC32MCREF[1:0] RC2MCREF 90 +0x07 Reserved – – – – – – – – Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL – – – – – – – ENABLE 91 +0x01 Reserved – – – – – – – – +0x02 CALA – CALA[6:0] 92 +0x03 CALB – – CALB[5:0] 92 +0x04 Reserved – – – – – – – – +0x05 COMP1 COMP[7:0] 92 +0x06 COMP2 COMP[15:8] 93 +0x07 Reserved – – – – – – – – Offset Source Interrupt Description 0x00 OSCF_vect PLL and external oscillator failure interrupt vector (NMI) XMEGA B [MANUAL] 95 Atmel-8291C-AVR-XMEGA B -09/2014 8. Power Management and Sleep Modes 8.1 Features z Power management for adjusting power consumption and functions z Five sleep modes z Idle z Power down z Power save z Standby z Extended standby z Power reduction register to disable clock and turn off unused peripherals in active and idle modes 8.2 Overview Various sleep modes and clock gating are provided in order to tailor power consumption to application requirements. This enables the XMEGA microcontroller to stop unused modules to save power. All sleep modes are available and can be entered from active mode. In active mode, the CPU is executing application code. When the device enters sleep mode, program execution is stopped and interrupts or a reset is used to wake the device again. The application code decides which sleep mode to enter and when. Interrupts from enabled peripherals and all enabled reset sources can restore the microcontroller from sleep to active mode. In addition, power reduction registers provide a method to stop the clock to individual peripherals from software. When this is done, the current state of the peripheral is frozen, and there is no power consumption from that peripheral. This reduces the power consumption in active mode and idle sleep modes and enables much more fine-tuned power management than sleep modes alone. 8.3 Sleep Modes Sleep modes are used to shut down modules and clock domains in the microcontroller in order to save power. XMEGA microcontrollers have five different sleep modes tuned to match the typical functional stages during application execution. A dedicated sleep instruction (SLEEP) is available to enter sleep mode. Interrupts are used to wake the device from sleep, and the available interrupt wake-up sources are dependent on the configured sleep mode. When an enabled interrupt occurs, the device will wake up and execute the interrupt service routine before continuing normal program execution from the first instruction after the SLEEP instruction. If other, higher priority interrupts are pending when the wake-up occurs, their interrupt service routines will be executed according to their priority before the interrupt service routine for the wake-up interrupt is executed. After wake-up, the CPU is halted for four cycles before execution starts. Table 8-1 on page 96 shows the different sleep modes and the active clock domains, oscillators, and wake-up sources. XMEGA B [MANUAL] 96 Atmel-8291C-AVR-XMEGA B -09/2014 Table 8-1. Active clock domains and wake-up sources in the different sleep modes. The wake-up time for the device is dependent on the sleep mode and the main clock source. The startup time for the system clock source must be added to the wake-up time for sleep modes where the system clock source is not kept running. For details on the startup time for the different oscillator options, refer to “System Clock and Clock Options” on page 77. The content of the register file, SRAM and registers are kept during sleep. If a reset occurs during sleep, the device will reset, start up, and execute from the reset vector. 8.3.1 Idle Mode In idle mode the CPU and nonvolatile memory are stopped (note that any ongoing programming will be completed), but all peripherals, including the interrupt controller, event system and DMA controller are kept running. Any enabled interrupt will wake the device. 8.3.2 Power-down Mode In power-down mode, all clocks, including the real-time counter clock source, are stopped. This allows operation only of asynchronous modules that do not require a running clock. The only interrupts that can wake up the MCU are the twowire interface address match interrupt, asynchronous port interrupts, and the USB resume interrupt. 8.3.3 Power-save Mode Power-save mode is identical to power down, with two exceptions: 1. If the real-time counter (RTC) is enabled, it will keep running during sleep, and the device can also wake up from either an RTC overflow or compare match interrupt. 2. If the LCD is enabled, it will keep running during sleep, and the device can wake up from LCD frame completed interrupt. 8.3.4 Standby Mode Standby mode is identical to power down, with the exception that the enabled system clock sources are kept running while the CPU, peripheral, and RTC/LCD clocks are stopped. This reduces the wake-up time. Active Clock Domain Oscillators Wake-up Sources Sleep Modes CPU Clock Peripheral and USB Clock RTC and LCD Clock System Clock Source RTC Clock Source USB Resume Asynchronous Port Interrupts TWI Address Match Interrupts RTC and LCD Clock Interrupts All Interrupts Idle X X X X X X X X X Power down X X X Power save X X X X X X Standby X X X X Extended standby X X X X X X X XMEGA B [MANUAL] 97 Atmel-8291C-AVR-XMEGA B -09/2014 8.3.5 Extended Standby Mode Extended standby mode is identical to power-save mode, with the exception that the enabled system clock sources are kept running while the CPU and peripheral clocks are stopped. This reduces the wake-up time. 8.4 Power Reduction Registers The power reduction (PR) registers provide a method to stop the clock to individual peripherals. When this is done, the current state of the peripheral is frozen and the associated I/O registers cannot be read or written. Resources used by the peripheral will remain occupied; hence, the peripheral should be disabled before stopping the clock. Enabling the clock to a peripheral again puts the peripheral in the same state as before it was stopped. This can be used in idle mode and active modes to reduce the overall power consumption. In all other sleep modes, the peripheral clock is already stopped. Not all devices have all the peripherals associated with a bit in the power reduction registers. Setting a power reduction bit for a peripheral that is not available will have no effect. 8.5 Minimizing Power Consumption There are several possibilities to consider when trying to minimize the power consumption in an AVR MCU controlled system. In general, correct sleep modes should be selected and used to ensure that only the modules required for the application are operating. All unneeded functions should be disabled. In particular, the following modules may need special consideration when trying to achieve the lowest possible power consumption. 8.5.1 Analog-to-Digital Converter - ADC When entering idle mode, the ADC should be disabled if not used. In other sleep modes, the ADC is automatically disabled. When the ADC is turned off and on again, the next conversion will be an extended conversion. Refer to “ADC – Analog-to-Digital Converter” on page 326 for details on ADC operation. 8.5.2 Analog Comparator - AC When entering idle mode, the analog comparator should be disabled if not used. In other sleep modes, the analog comparator is automatically disabled. However, if the analog comparator is set up to use the internal voltage reference as input, the analog comparator should be disabled in all sleep modes. Otherwise, the internal voltage reference will be enabled, irrespective of sleep mode. Refer to “AC – Analog Comparator” on page 352 for details on how to configure the analog comparator. 8.5.3 Brownout Detector If the brownout detector is not needed by the application, this module should be turned off. If the brownout detector is enabled by the BODLEVEL fuses, it will be enabled in all sleep modes, and always consume power. In the deeper sleep modes, it can be turned off and set in sampled mode to reduce current consumption. Refer to “Brownout Detection” on page 109 for details on how to configure the brownout detector. 8.5.4 Watchdog Timer If the watchdog timer is not needed in the application, the module should be turned off. If the watchdog timer is enabled, it will be enabled in all sleep modes and, hence, always consume power. Refer to “WDT – Watchdog Timer” on page 115 for details on how to configure the watchdog timer. 8.5.5 Port Pins When entering a sleep mode, all port pins should be configured to use minimum power. Most important is to ensure that no pins drive resistive loads. In sleep modes where the Peripheral Clock (ClkPER) is stopped, the input buffers of the device will be disabled. This ensures that no power is consumed by the input logic when not needed. 8.5.6 On-chip Debug Systems If the On-chip debug system is enabled and the chip enters sleep mode, the main clock source is enabled and hence always consumes power. In the deeper sleep modes, this will contribute significantly to the total current consumption. XMEGA B [MANUAL] 98 Atmel-8291C-AVR-XMEGA B -09/2014 8.6 Register Description – Sleep 8.6.1 CTRL – Control Register z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:1 – SMODE[2:0]: Sleep Mode selection These bits select sleep modes according to Table 8-2. Table 8-2. Sleep mode selection. z Bit 0 – SEN: Sleep Enable This bit must be set to make the MCU enter the selected sleep mode when the SLEEP instruction is executed. To avoid unintentional entering of sleep modes, it is recommended to write SEN just before executing the SLEEP instruction and clear it immediately after waking up. 8.7 Register Description – Power Reduction 8.7.1 PRGEN – General Power Reduction register z Bit 7 – LCD: LCD Module Setting this bit stops the clock to the LCD module. When the bit is cleared the peripheral should be reinitialized to ensure proper operation. Bit 7 6 5 4 3 2 1 0 +0x00 – – – – SMODE[2:0] SEN Read/Write R R R R R/W R/W R/W R/W Initial Value 00000000 SMODE[2:0] Group configuration Description 000 IDLE Idle mode 001 – Reserved 010 PDOWN Power-down mode 011 PSAVE Power-save mode 100 – Reserved 101 – Reserved 110 STDBY Standby mode 111 ESTDBY Extended standby mode Bit 7 6 5 4 3 2 1 0 +0x00 LCD USB – AES – RTC EVSYS DMA Read/Write R/W R/W R R/W R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 99 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 6 – USB: USB Module Setting this bit stops the clock to the USB module. When this bit is cleared, the peripheral should be reinitialized to ensure proper operation. z Bit 5 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 4 – AES: AES Module Setting this bit stops the clock to the AES module. When this bit is cleared, the peripheral should be reinitialized to ensure proper operation. z Bit 3 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 2 – RTC: Real-Time Counter Setting this bit stops the clock to the real-time counter. When this bit is cleared, the peripheral should be reinitialized to ensure proper operation. z Bit 1 – EVSYS: Event System Setting this stops the clock to the event system. When this bit is cleared, the module will continue as before it was stopped. z Bit 0 – DMA: DMA Controller Setting this bit stops the clock to the DMA controller. This bit can be set only if the DMA controller is disabled. 8.7.2 PRPA/B – Power Reduction Port A/B register Note: Disabling of analog modules stops the clock to the analog blocks themselves and not only the interfaces. z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1 – ADC: Power Reduction ADC Setting this bit stops the clock to the ADC. The ADC should be disabled before stopped. z Bit 0 – AC: Power Reduction Analog Comparator Setting this bit stops the clock to the analog comparator. The AC should be disabled before shutdown. 8.7.3 PRPC/E – Power Reduction Port C/E Register z Bit 7 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. Bit 7 6 5 4 3 2 1 0 +0x01/+0x02 – – – – – – ADC AC Read/Write R R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x03/+0x04/ +0x05/+0x06 – TWI – USART0 SPI HIRES TC1 TC0 Read/Write R R/W R R/W R/W R/W R/W R/W Initial Value 0 0000000 XMEGA B [MANUAL] 100 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 6 – TWI: Two-Wire Interface Setting this bit stops the clock to the two-wire interface. When this bit is cleared, the peripheral should be reinitialized to ensure proper operation. z Bit 5 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 4 – USART0 Setting this bit stops the clock to USART0. When this bit is cleared, the peripheral should be reinitialized to ensure proper operation. z Bit 3 – SPI: Serial Peripheral Interface Setting this bit stops the clock to the SPI. When this bit is cleared, the peripheral should be reinitialized to ensure proper operation. z Bit 2 – HIRES: High-Resolution Extension Setting this bit stops the clock to the high-resolution extension for the timer/counters. When this bit is cleared, the peripheral should be reinitialized to ensure proper operation. z Bit 1 – TC1: Timer/Counter 1 Setting this bit stops the clock to timer/counter 1. When this bit is cleared, the peripheral will continue like before the shut down. z Bit 0 – TC0: Timer/Counter 0 Setting this bit stops the clock to timer/counter 0. When this bit is cleared, the peripheral will continue like before the shut down. XMEGA B [MANUAL] 101 Atmel-8291C-AVR-XMEGA B -09/2014 8.8 Register Summary - Sleep 8.9 Register Summary - Power Reduction Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL – – – – SMODE[2:0] SEN 98 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 PRGEN LCD USB – AES – RTC EVSYS DMA 98 +0x01 PRPA – – – – – – ADC AC 99 +0x02 PRPB – – – – – – ADC AC 99 +0x03 PRPC – TWI – USART0 SPI HIRES TC1 TC0 99 +0x04 Reserved – – – – – – – – +0x05 PRPE – – – USART0 – – – TC0 99 XMEGA B [MANUAL] 102 Atmel-8291C-AVR-XMEGA B -09/2014 9. Reset System 9.1 Features z Reset the microcontroller and set it to initial state when a reset source goes active z Multiple reset sources that cover different situations z Power-on reset z External reset z Watchdog reset z Brownout reset z PDI reset z Software reset z Asynchronous operation z No running system clock in the device is required for reset z Reset status register for reading the reset source from the application code 9.2 Overview The reset system issues a microcontroller reset and sets the device to its initial state. This is for situations where operation should not start or continue, such as when the microcontroller operates below its power supply rating. If a reset source goes active, the device enters and is kept in reset until all reset sources have released their reset. The I/O pins are immediately tri-stated. The program counter is set to the reset vector location, and all I/O registers are set to their initial values. The SRAM content is kept. However, if the device accesses the SRAM when a reset occurs, the content of the accessed location can not be guaranteed. After reset is released from all reset sources, the default oscillator is started and calibrated before the device starts running from the reset vector address. By default, this is the lowest program memory address, 0, but it is possible to move the reset vector to the lowest address in the boot section. The reset functionality is asynchronous, and so no running system clock is required to reset the device. The software reset feature makes it possible to issue a controlled system reset from the user software. The reset status register has individual status flags for each reset source. It is cleared at power-on reset, and shows which sources have issued a reset since the last power-on. An overview of the reset system is shown in Figure 9-1 on page 103. XMEGA B [MANUAL] 103 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 9-1. Reset system overview. 9.3 Reset Sequence A reset request from any reset source will immediately reset the device and keep it in reset as long as the request is active. When all reset requests are released, the device will go through three stages before the device starts running again: z Reset counter delay z Oscillator startup z Oscillator calibration If another reset requests occurs during this process, the reset sequence will start over again. 9.3.1 Reset Counter The reset counter can delay reset release with a programmable period from when all reset requests are released. The reset delay is timed from the 1kHz output of the ultra low power (ULP) internal oscillator, and in addition 24 System clock (clkSYS) cycles are counted before reset is released. The reset delay is set by the STARTUPTIME fuse bits. The selectable delays are shown in Table 9-1. Table 9-1. Reset delay MCU Status Register (MCUSR) Brown-out BODLEVEL [2:0] Reset Delay Counters TIMEOUT PORF BORF EXTRF WDRF ULP Oscillator SPIKE FILTER Pull-up Resistor JTRF Watchdog Reset SUT[1:0] Power-on Reset Software Reset External Reset PDI Reset SUT[1:0] Number of 1kHz ULP Oscillator Clock Cycles Recommended Usage 00 64K ClkULP+ 24 ClkSYS Stable frequency at startup 01 4K ClkULP + 24 ClkSYS Slowly rising power 10 Reserved - 11 24 ClkSYS Fast rising power or BOD enabled XMEGA B [MANUAL] 104 Atmel-8291C-AVR-XMEGA B -09/2014 Whenever a reset occurs, the clock system is reset and the internal 2MHz internal oscillator is chosen as the source for ClkSYS. 9.3.2 Oscillator Startup After the reset delay, the 2MHz internal oscillator clock is started, and its calibration values are automatically loaded from the calibration row to the calibration registers. 9.4 Reset Sources 9.4.1 Power-on Reset A power-on reset (POR) is generated by an on-chip detection circuit. The POR is activated when the VCC rises and reaches the POR threshold voltage (VPOT), and this will start the reset sequence. The POR is also activated to power down the device properly when the VCC falls and drops below the VPOT level. The VPOT level is higher for falling VCCthan for rising VCC. Consult the datasheet for POR characteristics data. Figure 9-2. MCU startup, RESET tied to VCC. Figure 9-3. MCU startup, RESET extended externally, 9.4.2 Brownout Detection The on-chip brownout detection (BOD) circuit monitors the VCC level during operation by comparing it to a fixed, programmable level that is selected by the BODLEVEL fuses. If disabled, BOD is forced on at the lowest level during chip erase and when the PDI is enabled. When the BOD is enabled and VCC decreases to a value below the trigger level (VBOT- in Figure 9-4), the brownout reset is immediately activated. V RESET TIME-OUT INTERNAL RESET t TOUT VPOT VRST CC RESET TIME-OUT INTERNAL RESET t TOUT VPOT VRST VCC XMEGA B [MANUAL] 105 Atmel-8291C-AVR-XMEGA B -09/2014 When VCC increases above the trigger level (VBOT+ in Figure 9-4), the reset counter starts the MCU after the timeout period, tTOUT, has expired. The trigger level has a hysteresis to ensure spike free brownout detection. The hysteresis on the detection level should be interpreted as VBOT+= VBOT + VHYST/2 and VBOT- = VBOT - VHYST/2. The BOD circuit will detect a drop in VCC only if the voltage stays below the trigger level for longer than tBOD. Figure 9-4. Brownout detection reset. For BOD characterization data consult the device datasheet. The programmable BODLEVEL setting is shown in Table 9- 2. Table 9-2. Programmable BODLEVEL setting. Notes: 1. The values are nominal values only. For accurate, actual numbers, consult the device datasheet. 2. Changing these fuse bits will have no effect until leaving programming mode. The BOD circuit has three modes of operation: z Disabled: In this mode, there is no monitoring of the VCC level. z Enabled: In this mode, the VCC level is continuously monitored, and a drop in VCC below VBOT for a period of tBOD will give a brownout reset z Sampled: In this mode, the BOD circuit will sample the VCC level with a period identical to that of the 1kHz output from the ultra low power (ULP) internal oscillator. Between each sample, the BOD is turned off. This mode will BOD level Fuse BODLEVEL[2:0](2) VBOT(1) Unit BOD level 0 111 1.6 V BOD level 1 110 1.8 BOD level 2 101 2.0 BOD level 3 100 2.2 BOD level 4 011 2.4 BOD level 5 010 2.6 BOD level 6 001 2.8 BOD level 7 000 3.0 VCC TIME-OUT INTERNAL RESET VBOTVBOT+ t TOUT t BOD XMEGA B [MANUAL] 106 Atmel-8291C-AVR-XMEGA B -09/2014 reduce the power consumption compared to the enabled mode, but a fall in the VCC level between two positive edges of the 1kHz ULP oscillator output will not be detected. If a brownout is detected in this mode, the BOD circuit is set in enabled mode to ensure that the device is kept in reset until VCC is above VBOT again The BODACT fuse determines the BOD setting for active mode and idle mode, while the BODPD fuse determines the brownout detection setting for all sleep modes, except idle mode. Table 9-3. BOD setting fuse decoding. 9.4.3 External Reset The external reset circuit is connected to the external RESET pin. The external reset will trigger when the RESET pin is driven below the RESET pin threshold voltage, VRST, for longer than the minimum pulse period, tEXT. The reset will be held as long as the pin is kept low. The RESET pin includes an internal pull-up resistor. Figure 9-5. External reset characteristics. For external reset characterization data consult the device datasheet. 9.4.4 Watchdog Reset The watchdog timer (WDT) is a system function for monitoring correct program operation. If the WDT is not reset from the software within a programmable timout period, a watchdog reset will be given. The watchdog reset is active for one to two clock cycles of the 2MHz internal oscillator. BODACT[1:0]/ BODPD[1:0] Mode 00 Reserved 01 Sampled 10 Enabled 11 Disabled CC t EXT XMEGA B [MANUAL] 107 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 9-6. Watchdog reset. For information on configuration and use of the WDT, refer to the “WDT – Watchdog Timer” on page 110. 9.4.5 Software Reset The software reset makes it possible to issue a system reset from software by writing to the software reset bit in the reset control register.The reset will be issued within two CPU clock cycles after writing the bit. It is not possible to execute any instruction from when a software reset is requested until it is issued. Figure 9-7. Software reset. 9.4.6 Program and Debug Interface Reset The program and debug interface reset contains a separate reset source that is used to reset the device during external programming and debugging. This reset source is accessible only from external debuggers and programmers. 1-2 2MHz CC Cycles 1-2 2MHz CC Cycles SOFTWARE XMEGA B [MANUAL] 108 Atmel-8291C-AVR-XMEGA B -09/2014 9.5 Register Description 9.5.1 STATUS – Status register z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 5 – SRF: Software Reset Flag This flag is set if a software reset occurs. The flag will be cleared by a power-on reset or by writing a one to the bit location. z Bit 4 – PDIRF: Program and Debug Interface Reset Flag This flag is set if a programming interface reset occurs. The flag will be cleared by a power-on reset or by writing a one to the bit location. z Bit 3 – WDRF: Watchdog Reset Flag This flag is set if a watchdog reset occurs. The flag will be cleared by a power-on reset or by writing a one to the bit location. z Bit 2 – BORF: Brownout Reset Flag This flag is set if a brownout reset occurs. The flag will be cleared by a power-on reset or by writing a one to the bit location. z Bit 1 – EXTRF: External Reset Flag This flag is set if an external reset occurs. The flag will be cleared by a power-on reset or by writing a one to the bit location. z Bit 0 – PORF: Power On Reset Flag This flag is set if a power-on reset occurs. Writing a one to the flag will clear the bit location. 9.5.2 CTRL – Control register z Bit 7:1 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 0 – SWRST: Software Reset Bit 7 6 5 4 3 2 1 0 +0x00 – – SRF PDIRF WDRF BORF EXTRF PORF Read/Write R R R/W R/W R/W R/W R/W R/W Initial Value - ------- Bit 7 6 5 4 3 2 1 0 +0x01 – – – – – – – SWRST Read/Write R R R R R R R R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 109 Atmel-8291C-AVR-XMEGA B -09/2014 When this bit is set, a software reset will occur. The bit is cleared when a reset is issued. This bit is protected by the configuration change protection mechanism. For details, refer to “Configuration Change Protection” on page 13. 9.6 Register Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 STATUS – – SRF PDIRF WDRF BORF EXTRF PORF 108 +0x01 CTRL – – – – – – – SWRST 108 XMEGA B [MANUAL] 110 Atmel-8291C-AVR-XMEGA B -09/2014 10. WDT – Watchdog Timer 10.1 Features z Issues a device reset if the timer is not reset before its timeout period z Asynchronous operation from dedicated oscillator z 1kHz output of the 32kHz ultra low power oscillator z 11 selectable timeout periods, from 8ms to 8s. z Two operation modes: z Normal mode z Window mode z Configuration lock to prevent unwanted changes 10.2 Overview The watchdog timer (WDT) is a system function for monitoring correct program operation. It makes it possible to recover from error situations such as runaway or deadlocked code. The WDT is a timer, configured to a predefined timeout period, and is constantly running when enabled. If the WDT is not reset within the timeout period, it will issue a microcontroller reset. The WDT is reset by executing the WDR (watchdog timer reset) instruction from the application code. The window mode makes it possible to define a time slot or window inside the total timeout period during which WDT must be reset. If the WDT is reset outside this window, either too early or too late, a system reset will be issued. Compared to the normal mode, this can also catch situations where a code error causes constant WDR execution. The WDT will run in active mode and all sleep modes, if enabled. It is asynchronous, runs from a CPU-independent clock source, and will continue to operate to issue a system reset even if the main clocks fail. The configuration change protection mechanism ensures that the WDT settings cannot be changed by accident. For increased safety, a fuse for locking the WDT settings is also available. 10.3 Normal Mode Operation In normal mode operation, a single timeout period is set for the WDT. If the WDT is not reset from the application code before the timeout occurs, then the WDT will issue a system reset. There are 11 possible WDT timeout (TOWDT) periods, selectable from 8ms to 8s, and the WDT can be reset at any time during the timeout period. A new WDT timeout period will be started each time the WDT is reset by the WDR instruction. The default timeout period is controlled by fuses. Normal mode operation is illustrated in Figure 10-1 on page 110. Figure 10-1. Normal mode operation. XMEGA B [MANUAL] 111 Atmel-8291C-AVR-XMEGA B -09/2014 10.4 Window Mode Operation In window mode operation, the WDT uses two different timeout periods, a "closed" window timeout period (TOWDTW) and the normal timeout period (TOWDT). The closed window timeout period defines a duration of from 8ms to 8s where the WDT cannot be reset. If the WDT is reset during this period, the WDT will issue a system reset. The normal WDT timeout period, which is also 8ms to 8s, defines the duration of the "open" period during which the WDT can (and should) be reset. The open period will always follow the closed period, and so the total duration of the timeout period is the sum of the closed window and the open window timeout periods. The default closed window timeout period is controlled by fuses (both open and closed periods are controlled by fuses). The window mode operation is illustrated in Figure 10-2. Figure 10-2. Window mode operation. 10.5 Watchdog Timer Clock The WDT is clocked from the 1kHz output from the 32kHz ultra low power (ULP) internal oscillator. Due to the ultra low power design, the oscillator is not very accurate, and so the exact timeout period may vary from device to device. When designing software which uses the WDT, this device-to-device variation must be kept in mind to ensure that the timeout periods used are valid for all devices. For more information on ULP oscillator accuracy, consult the device datasheet. 10.6 Configuration Protection and Lock The WDT is designed with two security mechanisms to avoid unintentional changes to the WDT settings. The first mechanism is the configuration change protection mechanism, employing a timed write procedure for changing the WDT control registers. In addition, for the new configuration to be written to the control registers, the register’s change enable bit must be written at the same time. The second mechanism locks the configuration by setting the WDT lock fuse. When this fuse is set, the watchdog time control register cannot be changed; hence, the WDT cannot be disabled from software. After system reset, the WDT will resume at the configured operation. When the WDT lock fuse is programmed, the window mode timeout period cannot be changed, but the window mode itself can still be enabled or disabled. XMEGA B [MANUAL] 112 Atmel-8291C-AVR-XMEGA B -09/2014 10.7 Registers Description 10.7.1 CTRL – Control register z Bits 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bits 5:2 – PER[3:0]: Timeout Period These bits determine the watchdog timeout period as a number of 1kHz ULP oscillator cycles. In window mode operation, these bits define the open window period. The different typical timeout periods are found in Table 10-1. The initial values of these bits are set by the watchdog timeout period (WDP) fuses, which are loaded at power-on. In order to change these bits, the CEN bit must be written to 1 at the same time. These bits are protected by the configuration change protection mechanism. For a detailed description, refer to “Configuration Change Protection” on page 13. Table 10-1. Watchdog timeout periods Note: Reserved settings will not give any timeout. Bit 7 6 5 4 3 2 1 0 +0x00 – – PER[3:0] ENABLE CEN Read/Write (unlocked) R R R/W R/W R/W R/W R/W R/W Read/Write (locked) R RRRRRRR Initial Value (x = fuse) 0 0 XXXXX0 PER[3:0] Group Configuration Typical Timeout Periods 0000 8CLK 8ms 0001 16CLK 16ms 0010 32CLK 32ms 0011 64CLK 64ms 0100 128CLK 0.128s 0101 256CLK 0.256s 0110 512CLK 0.512s 0111 1KCLK 1.0s 1000 2KCLK 2.0s 1001 4KCLK 4.0s 1010 8KCLK 8.0s 1011 – Reserved 1100 – Reserved 1101 – Reserved 1110 – Reserved 1111 – Reserved XMEGA B [MANUAL] 113 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 1 – ENABLE: Enable This bit enables the WDT. Clearing this bit disables the watchdog timer. In order to change this bit, the CEN bit in “CTRL – Control register” on page 112 must be written to one at the same time. This bit is protected by the configuration change protection mechanism, For a detailed description, refer to “Configuration Change Protection” on page 13. z Bit 0 – CEN: Change Enable This bit enables the ability to change the configuration of the “CTRL – Control register” on page 112. When writing a new value to this register, this bit must be written to one at the same time for the changes to take effect. This bit is protected by the configuration change protection mechanism. For a detailed description, refer to “Configuration Change Protection” on page 13. 10.7.2 WINCTRL – Window Mode Control register z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 5:2 – WPER[3:0]: Window Mode Timeout Period These bits determine the closed window period as a number of 1kHz ULP oscillator cycles in window mode operation. The typical different closed window periods are found in Table 10-2. The initial values of these bits are set by the watchdog window timeout period (WDWP) fuses, and are loaded at power-on. In normal mode these bits are not in use. In order to change these bits, the WCEN bit must be written to one at the same time. These bits are protected by the configuration change protection mechanism. For a detailed description, refer to “Configuration Change Protection” on page 13. Table 10-2. Watchdog closed window periods Bit 7 6 5 4 3 2 1 0 +0x01 – – WPER[3:0] WEN WCEN Read/Write (unlocked) R R R/W R/W R/W R/W R/W R/W Read/Write (locked) R R R R R R R/W R/W Initial Value (x = fuse) 0 0 XXXXX0 WPER[3:0] Group Configuration Typical Closed Window Periods 0000 8CLK 8ms 0001 16CLK 16ms 0010 32CLK 32ms 0011 64CLK 64ms 0100 128CLK 0.128s 0101 256CLK 0.256s 0110 512CLK 0.512s 0111 1KCLK 1.0s 1000 2KCLK 2.0s 1001 4KCLK 4.0s XMEGA B [MANUAL] 114 Atmel-8291C-AVR-XMEGA B -09/2014 Note: Reserved settings will not give any timeout for the window. z Bit 1 – WEN: Window Mode Enable This bit enables the window mode. In order to change this bit, the WCEN bit in “WINCTRL – Window Mode Control register” on page 113 must be written to one at the same time. This bit is protected by the configuration change protection mechanism. For a detailed description, refer to “Configuration Change Protection” on page 13. z Bit 0 – WCEN: Window Mode Change Enable This bit enables the ability to change the configuration of the “WINCTRL – Window Mode Control register” on page 113. When writing a new value to this register, this bit must be written to one at the same time for the changes to take effect. This bit is protected by the configuration change protection mechanism, but not protected by the WDT lock fuse. 10.7.3 STATUS – Status register z Bit 7:1 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 0 – SYNCBUSY: Synchronization Busy Flag This flag is set after writing to the CTRL or WINCTRL registers and the data are being synchronized from the system clock to the WDT clock domain. This bit is automatically cleared after the synchronization is finished. Synchronization will take place only when the ENABLE bit for the Watchdog Timer is set. 10.8 Register Summary 1010 8KCLK 8.0s 1011 – Reserved 1100 – Reserved 1101 – Reserved 1110 – Reserved 1111 – Reserved WPER[3:0] Group Configuration Typical Closed Window Periods Bit 7 6 5 4 3 2 1 0 +0x02 – – – – – – – SYNCBUSY Read/Write R R R R R R R R Initial Value 0 0 0 0 0 0 0 0 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL – – PER[3:0] ENABLE CEN 112 +0x01 WINCTRL – – WPER[3:0] WEN WCEN 113 +0x02 STATUS – – – – – – – SYNCBUSY 114 XMEGA B [MANUAL] 115 Atmel-8291C-AVR-XMEGA B -09/2014 11. Interrupts and Programmable Multilevel Interrupt Controller 11.1 Features z Short and predictable interrupt response time z Separate interrupt configuration and vector address for each interrupt z Programmable multilevel interrupt controller z Interrupt prioritizing according to level and vector address z Three selectable interrupt levels for all interrupts: low, medium and high z Selectable, round-robin priority scheme within low-level interrupts z Non-maskable interrupts for critical functions z Interrupt vectors optionally placed in the application section or the boot loader section 11.2 Overview Interrupts signal a change of state in peripherals, and this can be used to alter program execution. Peripherals can have one or more interrupts, and all are individually enabled and configured. When an interrupt is enabled and configured, it will generate an interrupt request when the interrupt condition is present. The programmable multilevel interrupt controller (PMIC) controls the handling and prioritizing of interrupt requests. When an interrupt request is acknowledged by the PMIC, the program counter is set to point to the interrupt vector, and the interrupt handler can be executed. All peripherals can select between three different priority levels for their interrupts: low, medium, and high. Interrupts are prioritized according to their level and their interrupt vector address. Medium-level interrupts will interrupt low-level interrupt handlers. High-level interrupts will interrupt both medium- and low-level interrupt handlers. Within each level, the interrupt priority is decided from the interrupt vector address, where the lowest interrupt vector address has the highest interrupt priority. Low-level interrupts have an optional round-robin scheduling scheme to ensure that all interrupts are serviced within a certain amount of time. Non-maskable interrupts (NMI) are also supported, and can be used for system critical functions. 11.3 Operation Interrupts must be globally enabled for any interrupts to be generated. This is done by setting the global interrupt enable ( I ) bit in the CPU status register. The I bit will not be cleared when an interrupt is acknowledged. Each interrupt level must also be enabled before interrupts with the corresponding level can be generated. When an interrupt is enabled and the interrupt condition is present, the PMIC will receive the interrupt request. Based on the interrupt level and interrupt priority of any ongoing interrupts, the interrupt is either acknowledged or kept pending until it has priority. When the interrupt request is acknowledged, the program counter is updated to point to the interrupt vector. The interrupt vector is normally a jump to the interrupt handler; the software routine that handles the interrupt. After returning from the interrupt handler, program execution continues from where it was before the interrupt occurred. One instruction is always executed before any pending interrupt is served. The PMIC status register contains state information that ensures that the PMIC returns to the correct interrupt level when the RETI (interrupt return) instruction is executed at the end of an interrupt handler. Returning from an interrupt will return the PMIC to the state it had before entering the interrupt. The status register (SREG) is not saved automatically upon an interrupt request. The RET (subroutine return) instruction cannot be used when returning from the interrupt handler routine, as this will not return the PMIC to its correct state. XMEGA B [MANUAL] 116 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 11-1. Interrupt controller overview. 11.4 Interrupts All interrupts and the reset vector each have a separate program vector address in the program memory space. The lowest address in the program memory space is the reset vector. All interrupts are assigned individual control bits for enabling and setting the interrupt level, and this is set in the control registers for each peripheral that can generate interrupts. Details on each interrupt are described in the peripheral where the interrupt is available. All interrupts have an interrupt flag associated with it. When the interrupt condition is present, the interrupt flag will be set, even if the corresponding interrupt is not enabled. For most interrupts, the interrupt flag is automatically cleared when executing the interrupt vector. Writing a logical one to the interrupt flag will also clear the flag. Some interrupt flags are not cleared when executing the interrupt vector, and some are cleared automatically when an associated register is accessed (read or written). This is described for each individual interrupt flag. If an interrupt condition occurs while another, higher priority interrupt is executing or pending, the interrupt flag will be set and remembered until the interrupt has priority. If an interrupt condition occurs while the corresponding interrupt is not enabled, the interrupt flag will be set and remembered until the interrupt is enabled or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while global interrupts are disabled, the corresponding interrupt flag will be set and remembered until global interrupts are enabled. All pending interrupts are then executed according to their order of priority. Interrupts can be blocked when executing code from a locked section; e.g., when the boot lock bits are programmed. This feature improves software security. Refer to “Memory Programming” on page 375 for details on lock bit settings. Interrupts are automatically disabled for up to four CPU clock cycles when the configuration change protection register is written with the correct signature. Refer to “Configuration Change Protection” on page 13 for more details. 11.4.1 NMI – Non-Maskable Interrupts Which interrupts represent NMI and which represent regular interrupts cannot be selected. Non-maskable interrupts must be enabled before they can be used. Refer to the device datasheet for NMI present on each device. An NMI will be executed regardless of the setting of the I bit, and it will never change the I bit. No other interrupts can interrupt a NMI handler. If more than one NMI is requested at the same time, priority is static according to the interrupt vector address, where the lowest address has highest priority. 11.4.2 Interrupt Response Time The interrupt response time for all the enabled interrupts is three CPU clock cycles, minimum; one cycle to finish the ongoing instruction and two cycles to store the program counter to the stack. After the program counter is pushed on the stack, the program vector for the interrupt is executed. The jump to the interrupt handler takes three clock cycles. Peripheral 1 Interrupt Controller INT REQ INT LEVEL INT REQ INT LEVEL CPU INT REQ CTRL LEVEL Enable CPU.SREG Global Interrupt Enable Priority decoder STATUS INTPRI INT ACK INT ACK Peripheral n INT LEVEL INT REQ INT ACK CPU CPU INT ACK CPU ”RETI” Sleep Controller Wake-up XMEGA B [MANUAL] 117 Atmel-8291C-AVR-XMEGA B -09/2014 If an interrupt occurs during execution of a multicycle instruction, this instruction is completed before the interrupt is served. See Figure 11-2 on page 117 for more details. Figure 11-2. Interrupt execution of a multicycle instruction. If an interrupt occurs when the device is in sleep mode, the interrupt execution response time is increased by five clock cycles. In addition, the response time is increased by the start-up time from the selected sleep mode. A return from an interrupt handling routine takes four to five clock cycles, depending on the size of the program counter. During these clock cycles, the program counter is popped from the stack and the stack pointer is incremented. XMEGA B [MANUAL] 118 Atmel-8291C-AVR-XMEGA B -09/2014 11.5 Interrupt level The interrupt level is independently selected for each interrupt source. For any interrupt request, the PMIC also receives the interrupt level for the interrupt. The interrupt levels and their corresponding bit values for the interrupt level configuration of all interrupts is shown in Table 11-1. Table 11-1. Interrupt levels The interrupt level of an interrupt request is compared against the current level and status of the interrupt controller. An interrupt request of a higher level will interrupt any ongoing interrupt handler from a lower level interrupt. When returning from the higher level interrupt handler, the execution of the lower level interrupt handler will continue. 11.6 Interrupt priority Within each interrupt level, all interrupts have a priority. When several interrupt requests are pending, the order in which interrupts are acknowledged is decided both by the level and the priority of the interrupt request. Interrupts can be organized in a static or dynamic (round-robin) priority scheme. High- and medium-level interrupts and the NMI will always have static priority. For low-level interrupts, static or dynamic priority scheduling can be selected. 11.6.1 Static priority Interrupt vectors (IVEC) are located at fixed addresses. For static priority, the interrupt vector address decides the priority within one interrupt level, where the lowest interrupt vector address has the highest priority. Refer to the device datasheet for the interrupt vector table with the base address for all modules and peripherals with interrupt capability. Refer to the interrupt vector summary of each module and peripheral in this manual for a list of interrupts and their corresponding offset address within the different modules and peripherals. Interrupt Level Configuration Group Configuration Description 00 OFF Interrupt disabled. 01 LO Low-level interrupt 10 MED Medium-level interrupt 11 HI High-level interrupt XMEGA B [MANUAL] 119 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 11-3. Static priority. 11.6.2 Round-robin Scheduling To avoid the possible starvation problem for low-level interrupts with static priority, where some interrupts might never be served, the PMIC offers round-robin scheduling for low-level interrupts. When round-robin scheduling is enabled, the interrupt vector address for the last acknowledged low-level interrupt will have the lowest priority the next time one or more interrupts from the low level is requested. Figure 11-4. Round-robin scheduling. XMEGA B [MANUAL] 120 Atmel-8291C-AVR-XMEGA B -09/2014 11.7 Interrupt vector locations Table 11-2 shows reset and Interrupt vectors placement for the various combinations of BOOTRST and IVSEL settings. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the Boot section or vice versa. Table 11-2. Reset and interrupt vectors placement BOOTRST IVSEL Reset Address Interrupt Vectors Start Address 1 0 0x0000 0x0002 1 1 0x0000 Boot Reset Address + 0x0002 0 0 Boot Reset Address 0x0002 0 1 Boot Reset Address Boot Reset Address + 0x0002 XMEGA B [MANUAL] 121 Atmel-8291C-AVR-XMEGA B -09/2014 11.8 Register Description 11.8.1 STATUS – Status register z Bit 7 – NMIEX: Non-Maskable Interrupt Executing This flag is set if a non-maskable interrupt is executing. The flag will be cleared when returning (RETI) from the interrupt handler. z Bit 6:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2 – HILVLEX: High-level Interrupt Executing This flag is set when a high-level interrupt is executing or when the interrupt handler has been interrupted by an NMI. The flag will be cleared when returning (RETI) from the interrupt handler. z Bit 1 – MEDLVLEX: Medium-level Interrupt Executing This flag is set when a medium-level interrupt is executing or when the interrupt handler has been interrupted by an interrupt from higher level or an NMI. The flag will be cleared when returning (RETI) from the interrupt handler. z Bit 0 – LOLVLEX: Low-level Interrupt Executing This flag is set when a low-level interrupt is executing or when the interrupt handler has been interrupted by an interrupt from higher level or an NMI. The flag will be cleared when returning (RETI) from the interrupt handler. 11.8.2 INTPRI – Interrupt priority register z Bit 7:0 – INTPRI: Interrupt Priority When round-robin scheduling is enabled, this register stores the interrupt vector of the last acknowledged low-level interrupt. The stored interrupt vector will have the lowest priority the next time one or more low-level interrupts are pending. The register is accessible from software to change the priority queue. This register is not reinitialized to its initial value if round-robing scheduling is disabled, and so if default static priority is needed, the register must be written to zero. Bit 7 6 5 4 3 2 1 0 +0x00 NMIEX – – – – HILVLEX MEDLVLEX LOLVLEX Read/Write R R R R R R R R Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x01 INTPRI[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 122 Atmel-8291C-AVR-XMEGA B -09/2014 11.8.3 CTRL – Control register z Bit 7 – RREN: Round-robin Scheduling Enable When the RREN bit is set, the round-robin scheduling scheme is enabled for low-level interrupts. When this bit is cleared, the priority is static according to interrupt vector address, where the lowest address has the highest priority. z Bit 6 – IVSEL: Interrupt Vector Select When the IVSEL bit is cleared (zero), the interrupt vectors are placed at the start of the application section in flash. When this bit is set (one), the interrupt vectors are placed in the beginning of the boot section of the flash. Refer to the device datasheet for the absolute address. This bit is protected by the configuration change protection mechanism. Refer to “Configuration Change Protection” on page 13 for details. z Bit 5:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2 – HILVLEN: High-level Interrupt Enable (1) When this bit is set, all high-level interrupts are enabled. If this bit is cleared, high-level interrupt requests will be ignored. z Bit 1 – MEDLVLEN: Medium-level Interrupt Enable(1) When this bit is set, all medium-level interrupts are enabled. If this bit is cleared, medium-level interrupt requests will be ignored. z Bit 0 – LOLVLEN: Low-level Interrupt Enable(1) When this bit is set, all low-level interrupts are enabled. If this bit is cleared, low-level interrupt requests will be ignored. Note: 1. Ignoring interrupts will be effective one cycle after the bit is cleared. 11.9 Register Summary Bit 7 6 5 4 3 2 1 0 +0x02 RREN IVSEL – – – HILVLEN MEDLVLEN LOLVLEN Read/Write R/W R/W R R R R/W R/W R/W Initial Value 0 00000 0 0 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 STATUS NMIEX – – – – HILVLEX MEDLVLEX LOLVLEX 121 +0x01 INTPRI INTPRI[7:0] 121 +0x02 CTRL RREN IVSEL – – – HILVLEN MEDLVLEN LOLVLEN 122 XMEGA B [MANUAL] 123 Atmel-8291C-AVR-XMEGA B -09/2014 12. I/O Ports 12.1 Features z General purpose input and output pins with individual configuration z Output driver with configurable driver and pull settings: z Totem-pole z Wired-AND z Wired-OR z Bus-keeper z Inverted I/O z Input with synchronous and/or asynchronous sensing with interrupts and events z Sense both edges z Sense rising edges z Sense falling edges z Sense low level z Optional pull-up and pull-down resistor on input and Wired-OR/AND configurations z Asynchronous pin change sensing that can wake the device from all sleep modes z Two port interrupts with pin masking per I/O port z Efficient and safe access to port pins z Hardware read-modify-write through dedicated toggle/clear/set registers z Configuration of multiple pins in a single operation z Mapping of port registers into bit-accessible I/O memory space z Peripheral clocks output on port pin z Real-time counter clock output to port pin z Event channels can be output on port pin z Remapping of digital peripheral pin functions z Selectable USART, SPI, and timer/counter input/output pin locations 12.2 Overview AVR XMEGA microcontrollers have flexible general purpose I/O ports. One port consists of up to eight port pins: pin 0 to 7. Each port pin can be configured as input or output with configurable driver and pull settings. They also implement synchronous and asynchronous input sensing with interrupts and events for selectable pin change conditions. Asynchronous pin-change sensing means that a pin change can wake the device from all sleep modes, included the modes where no clocks are running. All functions are individual and configurable per pin, but several pins can be configured in a single operation. The pins have hardware read-modify-write (RMW) functionality for safe and correct change of drive value and/or pull resistor configuration. The direction of one port pin can be changed without unintentionally changing the direction of any other pin. The port pin configuration also controls input and output selection of other device functions. It is possible to have both the peripheral clock and the real-time clock output to a port pin, and available for external use. The same applies to events from the event system that can be used to synchronize and control external functions. Other digital peripherals, such as USART, SPI, and timer/counters, can be remapped to selectable pin locations in order to optimize pin-out versus application needs. Figure 12-1 on page 124 shows the I/O pin functionality and the registers that are available for controlling a pin. XMEGA B [MANUAL] 124 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 12-1. General I/O pin functionality. 12.3 I/O Pin Use and Configuration Each port has one data direction (DIR) register and one data output value (OUT) register that are used for port pin control. The data input value (IN) register is used for reading the port pins. In addition, each pin has a pin configuration (PINnCTRL) register for additional pin configuration. Direction of the pin is decided by the DIRn bit in the DIR register. If DIRn is written to one, pin n is configured as an output pin. If DIRn is written to zero, pin n is configured as an input pin. When direction is set as output, the OUTn bit in OUT is used to set the value of the pin. If OUTn is written to one, pin n is driven high. If OUTn is written to zero, pin n is driven low. The IN register is used for reading pin values. A pin value can always be read regardless of whether the pin is configured as input or output, except if digital input is disabled. The I/O pins are tri-stated when a reset condition becomes active, even if no clocks are running. The pin n configuration (PINnCTRL) register is used for additional I/O pin configuration. A pin can be set in a totem-pole, wired-AND, or wired-OR configuration. It is also possible to enable inverted input and output for a pin. A totem-pole output has four possible pull configurations: totem-pole (push-pull), pull-down, pull-up, and bus-keeper. The bus-keeper is active in both directions. This is to avoid oscillation when disabling the output. The totem-pole Q D R Q D R Synchronizer D Q R D Q R DIRn OUTn PINnCTRL INn Pxn D Q R C o n t r o l L o g i c Input Disable Wired AND/OR Digital Input Pin Analog Input/Output Inverted I/O Pull Enable Pull Keep Pull Direction XMEGA B [MANUAL] 125 Atmel-8291C-AVR-XMEGA B -09/2014 configurations with pull-up and pull-down have active resistors only when the pin is set as input. This feature eliminates unnecessary power consumption. For wired-AND and wired-OR configuration, the optional pull-up and pull-down resistors are active in both input and output directions. Since pull configuration is configured through the pin configuration register, all intermediate port states during switching of the pin direction and pin values are avoided. The I/O pin configurations are summarized with simplified schematics in Figure 12-2 on page 125 to Figure 12-7 on page 127. 12.3.1 Totem-pole In the totem-pole (push-pull) configuration, the pin is driven low or high according to the corresponding bit setting in the OUT register. In this configuration, there is no current limitation for sink or source other than what the pin is capable of. If the pin is configured for input, the pin will float if no external pull resistor is connected. Figure 12-2. I/O pin configuration - Totem-pole (push-pull). 12.3.1.1 Totem-pole with Pull-down In this mode, the configuration is the same as for totem-pole mode, expect the pin is configured with an internal pull-down resistor when set as input. Figure 12-3. I/O pin configuration - Totem-pole with pull-down (on input). XMEGA B [MANUAL] 126 Atmel-8291C-AVR-XMEGA B -09/2014 12.3.1.2 Totem-pole with Pull-up In this mode, the configuration is as for totem-pole, expect the pin is configured with internal pull-up when set as input. Figure 12-4. I/O pin configuration - Totem-pole with pull-up (on input). 12.3.2 Bus-keeper In the bus-keeper configuration, it provides a weak bus-keeper that will keep the pin at its logic level when the pin is no longer driven to high or low. If the last level on the pin/bus was 1, the bus-keeper configuration will use the internal pull resistor to keep the bus high. If the last logic level on the pin/bus was 0, the bus-keeper will use the internal pull resistor to keep the bus low. Figure 12-5. I/O pin configuration - Totem-pole with bus-keeper. XMEGA B [MANUAL] 127 Atmel-8291C-AVR-XMEGA B -09/2014 12.3.3 Wired-OR In the wired-OR configuration, the pin will be driven high when the corresponding bits in the OUT and DIR registers are written to one. When the OUT register is set to zero, the pin is released, allowing the pin to be pulled low with the internal or an external pull-resistor. If internal pull-down is used, this is also active if the pin is set as input. Figure 12-6. Output configuration - Wired-OR with optional pull-down. 12.3.4 Wired-AND In the wired-AND configuration, the pin will be driven low when the corresponding bits in the OUT and DIR registers are written to zero. When the OUT register is set to one, the pin is released allowing the pin to be pulled high with the internal or an external pull-resistor. If internal pull-up is used, this is also active if the pin is set as input. Figure 12-7. Output configuration - Wired-AND with optional pull-up. XMEGA B [MANUAL] 128 Atmel-8291C-AVR-XMEGA B -09/2014 12.4 Reading the Pin Value Independent of the pin data direction, the pin value can be read from the IN register, as shown in Figure 12-1 on page 124. If the digital input is disabled, the pin value cannot be read. The IN register bit and the preceding flip-flop constitute a synchronizer. The synchronizer introduces a delay on the internal signal line. Figure 12-8 on page 128 shows a timing diagram of the synchronization when reading an externally applied pin value. The maximum and minimum propagation delays are denoted as tpd,max and tpd,min, respectively. Figure 12-8. Synchronization when reading a pin value. XMEGA B [MANUAL] 129 Atmel-8291C-AVR-XMEGA B -09/2014 12.5 Input Sense Configuration Input sensing is used to detect an edge or level on the I/O pin input. The different sense configurations that are available for each pin are detection of a rising edge, falling edge, or any edge or detection of a low level. High level can be detected by using the inverted input configuration. Input sensing can be used to trigger interrupt requests (IREQ) or events when there is a change on the pin. The I/O pins support synchronous and asynchronous input sensing. Synchronous sensing requires the presence of the peripheral clock, while asynchronous sensing does not require any clock. Figure 12-9. Input sensing. 12.6 Port Interrupt Each port has two interrupt vectors, and it is configurable which pins on the port will trigger each interrupt. Port interrupts must be enabled before they can be used. Which sense configurations can be used to generate interrupts is dependent on whether synchronous or asynchronous input sensing is available for the selected pin. For synchronous sensing, all sense configurations can be used to generate interrupts. For edge detection, the changed pin value must be sampled once by the peripheral clock for an interrupt request to be generated. For asynchronous sensing, only port pin 2 on each port has full asynchronous sense support. This means that for edge detection, pin 2 will detect and latch any edge and it will always trigger an interrupt request. The other port pins have limited asynchronous sense support. This means that for edge detection, the changed value must be held until the device wakes up and a clock is present. If the pin value returns to its initial value before the end of the device wake-up time, the device will still wake up, but no interrupt request will be generated. A low level can always be detected by all pins, regardless of a peripheral clock being present or not. If a pin is configured for low-level sensing, the interrupt will trigger as long as the pin is held low. In active mode, the low level must be held until the completion of the currently executing instruction for an interrupt to be generated. In all sleep modes, the low level must be kept until the end of the device wake-up time for an interrupt to be generated. If the low level disappears before the end of the wake-up time, the device will still wake up, but no interrupt will be generated. Table 12-1, Table 12-2, and Table 12-3 on page 130 summarize when interrupts can be triggered for the various input sense configurations. D Q R INVERTED I/O Interrupt Control D Q R Pxn Synchronizer INn EDGE DETECT Synchronous sensing EDGE DETECT Asynchronous sensing IRQ Synchronous Events Asynchronous Events XMEGA B [MANUAL] 130 Atmel-8291C-AVR-XMEGA B -09/2014 Table 12-1. Synchronous sense support. Table 12-2. Full asynchronous sense support. Table 12-3. Limited asynchronous sense support. 12.7 Port Event Port pins can generate an event when there is a change on the pin. The sense configurations decide the conditions for each pin to generate events. Event generation requires the presence of a peripheral clock, and asynchronous event generation is not possible. For edge sensing, the changed pin value must be sampled once by the peripheral clock for an event to be generated. For level sensing, a low-level pin value will not generate events, and a high-level pin value will continuously generate events. For events to be generated on a low level, the pin configuration must be set to inverted I/O. Table 12-4. Event sense support Sense Settings Supported Interrupt Description Rising edge Yes Always triggered Falling edge Yes Always triggered Any edge Yes Always triggered Low level Yes Pin level must be kept unchanged during wake up Sense Settings Supported Interrupt Description Rising edge Yes Always triggered Falling edge Yes Always triggered Both edges Yes Always triggered Low level Yes Pin level must be kept unchanged during wake up Sense Settings Supported Interrupt Description Rising edge No - Falling edge No - Any edge Yes Pin value must be kept unchanged during wake up Low level Yes Pin level must be kept unchanged during wake up Sense Settings Signal event Data event Rising edge Rising edge Pin value Falling edge Falling edge Pin value Both edge Any edge Pin value Low level Pin value Pin value XMEGA B [MANUAL] 131 Atmel-8291C-AVR-XMEGA B -09/2014 12.8 Alternate Port Functions Most port pins have alternate pin functions in addition to being a general purpose I/O pin. When an alternate function is enabled, it might override the normal port pin function or pin value. This happens when other peripherals that require pins are enabled or configured to use pins. If and how a peripheral will override and use pins is described in the section for that peripheral. The port override signals and related logic (grey) are shown in Figure 12-10 on page 131. These signals are not accessible from software, but are internal signals between the overriding peripheral and the port pin. Figure 12-10. Port override signals and related logic. Q D R Q D R Synchronizer D Q R D Q R DIRn OUTn PINnCTRL INn Pxn D Q R C o n t r o l L o g i c Digital Input Disable (DID) Wired AND/OR Digital Input Pin Analog Input/Output Inverted I/O Pull Enable Pull Keep Pull Direction DID Override Enable DID Override Value OUT Override Enable OUT Override Value DIR Override Enable DIR Override Value XMEGA B [MANUAL] 132 Atmel-8291C-AVR-XMEGA B -09/2014 12.9 Clock and Event Output It is possible to output the peripheral clock and event channel 0 events to a pin. This can be used to clock, control, and synchronize external functions and hardware to internal device timing. The output port pin is selectable. If an event occurs, it remains visible on the port pin as long as the event lasts; normally one peripheral clock cycle. 12.10 Multi-pin configuration The multi-pin configuration function is used to configure multiple port pins using a single write operation to only one of the port pin configuration registers. A mask register decides which port pin is configured when one port pin register is written, while avoiding several pins being written the same way during identical write operations. 12.11 Virtual Ports Virtual port registers allow the port registers to be mapped virtually in the bit-accessible I/O memory space. When this is done, writing to the virtual port register will be the same as writing to the real port register. This enables the use of I/O memory-specific instructions, such as bit-manipulation instructions, on a port register that normally resides in the extended I/O memory space. There are four virtual ports, and so four ports can be mapped at the same time. XMEGA B [MANUAL] 133 Atmel-8291C-AVR-XMEGA B -09/2014 12.12 Register Descriptions – Ports 12.12.1 DIR – Data Direction register z Bit 7:0 – DIR[7:0]: Data Direction This register sets the data direction for the individual pins of the port. If DIRn is written to one, pin n is configured as an output pin. If DIRn is written to zero, pin n is configured as an input pin. 12.12.2 DIRSET – Data Direction Set Register z Bit 7:0 – DIRSET[7:0]: Port Data Direction Set This register can be used instead of a read-modify-write to set individual pins as output. Writing a one to a bit will set the corresponding bit in the DIR register. Reading this register will return the value of the DIR register. 12.12.3 DIRCLR – Data Direction Clear register z Bit 7:0 – DIRCLR[7:0]: Port Data Direction Clear This register can be used instead of a read-modify-write to set individual pins as input. Writing a one to a bit will clear the corresponding bit in the DIR register. Reading this register will return the value of the DIR register. Bit 7 6 5 4 3 2 1 0 +0x00 DIR[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x01 DIRSET[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0000000 Bit 7 6 5 4 3 2 1 0 +0x02 DIRCLR[7:0] 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 XMEGA B [MANUAL] 134 Atmel-8291C-AVR-XMEGA B -09/2014 12.12.4 DIRTGL – Data Direction Toggle register z Bit 7:0 – DIRTGL[7:0]: Port Data Direction Toggle This register can be used instead of a read-modify-write to toggle the direction of individual pins. Writing a one to a bit will toggle the corresponding bit in the DIR register. Reading this register will return the value of the DIR register. 12.12.5 OUT – Data Output Value register z Bit 7:0 – OUT[7:0]: Port Data Output value This register sets the data output value for the individual pins of the port. If OUTn is written to one, pin n is driven high. If OUTn is written to zero, pin n is driven low. For this setting to have any effect, the pin direction must be set as output. 12.12.6 OUTSET – Data Output Value Set register z Bit 7:0 – OUTSET[7:0]: Data Output Value Set This register can be used instead of a read-modify-write to set the output value of individual pins to one. Writing a one to a bit will set the corresponding bit in the OUT register. Reading this register will return the value in the OUT register. 12.12.7 OUTCLR – Data Output Value Clear register z Bit 7:0 – OUTCLR[7:0]: Data Output Value Clear This register can be used instead of a read-modify-write to set the output value of individual pins to zero. Writing a one to a bit will clear the corresponding bit in the OUT register. Reading this register will return the value in the OUT register. Bit 7 6 5 4 3 2 1 0 +0x03 DIRTGL[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x04 OUT[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0000 Bit 7 6 5 4 3 2 1 0 +0x05 OUTSET[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x06 OUTCLR[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 000000 XMEGA B [MANUAL] 135 Atmel-8291C-AVR-XMEGA B -09/2014 12.12.8 OUTTGL – Data Output Value Toggle register z Bit 7:0 – OUTTGL[7:0]: Port Data Output Value Toggle This register can be used instead of a read-modify-write to toggle the output value of individual pins. Writing a one to a bit will toggle the corresponding bit in the OUT register. Reading this register will return the value in the OUT register. 12.12.9 IN – Data Input Value register z Bit 7:0 – IN[7:0]: Data Input Value This register shows the value present on the pins if the digital input driver is enabled. INn shows the value of pin n of the port. The input is not sampled and cannot be read if the digital input buffers are disabled. 12.12.10INTCTRL – Interrupt Control register z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:2/1:0 – INTnLVL[1:0]: Interrupt n Level These bits enable port interrupt n and select the interrupt level as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. Bit 7 6 5 4 3 2 1 0 +0x07 OUTTGL[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x08 IN[7:0] Read/Write RRRRRRRR Initial Value 0 0000000 Bit 7 6 5 4 3 2 1 0 +0x09 – – – – INT1LVL[1:0] INT0LVL[1:0] Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0000000 XMEGA B [MANUAL] 136 Atmel-8291C-AVR-XMEGA B -09/2014 12.12.11INT0MASK – Interrupt 0 Mask register z Bit 7:0 – INT0MSK[7:0]: Interrupt 0 Mask bits These bits are used to mask which pins can be used as sources for port interrupt 0. If INT0MASKn is written to one, pin n is used as source for port interrupt 0.The input sense configuration for each pin is decided by the PINnCTRL registers. 12.12.12INT1MASK – Interrupt 1 Mask register z Bit 7:0 – INT1MASK[7:0]: Interrupt 1 Mask bits These bits are used to mask which pins can be used as sources for port interrupt 1. If INT1MASKn is written to one, pin n is used as source for port interrupt 1.The input sense configuration for each pin is decided by the PINnCTRL registers. 12.12.13INTFLAGS – Interrupt Flag register z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1:0 – INTnIF: Interrupt n Flag The INTnIF flag is set when a pin change/state matches the pin's input sense configuration, and the pin is set as source for port interrupt n. Writing a one to this flag's bit location will clear the flag. For enabling and executing the interrupt, refer to the interrupt level description. Bit 7 6 5 4 3 2 1 0 +0x0A INT0MSK[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0B INT1MSK[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0000000 Bit 7 6 5 4 3 2 1 0 +0x0C – – – – – – INT1IF INT0IF Read/Write R R R R R R R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 137 Atmel-8291C-AVR-XMEGA B -09/2014 12.12.14REMAP – Pin Remap register The pin remap functionality is available for PORTC - PORTF only. z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 5 – SPI: SPI Remap Setting this bit to one will swap the pin locations of the SCK and MOSI pins to have pin compatibility between SPI and USART when the USART is operating as a SPI master. z Bit 4 – USART0: USART0 Remap Setting this bit to one will move the pin location of USART0 from Px[3:0] to Px[7:4]. z Bit 3 – TC0D: Timer/Counter 0 Output Compare D Setting this bit will move the location of OC0D from Px3 to Px7. z Bit 2 – TC0C: Timer/Counter 0 Output Compare C Setting this bit will move the location of OC0C from Px2 to Px6. z Bit 1 – TC0B: Timer/Counter 0 Output Compare B Setting this bit will move the location of OC0B from Px1 to Px5. If this bit is set and PWM from both timer/counter 0 and timer/counter 1 is enabled, the resulting PWM will be an OR-modulation between the two PWM outputs. z Bit 0 – TC0A: Timer/Counter 0 Output Compare A Setting this bit will move the location of OC0A from Px0 to Px4. If this bit is set and PWM from both timer/counter 0 and timer/counter 1 is enabled, the resulting PWM will be an OR-modulation between the two PWM outputs. See Figure 12- 11. Figure 12-11.I/O timer/counter. Bit 7 6 5 4 3 2 1 0 +0x0E – – SPI USART0 TC0D TC0C TC0B TC0A Read/Write R R R/W R/W R/W R/W R/W R/W Initial Value 0 0000000 OC0A OC1A OCA XMEGA B [MANUAL] 138 Atmel-8291C-AVR-XMEGA B -09/2014 12.12.15PINnCTRL – Pin n Configuration Register z Bit 7 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 6 – INVEN: Inverted I/O Enable Setting this bit will enable inverted output and input data on pin n. z Bit 5:3 – OPC: Output and Pull Configuration These bits set the output/pull configuration on pin n according to Table 12-5. Table 12-5. Output/pull configuration z Bit 2:0 – ISC[2:0]: Input/Sense Configuration These bits set the input and sense configuration on pin n according to Table 12-6 on page 138. The sense configuration decides how the pin can trigger port interrupts and events. If the input buffer is not disabled, the input cannot be read in the IN register. Table 12-6. Input/sense configuration. Bit 7 6 5 4 3 2 1 0 – INVEN OPC[2:0] ISC[2:0] 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 OPC[2:0] Group Configuration Description Output Configuration Pull Configuration 000 TOTEM Totem-pole (N/A) 001 BUSKEEPER Totem-pole Bus-keeper 010 PULLDOWN Totem-pole Pull-down (on input) 011 PULLUP Totem-pole Pull-up (on input) 100 WIREDOR Wired-OR (N/A) 101 WIREDAND Wired-AND (N/A) 110 WIREDORPULL Wired-OR Pull-down 111 WIREDANDPULL Wired-AND Pull-up ISC[2:0] Group Configuration Description 000 BOTHEDGES Sense both edges 001 RISING Sense rising edge 010 FALLING Sense falling edge 011 LEVEL Sense low level(1) XMEGA B [MANUAL] 139 Atmel-8291C-AVR-XMEGA B -09/2014 Note: 1. A low-level pin value will not generate events, and a high-level pin value will continuously generate events. 2. Only PORTA - PORTF support the input buffer disable option. If the pin is used for analog functionality, such as AC or ADC, it is recommended to configure the pin to INPUT_DISABLE. 100 – Reserved 101 – Reserved 110 – Reserved 111 INTPUT_DISABLE Digital input buffer disabled(2) ISC[2:0] Group Configuration Description XMEGA B [MANUAL] 140 Atmel-8291C-AVR-XMEGA B -09/2014 12.13 Register Descriptions – Port Configuration 12.13.1 MPCMASK – Multi-pin Configuration Mask register z Bit 7:0 – MPCMASK[7:0]: Multi-pin Configuration Mask The MPCMASK register enables configuration of several pins of a port at the same time. Writing a one to bit n makes pin n part of the multi-pin configuration. When one or more bits in the MPCMASK register is set, writing any of the PINnCTRL registers will update only the PINnCTRL registers matching the mask in the MPCMASK register for that port. The MPCMASK register is automatically cleared after any PINnCTRL register is written. 12.13.2 VPCTRLA – Virtual Port-map Control register A z Bit 7:4 – VP1MAP: Virtual Port 1 Mapping These bits decide which ports should be mapped to Virtual Port 1. The registers DIR, OUT, IN, and INTFLAGS will be mapped. Accessing the virtual port registers is equal to accessing the actual port registers. See Table 12-7 on page 141 for configuration. z Bit 3:0 – VP0MAP: Virtual Port 0 Mapping These bits decide which ports should be mapped to Virtual Port 0. The registers DIR, OUT, IN, and INTFLAGS will be mapped. Accessing the virtual port registers is equal to accessing the actual port registers. See Table 12-7 on page 141 for configuration. 12.13.3 VPCTRLB – Virtual Port-map Control register B z Bit 7:4 – VP3MAP: Virtual Port 3 Mapping These bits decide which ports should be mapped to Virtual Port 3. The registers DIR, OUT, IN, and INTFLAGS will be mapped. Accessing the virtual port registers is equal to accessing the actual port registers. See Table 12-7 on page 141 for configuration. Bit 7 6 5 4 3 2 1 0 +0x00 MPCMASK[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x02 VP1MAP[3:0] VP0MAP[3:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 000000 Bit 7 6 5 4 3 2 1 0 +0x03 VP3MAP[3:0] VP2MAP[3:0] 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 XMEGA B [MANUAL] 141 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 3:0 – VP2MAP: Virtual Port 2 Mapping These bits decide which ports should be mapped to Virtual Port 2. The registers DIR, OUT, IN, and INTFLAGS will be mapped. Accessing the virtual port registers is equal to accessing the actual port registers. See Table 12-7 on page 141 for configuration. Table 12-7. Virtual port mapping 12.13.4 CLKEVOUT – Clock and Event Out register z Bit 7 – CLKEVPIN: Clock and Event Output Pin Select Setting this pin enables output of clock and event pins on port pin 4 instead of port pin 7. z Bit 6 – RTCOUT: RTC Clock Output Enable Setting this bit enables output of the RTC clock source on PORTC pin 6. z Bit 5:4 – EVOUT[1:0]: Event Output Port These bits decide which port event channel 0 from the event system will be output to. Pin 7 on the selected port is the default used, and the CLKOUT bits must be set differently from those of EVOUT. The port pin must be configured as output for the event to be available on the pin. VPnMAP[3:0] Group Configuration Description 0000 PORTA PORTA mapped to Virtual Port n 0001 PORTB PORTB mapped to Virtual Port n 0010 PORTC PORTC mapped to Virtual Port n 0011 PORTD PORTD mapped to Virtual Port n 0100 PORTE PORTE mapped to Virtual Port n 0101 PORTF PORTF mapped to Virtual Port n 0110 PORTG PORTG mapped to Virtual Port n 0111 PORTH PORTH mapped to Virtual Port n 1000 PORTJ PORTJ mapped to Virtual Port n 1001 PORTK PORTK mapped to Virtual Port n 1010 PORTL PORTL mapped to Virtual Port n 1011 PORTM PORTM mapped to Virtual Port n 1100 PORTN PORTN mapped to Virtual Port n 1101 PORTP PORTP mapped to Virtual Port n 1110 PORTQ PORTQ mapped to Virtual Port n 1111 PORTR PORTR mapped to Virtual Port n Bit 7 6 5 4 3 2 1 0 +0x04 CLKEVPIN RTCOUT EVOUT[1:0] CLKOUTSEL[1:0] CLKOUT[1:0] 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 XMEGA B [MANUAL] 142 Atmel-8291C-AVR-XMEGA B -09/2014 Table 12-8 on page 142 shows the possible configurations. z Bits 3:2 – CLKOUTSEL[1:0]: Clock Output Select These bits are used to select which of the peripheral clocks will be output to the port pin if CLKOUT is configured. z Bit 1:0 – CLKOUT[1:0]: Clock Output Port These bits decide which port the peripheral clock will be output to. Pin 7 on the selected port is the default used. The CLKOUT setting will override the EVOUT setting. Thus, if both are enabled on the same port pin, the peripheral clock will be visible. The port pin must be configured as output for the clock to be available on the pin. Table 12-10 shows the possible configurations. Table 12-8. Event output pin selection. EVOUT[1:0] Group Configuration Description 00 OFF Event output disabled 01 PC Event channel 0 output on PORTC 10 PD Event channel 0 output on PORTD 11 PE Event channel 0 output on PORTE Table 12-9. Clock output clock selection. CLKOUTSEL[1:0] Group Configuration Description 00 CLK1X CLKPER output to pin 01 CLK2X CLKPER2 output to pin 10 CLK4X CLKPER4 output to pin 11 – (Reserved) Table 12-10. Clock output port configurations. CLKOUT[1:0] Group Configuration Description 00 OFF Clock output disabled 01 PC Clock output on PORTC 10 PD Clock output on PORTD 11 PE Clock output on PORTE XMEGA B [MANUAL] 143 Atmel-8291C-AVR-XMEGA B -09/2014 12.13.5 EVCTRL – Event Control register z Bit 7:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2:0 – EVOUTSEL[2:0]: Event Channel Output Selection These bits define which channel from the event system is output to the port pin. Table 12-11 shows the available selections. Bit 7 6 5 4 3 2 1 0 +0x06 – – – – – EVOUTSEL[2:0] Read/Write R R R R R R/W R/W R/W Initial Value 0 0 0 0 0 000 Table 12-11. Event channel output selection. EVOUTSEL[2:0] Group Configuration Description 000 0 Event channel 0 output to pin 001 1 Event channel 1 output to pin 010 2 Event channel 2 output to pin 011 3 Event channel 3 output to pin 100 4 Event channel 4 output to pin 101 5 Event channel 5 output to pin 110 6 Event channel 6 output to pin 111 7 Event channel 7 output to pin XMEGA B [MANUAL] 144 Atmel-8291C-AVR-XMEGA B -09/2014 12.14 Register Descriptions – Virtual Port 12.14.1 DIR – Data Direction register z Bit 7:0 – DIR[7:0]: Data Direction This register sets the data direction for the individual pins in the port mapped by VPCTRLA, virtual port-map control register A or VPCTRLB, virtual port-map control register B. When a port is mapped as virtual, accessing this register is identical to accessing the actual DIR register for the port. 12.14.2 OUT – Data Output Value register z Bit 7:0 – OUT[7:0]: Data Output value This register sets the data output value for the individual pins in the port mapped by VPCTRLA, virtual port-map control register A or VPCTRLB, virtual port-map control register B. When a port is mapped as virtual, accessing this register is identical to accessing the actual OUT register for the port. 12.14.3 IN – Data Input Value register z Bit 7:0 – IN[7:0]: Data Input value This register shows the value present on the pins if the digital input buffer is enabled. The configuration of VPCTRLA, virtual port-map control register A or VPCTRLB, virtual port-map control register A, decides the value in the register. When a port is mapped as virtual, accessing this register is identical to accessing the actual IN register for the port. Bit 7 6 5 4 3 2 1 0 +0x00 DIR[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x01 OUT[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0000000 Bit 7 6 5 4 3 2 1 0 +0x02 IN[7:0] 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 XMEGA B [MANUAL] 145 Atmel-8291C-AVR-XMEGA B -09/2014 12.14.4 INTFLAGS – Interrupt Flag register z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1:0 – INTnIF: Interrupt n Flag The INTnIF flag is set when a pin change/state matches the pin's input sense configuration, and the pin is set as source for port interrupt n. Writing a one to this flag's bit location will clear the flag. For enabling and executing the interrupt, refer to the interrupt level description. The configuration of VPCTRLA, virtual port-map control register A, or VPCTRLB, Virtual Port-map Control Register B, decides which flags are mapped. When a port is mapped as virtual, accessing this register is identical to accessing the actual INTFLAGS register for the port. Bit 7 6 5 4 3 2 1 0 +0x03 – – – – – – INT1IF INT0IF Read/Write R R R R R R R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 146 Atmel-8291C-AVR-XMEGA B -09/2014 12.15 Register Summary – Ports 12.16 Register Summary – Port Configuration 12.17 Register Summary – Virtual Ports Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 DIR DIR[7:0] 133 +0x01 DIRSET DIRSET[7:0] 133 +0x02 DIRCLR DIRCLR[7:0] 133 +0x03 DIRTGL DIRTGL[7:0] 134 +0x04 OUT OUT[7:0] 134 +0x05 OUTSET OUTSET[7:0] 134 +0x06 OUTCLR OUTCLR[7:0] 134 +0x07 OUTTGL OUTTGL[7:0] 135 +0x08 IN IN[7:0] 135 +0x09 INTCTRL – – – – INT1LVL[1:0] INT0LVL[1:0] 135 +0x0A INT0MASK INT0MSK[7:0] 136 +0x0B INT1MASK INT1MSK[7:0] 136 +0x0C INTFLAGS – – – – – – INT1IF INT0IF 136 +0x0D Reserved – – – – – – – – +0x0E REMAP – – SPI USART0 TC0D TC0C TC0B TC0A 137 +0x0F Reserved – – – – – – – – +0x10 PIN0CTRL – INVEN OPC[2:0] ISC[2:0] 138 +0x11 PIN1CTRL – INVEN OPC[2:0] ISC[2:0] 138 +0x12 PIN2CTRL – INVEN OPC[2:0] ISC[2:0] 138 +0x13 PIN3CTRL – INVEN OPC[2:0] ISC[2:0] 138 +0x14 PIN4CTRL – INVEN OPC[2:0] ISC[2:0] 138 +0x15 PIN5CTRL – INVEN OPC[2:0] ISC[2:0] 138 +0x16 PIN6CTRL – INVEN OPC[2:0] ISC[2:0] 138 +0x17 PIN7CTRL – INVEN OPC[2:0] ISC[2:0] 138 +0x18 Reserved – – – – – – – – +0x19 Reserved – – – – – – – – +0x1A Reserved – – – – – – – – +0x1B Reserved – – – – – – – – +0x1C Reserved – – – – – – – – +0x1D Reserved – – – – – – – – +0x1E Reserved – – – – – – – – +0x1F Reserved – – – – – – – – Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 MPCMASK MPCMASK[7:0] 140 +0x01 Reserved – – – – – – – – +0x02 VPCTRLA VP1MAP[3:0] VP0MAP[3:0] 140 +0x03 VPCTRLB VP3MAP[3:0] VP2MAP[3:0] 140 +0x04 CLKEVOU CLKEVPIN RTCOUT EVOUT[1:0] CLKOUTSEL CLKOUT[1:0] 141 +0x05 Reserved – – – – – – – – +0x06 EVCTRL – – – – – EVCTRL[2:0] 143 +0x07 Reserved – – – – – – – – Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 DIR DIR[7:0] 144 +0x01 OUT OUT[7:0] 144 +0x02 IN IN[7:0] 144 +0x03 INTFLAGS – – – – – – INT1IF INT0IF 145 XMEGA B [MANUAL] 147 Atmel-8291C-AVR-XMEGA B -09/2014 12.18 Interrupt Vector Summary – Ports Offset Source Interrupt Description 0x00 INT0_vect Port interrupt vector 0 offset 0x02 INT1_vect Port interrupt vector 1 offset XMEGA B [MANUAL] 148 Atmel-8291C-AVR-XMEGA B -09/2014 13. TC0/1 – 16-bit Timer/Counter Type 0 and 1 13.1 Features z 16-bit timer/counter z 32-bit timer/counter support by cascading two timer/counters z Up to four compare or capture (CC) channels z Four CC channels for timer/counters of type 0 z Two CC channels for timer/counters of type 1 z Double buffered timer period setting z Double buffered capture or compare channels z Waveform generation: z Frequency generation z Single-slope pulse width modulation z Dual-slope pulse width modulation z Input capture: z Input capture with noise cancelling z Frequency capture z Pulse width capture z 32-bit input capture z Timer overflow and error interrupts/events z One compare match or input capture interrupt/event per CC channel z Can be used with event system for: z Quadrature decoding z Count and direction control z Capture z Can be used with DMA and to trigger DMA transactions z High-resolution extension z Increases frequency and waveform resolution by 4x (2-bit) or 8x (3-bit) z Advanced waveform extension: z Low- and high-side output with programmable dead-time insertion (DTI) z Event controlled fault protection for safe disabling of drivers 13.2 Overview Atmel AVR XMEGA devices have a set of flexible, 16-bit timer/counters (TC). Their capabilities include accurate program execution timing, frequency and waveform generation, and input capture with time and frequency measurement of digital signals. Two timer/counters can be cascaded to create a 32-bit timer/counter with optional 32-bit capture. A timer/counter consists of a base counter and a set of compare or capture (CC) channels. The base counter can be used to count clock cycles or events. It has direction control and period setting that can be used for timing. The CC channels can be used together with the base counter to do compare match control, frequency generation, and pulse width waveform modulation, as well as various input capture operations. A timer/counter can be configured for either capture or compare functions, but cannot perform both at the same time. A timer/counter can be clocked and timed from the peripheral clock with optional prescaling or from the event system. The event system can also be used for direction control and capture trigger or to synchronize operations. There are two differences between timer/counter type 0 and type 1. Timer/counter 0 has four CC channels, and timer/counter 1 has two CC channels. All information related to CC channels 3 and 4 is valid only for timer/counter 0. Only Timer/Counter 0 has the split mode feature that split it into two 8-bit Timer/Counters with four compare channels each. XMEGA B [MANUAL] 149 Atmel-8291C-AVR-XMEGA B -09/2014 Some timer/counters have extensions to enable more specialized waveform and frequency generation. The advanced waveform extension (AWeX) is intended for motor control and other power control applications. It enables low- and highside output with dead-time insertion, as well as fault protection for disabling and shutting down external drivers. It can also generate a synchronized bit pattern across the port pins. The high-resolution (hi-res) extension can be used to increase the waveform output resolution by four or eight times by using an internal clock source running up to four times faster than the peripheral clock. A block diagram of the 16-bit timer/counter with extensions and closely related peripheral modules (in grey) is shown in Figure 13-1 on page 149. Figure 13-1. 16-bit timer/counter and closely related peripherals. 13.2.1 Definitions The following definitions are used throughout the documentation: Table 13-1. Timer/counter definitions In general, the term “timer” is used when the timer/counter clock control is handled by an internal source, and the term “counter” is used when the clock control is handled externally (e.g. counting external events). When used for compare operations, the CC channels are referred to as “compare channels.” When used for capture operations, the CC channels are referred to as “capture channels.” Name Description BOTTOM The counter reaches BOTTOM when it becomes zero. MAX The counter reaches MAXimum when it becomes all ones. TOP The counter reaches TOP when it becomes equal to the highest value in the count sequence. The TOP value can be equal to the period (PER) or the compare channel A (CCA) register setting. This is selected by the waveform generator mode. UPDATE The timer/counter signals an update when it reaches BOTTOM or TOP, depending on the waveform generator mode. XMEGA B [MANUAL] 150 Atmel-8291C-AVR-XMEGA B -09/2014 13.3 Block Diagram Figure 13-2 on page 150 shows a detailed block diagram of the timer/counter without the extensions. Figure 13-2. Timer/counter block diagram. The counter register (CNT), period registers with buffer (PER and PERBUF), and compare and capture registers with buffers (CCx and CCxBUF) are 16-bit registers. All buffer register have a buffer valid (BV) flag that indicates when the buffer contains a new value. During normal operation, the counter value is continuously compared to zero and the period (PER) value to determine whether the counter has reached TOP or BOTTOM. The counter value is also compared to the CCx registers. These comparisons can be used to generate interrupt requests, request DMA transactions or generate events for the event system. The waveform generator modes use these comparisons to set the waveform period or pulse width. A prescaled peripheral clock and events from the event system can be used to control the counter. The event system is also used as a source to the input capture. Combined with the quadrature decoding functionality in the event system (QDEC), the timer/counter can be used for quadrature decoding. Base Counter Compare/Capture (Unit x = {A,B,C,D}) Counter = CCx CCBUFx Waveform Generation BV = PERBUF PER CNT BV = 0 "count" "clear" "direction" "load" Control Logic CTRLD CTRLA OVF/UNF (INT/DMA Req.) ERRIF (INT Req.) TOP "match" CCxIF (INT/DMA Req.) Control Logic Clock Select "ev" UPDATE BOTTOM OCx Out Event Select XMEGA B [MANUAL] 151 Atmel-8291C-AVR-XMEGA B -09/2014 13.4 Clock and Event Sources The timer/counter can be clocked from the peripheral clock (clkPER) or the event system, and Figure 13-3 shows the clock and event selection. Figure 13-3. Clock and event selection. The peripheral clock is fed into a common prescaler (common for all timer/counters in a device). Prescaler outputs from 1 to 1/1024 are directly available for selection by the timer/counter. In addition, the whole range of prescaling from 1 to 215 times is available through the event system. Clock selection (CLKSEL) selects one of the prescaler outputs directly or an event channel as the counter (CNT) input. This is referred to as normal operation of the counter. For details, refer to “Normal Operation” on page 152. By using the event system, any event source, such as an external clock signal on any I/O pin, may be used as the clock input. In addition, the timer/counter can be controlled via the event system. The event selection (EVSEL) and event action (EVACT) settings are used to trigger an event action from one or more events. This is referred to as event action controlled operation of the counter. For details, refer to “Event Action Controlled Operation” on page 153. When event action controlled operation is used, the clock selection must be set to use an event channel as the counter input. By default, no clock input is selected and the timer/counter is not running. 13.5 Double Buffering The period register and the CC registers are all double buffered. Each buffer register has a buffer valid (BV) flag, which indicates that the buffer register contains a valid, i.e. new, value that can be copied into the corresponding period or CC register. When the period register and CC channels are used for a compare operation, the buffer valid flag is set when data is written to the buffer register and cleared on an UPDATE condition. This is shown for a compare register in Figure 13-4 on page 152. clkPER / 2{0,...,15} CKSEL CNT EVACT clkPER / {1,2,4,8,64,256,1024} Common Prescaler clkPER event channels (Encoding) Event System EVSEL Control Logic events XMEGA B [MANUAL] 152 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 13-4. Period and compare double buffering. When the CC channels are used for a capture operation, a similar double buffering mechanism is used, but in this case the buffer valid flag is set on the capture event, as shown in Figure 13-5. For capture, the buffer register and the corresponding CCx register act like a FIFO. When the CC register is empty or read, any content in the buffer register is passed to the CC register. The buffer valid flag is passed to set the CCx interrupt flag (IF) and generate the optional interrupt. Figure 13-5. Capture double buffering. Both the CCx and CCxBUF registers are available as an I/O register. This allows initialization and bypassing of the buffer register and the double buffering function. 13.6 Counter Operation Depending on the mode of operation, the counter is cleared, reloaded, incremented, or decremented at each timer/counter clock input. 13.6.1 Normal Operation In normal operation, the counter will count in the direction set by the direction (DIR) bit for each clock until it reaches TOP or BOTTOM. When up-counting and TOP is reached, the counter will be set to zero when the next clock is given. When down-counting, the counter is reloaded with the period register value when BOTTOM is reached. BV UPDATE "write enable" "data write" = CNT "match" CCxBUF EN CCx EN BV "capture" IF CNT CCxBUF EN CCx EN "INT/DMA request" data read XMEGA B [MANUAL] 153 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 13-6. Normal operation. As shown in Figure 13-6, it is possible to change the counter value when the counter is running. The write access has higher priority than count, clear, or reload, and will be immediate. The direction of the counter can also be changed during normal operation. Normal operation must be used when using the counter as timer base for the capture channels. 13.6.2 Event Action Controlled Operation The event selection and event action settings can be used to control the counter from the event system. For the counter, the following event actions can be selected: z Event system controlled up/down counting. z Event n will be used as count enable. z Event n+1 will be used to select between up (1) and down (0). The pin configuration must be set to low level sensing. z Event system controlled quadrature decode counting. 13.6.3 32-bit Operation Two timer/counters can be used together to enable 32-bit counter operation. By using two timer/counters, the overflow event from one timer/counter (least-significant timer) can be routed via the event system and used as the clock input for another timer/counter (most-significant timer). 13.6.4 Changing the Period The counter period is changed by writing a new TOP value to the period register. If double buffering is not used, any period update is immediate, as shown in Figure 13-7 on page 153. Figure 13-7. Changing the period without buffering. CNT BOTTOM MAX "update" TOP CNT written DIR CNT MAX New TOP written to PER that is higher than current CNT Counter Wraparound New TOP written to PER that is lower than current CNT "update" "write" BOTTOM XMEGA B [MANUAL] 154 Atmel-8291C-AVR-XMEGA B -09/2014 A counter wraparound can occur in any mode of operation when up-counting without buffering, as shown in Figure 13-8. This due to the fact that CNT and PER are continuously compared, and if a new TOP value that is lower than current CNT is written to PER, it will wrap before a compare match happen. Figure 13-8. Unbuffered dual-slope operation. When double buffering is used, the buffer can be written at any time and still maintain correct operation. The period register is always updated on the UPDATE condition, as shown for dual-slope operation in Figure 13-9. This prevents wraparound and the generation of odd waveforms. Figure 13-9. Changing the period using buffering. 13.7 Capture Channel The CC channels can be used as capture channels to capture external events and give them a timestamp. To use capture, the counter must be set for normal operation. Events are used to trigger the capture; i.e., any events from the event system, including pin change from any pin, can trigger a capture operation. The event source select setting selects which event channel will trigger CC channel A. The subsequent event channels then trigger events on subsequent CC channels, if configured. For example, setting the event source select to event channel 2 results in CC channel A being triggered by event channel 2, CC channel B triggered by event channel 3, and so on. CNT MAX New TOP written to PER that is higher than current CNT New TOP written to PER that is lower than current CNT "update" "write" Counter Wraparound BOTTOM CNT MAX New Period written to PERBUF that is higher than current CNT New Period written to PERBUF that is lower than current CNT "update" "write" New PER is updated with PERBUF value. BOTTOM XMEGA B [MANUAL] 155 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 13-10.Event source selection for capture operation. The event action setting in the timer/counter will determine the type of capture that is done. The CC channels must be enabled individually before capture can be done. When the capture condition occur, the timer/counter will time-stamp the event by copying the current CNT value in the count register into the enabled CC channel register. When an I/O pin is used as an event source for the capture, the pin must be configured for edge sensing. For details on sense configuration on I/O pins, refer to “Input Sense Configuration” on page 129. If the period register value is lower than 0x8000, the polarity of the I/O pin edge will be stored in the most-significant bit (msb) of the capture register. If the msb of the capture register is zero, a falling edge generated the capture. If the msb is one, a rising edge generated the capture. 13.7.1 Input Capture Selecting the input capture event action makes the enabled capture channel perform an input capture on an event. The interrupt flags will be set and indicate that there is a valid capture result in the corresponding CC register. At the same time, the buffer valid flags indicate valid data in the buffer registers. The counter will continuously count from BOTTOM to TOP, and then restart at BOTTOM, as shown in Figure 13-11. The figure also shows four capture events for one capture channel. Figure 13-11.Input capture timing. 13.7.2 Frequency Capture Selecting the frequency capture event action makes the enabled capture channel perform an input capture and restart on positive edge events. This enables the timer/counter to measure the period or frequency of a signal directly. The capture result will be the time (T) from the previous timer/counter restart until the event occurred. This can be used to calculate the frequency (f) of the signal: Event System CH0MUX CH1MUX CHnMUX Rotate Event channel n Event Source Selection CCA capture CCB capture CCC capture CCD capture Event channel 0 Event channel 1 events CNT TOP BOTTOM Capture 0 Capture 1 Capture 2 Capture 3 f 1 T = --- XMEGA B [MANUAL] 156 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 13-12 on page 156 shows an example where the period of an external signal is measured twice. Figure 13-12.Frequency capture of an external signal. Since all capture channels use the same counter (CNT), only one capture channel must be enabled at a time. If two capture channels are used with different sources, the counter will be restarted on positive edge events from both input sources, and the result will have no meaning. 13.7.3 Pulse Width Capture Selecting the pulse width measure event action makes the enabled compare channel perform the input capture action on falling edge events and the restart action on rising edge events. The counter will then restart on positive edge events, and the input capture will be performed on the negative edge event. The event source must be an I/O pin, and the sense configuration for the pin must be set to generate an event on both edges. Figure 13-13 on page 156 shows and example where the pulse width is measured twice for an external signal. Figure 13-13.Pulse width capture of an external signal. Period (T) external signal events CNT MAX BOTTOM "capture" Pulsewitdh (tp) external signal events CNT MAX BOTTOM "capture" XMEGA B [MANUAL] 157 Atmel-8291C-AVR-XMEGA B -09/2014 13.7.4 32-bit Input Capture Two timer/counters can be used together to enable true 32-bit input capture. In a typical 32-bit input capture setup, the overflow event of the least-significant timer is connected via the event system and used as the clock input for the mostsignificant timer. The most-significant timer will be updated one peripheral clock period after an overflow occurs for the least-significant timer. To compensate for this, the capture event for the most-significant timer must be equally delayed by setting the event delay bit for this timer. 13.7.5 Capture Overflow The timer/counter can detect buffer overflow of the input capture channels. When both the buffer valid flag and the capture interrupt flag are set and a new capture event is detected, there is nowhere to store the new timestamp. If a buffer overflow is detected, the new value is rejected, the error interrupt flag is set, and the optional interrupt is generated. 13.8 Compare Channel Each compare channel continuously compares the counter value (CNT) with the CCx register. If CNT equals CCx, the comparator signals a match. The match will set the CC channel's interrupt flag at the next timer clock cycle, and the event and optional interrupt are generated. The compare buffer register provides double buffer capability equivalent to that for the period buffer. The double buffering synchronizes the update of the CCx register with the buffer value to either the TOP or BOTTOM of the counting sequence according to the UPDATE condition. The synchronization prevents the occurrence of odd-length, nonsymmetrical pulses for glitch-free output. 13.8.1 Waveform Generation The compare channels can be used for waveform generation on the corresponding port pins. To make the waveform visible on the connected port pin, the following requirements must be fulfilled: 1. A waveform generation mode must be selected. 2. Event actions must be disabled. 3. The CC channels used must be enabled. This will override the corresponding port pin output register. 4. The direction for the associated port pin must be set to output. Inverted waveform output is achieved by setting the invert output bit for the port pin. 13.8.2 Frequency (FRQ) Waveform Generation For frequency generation the period time (T) is controlled by the CCA register instead of PER. The waveform generation (WG) output is toggled on each compare match between the CNT and CCA registers, as shown in Figure 13-14 on page 158. XMEGA B [MANUAL] 158 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 13-14.Frequency waveform generation. The waveform frequency (fFRQ) is defined by the following equation: where N represents the prescaler divider used. The waveform generated will have a maximum frequency of half of the peripheral clock frequency (fclkPER) when CCA is set to zero (0x0000) and no prescaling is used. This also applies when using the hi-res extension, since this increases the resolution and not the frequency. 13.8.3 Single-slope PWM Generation For single-slope PWM generation, the period (T) is controlled by PER, while CCx registers control the duty cycle of the WG output. Figure 13-15 shows how the counter counts from BOTTOM to TOP and then restarts from BOTTOM. The waveform generator (WG) output is set on the compare match between the CNT and CCx registers and cleared at TOP. Figure 13-15.Single-slope pulse width modulation. The PER register defines the PWM resolution. The minimum resolution is 2 bits (PER=0x0003), and the maximum resolution is 16 bits (PER=MAX). The following equation calculate the exact resolution for single-slope PWM (RPWM_SS): The single-slope PWM frequency (fPWM_SS) depends on the period setting (PER) and the peripheral clock frequency (fclkPER), and can be calculated by the following equation: CNT MAX "update" TOP Period (T) Direction Change CNT written BOTTOM WG Output f FRQ fclkPER 2N CCA ( ) + 1 = ---------------------------------- CNT MAX TOP Period (T) "match" BOTTOM WG Output CCx=BOTTOM CCx CCx=TOP "update" RPWM_SS log( ) PER 1 + log( ) 2 = --------------------------------- XMEGA B [MANUAL] 159 Atmel-8291C-AVR-XMEGA B -09/2014 where N represents the prescaler divider used. The waveform generated will have a maximum frequency of half of the peripheral clock frequency (fclkPER) when CCA is set to zero (0x0000) and no prescaling is used. This also applies when using the hi-res extension, since this increases the resolution and not the frequency. 13.8.4 Dual-slope PWM For dual-slope PWM generation, the period (T) is controlled by PER, while CCx registers control the duty cycle of the WG output. Figure 13-16 shows how for dual-slope PWM the counter counts repeatedly from BOTTOM to TOP and then from TOP to BOTTOM. The waveform generator output is set on BOTTOM, cleared on compare match when up-counting, and set on compare match when down-counting. Figure 13-16.Dual-slope pulse width modulation. Using dual-slope PWM results in a lower maximum operation frequency compared to the single-slope PWM operation. The period register (PER) defines the PWM resolution. The minimum resolution is 2 bits (PER=0x0003), and the maximum resolution is 16 bits (PER=MAX). The following equation calculate the exact resolution for dual-slope PWM (RPWM_DS): The PWM frequency depends on the period setting (PER) and the peripheral clock frequency (fclkPER), and can be calculated by the following equation: N represents the prescaler divider used. The waveform generated will have a maximum frequency of half of the peripheral clock frequency (fclkPER) when CCA is set to zero (0x0000) and no prescaling is used. This also applies when using the hi-res extension, since this increases the resolution and not the frequency. 13.8.5 Port Override for Waveform Generation To make the waveform generation available on the port pins, the corresponding port pin direction must be set as output. The timer/counter will override the port pin values when the CC channel is enabled (CCENx) and a waveform generation mode is selected. f PWM_SS fclkPER N( ) PER 1 + = ----------------------------- CNT MAX TOP Period (T) BOTTOM WG Output CCx=BOTTOM CCx CCx=TOP "match" "update" RPWM_DS log( ) PER 1 + log( ) 2 = --------------------------------- f PWM_DS fclkPER 2NPER = -------------------- XMEGA B [MANUAL] 160 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 13-17 on page 160 shows the port override for a timer/counter. The timer/counter CC channel will override the port pin output value (OUT) on the corresponding port pin. Enabling inverted I/O on the port pin (INVEN) inverts the corresponding WG output. Figure 13-17.Port override for timer/counter 0 and 1. 13.9 Interrupts and events The timer/counter can generate both interrupts and events. The counter can generate an interrupt on overflow/underflow, and each CC channel has a separate interrupt that is used for compare or capture. In addition, an error interrupt can be generated if any of the CC channels is used for capture and a buffer overflow condition occurs on a capture channel. Events will be generated for all conditions that can generate interrupts. For details on event generation and available events, refer to “Event System” on page 63. 13.10 DMA Support The interrupt flags can be used to trigger DMA transactions. Table 13-2 lists the transfer triggers available from the timer/counter and the DMA action that will clear the transfer trigger. For more details on using DMA, refer to “DMAC - Direct Memory Access Controller” on page 47. Table 13-2. DMA request sources 13.11 Timer/Counter Commands A set of commands can be given to the timer/counter by software to immediately change the state of the module. These commands give direct control of the UPDATE, RESTART, and RESET signals. An update command has the same effect as when an update condition occurs. The update command is ignored if the lock update bit is set. The software can force a restart of the current waveform period by issuing a restart command. In this case the counter, direction, and all compare outputs are set to zero. A reset command will set all timer/counter registers to their initial values. A reset can be given only when the timer/counter is not running (OFF). OUT CCExEN INVEN OCx Waveform Request Acknowledge Comment OVFIF/UNFIF DMA controller writes to CNT DMA controller writes to PER DMA controller writes to PERBUF DMA controller writes to DTHSBUF or DTLSBUF in AWeX when in Pattern Generation Mode ERRIF N/A CCxIF DMA controller access of CCx DMA controller access of CCxBUF Input capture operation Output compare operation XMEGA B [MANUAL] 161 Atmel-8291C-AVR-XMEGA B -09/2014 13.12 Register Description 13.12.1 CTRLA – Control register A z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:0 – CLKSEL[3:0]: Clock Select These bits select the clock source for the timer/counter according to Table 13-3. CLKSEL=0001 must be set to ensure a correct output from the waveform generator when the hi-res extension is enabled. Table 13-3. Clock select options 13.12.2 CTRLB – Control register B z Bit 7:4 – CCxEN: Compare or Capture Enable Setting these bits in the FRQ or PWM waveform generation mode of operation will override the port output register for the corresponding OCn output pin. When input capture operation is selected, the CCxEN bits enable the capture operation for the corresponding CC channel. Bit 7 6 5 4 3 2 1 0 +0x00 – – – – CLKSEL[3:0] Read/Write R R R R R/W R/W R/W R/W Initial Value 00000000 CLKSEL[3:0] Group Configuration Description 0000 OFF None (i.e, timer/counter in OFF state) 0001 DIV1 Prescaler: Clk 0010 DIV2 Prescaler: Clk/2 0011 DIV4 Prescaler: Clk/4 0100 DIV8 Prescaler: Clk/8 0101 DIV64 Prescaler: Clk/64 0110 DIV256 Prescaler: Clk/256 0111 DIV1024 Prescaler: Clk/1024 1nnn EVCHn Event channel n, n= [0,...,7] Bit 7 6 5 4 3 2 1 0 +0x01 CCDEN CCCEN CCBEN CCAEN – WGMODE[2:0] Read/Write R/W R/W R/W R/W R R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 162 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 3 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 2:0 – WGMODE[2:0]: Waveform Generation Mode These bits select the waveform generation mode, and control the counting sequence of the counter, TOP value, UPDATE condition, interrupt/event condition, and type of waveform that is generated according to Table 13-4. No waveform generation is performed in the normal mode of operation. For all other modes, the result from the waveform generator will only be directed to the port pins if the corresponding CCxEN bit has been set to enable this. The port pin direction must be set as output. Table 13-4. Timer waveform generation mode. 13.12.3 CTRLC – Control register C z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:0 – CMPx: Compare Output Value x These bits allow direct access to the waveform generator's output compare value when the timer/counter is set in the OFF state. This is used to set or clear the WG output value when the timer/counter is not running. WGMODE[2:0] Group Configuration Mode of Operation Top Update OVFIF/Event 000 NORMAL Normal PER TOP TOP 001 FRQ Frequency CCA TOP TOP 010 Reserved - - - 011 SINGLESLOPE Single-slope PWM PER BOTTOM BOTTOM 100 Reserved - - - 101 DSTOP Dual-slope PWM PER BOTTOM TOP 110 DSBOTH Dual-slope PWM PER BOTTOM TOP and BOTTOM 111 DSBOTTOM Dual-slope PWM PER BOTTOM BOTTOM Bit 7 6 5 4 3 2 1 0 +0x02 – – – – CMPD CMPC CMPB CMPA Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0000 XMEGA B [MANUAL] 163 Atmel-8291C-AVR-XMEGA B -09/2014 13.12.4 CTRLD – Control register D z Bit 7:5 – EVACT[2:0]: Event Action These bits define the event action the timer will perform on an event according to Table 13-5 on page 163. The EVSEL setting will decide which event source or sources have control in this case. Table 13-5. Timer event action selection. Selecting any of the capture event actions changes the behavior of the CCx registers and related status and control bits to be used for capture. The error status flag (ERRIF) will indicate a buffer overflow in this configuration. See “Event Action Controlled Operation” on page 153 for further details. z Bit 4 – EVDLY: Timer Delay Event When this bit is set, the selected event source is delayed by one peripheral clock cycle. This is intended for 32-bit input capture operation. Adding the event delay is necessary to compensate for the carry propagation delay when cascading two counters via the event system. z Bit 3:0 – EVSEL[3:0]:Timer Event Source Select These bits select the event channel source for the timer/counter. For the selected event channel to have any effect, the event action bits (EVACT) must be set according to Table 13-6. When the event action is set to a capture operation, the selected event channel n will be the event channel source for CC channel A, and event channel (n+1)%8, (n+2)%8, and (n+3)%8 will be the event channel source for CC channel B, C, and D. Table 13-6. Timer event source selection Bit 7 6 5 4 3 2 1 0 +0x03 EVACT[2:0] EVDLY EVSEL[3:0] 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 EVACT[2:0] Group Configuration Event Action 000 OFF None 001 CAPT Input capture 010 UPDOWN Externally controlled up/ down count 011 QDEC Quadrature decode 100 RESTART Restart waveform period 101 FRQ Frequency capture 110 PW Pulse width capture 111 Reserved EVSEL[3:0] Group Configuration Event Source 0000 OFF None 0001 – Reserved 0010 – Reserved 0011 – Reserved XMEGA B [MANUAL] 164 Atmel-8291C-AVR-XMEGA B -09/2014 13.12.5 CTRLE – Control register E z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1:0 – BYTEM[1:0]: Byte Mode These bits select the timer/counter operation mode according to Table 13-7. Table 13-7. Clock select 13.12.6 INTCTRLA – Interrupt Enable register A z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. 0100 – Reserved 0101 – Reserved 0110 – Reserved 0111 – Reserved 1nnn CHn Event channel n, n={0,...,7} EVSEL[3:0] Group Configuration Event Source Bit 7 6 5 4 3 2 1 0 +0x04 – – – – – – BYTEM[1:0] Read/Write R R R R R R R R/W Initial Value 00000000 BYTEM[1:0] Group Configuration Description 00 NORMAL Timer/counter is set to normal mode (timer/counter type 0) 01 BYTEMODE Upper byte of the counter (CNTH) will be set to zero after each counter clock cycle 10 SPLITMODE Timer/counter 0 is split into two 8-bit timer/counters (timer/counter type 2) 11 – Reserved Bit 7 6 5 4 3 2 1 0 +0x06 – – – – ERRINTLVL[1:0] OVFINTLVL[1:0] Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 165 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 3:2 – ERRINTLVL[1:0]:Timer Error Interrupt Level These bits enable the timer error interrupt and select the interrupt level as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. z Bit 1:0 – OVFINTLVL[1:0]:Timer Overflow/Underflow Interrupt Level These bits enable the timer overflow/underflow interrupt and select the interrupt level as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. 13.12.7 INTCTRLB – Interrupt Enable register B z Bit 7:0 – CCxINTLVL[7:0] - Compare or Capture x Interrupt Level These bits enable the timer compare or capture interrupt for channel x and select the interrupt level as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. 13.12.8 CTRLFCLR/CTRLFSET – Control register F Clear/Set This register is mapped into two I/O memory locations, one for clearing (CTRLxCLR) and one for setting the register bits (CTRLxSET) when written. Both memory locations will give the same result when read. The individual status bit can be set by writing a one to its bit location in CTRLxSET, and cleared by writing a one to its bit location in CTRLxCLR. This allows each bit to be set or cleared without use of a read-modify-write operation on a single register. 13.12.8.1 CTRLFCLR 13.12.8.2 CTRLFSET z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:2 – CMD[1:0]: Command These bits can be used for software control of update, restart, and reset of the timer/counter. The command bits are always read as zero. Bit 7 6 5 4 3 2 1 0 +0x07 CCDINTLVL[1:0] CCCINTLVL[1:0] CCBINTLVL[1:0] CCAINTLVL[1:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0000000 Bit 7 6 5 4 3 2 1 0 +0x08 – – – – CMD[1:0] LUPD DIR Read/Write R R R R R R R/W R/W Initial Value 0 0 0 00000 Bit 7 6 5 4 3 2 1 0 +0x09 – – – – CMD[1:0] LUPD DIR Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 00000 XMEGA B [MANUAL] 166 Atmel-8291C-AVR-XMEGA B -09/2014 Table 13-8. Command selections z Bit 1 – LUPD: Lock Update When this bit is set, no update of the buffered registers is performed, even though an UPDATE condition has occurred. Locking the update ensures that all buffers, including DTI buffers, are valid before an update is performed. This bit has no effect when input capture operation is enabled. z Bit 0 – DIR: Counter Direction When zero, this bit indicates that the counter is counting up (incrementing). A one indicates that the counter is in the down-counting (decrementing) state. Normally this bit is controlled in hardware by the waveform generation mode or by event actions, but this bit can also be changed from software. 13.12.9 CTRLGCLR/CTRLGSET – Control register G Clear/Set Refer to “CTRLFCLR/CTRLFSET – Control register F Clear/Set” on page 165 for information on how to access this type of status register. z Bit 7:5 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 4:1 – CCxBV: Compare or Capture x Buffer Valid These bits are set when a new value is written to the corresponding CCxBUF register. These bits are automatically cleared on an UPDATE condition. Note that when input capture operation is used, this bit is set on a capture event and cleared if the corresponding CCxIF is cleared. z Bit 0 – PERBV: Period Buffer Valid This bit is set when a new value is written to the PERBUF register. This bit is automatically cleared on an UPDATE condition. CMD Group Configuration Command Action 00 NONE None 01 UPDATE Force update 10 RESTART Force restart 11 RESET Force hard reset (ignored if T/C is not in OFFstate) Bit 7 6 5 4 3 2 1 0 +0x0A/ +0x0B – – – CCDBV CCCBV CCBBV CCABV PERBV Read/Write R R R R/W R/W R/W R/W R/W Initial Value 0 0 0 00000 XMEGA B [MANUAL] 167 Atmel-8291C-AVR-XMEGA B -09/2014 13.12.10INTFLAGS – Interrupt Flag register z Bit 7:4 – CCxIF: Compare or Capture Channel x Interrupt Flag The compare or capture interrupt flag (CCxIF) is set on a compare match or on an input capture event on the corresponding CC channel. For all modes of operation except for capture, the CCxIF will be set when a compare match occurs between the count register (CNT) and the corresponding compare register (CCx). The CCxIF is automatically cleared when the corresponding interrupt vector is executed. For input capture operation, the CCxIF will be set if the corresponding compare buffer contains valid data (i.e., when CCxBV is set). The flag will be cleared when the CCx register is read. Executing the interrupt vector in this mode of operation will not clear the flag. The flag can also be cleared by writing a one to its bit location. The CCxIF can be used for requesting a DMA transfer. A DMA read or write access of the corresponding CCx or CCxBUF will then clear the CCxIF and release the request. z Bit 3:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1 – ERRIF: Error Interrupt Flag This flag is set on multiple occasions, depending on the mode of operation. In the FRQ or PWM waveform generation mode of operation, ERRIF is set on a fault detect condition from the fault protection feature in the AWeX extention. For timer/counters which do not have the AWeX extention available, this flag is never set in FRQ or PWM waveform generation mode. For capture operation, ERRIF is set if a buffer overflow occurs on any of the CC channels. For event controlled QDEC operation, ERRIF is set when an incorrect index signal is given. This flag is automatically cleared when the corresponding interrupt vector is executed. The flag can also be cleared by writing a one to this location. z Bit 0 – OVFIF: Overflow/Underflow Interrupt Flag This flag is set either on a TOP (overflow) or BOTTOM (underflow) condition, depending on the WGMODE setting. OVFIF is automatically cleared when the corresponding interrupt vector is executed. The flag can also be cleared by writing a one to its bit location. OVFIF can also be used for requesting a DMA transfer. A DMA write access of CNT, PER, or PERBUF will then clear the OVFIF bit. Bit 7 6 5 4 3 2 1 0 +0x0C CCDIF CCCIF CCBIF CCAIF – – ERRIF OVFIF 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 XMEGA B [MANUAL] 168 Atmel-8291C-AVR-XMEGA B -09/2014 13.12.11TEMP – Temporary bits for 16-bit Access The TEMP register is used for single-cycle, 16-bit access to the 16-bit timer/counter registers by the CPU. The DMA controller has a separate temporary storage register. There is one common TEMP register for all the 16-bit Timer/counter registers. For more details, refer to “Accessing 16-bit Registers” on page 13. 13.12.12CNTL – Counter register Low The CNTH and CNTL register pair represents the 16-bit value, CNT. CNT contains the 16-bit counter value in the timer/counter. CPU and DMA write access has priority over count, clear, or reload of the counter. For more details on reading and writing 16-bit registers, refer to “Accessing 16-bit Registers” on page 13. z Bit 7:0 – CNT[7:0]: Counter low byte These bits hold the LSB of the 16-bit counter register. 13.12.13CNTH – Counter register High z Bit 7:0 – CNT[15:8]: Counter high byte These bits hold the MSB of the 16-bit counter register. 13.12.14PERL – Period register Low The PERH and PERL register pair represents the 16-bit value, PER. PER contains the 16-bit TOP value in the timer/counter. z Bit 7:0 – PER[7:0]: Period low byte These bits hold the LSB of the 16-bit period register. Bit 7 6 5 4 3 2 1 0 +0x0F TEMP[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 00000 Bit 7 6 5 4 3 2 1 0 +0x20 CNT[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x21 CNT[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x26 PER[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1 111111 XMEGA B [MANUAL] 169 Atmel-8291C-AVR-XMEGA B -09/2014 13.12.15PERH – Period register High z Bit 7:0 – PER[15:8]: Period high byte These bits hold the MSB of the 16-bit period register. 13.12.16CCxL – Compare or Capture x register Low The CCxH and CCxL register pair represents the 16-bit value, CCx. These 16-bit register pairs have two functions, depending of the mode of operation. For capture operation, these registers constitute the second buffer level and access point for the CPU and DMA. For compare operation, these registers are continuously compared to the counter value. Normally, the outputs form the comparators are then used for generating waveforms. CCx registers are updated with the buffer value from their corresponding CCxBUF register when an UPDATE condition occurs. z Bit 7:0 – CCx[7:0]: Compare or Capture x low byte These bits hold the LSB of the 16-bit compare or capture register. 13.12.17CCxH – Compare or Capture x register High z Bit 7:0 – CCx[15:8]: Compare or Capture x high byte These bits hold the MSB of the 16-bit compare or capture register. Bit 7 6 5 4 3 2 1 0 +0x27 PER[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1 1 1 1 1 1 1 Bit 7 6 5 4 3 2 1 0 CCx[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 CCx[15:8] 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 XMEGA B [MANUAL] 170 Atmel-8291C-AVR-XMEGA B -09/2014 13.12.18PERBUFL – Timer/Counter Period Buffer Low The PERBUFH and PERBUFL register pair represents the 16-bit value, PERBUF. This 16-bit register serves as the buffer for the period register (PER). Accessing this register using the CPU or DMA will affect the PERBUFV flag. z Bit 7:0 – PERBUF[7:0]: Period Buffer low byte These bits hold the LSB of the 16-bit period buffer register. 13.12.19PERBUFH – Timer/Counter Period Buffer High z Bit 7:0 – PERBUF[15:8]: Period Buffer high byte These bits hold the MSB of the 16-bit period buffer register. 13.12.20CCxBUFL – Compare or Capture x Buffer register Low The CCxBUFH and CCxBUFL register pair represents the 16-bit value, CCxBUF. These 16-bit registers serve as the buffer for the associated compare or capture registers (CCx). Accessing any of these registers using the CPU or DMA will affect the corresponding CCxBV status bit. z Bit 7:0 – CCxBUF[7:0]: Compare or Capture Buffer low byte These bits hold the LSB of the 16-bit compare or capture buffer register. Bit 7 6 5 4 3 2 1 0 +0x36 PERBUF[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1111111 Bit 7 6 5 4 3 2 1 0 +0x37 PERBUF[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1 1 1 1 1 1 1 Bit 7 6 5 4 3 2 1 0 CCxBUFx[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 171 Atmel-8291C-AVR-XMEGA B -09/2014 13.12.21CCxBUFH – Compare or Capture x Buffer register High z Bit 7:0 – CCxBUF[15:8]: Compare or Capture Buffer high byte These bits hold the MSB of the 16-bit compare or capture buffer register. Bit 7 6 5 4 3 2 1 0 CCxBUF[15:8] 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 XMEGA B [MANUAL] 172 Atmel-8291C-AVR-XMEGA B -09/2014 13.13 Register Summary 13.14 Interrupt Vector Summary Note: 1. Available only on timer/counters with four compare or capture channels. Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRLA – – – – CLKSEL[3:0] 161 +0x01 CTRLB CCDEN CCCEN CCBEN CCAEN – WGMODE[2:0] 161 +0x02 CTRLC – – – – CMPD CMPC CMPB CMPA 162 +0x03 CTRLD EVACT[2:0] EVDLY EVSEL[3:0] 163 +0x04 CTRLE – – – – – – BYTEM 164 +0x05 Reserved – – – – – – – – +0x06 INTCTRLA – – – – ERRINTLVL[1:0] OVINTLVL[1:0] 164 +0x07 INTCTRLB CCCINTLVL[1:0] CCCINTLVL[1:0] CCBINTLVL[1:0] CCAINTLVL[1:0] 164 +0x08 CTRLFCLR – – – – CMD[1:0] LUPD DIR 165 +0x09 CTRLFSET – – – – CMD[1:0] LUPD DIR 166 +0x0A CTRLGCLR – – – CCDBV CCCBV CCBBV CCABV PERBV 166 +0x0B CTRLGSET – – – CCDBV CCCBV CCBBV CCABV PERBV 166 +0x0C INTFLAGS CCDIF CCCIF CCBIF CCAIF – – ERRIF OVFIF 167 +0x0D Reserved – – – – – – – – +0x0E Reserved – – – – – – – – +0x0F TEMP TEMP[7:0] 168 +0x10 to Reserved – – – – – – – – +0x20 CNTL CNT[7:0] 168 +0x21 CNTH CNT[15:8] 168 +0x22 to Reserved – – – – – – – – +0x26 PERL PER[7:0] 168 +0x27 PERH PER[8:15] 169 +0x28 CCAL CCA[7:0] 169 +0x29 CCAH CCA[15:8] 169 +0x2A CCBL CCB[7:0] 169 +0x2B CCBH CCB[15:8] 169 +0x2C CCCL CCC[7:0] 169 +0x02D CCCH CCC[15:8] 169 +0x2E CCDL CCD[7:0] 169 +0x2F CCDH CCD[15:8] 169 +0x30 to Reserved – – – – – – – – +0x36 PERBUFL PERBUF[7:0] 170 +0x37 PERBUFH PERBUF[15:8] 170 +0x38 CCABUFL CCABUF[7:0] 170 +0x39 CCABUFH CCABUF[15:8] 171 +0x3A CCBBUFL CCBBUF[7:0] 170 +0x3B CCBBUFH CCBBUF[15:8] 171 +0x3C CCCBUFL CCCBUF[7:0] 170 +0x3D CCCBUFH CCCBUF[15:8] 171 +0x3E CCDBUFL CCDBUF[7:0] 170 +0x3F CCDBUFH CCDBUF[15:8] 171 Offset Source Interrupt Description 0x00 OVF_vect Timer/counter overflow/underflow interrupt vector offset 0x02 ERR_vect Timer/counter error interrupt vector offset 0x04 CCA_vect Timer/counter compare or capture channel A interrupt vector offset 0x06 CCB_vect Timer/counter compare or capture channel B interrupt vector offset 0x08 CCC_vect(1) Timer/counter compare or capture channel C interrupt vector offset 0x0A CCD_vect(1) Timer/counter compare or capture channel D interrupt vector offset XMEGA B [MANUAL] 173 Atmel-8291C-AVR-XMEGA B -09/2014 14. TC2 – 16-bit Timer/Counter Type 2 14.1 Features z A system of two eight-bit timer/counters z Low-byte timer/counter z High-byte timer/counter z Eight compare channels z Four compare channels for the low-byte timer/counter z Four compare channels for the high-byte timer/counter z Waveform generation z Single slope pulse width modulation z Timer underflow interrupts/events z One compare match interrupt/event per compare channel for the low-byte timer/counter z Can be used with the event system for count control z Can be used to trigger DMA transactions 14.2 Overview A timer/counter 2 is realized when a timer/counter 0 is set in split mode. It is a system of two eight-bit timer/counters, each with four compare channels. This results in eight configurable pulse width modulation (PWM) channels with individually controlled duty cycles, and is intended for applications that require a high number of PWM channels. The two eight-bit timer/counters in this system are referred to as the low-byte timer/counter and high-byte timer/counter, respectively. The difference between them is that only the low-byte timer/counter can be used to generate compare match interrupts, events and DMA triggers. The two eight-bit timer/counters have a shared clock source and separate period and compare settings. They can be clocked and timed from the peripheral clock, with optional prescaling, or from the event system. The counters are always counting down. The timer/counter 2 is set back to timer/counter 0 by setting it in normal mode; hence, one timer/counter can exist only as either type 0 or type 2. A detailed block diagram of the timer/counter 2 showing the low-byte (L) and high-byte (H) timer/counter register split and compare modules is shown in Figure 14-1 on page 174. XMEGA B [MANUAL] 174 Atmel-8291C-AVR-XMEGA B -09/2014 14.3 Block Diagram Figure 14-1. Block diagram of the 16-bit timer/counter 0 with split mode. 14.4 Clock Sources The timer/counter can be clocked from the peripheral clock (clkPER) and from the event system. Figure 14-2 shows the clock and event selection. Figure 14-2. Clock selection. Base Counter Compare (Unit x = {A,B,C,D}) Counter HPER = 0 Control Logic CTRLA HUNF (INT/DMA Req.) BOTTOML LPER Compare (Unit x = {A,B,C,D}) Waveform Generation LCMPx (INT/DMA Req.) OCLx Out = LCMPx "match" BOTTOMH LCNT "count low" "load low" = HCMPx Waveform Generation "match" OCHx Out = 0 "count high" "load high" HCNT Clock Select LUNF (INT/DMA Req.) clkPER / 2{0,...,15} CLKSEL CNT clkPER / {1,2,4,8,64,256,1024} Common Prescaler clkPER event channels Event System events XMEGA B [MANUAL] 175 Atmel-8291C-AVR-XMEGA B -09/2014 The peripheral clock (clkPER) is fed into the common prescaler (common for all timer/counters in a device). A selection of prescaler outputs from 1 to 1/1024 is directly available. In addition, the whole range of time prescalings from 1 to 215 is available through the event system. The clock selection (CLKSEL) selects one of the clock prescaler outputs or an event channel for the high-byte counter (HCNT) and low-byte counter (LCNT). By using the event system, any event source, such as an external clock signal, on any I/O pin can be used as the clock input. By default, no clock input is selected, and the counters are not running. 14.5 Counter Operation The counters will always count in single-slope mode. Each counter counts down for each clock cycle until it reaches BOTTOM, and then reloads the counter with the period register value at the following clock cycle. Figure 14-3. Counter operation. As shown in Figure 14-3, the counter can change the counter value while running. The write access has higher priority than the count clear, and reloads and will be immediate. 14.5.1 Changing the Period The counter period is changed by writing a new TOP value to the period register. Since the counter is counting down, the period register can be written at any time without affecting the current period, as shown in Figure 14-4 on page 175. This prevents wraparound and generation of odd waveforms. Figure 14-4. Changing the period. 14.6 Compare Channel Each compare channel continuously compares the counter value with the CMPx register. If CNT equals CMPx, the comparator signals a match. For the low-byte timer/counter, the match will set the compare channel's interrupt flag at the next timer clock cycle, and the event and optional interrupt is generated. The high-byte timer/counter does not have compare interrupt/event. CNT BOTTOM MAX "reload" TOP CNT written CNT MAX New TOP written to PER that is higher than current CNT New TOP written to PER that is lower than current CNT "reload" "write" BOTTOM XMEGA B [MANUAL] 176 Atmel-8291C-AVR-XMEGA B -09/2014 14.6.1 Waveform Generation The compare channels can be used for waveform generation on the corresponding port pins. To make the waveform visible on the connected port pin, the following requirements must be fulfilled: 1. The compare channels to be used must be enabled. This will override the corresponding port pin output register. 2. The direction for the associated port pin must be set to output. Inverted waveform output can be achieved by setting invert I/O on the port pin. Refer to “I/O Ports” on page 123 for more details. 14.6.2 Single-slope PWM Generation For PWM generation, the period (T) is controlled by the PER register, while the CMPx registers control the duty cycle of the waveform generator (WG) output. Figure 14-5 on page 176 shows how the counter counts from TOP to BOTTOM, and then restarts from TOP. The WG output is set on the compare match between the CNT and CMPx registers, and cleared at BOTTOM. Figure 14-5. Single-slope pulse width modulation. The PER register defines the PWM resolution. The minimum resolution is two bits (PER=0x0003), and the maximum resolution is eight bits (PER=MAX). The following equation is used to calculate the exact resolution for a single-slope PWM (RPWM_SS) waveform: The single, slow PWM frequency (fPWM_SS) depends on the period setting (PER) and the peripheral clock frequency (fPER), and it is calculated by using the following equation: where N represents the prescaler divider used (1, 2, 4, 8, 64, 256, 1024, or event channel n). 14.6.3 Port Override for Waveform Generation To make the waveform generation available on the port pins, the corresponding port pin direction must be set as output. The timer/counter will override the port pin values when the CMP channel is enabled (LCMPENx/HCMPENx). Figure 14-6 on page 177 shows the port override for the low- and high-byte timer/counters. For the low-byte timer/counter, CMP channels A to D will override the output value (OUTxn) of port pins 0 to 3 on the corresponding port pins (Pxn). For the high-byte timer/counter, CMP channels E to H will override port pins 4 to 7. Enabling inverted I/O on the port pin (INVENxn) inverts the corresponding WG output. CNT MAX TOP Period (T) "match" BOTTOM WG Output CMPx=BOT CMPx CMPx=TOP RPWM_SS log( ) PER 1 + log( ) 2 = --------------------------------- f PWM_SS f PER N( ) PER 1 + = ----------------------------- XMEGA B [MANUAL] 177 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 14-6. Port override for low- and high-byte timer/counters. 14.7 Interrupts and Events The timer/counters can generate interrupts and events. The counter can generate an interrupt on underflow, and each CMP channel for the low-byte counter has a separate compare interrupt. Events will be generated for all conditions that can generate interrupts. For details on event generation and available events, refer to “Event System” on page 63. 14.8 DMA Support Timer/counter underflow and compare interrupt flags can trigger a DMA transaction. The acknowledge condition that clears the flag/request is listed in Table 14-1. Table 14-1. DMA request sources. 14.9 Timer/Counter Commands A set of commands can be given to the timer/counter by software to immediately change the state of the module. These commands give direct control of the update, restart, and reset signals. The software can force a restart of the current waveform period by issuing a restart command. In this case the counter, direction, and all compare outputs are set to zero. A reset command will set all timer/counter registers to their initial values. A reset can only be given when the timer/counter is not running (OFF). OUT LCMPENx / HCMPENx INVEN OCx Waveform Request Acknowledge Comment LUNFIF DMAC writes to LCNT DMAC writes to LPER HUNFIF DMAC writes to HCNT DMAC writes to HPER CCIF{D,C,B,A} DMAC access of LCMP{D,C,B,A} Output compare operation XMEGA B [MANUAL] 178 Atmel-8291C-AVR-XMEGA B -09/2014 14.10 Register Description 14.10.1 CTRLA – Control register A z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:0 – CLKSEL[3:0]: Clock Select These bits select clock source for the timer/counter according to Table 14-2. The clock select is identical for both highand low-byte timer/counters. Table 14-2. Clock select 14.10.2 CTRLB – Control register B z Bit 7:0 – HCMPENx/LCMPENx: High/Low Byte Compare Enable x Setting these bits will enable the compare output and override the port output register for the corresponding OCn output pin. Bit 7 6 5 4 3 2 1 0 +0x00 – – – – CLKSEL[3:0] Read/Write R R R R R/W R/W R/W R/W Initial Value 00000000 CLKSEL[3:0] Group Configuration Description 0000 OFF None (i.e., timer/counter in OFF state) 0001 DIV1 Prescaler: ClkPER 0010 DIV2 Prescaler: ClkPER/2 0011 DIV4 Prescaler: ClkPER/4 0100 DIV8 Prescaler: ClkPER/8 0101 DIV64 Prescaler: ClkPER/64 0110 DIV256 Prescaler: ClkPER/256 0111 DIV1024 Prescaler: ClkPER/1024 1nnn EVCHn Event channel n, n= [0,...,7] Bit 7 6 5 4 3 2 1 0 +0x01 HCMPEND HCMPENC HCMPENB HCMPENA LCMPEND LCMPENC LCMPENB LCMPENA Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 000000 XMEGA B [MANUAL] 179 Atmel-8291C-AVR-XMEGA B -09/2014 14.10.3 CTRLC – Control register C z Bit 7:0 – HCMPx/LCMPx: High/Low Compare x Output Value These bits allow direct access to the waveform generator's output compare value when the timer/counter is OFF. This is used to set or clear the WG output value when the timer/counter is not running. 14.10.4 CTRLE – Control register E z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 0:1 – BYTEM[1:0]: Byte Mode These bits select the timer/counter operation mode according to Table 14-3. Table 14-3. Byte mode. Bit 7 6 5 4 3 2 1 0 +0x02 HCMPD HCMPC HCMPB HCMPA LCMPD LCMPC LCMPB LCMPA Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0000 Bit 7 6 5 4 3 2 1 0 +0x04 – – – – – – BYTEM[1:0] Read/Write R R R R R R R/W R/W Initial Value 00000000 BYTEM[1:0] Group Configuration Description 00 NORMAL Timer/counter is set to normal mode (timer/counter type 0) 01 BYTEMODE Upper byte of the counter (HCNT) will be set to zero after each counter clock. 10 SPLITMODE Timer/counter is split into two eight-bit timer/counters (timer/counter type 2) 11 — Reserved XMEGA B [MANUAL] 180 Atmel-8291C-AVR-XMEGA B -09/2014 14.10.5 INTCTRLA – Interrupt Enable register A z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:2 – HUNFINTLVL[1:0]: High-byte Timer Underflow Interrupt Level These bits enable the high-byte timer underflow interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when HUNFIF in the INTFLAGS register is set. z Bit 1:0 – LUNFINTLVL[1:0]: Low-byte Timer Underflow Interrupt Level These bits enable the low-byte timer underflow interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when LUNFIF in the INTFLAGS register is set. 14.10.6 INTCTRLB – Interrupt Enable register B z Bit 7:0 – LCMPxINTLVL[1:0]: Low-byte Compare x Interrupt Level These bits enable the low-byte timer compare interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when LCMPxIF in the INTFLAGS register is set. 14.10.7 CTRLF – Control register F z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:2 – CMD[1:0]: Timer/Counter Command These command bits are used for software control of timer/counter update, restart, and reset. The command bits are always read as zero. The CMD bits must be used together with CMDEN. Bit 7 6 5 4 3 2 1 0 +0x06 – – – – HUNFINTLVL[1:0] LUNFINTLVL[1:0] Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0000 Bit 7 6 5 4 3 2 1 0 +0x07 LCMPDINTLVL[1:0] LCMPCINTLVL[1:0] LCMPBINTLVL[1:0] LCMPAINTLVL[1:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0000000 Bit 7 6 5 4 3 2 1 0 +0x08 – – – – CMD[1:0] CMDEN[1:0] Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 00000 XMEGA B [MANUAL] 181 Atmel-8291C-AVR-XMEGA B -09/2014 Table 14-4. Command selections. z Bit 1:0 – CMDEN[1:0]: Command Enable These bits are used to indicate for which timer/counter the command (CMD) is valid. Table 14-5. Command enable selections. 14.10.8 INTFLAGS – Interrupt Flag register z Bit 7:4 – LCMPxIF: Compare Channel x Interrupt Flag The compare interrupt flag (LCMPxIF) is set on a compare match on the corresponding CMP channel. For all modes of operation, LCMPxIF will be set when a compare match occurs between the count register (LCNT) and the corresponding compare register (LCMPx). The LCMPxIF is automatically cleared when the corresponding interrupt vector is executed. The flag can also be cleared by writing a one to its bit location. z Bit 3:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1 – HUNFIF: High-byte Timer Underflow Interrupt Flag HUNFIF is set on a BOTTOM (underflow) condition. This flag is automatically cleared when the corresponding interrupt vector is executed. The flag can also be cleared by writing a one to its bit location. z Bit 0 – LUNFIF: Low-byte Timer Underflow Interrupt Flag LUNFIF is set on a BOTTOM (underflow) condition. This flag is automatically cleared when the corresponding interrupt vector is executed. The flag can also be cleared by writing a one to its bit location. CMD Group Configuration Description 00 NONE None 01 — Reserved 10 RESTART Force restart 11 RESET Force hard reset (ignored if T/C is not in OFF state) CMDEN Group Configuration Description 00 – Reserved 01 LOW Command valid for low-byte T/C 10 HIGH Command valid for high-byte T/C 11 BOTH Command valid for both low-byte and high-byte T/C Bit 7 6 5 4 3 2 1 0 +0x0C LCMPDIF LCMPCIF LCMPBIF LCMPAIF – – HUNFIF LUNFIF 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 XMEGA B [MANUAL] 182 Atmel-8291C-AVR-XMEGA B -09/2014 14.10.9 LCNT – Low-byte Count register z Bit 7:0 – LCNT[7:0] LCNT contains the eight-bit counter value for the low-byte timer/counter. The CPU and DMA write accesses have priority over count, clear, or reload of the counter. 14.10.10HCNT – High-byte Count register z Bit 7:0 – HCNT[7:0] HCNT contains the eight-bit counter value for the high-byte timer/counter. The CPU and DMA write accesses have priority over count, clear, or reload of the counter. 14.10.11LPER – Low-byte Period register z Bit 7:0 – LPER[7:0] LPER contains the eight-bit period value for the low-byte timer/counter. 14.10.12HPER – High-byte Period register z Bit 7:0 – HPER[7:0] HPER contains the eight-bit period for the high-byte timer/counter. Bit 7 6 5 4 3 2 1 0 +0x20 LCNT[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x21 HCNT[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x27 LPER[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x26 HPER[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 000000 XMEGA B [MANUAL] 183 Atmel-8291C-AVR-XMEGA B -09/2014 14.10.13LCMPx – Low-byte Compare register x z Bit 7:0 – LCMPx[7:0], x=[A, B, C, D] LCMPx contains the eight-bit compare value for the low-byte timer/counter. These registers are all continuously compared to the counter value. Normally, the outputs from the comparators are then used for generating waveforms. 14.10.14HCMPx – High-byte Compare register x z Bit 7:0 – HCMPx[7:0], x=[A, B, C, D] HCMPx contains the eight-bit compare value for the high-byte timer/counter. These registers are all continuously compared to the counter value. Normally the outputs from the comparators are then used for generating waveforms. Bit 7 6 5 4 3 2 1 0 LCMPx[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 HCMPx[7:0] 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 XMEGA B [MANUAL] 184 Atmel-8291C-AVR-XMEGA B -09/2014 14.11 Register Summary 14.12 Interrupt Vector Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRLA – – – – CLKSEL[3:0] 178 +0x01 CTRLB HCMPDEN HCMPCEN HCMPBEN HCMPAEN LCMPDEN LCMPCEN LCMPBEN LCMPAEN 178 +0x02 CTRLC HCMPD HCMPC HCMPB HCMPA LCMPD LCMPC LCMPB LCMPA 179 +0x03 Reserved – – – – – – – – +0x04 CTRLE – – – – – – BYTEM[1:0] 179 +0x05 Reserved – – – – – – – – +0x06 INTCTRLA – – – – HUNFINTLVL[1:0] LUNFINTLVL[1:0] 180 +0x07 INTCTRLB LCMPDINTLVL[1:0] LCMPCINTLVL[1:0] LCMPBINTLVL[1:0] LCMPAINTLVL[1:0] 180 +0x08 Reserved – – – – – – – – +0x09 CTRLF – – – – CMD[1:0] CMDEN[1:0] 180 +0x0A Reserved – – – – – – – – +0x0B Reserved – – – – – – – – +0x0C INTFLAGS LCMPDIF LCMPCIF LCMPBIF LCMPAIF – – HUNFIF LUNFIF 181 +0x0D Reserved – – – – – – – – +0x0E Reserved – – – – – – – – +0x0F Reserved – – – – – – – – +0x10 to Reserved – – – – – – – – +0x20 LCNT Low-byte Timer/Counter Count Register 182 +0x21 HCNT High-byte Timer/Counter Count Register 182 +0x22 to Reserved – – – – – – – – +0x26 LPER Low-byte Timer/Counter Period Register 182 +0x27 HPER High-byte Timer/Counter Period Register 183 +0x28 LCMPA Low-byte Compare Register A 183 +0x29 HCMPA High-byte Compare Register A 183 +0x2A LCMPB Low-byte Compare Register B 183 +0x2B HCMPB High-byte Compare Register B 183 +0x2C LCMPC Low-byte Compare Register C 183 +0x02D HCMPC High-byte Compare Register C 183 +0x2E LCMPD Low-byte Compare Register D 183 +0x2F HCMPD High-byte Compare Register D 183 +0x30 to Reserved – – – – – – – – Offset Source Interrupt Description 0x00 LUNF_vect Low-byte Timer/counter underflow interrupt vector offset 0x02 HUNF_vect High-byte Timer/counter underflow interrupt vector offset 0x4 LCMPA_vect Low-byte Timer/counter compare channel A interrupt vector offset 0x6 LCMPB_vect Low-byte Timer/counter compare channel B interrupt vector offset 0x8 LCMPC_vect Low-byte Timer/counter compare channel C interrupt vector offset 0x0A LCMPD_vect Low-byte Timer/counter compare channel D interrupt vector offset XMEGA B [MANUAL] 185 Atmel-8291C-AVR-XMEGA B -09/2014 15. AWeX – Advanced Waveform Extension 15.1 Features z Waveform output with complementary output from each compare channel z Four dead-time insertion (DTI) units z 8-bit resolution z Separate high and low side dead-time setting z Double buffered dead time z Optionally halts timer during dead-time insertion z Pattern generation unit creating synchronised bit pattern across the port pins z Double buffered pattern generation z Optional distribution of one compare channel output across the port pins z Event controlled fault protection for instant and predictable fault triggering 15.2 Overview The advanced waveform extension (AWeX) provides extra functions to the timer/counter in waveform generation (WG) modes. It is primarily intended for use with different types of motor control and other power control applications. It enables low- and high side output with dead-time insertion and fault protection for disabling and shutting down external drivers. It can also generate a synchronized bit pattern across the port pins. Figure 15-1. Advanced waveform extention and closely related peripherals (grey). As shown in Figure 15-1 on page 185, each of the waveform generator outputs from timer/counter 0 are split into a complimentary pair of outputs when any AWeX features are enabled. These output pairs go through a dead-time insertion (DTI) unit that generates the non-inverted low side (LS) and inverted high side (HS) of the WG output with deadtime insertion between LS and HS switching. The DTI output will override the normal port value according to the port Timer/Counter 0 AWeX WG Channel A DTI Channel A WG Channel B DTI Channel B WG Channel C DTI Channel C WG Channel D DTI Channel D Port Override Pattern Generation Px0 Px1 Px2 Px3 Px4 Px5 Px6 Px7 Event System Fault Protection XMEGA B [MANUAL] 186 Atmel-8291C-AVR-XMEGA B -09/2014 override setting. Refer to “I/O Ports” on page 123 for more details. The pattern generation unit can be used to generate a synchronized bit pattern on the port it is connected to. In addition, the WG output from compare channel A can be distributed to and override all the port pins. When the pattern generator unit is enabled, the DTI unit is bypassed. The fault protection unit is connected to the event system, enabling any event to trigger a fault condition that will disable the AWeX output. The event system ensures predictable and instant fault reaction, and gives flexibility in the selection of fault triggers. 15.3 Port Override The port override logic is common for all the timer/counter extensions. Figure 15-2 on page 187 shows a schematic diagram of the port override logic. When the dead-time enable (DTIENx) bit is set, the timer/counter extension takes control over the pin pair for the corresponding channel. Given this condition, the output override enable (OOE) bits take control over the CCxEN bits. XMEGA B [MANUAL] 187 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 15-2. Timer/counter extensions and port override logic. 15.4 Dead-time Insertion The dead-time insertion (DTI) unit generates OFF time where the non-inverted low side (LS) and inverted high side (HS) of the WG output are both low. This OFF time is called dead time, and dead-time insertion ensures that the LS and HS never switch simultaneously. The DTI unit consists of four equal dead-time generators, one for each compare channel in timer/counter 0. Figure 15-3 on page 188 shows the block diagram of one DTI generator. The four channels have a common register that controls the OUT0 OUTOVEN0 CCAEN DTICCAEN INVEN0 OUT1 OUTOVEN1 CCBEN INVEN1 Px0 Px1 Channel A DTI LS HS OC0A OC0B OCALS OCAHS WG 0A WG 0B WG 0A CWCM OUT2 OUTOVEN2 CCCEN DTICCBEN INVEN2 OUT3 OUTOVEN3 CCDEN INVEN3 Px2 Px3 Channel B DTI LS HS OC0C OC0D OCBLS OCBHS WG 0C WG 0D OUT4 OUTOVEN4 CCAEN DTICCCEN INVEN4 OUT5 OUTOVEN5 CCBEN INVEN5 Px4 Px5 Channel C DTI LS HS OC1A OC1B OCCLS OCCHS WG 1A WG 1B OUT6 OUTOVEN6 DTICCDEN INVEN6 OUT7 OUTOVEN7 INVEN7 Px6 Px7 Channel D DTI LS HS OCDLS OCDHS WG 0B WG 0D WG 0C "0" "0" XMEGA B [MANUAL] 188 Atmel-8291C-AVR-XMEGA B -09/2014 dead time. The high side and low side have independent dead-time setting, and the dead-time registers are double buffered. Figure 15-3. Dead-time generator block diagram. As shown in Figure 15-4 on page 188, the 8-bit dead-time counter is decremented by one for each peripheral clock cycle, until it reaches zero. A nonzero counter value will force both the low side and high side outputs into their OFF state. When a change is detected on the WG output, the dead-time counter is reloaded according to the edge of the input. A positive edge initiates a counter reload of the DTLS register, and a negative edge a reload of DTHS register. Figure 15-4. Dead-time generator timing diagram. 15.5 Pattern Generation The pattern generator unit reuses the DTI registers to produce a synchronized bit pattern across the port it is connected to. In addition, the waveform generator output from compare channel A (CCA) can be distributed to and override all the port pins. These features are primarily intended for handling the commutation sequence in brushless DC motor (BLDC) and stepper motor applications. A block diagram of the pattern generator is shown in “Pattern generator block diagram.” on page 189. For each port pin where the corresponding OOE bit is set, the multiplexer will output the waveform from CCA. Dead Time Generator Edge Detect BV BV D Q = 0 DTLSBUF DTLS DTHSBUF DTHS "DTLS" (To PORT) "DTHS" (To PORT) Counter EN LOAD WG output "dti_cnt" "WG output" "DTLS" "DTHS" tDTILS tDTIHS T tP XMEGA B [MANUAL] 189 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 15-5. Pattern generator block diagram. As with the other timer/counter double buffered registers, the register update is synchronized to the UPDATE condition set by the waveform generation mode. If the synchronization provided is not required by the application, the application code can simply access the DTIOE and PORTx registers directly. The pin directions must be set for any output from the pattern generator to be visible on the port. 15.6 Fault Protection The fault protection feature enables fast and deterministic action when a fault is detected. The fault protection is event controlled. Thus, any event from the event system can be used to trigger a fault action, such as over-current indication from analog comparator or ADC measurements. When fault protection is enabled, an incoming event from any of the selected event channels can trigger the event action. Each event channel can be separately enabled as a fault protection input, and the specified event channels will be ORed together, allowing multiple event sources to be used for fault protection at the same time. 15.6.1 Fault Actions When a fault is detected, the direction clear action will clear the direction (DIR) register in the associated port, setting all port pins as tri-stated inputs. The fault detection flag is set, the timer/counter’s error interrupt flag is set, and the optional interrupt is generated. There is maximum of two peripheral clock cycles from when an event occurs in a peripheral until the fault protection triggers the event action. Fault protection is fully independent of the CPU and DMA, but requires the peripheral clock to run. 15.6.2 Fault Restore Modes How the AWeX and timer/counter return from the fault state to normal operation after a fault, when the fault condition is no longer active, can be selected from one of two different modes: z In latched mode, the waveform output will remain in the fault state until the fault condition is no longer active and the fault detect flag has been cleared by software. When both of these conditions are met, the waveform output will return to normal operation at the next UPDATE condition. z In cycle-by-cycle mode the waveform output will remain in the fault state until the fault condition is no longer active. When this condition is met, the waveform output will return to normal operation at the next UPDATE condition. Timer/Counter 0 (TCx0) BV DTLSBUF BV OUTOVEN DTHSBUF OUTx UPDATE CCA WG output EN EN 1 to 8 Expand Px[7:0] XMEGA B [MANUAL] 190 Atmel-8291C-AVR-XMEGA B -09/2014 When returning from a fault state the DIR[7:0] bits corresponding to the enabled DTI channels are restored. OUTOVEN is unaffected by the fault except that writing to the register from software is blocked. The UPDATE condition used to restore normal operation is the same as the one in the timer/counter. 15.6.3 Change Protection To avoid unintentional changes in the fault protection setup, all the control registers in the AWeX extension can be protected by writing the corresponding lock bit in the advanced waveform extension lock register. For more details, refer to “I/O Memory Protection” on page 25 and “AWEXLOCK – Advanced Waveform Extension Lock register” on page 44. When the lock bit is set, control register A, the output override enable register, and the fault detection event mask register cannot be changed. To avoid unintentional changes in the fault event setup, it is possible to lock the event system channel configuration by writing the corresponding event system lock register. For more details, refer to “I/O Memory Protection” on page 25 and “EVSYSLOCK – Event System Lock register” on page 43. 15.6.4 On-Chip Debug When fault detection is enabled, an on-chip debug (OCD) system receives a break request from the debugger, which will by default function as a fault source. When an OCD break request is received, the AWeX and corresponding timer/counter will enter a fault state, and the specified fault action will be performed. After the OCD exits from the break condition, normal operation will be started again. In cycle-by-cycle mode, the waveform output will start on the first UPDATE condition after exit from break, while in latched mode, the fault condition flag must be cleared in software before the output will be restored. This feature guarantees that the output waveform enters a safe state during a break. It is possible to disable this feature. XMEGA B [MANUAL] 191 Atmel-8291C-AVR-XMEGA B -09/2014 15.7 Register Description 15.7.1 CTRL – Control register z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 5 – PGM: Pattern Generation Mode Setting this bit enables the pattern generation mode. This will override the DTI, and the pattern generation reuses the dead-time registers for storing the pattern. z Bit 4 – CWCM: Common Waveform Channel Mode If this bit is set, the CC channel A waveform output will be used as input for all the dead-time generators. CC channel B, C, and D waveforms will be ignored. z Bit 3:0 – DTICCxEN: Dead-Time Insertion CCx Enable Setting these bits enables the dead-time generator for the corresponding CC channel. This will override the timer/counter waveform outputs. 15.7.2 FDEMASK – Fault Detect Event Mask register z Bit 7:0 – FDEVMASK[7:0]: Fault Detect Event Mask These bits enable the corresponding event channel as a fault condition input source. Events from all event channels will be ORed together, allowing multiple sources to be used for fault detection at the same time. When a fault is detected, the fault detect flag (FDF) is set and the fault detect action (FDACT) will be performed. Bit 7 6 5 4 3 2 1 0 +0x00 – – PGM CWCM DTICCDEN DTICCCEN DTICCBEN DTICCAEN Read/Write R R R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x02 FDEVMASK[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 000000 XMEGA B [MANUAL] 192 Atmel-8291C-AVR-XMEGA B -09/2014 15.7.3 FDCTRL - Fault Detection Control register z Bit 7:5 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 4 – FDDBD: Fault Detection on Debug Break Detection By default, when this bit is cleared and fault protection is enabled, and OCD break request is treated as a fault. When this bit is set, an OCD break request will not trigger a fault condition. z Bit 3 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 2 – FDMODE: Fault Detection Restart Mode This bit sets the fault protection restart mode. When this bit is cleared, latched mode is used, and when it is set, cycle-bycycle mode is used. In latched mode, the waveform output will remain in the fault state until the fault condition is no longer active and the FDF has been cleared by software. When both conditions are met, the waveform output will return to normal operation at the next UPDATE condition. In cycle-by-cycle mode, the waveform output will remain in the fault state until the fault condition is no longer active. When this condition is met, the waveform output will return to normal operation at the next UPDATE condition. z Bit 1:0 – FDACT[1:0]: Fault Detection Action These bits define the action performed, according to Table 15-1, when a fault condition is detected. Table 15-1. Fault action. Bit 7 6 5 4 3 2 1 0 +0x03 – – – FDDBD – FDMODE FDACT[1:0] Read/Write R R R R/W R R/W R/W R/W Initial Value 00000000 FDACT[1:0] Group Configuration Description 00 NONE None (fault protection disabled) 01 – Reserved 10 – Reserved 11 CLEARDIR Clear all direction (DIR) bits which correspond to the enabled DTI channel(s); i.e., tri-state the outputs XMEGA B [MANUAL] 193 Atmel-8291C-AVR-XMEGA B -09/2014 15.7.4 STATUS – Status register z Bit 7:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2 – FDF: Fault Detect Flag This flag is set when a fault detect condition is detected; i.e., when an event is detected on one of the event channels enabled by FDEVMASK. This flag is cleared by writing a one to its bit location. z Bit 1 – DTHSBUFV: Dead-time High Side Buffer Valid If this bit is set, the corresponding DT buffer is written and contains valid data that will be copied into the DTLS register on the next UPDATE condition. If this bit is zero, no action will be taken. The connected timer/counter unit’s lock update (LUPD) flag also affects the update for dead-time buffers. z Bit 0 – DTLSBUFV: Dead-time Low Side Buffer Valid If this bit is set, the corresponding DT buffer is written and contains valid data that will be copied into the DTHS register on the next UPDATE condition. If this bit is zero, no action will be taken. The connected timer/counter unit's lock update (LUPD) flag also affects the update for dead-time buffers. 15.7.5 DTBOTH – Dead-time Concurrent Write to Both Sides z Bit 7:0 – DTBOTH: Dead-time Both Sides Writing to this register will update the DTHS and DTLS registers at the same time (i.e., at the same I/O write access). 15.7.6 DTBOTHBUF – Dead-time Concurrent Write to Both Sides Buffer register z Bit 7:0 – DTBOTHBUF: Dead-time Both Sides Buffer Writing to this memory location will update the DTHSBUF and DTLSBUF registers at the same time (i.e., at the same I/O write access). Bit 7 6 5 4 3 2 1 0 +0x04 – – – – – FDF DTHSBUFV DTLSBUFV Read/Write R R R R R R/W R/W R/W Initial Value 00000 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x06 DTBOTH[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x07 DTBOTHBUF[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 194 Atmel-8291C-AVR-XMEGA B -09/2014 15.7.7 DTLS – Dead-time Low Side register z Bit 7:0 – DTLS: Dead-time Low Side This register holds the number of peripheral clock cycles for the dead-time low side. 15.7.8 DTHS – Dead-time High Side register z Bit 7:0 – DTHS: Dead-time High Side This register holds the number of peripheral clock cycles for the dead-time high side. 15.7.9 DTLSBUF – Dead-time Low Side Buffer register z Bit 7:0 – DTLSBUF: Dead-time Low Side Buffer This register is the buffer for the DTLS register. If double buffering is used, valid content in this register is copied to the DTLS register on an UPDATE condition. 15.7.10 DTHSBUF – Dead-time High Side Buffer register z Bit 7:0 – DTHSBUF: Dead-time High Side Buffer This register is the buffer for the DTHS register. If double buffering is used, valid content in this register is copied to the DTHS register on an UPDATE condition. Bit 7 6 5 4 3 2 1 0 +0x08 DTLS[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x09 DTHS[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0A DTLSBUF[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x0B DTHSBUF[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 195 Atmel-8291C-AVR-XMEGA B -09/2014 15.7.11 OUTOVEN – Output Override Enable register Note: 1. Can be written only if the fault detect flag (FDF) is zero. z Bit 7:0 – OUTOVEN[7:0]: Output Override Enable These bits enable override of the corresponding port output register (i.e., one-to-one bit relation to pin position). The port direction is not overridden. 15.8 Register Summary Bit 7 6 5 4 3 2 1 0 +0x0C OUTOVEN[7:0] Read/Write R/W(1) R/W(1) R/W(1) R/W(1) R/W(1) R/W(1) R/W(1) R/W(1) Initial Value 0 0 0 0 0 0 0 0 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Pag +0x00 CTRL – – PGM CWCM DTICDAE DTICCCE DTICCBEN DTICCAEN 191 +0x01 Reserved – – – – – – – – +0x02 FDEMASK FDEVMASK[7:0] 191 +0x03 FDCTRL – – – FDDBD – FDMODE FDACT[1:0] 192 +0x04 STATUS – – – – – FDF DTBHSV DTBLSV 193 +0x05 Reserved – – – – – – – – +0x06 DTBOTH DTBOTH[7:0] 193 +0x07 DTBOTHBUF DTBOTHBUF[7:0] 193 +0x08 DTLS DTLS[7:0] 194 +0x09 DTHS DTHS[7:0] 194 +0x0A DTLSBUF DTLSBUF[7:0] 194 +0x0B DTHSBUF DTHSBUF[7:0] 194 +0x0C OUTOVEN OUTOVEN[7:0] 195 XMEGA B [MANUAL] 196 Atmel-8291C-AVR-XMEGA B -09/2014 16. Hi-Res – High-Resolution Extension 16.1 Features z Increases waveform generator resolution up to 8x (3 bits) z Supports frequency, single-slope PWM, and dual-slope PWM generation z Supports the AWeX when this is used for the same timer/counter 16.2 Overview The high-resolution (hi-res) extension can be used to increase the resolution of the waveform generation output from a timer/counter by four or eight. It can be used for a timer/counter doing frequency, single-slope PWM, or dual-slope PWM generation. It can also be used with the AWeX if this is used for the same timer/counter. The hi-res extension uses the peripheral 4x clock (ClkPER4). The system clock prescalers must be configured so the peripheral 4x clock frequency is four times higher than the peripheral and CPU clock frequency when the hi-res extension is enabled. Refer to “System Clock Selection and Prescalers” on page 79 for more details. Figure 16-1. Timer/counter operation with hi-res extension enabled. When the hi-res extension is enabled, the timer/counter must run from a non-prescaled peripheral clock. The timer/counter will ignore its two least-significant bits (lsb) in the counter, and counts by four for each peripheral clock cycle. Overflow/underflow and compare match of the 14 most-significant bits (msb) is done in the timer/counter. Count and compare of the two lsb is handled and compared in the hi-res extension running from the peripheral 4x clock. The two lsb of the timer/counter period register must be set to zero to ensure correct operation. If the count register is read from the application code, the two lsb will always be read as zero, since the timer/counter run from the peripheral clock. The two lsb are also ignored when generating events. When the hi-res plus feature is enabled, the function is the same as with the hi-res extension, but the resolution will increase by eight instead of four. This also means that the 3 lsb are handled by the hi-res extension instead of 2 lsb, as when only hi-res is enabled. The extra resolution is achieved by counting on both edges of the peripheral 4x clock. The hi-res extension will not output any pulse shorter than one peripheral clock cycle; i.e., a compare value lower than four will have no visible output. CNT[15:2] HiRes CCxBUF[15:0] = 0 = " match" = PER[15:2] 0 Waveform Generation BOTTOM TOP Time /Counter CCx[15:2] [1:0] 2 2 2 0 AWeX Fault Protection Dead - Time Insertion Pattern Generation clkPER clkPER4 Pxn XMEGA B [MANUAL] 197 Atmel-8291C-AVR-XMEGA B -09/2014 16.3 Register Description 16.3.1 CTRLA – Control register A z Bit 7:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2 – HRPLUS: High Resolution Plus Setting this bit enables high resolution plus. Hi-res plus is the same as hi-res, but will increase the resolution by eight (3 bits) instead of four. The extra resolution is achieved by operating at both edges of the peripheral 4x clock. z Bit 1:0 – HREN[1:0]: High Resolution Enable These bits enables the high-resolution mode for a timer/counter according to Table 16-1. Setting one or both HREN bits will enable high-resolution waveform generation output for the entire general purpose I/O port. This means that both timer/counters connected to the same port must enable hi-res if both are used for generating PWM or FRQ output on pins. Table 16-1. High resolution enable. 16.4 Register Summary Bit 7 6 5 4 3 2 1 0 +0x00 – – – – – HRPLUS HREN[1:0] Read/Write R R R R R R/W R/W R/W Initial Value 00000000 HREN[1:0] High Resolution Enabled 00 None 01 Timer/counter 0 10 Timer/counter 1 11 Both timer/counters Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRLA – – – – – HRPLUS HREN[1:0] 197 XMEGA B [MANUAL] 198 Atmel-8291C-AVR-XMEGA B -09/2014 17. RTC – Real-Time Counter 17.1 Features z 16-bit resolution z Selectable clock source z 32.768kHz external crystal z External clock z 32.768kHz internal oscillator z 32kHz internal ULP oscillator z Programmable 10-bit clock prescaling z One compare register z One period register z Clear counter on period overflow z Optional interrupt/event on overflow and compare match 17.2 Overview The 16-bit real-time counter (RTC) is a counter that typically runs continuously, including in low-power sleep modes, to keep track of time. It can wake up the device from sleep modes and/or interrupt the device at regular intervals. The reference clock is typically the 1.024kHz output from a high-accuracy crystal of 32.768kHz, and this is the configuration most optimized for low power consumption. The faster 32.768kHz output can be selected if the RTC needs a resolution higher than 1ms. The RTC can also be clocked from an external clock signal, the 32.768kHz internal oscillator or the 32kHz internal ULP oscillator. The RTC includes a 10-bit programmable prescaler that can scale down the reference clock before it reaches the counter. A wide range of resolutions and time-out periods can be configured. With a 32.768kHz clock source, the maximum resolution is 30.5μs, and time-out periods can range up to 2000 seconds. With a resolution of 1s, the maximum timeout period is more than18 hours (65536 seconds). The RTC can give a compare interrupt and/or event when the counter equals the compare register value, and an overflow interrupt and/or event when it equals the period register value. Figure 17-1. Real-time counter overview. 32.768kHz Crystal Osc 32.768kHz Int. Osc TOSC1 TOSC2 External Clock DIV32 DIV32 32kHz int ULP (DIV32) RTCSRC 10-bit prescaler clkRTC CNT PER COMP = = ”match”/ Compare TOP/ Overflow XMEGA B [MANUAL] 199 Atmel-8291C-AVR-XMEGA B -09/2014 17.2.1 Clock Domains The RTC is asynchronous, operating from a different clock source independently of the main system clock and its derivative clocks, such as the peripheral clock. For control and count register updates, it will take a number of RTC clock and/or peripheral clock cycles before an updated register value is available in a register or until a configuration change has effect on the RTC. This synchronization time is described for each register. Refer to “RTCCTRL – RTC Control register” on page 85 for selecting the asynchronous clock source for the RTC. 17.2.2 Interrupts and Events The RTC can generate both interrupts and events. The RTC will give a compare interrupt and/or event at the first count after the counter value equals the Compare register value. The RTC will give an overflow interrupt request and/or event at the first count after the counter value equals the Period register value. The overflow will also reset the counter value to zero. Due to the asynchronous clock domain, events will be generated only for every third overflow or compare match if the period register is zero. If the period register is one, events will be generated only for every second overflow or compare match. When the period register is equal to or above two, events will trigger at every overflow or compare match, just as the interrupt request. XMEGA B [MANUAL] 200 Atmel-8291C-AVR-XMEGA B -09/2014 17.3 Register Descriptions 17.3.1 CTRL – Control register z Bit 7:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2:0 – PRESCALER[2:0]: Clock Prescaling factor These bits define the prescaling factor for the RTC clock according to Table 17-1. Table 17-1. Real-time counter clock prescaling factor. 17.3.2 STATUS – Status register z Bit 7:1 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 0 – SYNCBUSY: Synchronization Busy Flag This flag is set when the CNT, CTRL, PER, or COMP register is busy synchronizing between the RTC clock and system clock domains. THis flag is automatically cleared when the synchronisation is complete Bit 7 6 5 4 3 2 1 0 +0x00 – – – – – PRESCALER[2:0] Read/Write R R R R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 PRESCALER[2:0] Group Configuration RTC Clock Prescaling 000 OFF No clock source, RTC stopped 001 DIV1 RTC clock / 1 (no prescaling) 010 DIV2 RTC clock / 2 011 DIV8 RTC clock / 8 100 DIV16 RTC clock / 16 101 DIV64 RTC clock / 64 110 DIV256 RTC clock / 256 111 DIV1024 RTC clock / 1024 Bit 7 6 5 4 3 2 1 0 +0x01 – – – – – – – SYNCBUSY Read/Write RRRRRRR R Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 201 Atmel-8291C-AVR-XMEGA B -09/2014 17.3.3 INTCTRL – Interrupt Control register z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:2 – COMPINTLVL[1:0]: Compare Match Interrupt Enable These bits enable the RTC compare match interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger when COMPIF in the INTFLAGS register is set. z Bit 1:0 – OVFINTLVL[1:0]: Overflow Interrupt Enable These bits enable the RTC overflow interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will trigger when OVFIF in the INTFLAGS register is set. 17.3.4 INTFLAGS – Interrupt Flag register z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1 – COMPIF: Compare Match Interrupt Flag This flag is set on the next count after a compare match condition occurs. It is cleared automatically when the RTC compare match interrupt vector is executed. The flag can also be cleared by writing a one to its bit location. z Bit 0 – OVFIF: Overflow Interrupt Flag This flag is set on the next count after an overflow condition occurs. It is cleared automatically when the RTC overflow interrupt vector is executed. The flag can also be cleared by writing a one to its bit location. Bit 7 6 5 4 3 2 1 0 +0x02 – – – – COMPINTLVL[1:0] OVFINTLVL[1:0] Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0000000 Bit 7 6 5 4 3 2 1 0 +0x03 – – – – – – COMPIF OVFIF Read/Write R R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 202 Atmel-8291C-AVR-XMEGA B -09/2014 17.3.5 TEMP – Temporary register z Bit 7:0 – TEMP[7:0]: Temporary bits This register is used for 16-bit access to the counter value, compare value, and TOP value registers. The low byte of the 16-bit register is stored here when it is written by the CPU. The high byte of the 16-bit register is stored when the low byte is read by the CPU. For more details, refer to “Accessing 16-bit Registers” on page 13. 17.3.6 CNTL – Counter register Low The CNTH and CNTL register pair represents the 16-bit value, CNT. CNT counts positive clock edges on the prescaled RTC clock. Reading and writing 16-bit values requires special attention. Refer to “Accessing 16-bit Registers” on page 13 for details. Due to synchronization between the RTC clock and system clock domains, there is a latency of two RTC clock cycles from updating the register until this has an effect. Application software needs to check that the SYNCBUSY flag in the “STATUS – Status register” on page 200 is cleared before writing to this register. z Bit 7:0 – CNT[7:0]: Counter Value low byte These bits hold the LSB of the 16-bit real-time counter value. 17.3.7 CNTH – Counter Register High z Bit 7:0 – CNT[15:8]: Counter Value high byte These bits hold the MSB of the 16-bit real-time counter value. Bit 7 6 5 4 3 2 1 0 +0x04 TEMP[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x08 CNT[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 000000 Bit 7 6 5 4 3 2 1 0 +0x09 CNT[15:8] 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 XMEGA B [MANUAL] 203 Atmel-8291C-AVR-XMEGA B -09/2014 17.3.8 PERL – Period register Low The PERH and PERL register pair represents the 16-bit value, PER. PER is constantly compared with the counter value (CNT). A match will set OVFIF in the INTFLAGS register and clear CNT. Reading and writing 16-bit values requires special attention. Refer to “Accessing 16-bit Registers” on page 13 for details. Due to synchronization between the RTC clock and system clock domains, there is a latency of two RTC clock cycles from updating the register until this has an effect. Application software needs to check that the SYNCBUSY flag in the “STATUS – Status register” on page 200 is cleared before writing to this register. z Bit 7:0 – PER[7:0]: Period low byte These bits hold the LSB of the 16-bit RTC TOP value. 17.3.9 PERH – Period register High z Bits 7:0 – PER[15:8]: Period high byte These bits hold the MSB of the 16-bit RTC TOP value. 17.3.10 COMPL – Compare register Low The COMPH and COMPL register pair represent the 16-bit value, COMP. COMP is constantly compared with the counter value (CNT). A compare match will set COMPIF in the INTFLAGS register. Reading and writing 16-bit values requires special attention. Refer “Accessing 16-bit Registers” on page 13 for details. Due to synchronization between the RTC clock and system clock domains, there is a latency of two RTC clock cycles from updating the register until this has an effect. Application software needs to check that the SYNCBUSY flag in the “STATUS – Status register” on page 200 is cleared before writing to this register. If the COMP value is higher than the PER value, no RTC compare match interrupt requests or events will ever be generated. z Bit 7:0 – COMP[7:0]: Compare value low byte These bits hold the LSB of the 16-bit RTC compare value. Bit 7 6 5 4 3 2 1 0 +0x0A PER[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1 111111 Bit 7 6 5 4 3 2 1 0 +0x0B PER[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 1 1111111 Bit 7 6 5 4 3 2 1 0 +0x0C COMP[7:0] 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 XMEGA B [MANUAL] 204 Atmel-8291C-AVR-XMEGA B -09/2014 17.3.11 COMPH – Compare register High z Bit 7:0 – COMP[15:8]: Compare value high byte These bits hold the MSB of the 16-bit RTC compare value. Bit 76543210 +0x0D COMP[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 205 Atmel-8291C-AVR-XMEGA B -09/2014 17.4 Register Summary 17.5 Interrupt Vector Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL – – – – – PRESCALER[2:0] 200 +0x01 STATUS – – – – – – – SYNCBUSY 200 +0x02 INTCTRL – – – – COMPINTLVL[1:0] OVFINTLVL[1:0] 201 +0x03 INTFLAGS – – – – – – COMPIF OVFIF 201 +0x04 TEMP TEMP[7:0] 202 +0x08 CNTL CNT[7:0] 202 +0x09 CNTH CNT[15:8] 202 +0x0A PERL PER[7:0] 203 +0x0B PERH PER[15:8] 203 +0x0C COMPL COMP[7:0] 204 +0x0D COMPH COMP[15:8] 203 Offset Source Interrupt Description 0x00 OVF_vect Real-time counter overflow interrupt vector 0x02 COMP_vect Real-time counter compare match interrupt vector XMEGA B [MANUAL] 206 Atmel-8291C-AVR-XMEGA B -09/2014 18. USB – Universal Serial Bus Interface 18.1 Features z USB 2.0 full speed (12Mbps) and low speed (1.5Mbps) device compliant interface z Integrated on-chip USB transceiver, no external components needed z 16 endpoint addresses with full endpoint flexibility for up to 31 endpoints z One input endpoint per endpoint address z One output endpoint per endpoint address z Endpoint address transfer type selectable to z Control transfers z Interrupt transfers z Bulk transfers z Isochronous transfers z Configurable data payload size per endpoint, up to 1023 bytes z Endpoint configuration and data buffers located in internal SRAM z Configurable location for endpoint configuration data z Configurable location for each endpoint's data buffer z Built-in direct memory access (DMA) to internal SRAM for: z Endpoint configurations z Reading and writing endpoint data z Ping-pong operation for higher throughput and double buffered operation z Input and output endpoint data buffers used in a single direction z CPU/DMA controller can update data buffer during transfer z Multipacket transfer for reduced interrupt load and software intervention z Data payload exceeding maximum packet size is transferred in one continuous transfer z No interrupts or software interaction on packet transaction level z Transaction complete FIFO for workflow management when using multiple endpoints z Tracks all completed transactions in a first-come, first-served work queue z Clock selection independent of system clock source and selection z Minimum 1.5MHz CPU clock required for low speed USB operation z Minimum 12MHz CPU clock required for full speed operation z Connection to event system z On chip debug possibilities during USB transactions 18.2 Overview The USB module is a USB 2.0 full speed (12Mbps) and low speed (1.5Mbps) device compliant interface. The USB supports 16 endpoint addresses. All endpoint addresses have one input and one output endpoint, for a total of 31 configurable endpoints and one control endpoint. Each endpoint address is fully configurable and can be configured for any of the four transfer types: control, interrupt, bulk, or isochronous. The data payload size is also selectable, and it supports data payloads up to 1023 bytes. No dedicated memory is allocated for or included in the USB module. Internal SRAM is used to keep the configuration for each endpoint address and the data buffer for each endpoint. The memory locations used for endpoint configurations and data buffers are fully configurable. The amount of memory allocated is fully dynamic, according to the number of endpoints in use and the configuration of these. The USB module has built-in direct memory access (DMA), and will read/write data from/to the SRAM when a USB transaction takes place. To maximize throughput, an endpoint address can be configured for ping-pong operation. When done, the input and output endpoints are both used in the same direction. The CPU or DMA controller can then read/write one data buffer while the USB module writes/reads the others, and vice versa. This gives double buffered communication. XMEGA B [MANUAL] 207 Atmel-8291C-AVR-XMEGA B -09/2014 Multipacket transfer enables a data payload exceeding the maximum packet size of an endpoint to be transferred as multiple packets without software intervention. This reduces the CPU intervention and the interrupts needed for USB transfers. For low-power operation, the USB module can put the microcontroller into any sleep mode when the USB bus is idle and a suspend condition is given. Upon bus resumes, the USB module can wake up the microcontroller from any sleep mode. Figure 18-1. USB OUT transfer: data packet from host to USB device. Figure 18-2. USB IN transfer: data packet from USB device to host after request from host. 18.3 Operation This section gives an overview of the USB module operation during normal transactions. For general details on USB and the USB protocol, please refer to http://www.usb.org and the USB specification documents. Internal SRAM USB USB Endpoints Configuration Table USBEPPTR USB Buffers ENDPOINT 1 DATA ENDPOINT 2 DATA ENDPOINT 3 DATA D A T A 0 D A T A 0 D A T A 0 D A T A 1 D A T A 0 D A T A 1 D A T A 0 D A T A 1 D A T A 0 D A T A 1 D A T A 0 BULK OUT EPT 2 BULK OUT EPT 3 BULK OUT EPT 1 DP DM HOST time D A T A 0 D A T A 0 D A T A 0 D A T A 1 D A T A 0 D A T A 1 D A T A 0 D A T A 1 D A T A 0 D A T A 1 D A T A 0 EPT 2 EPT 3 EPT 1 DP DM HOST I N T O K E N I N T O K E N I N T O K E N EPT 2 EPT 3 EPT 1 time Internal SRAM USB USB Endpoints Configuration Table USBEPPTR USB Buffers ENDPOINT 1 DATA ENDPOINT 2 DATA ENDPOINT 3 DATA CPU XMEGA B [MANUAL] 208 Atmel-8291C-AVR-XMEGA B -09/2014 18.3.1 Start of Frame When a start of frame (SOF) token is detected and storing of the frame numbers is enabled, the frame number from the token is stored in the frame number register (FRAMENUM) and the start of frame interrupt flag (SOFIF) in the interrupt flag B clear/set register (INTFLAGSBCLR/SET) is set. If there was a CRC or bit-stuff error, the frame error (FRAMEERR) flag in FRAMENUM is set. 18.3.2 SETUP When a SETUP token is detected, the USB module fetches the endpoint control register (CTRL) from the addressed output endpoint in the endpoint configuration table. If the endpoint type is not set to control, the USB module returns to idle and waits for the next token packet. Figure 18-3. SETUP transaction. The USB module then fetches the endpoint data pointer register (DATAPTR) and waits for a DATA0 packet. If a PID error or any other PID than DATA0 is detected, the USB module returns to idle and waits for the next token packet. The incoming data are written to the data buffer pointed to by DATAPTR. If a bit-stuff error is detected in the incoming data, the USB module returns to idle and waits for the next token packet. If the number of received data bytes exceeds the endpoint's maximum data payload size, as specified by the data size (SIZE) in the endpoint CTRL register, the remaining received data bytes are discarded. The packet will still be checked for bit-stuff and CRC errors. Software must never report a maximum data payload size to the host that is greater than specified in SIZE. If there was a bit-stuff or CRC error in the packet, the USB module returns to idle and waits for the next token packet. If data was successfully received, an ACK handshake is returned to the host, and the number of received data bytes, excluding the CRC, is written to the endpoint byte counter (CNT). If the number of received data bytes is the maximum data payload specified by SIZE, no CRC data are written in the data buffer. If the number of received data bytes is the maximum data payload specified by SIZE minus one, only the first CRC data byte is written in the data buffer. If the number of received data bytes is equal or less than the data byte payload specified by SIZE minus two, the two CRC data bytes are written in the data buffer. Finally, the setup transaction complete flag (SETUP), data buffer 0 not acknowledge flag (NACK0), and data toggle flag (TOGGLE) are set, while the remaining flags in the endpoint status register (STATUS) are cleared for the addressed input and output endpoints. The setup transaction complete interrupt flag (SETUPIF) in INTFLAGSBCLR/SET is set. The STALL flag in the endpoint CTRL register is cleared for the addressed input and output endpoints. When a SETUP token is detected and the device address of the token packet does not match that of the endpoint, the packet is discarded, and the USB module returns to idle and waits for the next token packet. 18.3.3 OUT When an OUT token is detected, the USB module fetches the endpoint CTRL and STATUS register data from the addressed output endpoint in its endpoint configuration table. If the endpoint is disabled, the USB module returns to idle and waits for the next token packet. SETUP TOKEN ADDRESS ADDRESS MATCH? ENDPOINT LEGAL ENDPOINT? EP TYPE CTRL SET? PID PID OK? DATA BIT STUFF BIT STUFF OK? CRC OK? ACK IDLE No No No No No No READ CONFIG UPDATE STATUS STORE DATA Yes Yes Yes Yes Yes Yes CRC XMEGA B [MANUAL] 209 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 18-4. OUT transaction. The USB module then fetches the endpoint DATAPTR register and waits for a DATA0 or DATA1 packet. If a PID error or any other PID than DATA0 or DATA1 is detected, the USB module returns to idle and waits for the next token packet. If the STALL flag in the endpoint CTRL register is set, the incoming data are discarded. If the endpoint is not isochronous, and the bit stuffing and CRC of the received data are OK, a STALL handshake is returned to the host, and the STALL interrupt flag is set. For isochronous endpoints, data from both a DATA0 and DATA1 packet will be accepted. For other endpoint types, the PID is checked against TOGGLE. If they don't match, the incoming data are discarded and a NAK handshake is returned to the host. If BUSNACK0 is set, the incoming data are discarded. The overflow flag (OVF) in the endpoint STATUS register and the overflow interrupt flag (OVFIF) in the INTFLAGSASET/CLR register are set. If the endpoint is not isochronous, a NAK handshake is returned to the host. The incoming data are written to the data buffer pointed to by DATAPTR. If a bit-stuff error is detected in the incoming data, the USB module returns to idle and waits for the next token packet. If the number of received data bytes exceeds the maximum data payload specified by SIZE, the remaining received data bytes are discarded. The packet will still be checked for bit-stuff and CRC errors. If there was a bit-stuff or CRC error in the packet, the USB module returns to idle and waits for the next token packet. If the endpoint is isochronous and there was a bit-stuff or CRC error in the incoming data, the number of received data bytes, excluding CRC, is written to the endpoint CNT register. Finally, CRC and BUSNACK0 in the endpoint and STATUS and CRCIF in INTFLAGSASET/CLR are set. If data was successfully received, an ACK handshake is returned to the host if the endpoint is not isochronous, and the number of received data bytes, excluding CRC, is written to CNT. If the number of received data bytes is the maximum data payload specified by SIZE no CRC data are written in the data buffer. If the number of received data bytes is the maximum data payload specified by SIZE minus one, only the first CRC data byte is written in the data buffer If the number of received data bytes is equal or less than the data payload specified by SIZE minus two, the two CRC data bytes are written in the data buffer. Finally, the transaction complete flag (TRNCOMPL0) and BUSNACK0 are set and TOGGLE is toggled if the endpoint is not isochronous. The transaction complete interrupt flag (TRNIF) in INTFLAGSBCLR/SET is set. The endpoint's configuration table address is written to the FIFO if the transaction complete FIFO mode is enabled. OUT TOKEN ADDRESS ADDRESS MATCH? ENDPOINT LEGAL ENDPOINT? EP STATUS ENABLED? PID PID OK? DATA BIT STUFF BIT STUFF OK? CRC OK? ACK IDLE No No No No No STALL & ISO? STALL? STALL ISO? DATA No BUSNACK0 SET? NAK Yes No No No READ CONFIG UPDATE STATUS STORE DATA STORE DATA No Yes Yes Yes Yes Yes Yes Yes READ CONFIG PIDO/1 OK? NAK UPDATE STATUS No Yes DATA BIT STUFF CRC BIT STUFF OK? CRC OK? BUSNACK0 SET? CRC Yes No Yes Yes No Yes No Yes XMEGA B [MANUAL] 210 Atmel-8291C-AVR-XMEGA B -09/2014 When an OUT token is detected and the device address of the token packet does not match that of the endpoint, the packet is discarded and the USB module returns to idle and waits for the next token packet. 18.3.4 IN If an IN token is detected the, the USB module fetches the endpoint CTRL and STATUS register data from the addressed input endpoint in the endpoint configuration table. If the endpoint is disabled, the USB module returns to idle and waits for the next token packet. If the STALL flag in endpoint CTRL register is set, and the endpoint is not isochronous, a STALL handshake is returned to the host, the STALL flag in the endpoint STATUS register and the STALL interrupt flag (STALLIF) in INTFLAGSACLR/SET are set. If BUSNACK0 is set, OVF in the endpoint STATUS register and OVFIF in the INTFLAGSACLR/SET register are set. If the endpoint is not isochronous, a NAK handshake is returned to the host. The data in the data buffer pointed to by the endpoint DATAPTR register are sent to the host in a DATA0 packet if the endpoint is isochronous; otherwise, a DATA0 or DATA1 packet according to TOGGLE is sent. When the number of data bytes specified in endpoint CNT is sent, the CRC is appended and sent to the host. If not, a ZLP handshake is returned to the host. For isochronous endpoints, BUSNACK0 and TRNCOMPL0 in the endpoint STATUS register are set. TRNIF is set, and the endpoint's configuration table address is written to the FIFO if the transaction complete FIFO mode is enabled. For all non-isochronous endpoints, the USB module waits for an ACK handshake from the host. If an ACK handshake is not received within 16 USB clock cycles, the USB module returns to idle and waits for the next token packet. If an ACK handshake was successfully received, BUSNACK0 and TRNCOMPL0 are set and TOGGLE is toggled. TRNIF is set and the endpoint's configuration table address is written to the FIFO if the transaction complete FIFO mode is enabled. When an IN token is detected and the device address of the token packet does not match that of the endpoint, the packet is discarded and the USB module returns to idle and waits for the next token packet. Figure 18-5. IN transaction. IN TOKEN ADDRESS ADDRESS MATCH? ENDPOINT LEGAL ENDPOINT? EP STATUS ENABLED? DATA ACK PAYLOAD OK? IDLE No No No No STALL & NO ISO? STALL NAK No READ CONFIG READ DATA READ CONFIG UPDATE STATUS Yes Yes Yes Yes Yes BUSNACK0 SET? ISO? Yes No ISO? ACK SET? Yes No Yes Yes No No ZLP CRC XMEGA B [MANUAL] 211 Atmel-8291C-AVR-XMEGA B -09/2014 18.4 SRAM Memory Mapping The USB module uses internal SRAM to store the: z Endpoint configuration table z USB frame number z Transaction complete FIFO The endpoint pointer register (EPPTR) is used to set the SRAM address for the endpoint configuration table. The USB frame number (FRAMENUM) and transaction complete FIFO (FIFO) locations are derived from this. The locations of these areas are selectable inside the internal SRAM. Figure on page 211 gives the relative memory location of each area. Figure 18-6. SRAM memory mapping. 18.5 Clock Generation The USB module requires a minimum 6MHz clock for USB low speed operation, and a minimum 48MHz clock for USB full speed operation. It can be clocked from internal or external clock sources by using the internal PLL, or directly from the 32MHz internal oscillator when it is tuned and calibrated to 48MHz. The CPU and peripherals clocks must run at a minimum of 1.5MHz for low speed operation, and a minimum of 12MHz for full speed operation. The USB module clock selection is independent of and separate from the main system clock selection. Selection and setup are done using the main clock control settings. For details, refer to “System Clock and Clock Options” on page 75. The Figure 18-7 on page 212 shows an overview of the USB module clock selection. FIFO EP_ADDRH_MAX EP_ADDRL_0 EP_ADDRH_0 (MAXEP+1) x 4 Bytes Active when FIFOEN==1 ENDPOINT DESCRIPTORS TABLE STATUS CTRL CNTL CNTH DATAPTRL DATAPTRH AUXDATAL AUXDATAH ENDPOINT 0 OUT STATUS CTRL CNTL CNTH DATAPTRL DATAPTRH AUXDATAL AUXDATAH ENDPOINT 0 IN STATUS CTRL CNTL CNTH DATAPTRL DATAPTRH AUXDATAL AUXDATAH ENDPOINT MAXEP IN (MAXEP+1) x 16 Bytes FRAME NUMBER FRAMENUML FRAMENUMH 2 Bytes Active when STFRNUM==1 0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07 (MAXEP+1)<<4 EPPTR EPPTR + (MAXEP+1)*16 SRAM ADDRESS XMEGA B [MANUAL] 212 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 18-7. Clock generation configuration. 18.6 Ping-pong Operation When an endpoint is configured for ping-pong operation, it uses the input and output data buffers to create a single, double-buffered endpoint that can be set to input or output direction. This provides double-buffered communication, as the CPU or DMA controller can access one of the buffers, while the other buffer is processing an ongoing transfer. Pingpong operation is identical to the IN and OUT transactions described above, unless otherwise noted in this section. Pingpong operation is not possible for control endpoints. When ping-pong operation is enabled for an endpoint, the endpoint in the opposite direction must be disabled. The data buffer, data pointer, byte counter, and auxiliary data from the enabled endpoint are used as bank 0, and, correspondingly, bank 1 for the opposite endpoint direction. The bank select (BANK) flag in the endpoint STATUS register indicates which data bank will be used in the next transaction. It is updated after each transaction. The TRNCOMPL0/TRNCOMPL1, underflow/overflow (UDF/OVF), and CRC flags in the STATUS register are set for either the enabled or the opposite endpoint direction according to the BANK flag. The data toggle (TOGGLE), data buffer 0/1 not acknowledge (BUSNACK0 and BUSNACK1), and BANK flags are updated for the enabled endpoint direction only. Figure 18-8. Ping-pong operation overview. USB module 48MHz full speed 6MHz for low speed USBSRC USB clock prescaler USBPSDIV PLL 48MHz Internal Oscillator Bank0 Available time for data processing by CPU to avoid NACK Without Ping-Pong With Ping-Pong Bank1 Endpoint single bank Endpoint Double bank USB data packet t t XMEGA B [MANUAL] 213 Atmel-8291C-AVR-XMEGA B -09/2014 18.7 Multipacket Transfers Multipacket transfer enables a data payload exceeding the maximum data payload size of an endpoint to be transferred as multiple packets without any software intervention. This reduces interrupts and software intervention to the higher level USB transfer, and frees up significant CPU time. Multipacket transfer is identical to the IN and OUT transactions described above, unless otherwise noted in this section. The application software provides the size and address of the SRAM buffer to be processed by the USB module for a specific endpoint, and the USB module will then split the buffer in the required USB data transfer. Figure 18-9. Multipacket overview. 18.7.1 For Input Endpoints The total number of data bytes to be sent is written to CNT, as for normal operation. The auxiliary data register (AUXDATA) is used to store the number of bytes that will be sent, and must be written to zero for a new transfer. When an IN token is received, the endpoint’s CNT and AUXDATA are fetched. If CNT minus AUXDATA is less than the endpoint SIZE, endpoint CNT minus endpoint AUXDATA number bytes are transmitted; otherwise, SIZE number of bytes are transmitted. If endpoint CNT is a multiple of SIZE and auto zero length packet (AZLP) is enabled, the last packet sent will be zero length. If a maximum payload size packet was sent (i.e., not the last transaction), AUXDATA is incremented by SIZE. TOGGLE will be toggled after the transaction has completed if the endpoint is not isochronous. If a short packet was sent (i.e., the last transaction), AUXDATA is incremented by the data payload. TOGGLE will be toggled if the endpoint is not isochronous, and BUSNACK, TRNIF, and TRNCOMPL0 will be set. 18.7.2 For Output Endpoints The number of data bytes received is stored in the endpoint’s CNT register, as for normal operation. Since the endpoint’s CNT is updated after each transaction, it must be set to zero when setting up a new transfer. The total number of bytes to be received must be written to AUXDATA. This value must be a multiple of SIZE, except for ISO 1023 bytes endpoints; otherwise, excess data may be written to SRAM locations used by other parts of the application. TOGGLE management is as for non-isochronous packets, and BUSNACK0/BUSNACK1 management is as for normal operation. If a maximum payload size packet is received, CNT is incremented by SIZE after the transaction has completed, and TOGGLE toggles if the endpoint is not isochronous. If the updated endpoint CNT is equal to AUXDATA, then BUSNACK0/BUSNACK1, TRNIF, and TRNCOMPL0/TRNCOMPL1 will be set. If a short or oversized packet is received, the endpoint’s CNT register will be incremented by the data payload after the transaction has completed. TOGGLE will be toggled if the endpoint is not isochronous, and BUSNACK0/BUSNACK1, TRNIF, and TRNCOMPL0/TRNCOMPL1 will be set. Transfer Complete Interrupt and data processing Without multipacket With multipacket XMEGA B [MANUAL] 214 Atmel-8291C-AVR-XMEGA B -09/2014 18.8 Auto Zero Length Packet Some IN transfer requires a zero length packet to be generated in order to signal end of transfer to the host. The auto zero length packet (AZLP) function can be enabled to perform this generation automatically, thus removing the need for application software or CPU intervention to perform this task. 18.9 Transaction Complete FIFO The transaction complete FIFO provides a convenient way to keep track of the endpoints that have completed IN or OUT transactions and need firmware intervention. It creates a first-come, first-served work queue for the application software. The FIFO size is (MAXEP[3:0] + 1) × 4 bytes, and grows downward, starting from EPPTR - 1. This SRAM memory is allocated only when the FIFO is enabled. Figure 18-10.Transfer complete FIFO. To manage the FIFO, a five-bit write pointer (FIFOWP) and five-bit read pointer (FIFORP) are used by the USB module and application software, respectively. FIFORP and FIFOWP are one's complemented, and thus hold negative values. The SRAM location of the data is the sum of EPPTR and the read or write pointer. The number of items in the FIFO is the difference between FIFOWP and FIFORP. For the programmer, the FIFORP and FIFOWP values have to be cast to a signed 8-bit integer, and then the offset into the FIFO from this signed integer must be deducted. The transaction complete interrupt flag (TRNIF) in the INFLAGSB[CLR,SET] register is set to indicate a non-empty FIFO when FIFORP != FIFOWP, cleared when they are equal, and also set when the FIFO is full. Each time an endpoint IN or OUT transaction completes successfully, its endpoint configuration table address is stored in the FIFO at the current write pointer position (i.e., EPPTR + 2 × FIFOWP) and FIFOWP is decremented. When the pointer reaches the FIFO size, it wraps to zero. When application software reads FIFORP, this is decremented in the same way. Reading the write pointer has no effect. The endpoint configuration table address can then be read directly from (EPPTR + 2 × FIFORP). Figure 18-11.USB transaction complete FIFO example. USB_TC_ FIFO TC_EP_ ADDRH_0 TC_EP_ ADDRL_0 TC_EP_ ADDRH_ MAX ENDPOINT DESCRIPTOR TABLE TC_EP_ ADDRH_1 TC_EP_ ADDRL_1 INTERNAL SRAM TC_EP_ ADDRH_2 TC_EP_ ADDRH_2 FIFOWP FIFORP EPPTR SRAM ADDRESS EPPTR – 4x( MAXEP+1) Ep X EpY EpZ t FIFO X Y Z FIFOWP FIFORP FIFO X Y FIFOWP FIFORP FIFO X FIFOWP FIFORP FIFO FIFOWP FIFORP XMEGA B [MANUAL] 215 Atmel-8291C-AVR-XMEGA B -09/2014 18.10 Interrupts and Events The USB module can generate interrupts and events. The module has 10 interrupt sources. These are split between two interrupt vectors, the transaction complete (TRNCOMPL) interrupt and the bus event (BUSEVENT) interrupt. An interrupt group is enabled by setting its interrupt level (INTLVL), while different interrupt sources are enabled individually or in groups. Figure 18-12 on page 215 summarizes the interrupts and event sources for the USB module, and shows how they are enabled. Figure 18-12.Interrupts and events scheme summary. 18.10.1 Transaction Complete Interrupt The transaction complete interrupt is generated per endpoint. When an interrupt occurs, the associated endpoint number is registered and optionally added to the FIFO. The following two interrupt sources use the interrupt vector: SUSPENDIF SOFIE RESUMEIF RSTIF CRCIF UNFIF OVFIF STALLIF BSEVIE STALLIE BUSSERRIE SOFIF SETUPIE TRNIF TRNIE SETUPIF Busevent Interrupt request Transaction Complete Interrupt request XMEGA B [MANUAL] 216 Atmel-8291C-AVR-XMEGA B -09/2014 Table 18-1. Transaction complete interrupt sources. 18.10.2 Bus Event Interrupt The bus event (BUSEVENT) interrupt is used for all interrupts that signal various types of USB line events or error conditions. These interrupts are related to the USB lines, and are generated for the USB module and per endpoint. The following eight interrupts use the interrupt vector: Table 18-2. Bus event interrupt source. 18.10.3 Events The USB module can generate several events, and these are available to the event system, allowing latency-free signaling to other peripherals or performance analysis of USB operation. Table 18-3. Event sources. 18.11 VBUS Detection Atmel AVR XMEGA devices can use any general purpose I/O pin to implement a VBUS detection function, and do not use a dedicated VBUS detect pin. Interrupt source Description Transfer complete (TRNIF) An IN or OUT transaction is completed Setup complete (SETUPIF) A SETUP transaction is completed Interrupt source Description Start of frame (SOFIF) A SOF token has been received Suspend (SUSPENDIF) The bus has been idle for 3ms Resume (RESUMEIF) A non-idle state is detected when the bus is suspended. The interrupt is asynchronous and can wake the device from all sleep modes Reset (RSTIF) A reset condition has been detected on the bus Isochronous CRC error (CRCIF) A CRC or bit-stuff error has been detected in an incoming packet to an isochronous endpoint Underflow (UNFIF) An endpoint is unable to return data to the host Overflow (OVFIF) An endpoint is unable to accept data from the host STALL (STALLIF) A STALL handshake has been returned to the host Event source Description SETUP SETUPIF Start of Frame SOFIF CRC error CRCIF Underflow/overflow UNFIF and OVFIF XMEGA B [MANUAL] 217 Atmel-8291C-AVR-XMEGA B -09/2014 18.12 On-chip Debug When a break point is reached during on-chip debug (OCD) sessions, the CPU clock can be below 12MHz. If this happens, the USB module will behave as follows: USB OCD break mode disabled: The USB module immediately acknowledges any OCD break request. The USB module will not be able to follow up on transactions received from the USB host, and its behaviour from the host point of view is not predictable. USB OCD break mode enabled: The USB module will immediately acknowledge any OCD break request only if there are no ongoing USB transactions. If there is an ongoing USB transaction, the USB module will acknowledge any OCD break request only when the ongoing USB transaction has been completed. The USB module will NACK any further transactions received from the USB host, whether they are SETUP, IN (ISO, BULK), or OUT (ISO, BULK). XMEGA B [MANUAL] 218 Atmel-8291C-AVR-XMEGA B -09/2014 18.13 Register Description – USB 18.13.1 CTRLA – Control register A z Bit 7 – ENABLE: USB Enable Setting this bit enables the USB interface. Clearing this bit disables the USB interface and immediately aborts any ongoing transactions. z Bit 6 – SPEED: Speed Select This bit selects between low and full speed operation. By default, this bit is zero, and low speed operation is selected. Setting this bit enables full speed operation. z Bit 5 – FIFOEN: USB FIFO Enable Setting this bit enables the USB transaction complete FIFO, and the FIFO stores the endpoint configuration table address of each endpoint that generates a transaction complete interrupt. Clearing this bit disables the FIFO and frees the allocated SRAM memory. z Bit 4 – STFRNUM: Store Frame Number Enable Setting this bit enables storing of the last SOF token frame number in the frame number (FRAMENUM) register. Clearing this bit disables the function. z Bit 3:0 – MAXEP[3:0]: Maximum Endpoint Address These bits select the number of endpoint addresses used by the USB module. Incoming packets with a higher endpoint number than this address will be discarded. Packets with endpoint addresses lower than or equal to this address will cause the USB module to look up the addressed endpoint in the endpoint configuration table. 18.13.2 CTRLB – Control register B z Bit 7:5 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 4 – PULLRST: Pull during Reset Setting this bit enables the pull-up on the USB lines to also be held when the device enters reset. The bit will be cleared on a power-on reset. z Bit 3 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. Bit 7 6 5 4 3 2 1 0 +0x00 ENABLE SPEED FIFOEN STFRNUM MAXEP[3:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x01 – – – PULLRST – RWAKEUP GNACK ATTACH Read/Write R R R R/W R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 219 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 2 – RWAKEUP: Remote Wake-up Setting this bit sends an upstream resume on the USB lines if the bus is in the suspend state for at least 5 ms. z Bit 1 – GNACK: Global NACK When this bit is set, the USB module will NACK all incoming transactions. Expect for a SETUP packet, this prevents the USB module from performing any on-chip SRAM access, giving all SRAM bandwidth to the CPU and/or DMA controller. z Bit 0 – ATTACH: Attach Setting this bit enables the internal D+ or D- pull-up (depending on the USB speed selection), and attaches the device to the USB lines. Clearing this bit disconnects the device from the USB lines. 18.13.3 STATUS – Status register z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3 – URESUME: Upstream Resume This flag is set when an upstream resume is sent. z Bit 2 – RESUME: Resume This flag is set when a downstream resume is received. z Bit 1 – SUSPEND: Bus Suspended This flag is set when the USB lines are in the suspended state (the bus has been idle for at least 3ms). z Bit 0 – BUSRST: Bus Reset This flag is set when a reset condition has been detected (the bus has been driven to SE0 for at least 2.5μs). 18.13.4 ADDR – Address register z Bit 7 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 6:0 – ADDR[6:0]: Device Address These bits contain the USB address the device will respond to. Bit 7 6 5 4 3 2 1 0 +0x02 – – – – URESUME RESUME SUSPEND BUSRST Read/Write RRRRRRRR Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x03 – ADDR[6:0] Read/Write R R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 XMEGA B [MANUAL] 220 Atmel-8291C-AVR-XMEGA B -09/2014 18.13.5 FIFOWP – FIFO Write Pointer register z Bit 7:5 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 4:0 – FIFOWP[4:0]: FIFO Write Pointer These bits contain the transaction complete FIFO write pointer. This register must be read only by the CPU or DMA controller. Writing this register will flush the FIFO write and read pointers. 18.13.6 FIFORP – FIFO Read Pointer register z Bit 7:5 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 4:0 – FIFORP[4:0]: FIFO Read Pointer These bits contain the transaction complete FIFO read pointer. This register must only be read by the CPU or DMA controller. Writing this register will flush the FIFO write and read pointer. 18.13.7 EPPTRL – Endpoint Configuration Table Pointer Low The EPPTRL and EPPTRH registers represent the 16-bit value, EPPTR, that contains the address to the endpoint configuration table. The pointer to the endpoint configuration table must be aligned to a 16-bit word; i.e., EPPTR[0] must be zero. Only the number of bits required to address the available internal SRAM memory is implemented for each device. Unused bits will always be read as zero. z Bit 7:0 – EPPTR[7:0]: Endpoint Configuration Table Pointer low byte This register contains the eight lsbs of the endpoint configuration table pointer (EPPTR). Bit 7 6 5 4 3 2 1 0 +0x04 – – – FIFOWP[4:0] Read/Write R R R R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x05 – – – FIFORP[4:0] Read/Write R R R R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x06 EPPTR[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 221 Atmel-8291C-AVR-XMEGA B -09/2014 18.13.8 EPPTRH – Endpoint Configuration Table Pointer High z Bit 7:0 – EPPTR[15:8]: Endpoint Configuration Table Pointer high byte This register contains the eight msbs of the endpoint configuration table pointer (EPPTR). 18.13.9 INTCTRLA – Interrupt Control register A z Bit 7 – SOFIE: Start Of Frame Interrupt Enable Setting this bit enables the start of frame (SOF) interrupt for the conditions that set the start of frame interrupt flag (SOFIF) in the INTFLAGSACLR/ INTFLAGSASET register. The INTLVL bits must be nonzero for the interrupts to be generated. z Bit 6 – BUSEVIE: Bus Event Interrupt Enable Setting this bit will enable the interrupt for the following three bus events: 1. Suspend: An interrupt will be generated for the conditions that set the suspend interrupt flag (SUSPENDIF) in the INTFLAGSACLR/SET register. 2. Resume: An interrupt will be generated for the conditions that set the resume interrupt flag (RESUMEIF) in the INTFLAGSACLR/SET register. 3. Reset: An interrupt will be generated for the conditions that set the reset interrupt flag (RESETIF) in the INTFLAGSACLR/SET register. The INTLVL bits must be nonzero for the interrupts to be generated. z Bit 5 – BUSERRIE: Bus Error Interrupt Enable Setting this bit will enable the interrupt for the following three bus error events: 1. Isochronous CRC Error: An interrupt will be generated for the conditions that set the CRC interrupt flag (CRCIF) in the INTFLAGSACLR/SET register during isochronous transfers. 2. Underflow: An interrupt will be generated for the conditions that set the underflow interrupt flag (UNFIF) in the INTFLAGSACLR/SET register. 3. Overflow: An interrupt will be generated for the conditions that set the overflow interrupt flag (OVFIF) in the INTFLAGSACLR/SET register. The INTLVL bits must be nonzero for the interrupts to be generated. z Bit 4 – STALLIE: STALL Interrupt Enable Setting this bit enables the STALL interrupt for the conditions that set the stall interrupt flag (STALLIF) in the INTFLAGSACLR/SET register. The INTLVL bits must be nonzero for the interrupts to be generated. Bit 7 6 5 4 3 2 1 0 +0x07 EPPTR[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x06 SOFIE BUSEVIE BUSERRIE STALLIE – – INTLVL[1:0] 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 XMEGA B [MANUAL] 222 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 3:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1:0 – INTLVL[1:0]: Interrupt Level These bits enable the USB interrupts and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. In addition, each USB interrupt source must be separately enabled. 18.13.10INTCTRLB – Interrupt Control register B z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1 – TRNIE: Transaction Complete Interrupt Enable Setting this bit enables the transaction complete interrupt for IN and OUT transactions. The INTLVL bits must be nonzero for interrupts to be generated. z Bit 0 – SETUPIE: SETUP Transaction Complete Interrupt Enable Setting this bit enables the SETUP Transaction Complete Interrupt for SETUP transactions. The INTLVL bits must be non-zero for the interrupts to be generated. 18.13.11INTFLAGSACLR/ INTFLAGSASET – Clear/ Set Interrupt Flag register A This register is mapped into two I/O memory locations, one for clearing (INTFLAGSACLR) and one for setting (INTFLAGSASET) the flags. The individual flags can be set by writing a one to their bit locations in INFLAGSASET, and cleared by writing a one to their bit locations in INT-FLAGSACLR. Both memory locations will provide the same result when read, and writing zero to any bit location has no effect. z Bit 7 – SOFIF: Start Of Frame Interrupt Flag This flag is set when a start of frame packet has been received. z Bit 6 – SUSPENDIF: Suspend Interrupt Flag This flag is set when the bus has been idle for 3ms. z Bit 5 – RESUMEIF: Resume Interrupt Flag This flag is set when a non-idle state has been detected on the bus while the USB module is in the suspend state. This interrupt is asynchronous, and is able to wake the CPU from sleep modes where the system clock is stopped, such as power-down and power-save sleep modes. z Bit 4 – RSTIF: Reset Interrupt Flag This flag is set when a reset condition has been detected on the bus. Bit 7 6 5 4 3 2 1 0 +0x07 – – – – – – TRNIE SETUPIE Read/Write R R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x0A/ +0x0B SOFIF SUSPENDIF RESUMEIF RESETIF CRCIF UNFIF OVFIF STALLIF 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 XMEGA B [MANUAL] 223 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 3 – CRCIF: Isochronous CRC Error Interrupt Flag This flag is set when a CRC error has been detected in an incoming data packet to an isochronous endpoint. z Bit 2 – UNFIF: Underflow Interrupt Flag This flag is set when the addressed endpoint in an IN transaction does not have data to send to the host. z Bit 1 – OVFIF: Overflow Interrupt Flag This flag is set when the addressed endpoint in an OUT transaction is not ready to accept data from the host. z Bit 0 – STALLIF: STALL Interrupt Flag This flag is set when the USB module has responded with a STALL handshake to either an IN or an OUT transaction. 18.13.12INTFLAGSBCLR/INTFLAGSBSET – Clear/Set Interrupt Flag register B This register is mapped into two I/O memory locations, one for clearing (INTFLAGSBCLR) and one for setting (INTFLAGSBSET) the flags. The individual flags can be set by writing a one to their bit locations in INFLAGSBSET, and cleared by writing a one to their bit locations in INTFLAGSBCLR. Both memory locations will provide the same result when read, and writing zero to any bit location has no effect. z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1 – TRNIF: Transaction Complete Interrupt Flag This flag is when there is a pending packet interrupt in the FIFO. z Bit 0 – SETUPIF: SETUP Transaction Complete Interrupt Flag This flag is set when a SETUP transaction has completed successfully. 18.13.13CALL – Calibration register Low CALL and CALH hold the 16-bit value, CAL. The USB PADs (D- and D+) are calibrated during production to enable operation without requiring external components on the USB lines. The calibration value is stored in the signature row of the device, and must be read from there and written to the CAL registers from software. z Bit 7:0 – CAL[7:0]: PAD Calibration low byte This byte holds the eight lsbs of CAL. Bit 7 6 5 4 3 2 1 0 +0x0C/ +0x0D – – – – – –- TRNIF SETUPIF Read/Write R R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 ++0x3A CAL[7:0] 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 XMEGA B [MANUAL] 224 Atmel-8291C-AVR-XMEGA B -09/2014 18.13.14CALH – Calibration register High z Bit 7:0 – CAL[15:8]: PAD Calibration high byte This byte holds the eight msbs of CAL. Bit 7 6 5 4 3 2 1 0 +0x3B CAL[15:8] 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 XMEGA B [MANUAL] 225 Atmel-8291C-AVR-XMEGA B -09/2014 18.14 Register Description – USB Endpoint Each of the 16 endpoint addresses have one input and one output endpoint. Each endpoint has eight bytes of configuration/status data located in internal SRAM. The address to the first configuration byte is (EPPTR[15:0] + 16 × endpoint address) for output endpoints and (EPPTR[15:0] + 16 × endpoint address + 8) for input endpoints. Some bit locations have different functions, depending on endpoint configuration type or direction, and this is reflected by using two different names for the bit locations. 18.14.1 STATUS – Status register Note: 1. For isochronous endpoints. z Bit 7 – STALL: STALL Flag This flag is set when an IN or OUT transaction has been responded to with a STALL handshake. This flag is cleared by writing a one to its bit location. z Bit 7 – CRC: CRC Error Flag This flag is set for isochronous output endpoints when a CRC error has been detected in an incoming data packet. This flag is cleared by writing a one to its bit location. z Bit 6 – UNF/OVF: Underflow/Overflow Flag UNF: For input endpoints, the UNF flag is set when an input endpoint is not ready to send data to the host in response of an IN token. OVF: For output endpoints, the OVF flag is set when an output endpoint is not ready to accept data from the host following an OUT token. z Bit 5 – TRNCOMPL0: Transaction Complete Flag This flag is set when an IN or OUT transaction has completed successfully. This flag is cleared by writing a one to its bit location. z Bit 4 – SETUP: SETUP Transaction Complete Flag This flag is set when a SETUP, IN, or OUT transaction has completed successfully. This flag is cleared by writing a one to its bit location. z Bit 4 – TRNCOMPL1: Transaction Complete Flag This flag is set when a SETUP, IN, or OUT transaction has completed successfully. This flag is cleared by writing a one to its bit location. z Bit 3 – BANK: Bank Select Flag When ping-pong mode is enabled, this bit indicates which bank will be used for the next transaction. BANK is toggled each time a transaction has completed successfully. This bit is not sed when ping-pong is disabled. This flag is cleared by writing a one to its bit location. z Bit 2 – BUSNACK1: Data Buffer 1 Not Acknowledge Flag When this flag is set, the USB module will discard incoming data to data buffer 1 in an OUT transaction, and will not return any data from data buffer 1 in an IN transaction. For control, bulk, and interrupt endpoints, a NAK handshake is returned. This flag is cleared by writing a one to its bit location. Bit 7 6 5 4 3 2 1 0 +0x00 STALL UNF/ OVF TRNCOMPL0 SETUP BANK BUSNACK1 BUSNACK0 TOGGLE CRC(1) TRNCOMPL1 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 XMEGA B [MANUAL] 226 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 1 – BUSNACK0: Data Buffer 0 Not Acknowledge Flag When this flag is set, the USB module will discard incoming data to data buffer 0 in an OUT transaction, and will not return any data from data buffer 0 in an IN transaction. For control, bulk, and interrupt endpoints, a NAK handshake is returned. This flag is cleared by writing a one to its bit location. z Bit 0 – TOGGLE: Data Toggle Flag This indicates if a DATA0 or DATA1 PID is expected in the next data packet for an output endpoint, and if a DATA0 or DATA1 PID will be sent in the next transaction for an input endpoint. This bit has no effect for isochronous endpoints, where both DATA0 and DATA1 PIDs are accepted for output endpoint, and only DATA0 PIDs are sent for input endpoints. 18.14.2 CTRL – Control Note: 1. For isochronous endpoints. z Bit 7:6 – TYPE[1:0]: Endpoint Type These bits are used to enable and select the endpoint type. If the endpoint is disabled, the remaining seven endpoint configuration bytes are never read or written by the USB module, and their SRAM locations are free to use for other application data. Table 18-4. Endpoint type. z Bit 5 – MULTIPKT: Multipacket Transfer Enable Setting this bit enables multipacket transfers. Multipacket transfer enables a data payload exceeding the maximum packet size of an endpoint to be transferred as multiple packets without interrupts or software intervention. See “Multipacket Transfers” on page 213 for details on multipacket transfers. z Bit 4 – PINGPONG: Ping-pong Enable Setting this bit enables ping-pong operation. Ping-pong operation enables both endpoints (IN and OUT) with same address to be used in the same direction to allow double buffering and maximize throughput. The endpoint in the opposite direction must be disabled when ping-pong operation is enabled. Ping-pong operation is not possible for control endpoints. See “Ping-pong Operation” on page 212 for details. z Bit 3 – INTDSBL: Interrupt Disable Setting this bit disables all enabled interrupts from the endpoint. Hence, only the interrupt flags in the STATUS register are updated when interrupt conditions occur. The FIFO does not store this endpoint configuration table address upon transaction complete for the endpoint when interrupts are disabled for an endpoint. Clearing this bit enables all previously enables interrupts again. Bit 7 6 5 4 3 2 1 0 +0x01 TYPE[1:0] MULTIPKT PINGPONG INTDSBL STALL SIZE[1:0] SIZE[2:0](1) 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 TYPE[1:0] Group Configuration Description 00 DISABLE Endpoint enabled 01 CONTROL Control 10 BULK Bulk/interrupt 11 ISOCHRONOUS Isochronous XMEGA B [MANUAL] 227 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 2 – STALL: Endpoint STALL This bit controls the STALL behavior if the endpoint. z Bit 1:0 – BUFSIZE[1:0]: Data Size These bits configure the maximum data payload size for the endpoint. Incoming data bytes exceeding the maximum data payload size are discarded. z Bit 2:0 – BUFSIZE[2:0]: Data Size These bits configure the maximum data payload size for the endpoint when configured for isochronous operation. Table 18-5. BUFSIZE configuration Note: 1. Setting only available for isochronous endpoints. 18.14.3 CNTL – Counter Low register The CNTL and CNTH registers represent the 10-bit value, CNT, that contains the number of bytes received in the last OUT or SETUP transaction for an OUT endpoint, or the number of bytes to be sent in the next IN transaction for an IN endpoint. z Bit 7:0 – CNT[7:0]: Endpoint Byte Counter This byte contains the eight lsbs of the USB endpoint counter (CNT). BUFSIZE[2:0] Group Configuration Description 000 8 8-byte buffer size 001 16 16-byte buffer size 010 32 32-byte buffer size 011 64 64-byte buffer size 100(1) 128 128-byte buffer size 101(1) 256 256-byte buffer size 110(1) 512 512-byte buffer size 111(1) 1023 1023-byte buffer size Bit 7 6 5 4 3 2 1 0 +0x02 CNT[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value XXXXXXXX XMEGA B [MANUAL] 228 Atmel-8291C-AVR-XMEGA B -09/2014 18.14.4 CNTH – Counter High register z Bit 6 – AZLP: Automatic Zero Length Packet When this bit is set, the USB module will manage the ZLP handshake by hardware. This applies to IN endpoints only. When this bit is zero, the ZLP handshake must be managed by firmware. z Bit 6:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1:0 – CNT[9:8]: Endpoint Byte Counter These bits contain the two msbs of the USB endpoint counter (CNT). 18.14.5 DATAPTRL – Data Pointer Low register The DATAPTRL and DATAPTRH registers represent the 16-bit value, DATAPTR, that contains the SRAM address to the endpoint data buffer. z Bit 7:0 – DATAPTR[7:0]: Endpoint Data Pointer Low This byte contains the eight lsbs of the endpoint data pointer (DATAPTR). 18.14.6 DATAPTRH – Data Pointer High register z Bit 15:0 - DPTR[15:8]: Endpoint Data Pointer High This byte contains the eight msbs of the endpoint data pointer (DATAPTR). Bit 7 6 5 4 3 2 1 0 +0x03 AZLP – – – – – CNT[9:8] Read/Write R/W R R R R R R/W R/W Initial Value X X X X X X X X Bit 7 6 5 4 3 2 1 0 +0x04 DATAPTR[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value X X X X X X X X Bit 7 6 5 4 3 2 1 0 +0x05 DATAPTR[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value X X X X X X X X XMEGA B [MANUAL] 229 Atmel-8291C-AVR-XMEGA B -09/2014 18.14.7 AUXDATAL – Auxiliary Data Low register The AUXDATAL and AUXDATAH registers represent the 16-bit value, AUXDATA, that is used for multipacket transfers. For IN endpoints, AUXDATA holds the total number of bytes sent. AUXDATA should be written to zero when setting up a new transfer. For OUT endpoints, AUXDATA holds the total data size for the complete transfer. This value must be a multiple of the maximum packet size, except for ISO 1023-byte endpoints. See “Multipacket Transfers” on page 213 for more details on setting up and using multipacket transfers. z Bit 7:0 – AUXDATA[7:0]: Auxiliary Data Low This byte contains the eight lsbs of the auxiliary data (AUXDATA). When multipacket transfer is not used, this SRAM location is free to use for other application data. 18.14.8 AUXDATAH – Auxiliary Data High register z Bit 7:0 – AUXDATA[15:8]: Auxiliary Data High This byte contains the eight msbs of the auxiliary data (AUXDATA). When multipacket transfer is not used, this SRAM location is free to use for other application data. Bit 7 6 5 4 3 2 1 0 +0x06 AUXDATA[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value X X X X X X X X Bit 7 6 5 4 3 2 1 0 +0x07 AUXDATA[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value X X X X X X X X XMEGA B [MANUAL] 230 Atmel-8291C-AVR-XMEGA B -09/2014 18.15 Register Description - Frame 18.15.1 FRAMENUML – Frame Number Low register The FRAMENUML and FRAMENUMH registers represent the 11-bit value, FRAMENUM, that holds the frame number from the most recently received start of frame packet. z Bit 7:0 – FRAMENUM[7:0]: Frame Number This byte contains the eight lsbs of the frame number (FRAMENUM). 18.15.2 FRAMENUMH – Frame Number High register z Bit 7 – FRAMEERR: Frame Error This flag is set if a CRC or bit-stuffing error was detected in the most recently received start of frame packet. z Bit 6:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2:0 – FRAMENUM[10:8]: Frame Number This byte contains the three msbs of the frame number (FRAMENUM). Bit 7 6 5 4 3 2 1 0 +0x00 FRAMENUM[7:0] Read/Write R R R R R R R R Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x01 FRAMEERR – – – – FRAMENUM[10:8] Read/Write R R R R R R R R Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 231 Atmel-8291C-AVR-XMEGA B -09/2014 18.16 Register Summary – USB Module 18.17 Register Summary – USB Endpoint The address to the first configuration byte is (EPPTR[15:0] + 16 × endpoint address) for OUT endpoints and (EPPTR[15:0] + 16 × endpoint address + 8) for IN endpoints. 18.18 Register Summary – Frame The address to the frame configuration byte is (MAXEP + 1) << 4. For instance with MAXEP = 3, the first address would be located at offset address 0x40. 18.19 USB Interrupt Vector Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRLA ENABLE SPEED FIFOEN STFRNUM MAXEP[3:0] 218 +0x01 CTRLB – – – PULLRST – RWAKEUP GNACK ATTACH 218 +0x02 STATUS – – – – UPRESUM RESUME SUSPEND BUSRST 219 +0x03 ADDR – ADDR[6:0] 219 +0x04 FIFOWP – – – FIFOWP[4:0] 220 +0x05 FIFORP – – – FIFORP[4:0] 220 +0x06 EPPTRL EPPTR[7:0] 220 +0x07 EPPTRH EPPTR[15:8] 221 +0x08 INTCTRLA SOFIE BUSEVIE BUSERRIE STALLIE – – INTLVL[1:0] 221 +0x09 INTCTRLB – – – – – – TRNIE SETUPIE 222 +0x0A INFLAGSACL SOFIF SUSPENDI RESUMEIF RSTIF CRCIF UNFIF OVFIF STALLIF 222 +0x0B INFLAGSASE SOFIF SUSPENDI RESUMEIF RSTIF CRCIF UNFIF OVFIF STALLIF 222 +0x0C INFLAGSBCL – – – – – – TRNIF SETUPIF 223 +0x0D INFLAGSBSE – – – – – – TRNIF SETUPIF 223 +0x0E Reserved – – – – – – – – +0x0F Reserved – – – – – – – – +0x10-0X39 Reserved – – – – – – – – +0x3A CALL CAL[7:0] 223 +0x3B CALH CAL[15:8] 224 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 STATUS STALL OVF/UNF TRNCOMP L0 SETUP BANK BUSNACK1 BUSNACK0 TOGGLE 225 CRC TRNCOMP Isochronous +0x01 CTRL TYPE[1:0] MULTIPKT PINGPONG INTDSB L STALL BUFSIZE[1:0] 226 BUFSIZE[2:0] Isochronous +0x02 CNTL CNT[7:0] 227 +0x03 CNTH AZLP – – – – – CNT[9:8] 228 +0x04 DATAPTR DATAPTR[7:0] 228 +0x05 DATAPTR DATAPTR[15:8] 228 +0x06 AUXDATA AUXDATA[7:0] 229 +0x07 AUXDATA AUXDATA[15:8] 229 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 FRAMENUM FRAMENUM[7:0] 230 +0x01 FRAMENUM FRAMEER – – – – FRAMENUM[10:8] 230 Offset Source Interrupt Description 0x00 BUSEVENT_vect SOF, suspend, resume, bus reset, CRC, underflow, overflow, and stall error interrupts 0x02 TRNCOMPL_vect Transaction complete interrupt XMEGA B [MANUAL] 232 Atmel-8291C-AVR-XMEGA B -09/2014 19. TWI – Two-Wire Interface 19.1 Features z Bidirectional, two-wire communication interface z Phillips I2 C compatible z System Management Bus (SMBus) compatible z Bus master and slave operation supported z Slave operation z Single bus master operation z Bus master in multi-master bus environment z Multi-master arbitration z Flexible slave address match functions z 7-bit and general call address recognition in hardware z 10-bit addressing supported z Address mask register for dual address match or address range masking z Optional software address recognition for unlimited number of addresses z Slave can operate in all sleep modes, including power-down z Slave address match can wake device from all sleep modes z 100kHz and 400kHz bus frequency support z Slew-rate limited output drivers z Input filter for bus noise and spike suppression z Support arbitration between start/repeated start and data bit (SMBus) z Slave arbitration allows support for address resolve protocol (ARP) (SMBus) 19.2 Overview The two-wire interface (TWI) is a bidirectional, two-wire communication interface. It is I2 C and System Management Bus (SMBus) compatible. The only external hardware needed to implement the bus is one pull-up resistor on each bus line. A device connected to the bus must act as a master or a slave. The master initiates a data transaction by addressing a slave on the bus and telling whether it wants to transmit or receive data. One bus can have many slaves and one or several masters that can take control of the bus. An arbitration process handles priority if more than one master tries to transmit data at the same time. Mechanisms for resolving bus contention are inherent in the protocol. The TWI module supports master and slave functionality. The master and slave functionality are separated from each other, and can be enabled and configured separately. The master module supports multi-master bus operation and arbitration. It contains the baud rate generator. Both 100kHz and 400kHz bus frequency is supported. Quick command and smart mode can be enabled to auto-trigger operations and reduce software complexity. The slave module implements 7-bit address match and general address call recognition in hardware. 10-bit addressing is also supported. A dedicated address mask register can act as a second address match register or as a register for address range masking. The slave continues to operate in all sleep modes, including power-down mode. This enables the slave to wake up the device from all sleep modes on TWI address match. It is possible to disable the address matching to let this be handled in software instead. The TWI module will detect START and STOP conditions, bus collisions, and bus errors. Arbitration lost, errors, collision, and clock hold on the bus are also detected and indicated in separate status flags available in both master and slave modes. It is possible to disable the TWI drivers in the device, and enable a four-wire digital interface for connecting to an external TWI bus driver. This can be used for applications where the device operates from a different VCC voltage than used by the TWI bus. XMEGA B [MANUAL] 233 Atmel-8291C-AVR-XMEGA B -09/2014 19.3 General TWI Bus Concepts The TWI provides a simple, bidirectional, two-wire communication bus consisting of a serial clock line (SCL) and a serial data line (SDA). The two lines are open-collector lines (wired-AND), and pull-up resistors (Rp) are the only external components needed to drive the bus. The pull-up resistors provide a high level on the lines when none of the connected devices are driving the bus The TWI bus is a simple and efficient method of interconnecting multiple devices on a serial bus. A device connected to the bus can be a master or slave, where the master controls the bus and all communication. Figure 19-1 on page 233 illustrates the TWI bus topology. Figure 19-1. TWI bus topology. A unique address is assigned to all slave devices connected to the bus, and the master will use this to address a slave and initiate a data transaction. Several masters can be connected to the same bus, called a multi-master environment. An arbitration mechanism is provided for resolving bus ownership among masters, since only one master device may own the bus at any given time. A device can contain both master and slave logic, and can emulate multiple slave devices by responding to more than one address. A master indicates the start of a transaction by issuing a START condition (S) on the bus. An address packet with a slave address (ADDRESS) and an indication whether the master wishes to read or write data (R/W) are then sent. After all data packets (DATA) are transferred, the master issues a STOP condition (P) on the bus to end the transaction. The receiver must acknowledge (A) or not-acknowledge (A) each byte received. Figure 19-2 on page 234 shows a TWI transaction. TWI DEVICE #1 RP RP RS RS SDA SCL VCC TWI DEVICE #2 RS RS TWI DEVICE #N RS RS Note: RS is optional XMEGA B [MANUAL] 234 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 19-2. Basic TWI transaction diagram topology for a 7-bit address bus. The master provides the clock signal for the transaction, but a device connected to the bus is allowed to stretch the lowlevel period of the clock to decrease the clock speed. 19.3.1 Electrical Characteristics The TWI module in XMEGA devices follows the electrical specifications and timing of I2 C bus and SMBus. These specifications are not 100% compliant, and so to ensure correct behavior, the inactive bus timeout period should be set in TWI master mode. Refer to “TWI Master Operation” on page 239 for more details. 19.3.2 START and STOP Conditions Two unique bus conditions are used for marking the beginning (START) and end (STOP) of a transaction. The master issues a START condition (S) by indicating a high-to-low transition on the SDA line while the SCL line is kept high. The master completes the transaction by issuing a STOP condition (P), indicated by a low-to-high transition on the SDA line while SCL line is kept high. Figure 19-3. START and STOP conditions. Multiple START conditions can be issued during a single transaction. A START condition that is not directly following a STOP condition is called a repeated START condition (Sr). 19.3.3 Bit Transfer As illustrated by Figure 19-4, a bit transferred on the SDA line must be stable for the entire high period of the SCL line. Consequently the SDA value can only be changed during the low period of the clock. This is ensured in hardware by the TWI module. S ADDRESS P 6 ... 0 R/W ACK ACK 7 ... 0 DATA ACK/NACK 7 ... 0 DATA SDA SCL S ADDRESS R/W A DATA A DATA A/A P Address Packet Data Packet #0 Transaction Data Packet #1 Direction The slave provides data on the bus The master provides data on the bus The master or slave can provide data on the bus SDA SCL START Condition STOP Condition S P XMEGA B [MANUAL] 235 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 19-4. Data validity. Combining bit transfers results in the formation of address and data packets. These packets consist of eight data bits (one byte) with the most-significant bit transferred first, plus a single-bit not-acknowledge (NACK) or acknowledge (ACK) response. The addressed device signals ACK by pulling the SCL line low during the ninth clock cycle, and signals NACK by leaving the line SCL high. 19.3.4 Address Packet After the START condition, a 7-bit address followed by a read/write (R/W) bit is sent. This is always transmitted by the master. A slave recognizing its address will ACK the address by pulling the data line low for the next SCL cycle, while all other slaves should keep the TWI lines released and wait for the next START and address. The address, R/W bit, and acknowledge bit combined is the address packet. Only one address packet for each START condition is allowed, also when 10-bit addressing is used. The R/W bit specifies the direction of the transaction. If the R/W bit is low, it indicates a master write transaction, and the master will transmit its data after the slave has acknowledged its address. If the R/W bit is high, it indicates a master read transaction, and the slave will transmit its data after acknowledging its address. 19.3.5 Data Packet An address packet is followed by one or more data packets. All data packets are nine bits long, consisting of one data byte and an acknowledge bit. The direction bit in the previous address packet determines the direction in which the data are transferred. 19.3.6 Transaction A transaction is the complete transfer from a START to a STOP condition, including any repeated START conditions in between. The TWI standard defines three fundamental transaction modes: Master write, master read, and a combined transaction. Figure 19-5 on page 235 illustrates the master write transaction. The master initiates the transaction by issuing a START condition (S) followed by an address packet with the direction bit set to zero (ADDRESS+W). Figure 19-5. Master write transaction. Assuming the slave acknowledges the address, the master can start transmitting data (DATA) and the slave will ACK or NACK (A/A) each byte. If no data packets are to be transmitted, the master terminates the transaction by issuing a STOP condition (P) directly after the address packet. There are no limitations to the number of data packets that can be SDA SCL DATA Valid Change Allowed S ADDRESS W A DATA A DATA A/A P Address Packet Data Packet Transaction N data packets XMEGA B [MANUAL] 236 Atmel-8291C-AVR-XMEGA B -09/2014 transferred. If the slave signals a NACK to the data, the master must assume that the slave cannot receive any more data and terminate the transaction. Figure 19-6 on page 236 illustrates the master read transaction. The master initiates the transaction by issuing a START condition followed by an address packet with the direction bit set to one (ADDRESS+R). The addressed slave must acknowledge the address for the master to be allowed to continue the transaction. Figure 19-6. Master read transaction. Assuming the slave acknowledges the address, the master can start receiving data from the slave. There are no limitations to the number of data packets that can be transferred. The slave transmits the data while the master signals ACK or NACK after each data byte. The master terminates the transfer with a NACK before issuing a STOP condition. Figure 19-7 illustrates a combined transaction. A combined transaction consists of several read and write transactions separated by repeated START conditions (Sr). Figure 19-7. Combined Transaction. 19.3.7 Clock and Clock Stretching All devices connected to the bus are allowed to stretch the low period of the clock to slow down the overall clock frequency or to insert wait states while processing data. A device that needs to stretch the clock can do this by holding/forcing the SCL line low after it detects a low level on the line. Three types of clock stretching can be defined, as shown in Figure 19-8. Figure 19-8. Clock stretching(1). Note: 1. Clock stretching is not supported by all I2 C slaves and masters. If a slave device is in sleep mode and a START condition is detected, the clock stretching normally works during the wake-up period. For AVR XMEGA devices, the clock stretching will be either directly before or after the ACK/NACK bit, as AVR XMEGA devices do not need to wake up for transactions that are not addressed to it. A slave device can slow down the bus frequency by stretching the clock periodically on a bit level. This allows the slave to run at a lower system clock frequency. However, the overall performance of the bus will be reduced accordingly. Both S ADDRESS R A DATA A DATA A P Transaction Address Packet Data Packet N data packets S ADDRESS R/W A DATA A/A Sr ADDRESS R/W DATA A/A P Transaction Address Packet #1 N Data Packets Address Packet #2 M Data Packets Direction Direction A SDA SCL S bit 7 bit 6 bit 0 ACK/NACK Periodic clock stretching Random clock stretching Wakeup clock stretching XMEGA B [MANUAL] 237 Atmel-8291C-AVR-XMEGA B -09/2014 the master and slave device can randomly stretch the clock on a byte level basis before and after the ACK/NACK bit. This provides time to process incoming or prepare outgoing data, or perform other time-critical tasks. In the case where the slave is stretching the clock, the master will be forced into a wait state until the slave is ready, and vice versa. 19.3.8 Arbitration A master can start a bus transaction only if it has detected that the bus is idle. As the TWI bus is a multi-master bus, it is possible that two devices may initiate a transaction at the same time. This results in multiple masters owning the bus simultaneously. This is solved using an arbitration scheme where the master loses control of the bus if it is not able to transmit a high level on the SDA line. The masters who lose arbitration must then wait until the bus becomes idle (i.e., wait for a STOP condition) before attempting to reacquire bus ownership. Slave devices are not involved in the arbitration procedure. Figure 19-9. TWI arbitration. Figure 19-9 shows an example where two TWI masters are contending for bus ownership. Both devices are able to issue a START condition, but DEVICE1 loses arbitration when attempting to transmit a high level (bit 5) while DEVICE2 is transmitting a low level. Arbitration between a repeated START condition and a data bit, a STOP condition and a data bit, or a repeated START condition and a STOP condition are not allowed and will require special handling by software. 19.3.9 Synchronization A clock synchronization algorithm is necessary for solving situations where more than one master is trying to control the SCL line at the same time. The algorithm is based on the same principles used for the clock stretching previously described. Figure 19-10 shows an example where two masters are competing for control over the bus clock. The SCL line is the wired-AND result of the two masters clock outputs. DEVICE1_SDA SDA (wired-AND) DEVICE2_SDA SCL S bit 7 bit 6 bit 5 bit 4 DEVICE1 Loses arbitration XMEGA B [MANUAL] 238 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 19-10.Clock synchronization. A high-to-low transition on the SCL line will force the line low for all masters on the bus, and they will start timing their low clock period. The timing length of the low clock period can vary among the masters. When a master (DEVICE1 in this case) has completed its low period, it releases the SCL line. However, the SCL line will not go high until all masters have released it. Consequently, the SCL line will be held low by the device with the longest low period (DEVICE2). Devices with shorter low periods must insert a wait state until the clock is released. All masters start their high period when the SCL line is released by all devices and has gone high. The device which first completes its high period (DEVICE1) forces the clock line low, and the procedure is then repeated. The result is that the device with the shortest clock period determines the high period, while the low period of the clock is determined by the device with the longest clock period. 19.4 TWI Bus State Logic The bus state logic continuously monitors the activity on the TWI bus lines when the master is enabled. It continues to operate in all sleep modes, including power-down. The bus state logic includes START and STOP condition detectors, collision detection, inactive bus timeout detection, and a bit counter. These are used to determine the bus state. Software can get the current bus state by reading the bus state bits in the master status register. The bus state can be unknown, idle, busy, or owner, and is determined according to the state diagram shown in Figure 19-11. The values of the bus state bits according to state are shown in binary in the figure. DEVICE1_SCL SCL (wired-AND) Wait State DEVICE2_SCL High Period Count Low Period Count XMEGA B [MANUAL] 239 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 19-11.Bus state, state diagram. After a system reset and/or TWI master enable, the bus state is unknown. The bus state machine can be forced to enter idle by writing to the bus state bits accordingly. If no state is set by application software, the bus state will become idle when the first STOP condition is detected. If the master inactive bus timeout is enabled, the bus state will change to idle on the occurrence of a timeout. After a known bus state is established, only a system reset or disabling of the TWI master will set the state to unknown. When the bus is idle, it is ready for a new transaction. If a START condition generated externally is detected, the bus becomes busy until a STOP condition is detected. The STOP condition will change the bus state to idle. If the master inactive bus timeout is enabled, the bus state will change from busy to idle on the occurrence of a timeout. If a START condition is generated internally while in idle state, the owner state is entered. If the complete transaction was performed without interference, i.e., no collisions are detected, the master will issue a STOP condition and the bus state will change back to idle. If a collision is detected, the arbitration is assumed lost and the bus state becomes busy until a STOP condition is detected. A repeated START condition will only change the bus state if arbitration is lost during the issuing of the repeated START. Arbitration during repeated START can be lost only if the arbitration has been ongoing since the first START condition. This happens if two masters send the exact same ADDRESS+DATA before one of the masters issues a repeated START (Sr). 19.5 TWI Master Operation The TWI master is byte-oriented, with an optional interrupt after each byte. There are separate interrupts for master write and master read. Interrupt flags can also be used for polled operation. There are dedicated status flags for indicating ACK/NACK received, bus error, arbitration lost, clock hold, and bus state. When an interrupt flag is set, the SCL line is forced low. This will give the master time to respond or handle any data, and will in most cases require software interaction. Figure 19-12 shows the TWI master operation. The diamond shaped symbols (SW) indicate where software interaction is required. Clearing the interrupt flags releases the SCL line. P + Timeout Write ADDRESS IDLE (0b01) S BUSY (0b11) UNKNOWN (0b00) OWNER (0b10) Arbitration Lost Command P Write ADDRESS(Sr) Sr (S) RESET P + Timeout XMEGA B [MANUAL] 240 Atmel-8291C-AVR-XMEGA B -09/2014 Figure 19-12.TWI master operation. The number of interrupts generated is kept to a minimum by automatic handling of most conditions. Quick command and smart mode can be enabled to auto-trigger operations and reduce software complexity. 19.5.1 Transmitting Address Packets After issuing a START condition, the master starts performing a bus transaction when the master address register is written with the 7-bit slave address and direction bit. If the bus is busy, the TWI master will wait until the bus becomes idle before issuing the START condition. Depending on arbitration and the R/W direction bit, one of four distinct cases (M1 to M4) arises following the address packet. The different cases must be handled in software. 19.5.1.1 Case M1: Arbitration lost or bus error during address packet If arbitration is lost during the sending of the address packet, the master write interrupt flag and arbitration lost flag are both set. Serial data output to the SDA line is disabled, and the SCL line is released. The master is no longer allowed to perform any operation on the bus until the bus state has changed back to idle. A bus error will behave in the same way as an arbitration lost condition, but the error flag is set in addition to the write interrupt and arbitration lost flags. 19.5.1.2 Case M2: Address packet transmit complete - Address not acknowledged by slave If no slave device responds to the address, the master write interrupt flag and the master received acknowledge flag are set. The clock hold is active at this point, preventing further activity on the bus. 19.5.1.3 Case M3: Address packet transmit complete - Direction bit cleared If the master receives an ACK from the slave, the master write interrupt flag is set and the master received acknowledge flag is cleared. The clock hold is active at this point, preventing further activity on the bus. BUSY P IDLE S BUSY Sr P M3 M3 M2 M2 M1 M1 R DATA ADDRESS W DATA A/A Wait for IDLE APPLICATION SW SW Sr P M3 M2 SW A BUSY M4 A/A A/A A/A M4 A IDLE IDLE MASTER READ INTERRUPT + HOLD MASTER WRITE INTERRUPT + HOLD SW SW SW R/W BUSY SW Driver software The master provides data on the bus Slave provides data on the bus A A R/W BUSY M4 Bus state Mn Diagram connections XMEGA B [MANUAL] 241 Atmel-8291C-AVR-XMEGA B -09/2014 19.5.1.4 Case M4: Address packet transmit complete - Direction bit set If the master receives an ACK from the slave, the master proceeds to receive the next byte of data from the slave. When the first data byte is received, the master read interrupt flag is set and the master received acknowledge flag is cleared. The clock hold is active at this point, preventing further activity on the bus. 19.5.2 Transmitting Data Packets Assuming case M3 above, the master can start transmitting data by writing to the master data register. If the transfer was successful, the slave will signal with ACK. The master write interrupt flag is set, the master received acknowledge flag is cleared, and the master can prepare new data to send. During data transfer, the master is continuously monitoring the bus for collisions. The received acknowledge flag must be checked by software for each data packet transmitted before the next data packet can be transferred. The master is not allowed to continue transmitting data if the slave signals a NACK. If a collision is detected and the master loses arbitration during transfer, the arbitration lost flag is set. 19.5.3 Receiving Data Packets Assuming case M4 above, the master has already received one byte from the slave. The master read interrupt flag is set, and the master must prepare to receive new data. The master must respond to each byte with ACK or NACK. Indicating a NACK might not be successfully executed, as arbitration can be lost during the transmission. If a collision is detected, the master loses arbitration and the arbitration lost flag is set. 19.6 TWI Slave Operation The TWI slave is byte-oriented with optional interrupts after each byte. There are separate slave data and address/stop interrupts. Interrupt flags can also be used for polled operation. There are dedicated status flags for indicating ACK/NACK received, clock hold, collision, bus error, and read/write direction. When an interrupt flag is set, the SCL line is forced low. This will give the slave time to respond or handle data, and will in most cases require software interaction. Figure 19-13. shows the TWI slave operation. The diamond shapes symbols (SW) indicate where software interaction is required. Figure 19-13.TWI slave operation. The number of interrupts generated is kept to a minimum by automatic handling of most conditions. Quick command can be enabled to auto-trigger operations and reduce software complexity. Promiscuous mode can be enabled to allow the slave to respond to all received addresses. S S3 S2 ADDRESS A S1 R W DATA A/A DATA P S2 Sr S3 P S2 Sr S3 SLAVE ADDRESS INTERRUPT SLAVE DATA INTERRUPT A Collision (SMBus) SW SW SW SW A/A A/A SW Release Hold S1 A S1 SW Interrupt on STOP Condition Enabled S1 SW Driver software The master provides data on the bus Slave provides data on the bus Sn Diagram connections XMEGA B [MANUAL] 242 Atmel-8291C-AVR-XMEGA B -09/2014 19.6.1 Receiving Address Packets When the TWI slave is properly configured, it will wait for a START condition to be detected. When this happens, the successive address byte will be received and checked by the address match logic, and the slave will ACK a correct address and store the address in the DATA register. If the received address is not a match, the slave will not acknowledge and store address, and will wait for a new START condition. The slave address/stop interrupt flag is set when a START condition succeeded by a valid address byte is detected. A general call address will also set the interrupt flag. A START condition immediately followed by a STOP condition is an illegal operation, and the bus error flag is set. The R/W direction flag reflects the direction bit received with the address. This can be read by software to determine the type of operation currently in progress. Depending on the R/W direction bit and bus condition, one of four distinct cases (S1 to S4) arises following the address packet. The different cases must be handled in software. 19.6.1.1 Case S1: Address packet accepted - Direction bit set If the R/W direction flag is set, this indicates a master read operation. The SCL line is forced low by the slave, stretching the bus clock. If ACK is sent by the slave, the slave hardware will set the data interrupt flag indicating data is needed for transmit. Data, repeated START, or STOP can be received after this. If NACK is sent by the slave, the slave will wait for a new START condition and address match. 19.6.1.2 Case S2: Address packet accepted - Direction bit cleared If the R/W direction flag is cleared, this indicates a master write operation. The SCL line is forced low, stretching the bus clock. If ACK is sent by the slave, the slave will wait for data to be received. Data, repeated START, or STOP can be received after this. If NACK is sent, the slave will wait for a new START condition and address match. 19.6.1.3 Case S3: Collision If the slave is not able to send a high level or NACK, the collision flag is set, and it will disable the data and acknowledge output from the slave logic. The clock hold is released. A START or repeated START condition will be accepted. 19.6.1.4 Case S4: STOP condition received. When the STOP condition is received, the slave address/stop flag will be set, indicating that a STOP condition, and not an address match, occurred. 19.6.2 Receiving Data Packets The slave will know when an address packet with R/W direction bit cleared has been successfully received. After acknowledging this, the slave must be ready to receive data. When a data packet is received, the data interrupt flag is set and the slave must indicate ACK or NACK. After indicating a NACK, the slave must expect a STOP or repeated START condition. 19.6.3 Transmitting Data Packets The slave will know when an address packet with R/W direction bit set has been successfully received. It can then start sending data by writing to the slave data register. When a data packet transmission is completed, the data interrupt flag is set. If the master indicates NACK, the slave must stop transmitting data and expect a STOP or repeated START condition. 19.7 Enabling External Driver Interface An external driver interface can be enabled. When this is done, the internal TWI drivers with input filtering and slew rate control are bypassed. The normal I/O pin function is used, and the direction must be configured by the user software. When this mode is enabled, an external TWI compliant tri-state driver is needed for connecting to a TWI bus. By default, port pins 0 (Pn0) and 1 (Pn1) are used for SDA and SCL. The external driver interface uses port pins 0 to 3 for the SDA_IN, SCL_IN, SDA_OUT, and SCL_OUT signals. XMEGA B [MANUAL] 243 Atmel-8291C-AVR-XMEGA B -09/2014 19.8 Register Description – TWI 19.8.1 CTRL – Common Control Register z Bit 7:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2:1 – SDAHOLD[1:0]: SDA Hold Time Enable. Setting these bits to one enables an internal hold time on SDA with respect to the negative edge of SCL. Table 19-1. SDA hold time. z Bit 0 – EDIEN: External Driver Interface Enable Setting this bit enables the use of the external driver interface, and clearing this bit enables normal two-wire mode. See Table 19-2 for details. Table 19-2. External driver interface enable. Bit 7 6 5 4 3 2 1 0 +0x00 – – – – – SDAHOLD[1:0] EDIEN Read/Write R R R R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 SDAHOLD[1:0] Group Configuration Description 00 OFF SDA hold time off 01 50NS Typical 50ns hold time 10 300NS Typical 100ns hold time 11 400NS Typical 400ns hold time EDIEN Mode Comment 0 Normal TWI Two-pin interface, slew rate control, and input filter. 1 External driver interface Four-pin interface, standard I/O, no slew rate control, and no input filter. XMEGA B [MANUAL] 244 Atmel-8291C-AVR-XMEGA B -09/2014 19.9 Register Description – TWI Master 19.9.1 CTRLA – Control register A z Bit 7:6 – INTLVL[1:0]: Interrupt Level These bits select the interrupt level for the TWI master interrupt, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. z Bit 5 – RIEN: Read Interrupt Enable Setting the read interrupt enable (RIEN) bit enables the read interrupt when the read interrupt flag (RIF) in the STATUS register is set. In addition the INTLVL bits must be nonzero for TWI master interrupts to be generated. z Bit 4 – WIEN: Write Interrupt Enable Setting the write interrupt enable (WIEN) bit enables the write interrupt when the write interrupt flag (WIF) in the STATUS register is set. In addition the INTLVL bits must be nonzero for TWI master interrupts to be generated. z Bit 3 – ENABLE: Enable TWI Master Setting the enable TWI master (ENABLE) bit enables the TWI master. z Bit 2:0 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. 19.9.2 CTRLB – Control register B z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:2 – TIMEOUT[1:0]: Inactive Bus Timeout Setting the inactive bus timeout (TIMEOUT) bits to a nonzero value will enable the inactive bus timeout supervisor. If the bus is inactive for longer than the TIMEOUT setting, the bus state logic will enter the idle state. Table 19-3 lists the timeout settings. Bit 7 6 5 4 3 2 1 0 +0x00 INTLVL[1:0] RIEN WIEN ENABLE – – – Read/Write R/W R/W R/W R/W R/W R R R Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x01 – – – – TIMEOUT[1:0] QCEN SMEN Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 245 Atmel-8291C-AVR-XMEGA B -09/2014 Table 19-3. TWI master inactive bus timeout settings. z Bit 1 – QCEN: Quick Command Enable When quick command is enabled, the corresponding interrupt flag is set immediately after the slave acknowledges the address (read or write interrupt). At this point, software can issue either a STOP or a repeated START condition. z Bit 0 – SMEN: Smart Mode Enable Setting this bit enables smart mode. When smart mode is enabled, the acknowledge action, as set by the ACKACT bit in the CTRLC register, is sent immediately after reading the DATA register. 19.9.3 CTRLC – Control register C z Bits 7:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2 – ACKACT: Acknowledge Action This bit defines the master's acknowledge behavior in master read mode. The acknowledge action is executed when a command is written to the CMD bits. If SMEN in the CTRLB register is set, the acknowledge action is performed when the DATA register is read. Table 19-4 lists the acknowledge actions. Table 19-4. ACKACT bit description. z Bit 1:0 – CMD[1:0]: Command Writing the command (CMD) bits triggers a master operation as defined by Table 19-5. The CMD bits are strobe bits, and always read as zero. The acknowledge action is only valid in master read mode (R). In master write mode (W), a command will only result in a repeated START or STOP condition. The ACKACT bit and the CMD bits can be written at the same time, and then the acknowledge action will be updated before the command is triggered. TIMEOUT[1:0] Group Configuration Description 00 DISABLED Disabled, normally used for I2 C 01 50US 50μs, normally used for SMBus at 100kHz 10 100US 100μs 11 200US 200μs Bit 7 6 5 4 3 2 1 0 +0x02 – – – – – ACKACT CMD[1:0] Read/Write R R R R R R/W R/W R/W Initial Value 00000000 ACKACT Action 0 Send ACK 1 Send NACK XMEGA B [MANUAL] 246 Atmel-8291C-AVR-XMEGA B -09/2014 Table 19-5. CMD bit description. Writing a command to the CMD bits will clear the master interrupt flags and the CLKHOLD flag. 19.9.4 STATUS – Status register z Bit 7 – RIF: Read Interrupt Flag This flag is set when a byte is successfully received in master read mode; i.e., no arbitration was lost or bus error occurred during the operation. Writing a one to this bit location will clear RIF. When this flag is set, the master forces the SCL line low, stretching the TWI clock period. Clearing the interrupt flags will release the SCL line. This flag is also cleared automatically when: z Writing to the ADDR register z Writing to the DATA register z Reading the DATA register z Writing a valid command to the CMD bits in the CTRLC register z Bit 6 – WIF: Write Interrupt Flag This flag is set when a byte is transmitted in master write mode. The flag is set regardless of the occurrence of a bus error or an arbitration lost condition. WIF is also set if arbitration is lost during sending of a NACK in master read mode, and if issuing a START condition when the bus state is unknown. Writing a one to this bit location will clear WIF. When this flag is set, the master forces the SCL line low, stretching the TWI clock period. Clearing the interrupt flags will release the SCL line. The flag is also cleared automatically for the same conditions as RIF. z Bit 5 – CLKHOLD: Clock Hold This flag is set when the master is holding the SCL line low. This is a status flag and a read-only flag that is set when RIF or WIF is set. Clearing the interrupt flags and releasing the SCL line will indirectly clear this flag. The flag is also cleared automatically for the same conditions as RIF. CMD[1:0] Group Configuration MODE Operation 00 NOACT X Reserved 01 START X Execute acknowledge action succeeded by repeated START condition 10 BYTEREC W No operation R Execute acknowledge action succeeded by a byte receive 11 STOP X Execute acknowledge action succeeded by issuing a STOP condition Bit 7 6 5 4 3 2 1 0 +0x03 RIF WIF CLKHOLD RXACK ARBLOST BUSERR BUSSTATE[1:0] Read/Write R/W R/W R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 247 Atmel-8291C-AVR-XMEGA B -09/2014 z Bit 4 – RXACK: Received Acknowledge This flag contains the most recently received acknowledge bit from the slave. This is a read-only flag. When read as zero, the most recent acknowledge bit from the slave was ACK, and when read as one the most recent acknowledge bit was NACK. z Bit 3 – ARBLOST: Arbitration Lost This flag is set if arbitration is lost while transmitting a high data bit or a NACK bit, or while issuing a START or repeated START condition on the bus. Writing a one to this bit location will clear ARBLOST. Writing the ADDR register will automatically clear ARBLOST. z Bit 2 – BUSERR: Bus Error This flag is set if an illegal bus condition has occurred. An illegal bus condition occurs if a repeated START or a STOP condition is detected, and the number of received or transmitted bits from the previous START condition is not a multiple of nine. Writing a one to this bit location will clear BUSERR. Writing the ADDR register will automatically clear BUSERR. z Bit 1:0 – BUSSTATE[1:0]: Bus State These bits indicate the current TWI bus state as defined in Table 19-6. The change of bus state is dependent on bus activity. Refer to the “TWI Bus State Logic” on page 238. Table 19-6. TWI master bus state. Writing 01 to the BUSSTATE bits forces the bus state logic into the idle state. The bus state logic cannot be forced into any other state. When the master is disabled, and after reset, the bus state logic is disabled and the bus state is unknown. 19.9.5 BAUD – Baud Rate register The baud rate (BAUD) register defines the relation between the system clock and the TWI bus clock (SCL) frequency. The frequency relation can be expressed by using the following equation: [1] The BAUD register must be set to a value that results in a TWI bus clock frequency (fTWI) equal or less than 100kHz or 400kHz, depending on which standard the application should comply with. The following equation [2] expresses equation [1] solved for the BAUD value: BUSSTATE[1:0] Group Configuration Description 00 UNKNOWN Unknown bus state 01 IDLE Idle bus state 10 OWNER Owner bus state 11 BUSY Busy bus state Bit 7 6 5 4 3 2 1 0 +0x04 BAUD[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 00000 f TWI f sys 2(5 + ( ) BAUD ) = ---------------------------------------[Hz] XMEGA B [MANUAL] 248 Atmel-8291C-AVR-XMEGA B -09/2014 [2] The BAUD register should be written only while the master is disabled. 19.9.6 ADDR – Address register When the address (ADDR) register is written with a slave address and the R/W bit while the bus is idle, a START condition is issued and the 7-bit slave address and the R/W bit are transmitted on the bus. If the bus is already owned when ADDR is written, a repeated START is issued. If the previous transaction was a master read and no acknowledge is sent yet, the acknowledge action is sent before the repeated START condition. After completing the operation and the acknowledge bit from the slave is received, the SCL line is forced low if arbitration was not lost. WIF is set. If the bus state is unknown when ADDR is written, WIF is set and BUSERR is set. All TWI master flags are automatically cleared when ADDR is written. This includes BUSERR, ARBLOST, RIF, and WIF. The master ADDR can be read at any time without interfering with ongoing bus activity. 19.9.7 DATA – Data register The data (DATA) register is used when transmitting and receiving data. During data transfer, data are shifted from/to the DATA register and to/from the bus. This implies that the DATA register cannot be accessed during byte transfers, and this is prevented by hardware. The DATA register can only be accessed when the SCL line is held low by the master; i.e., when CLKHOLD is set. In master write mode, writing the DATA register will trigger a data byte transfer followed by the master receiving the acknowledge bit from the slave. WIF and CLKHOLD are set. In master read mode, RIF and CLKHOLD are set when one byte is received in the DATA register. If smart mode is enabled, reading the DATA register will trigger the bus operation as set by the ACKACT bit. If a bus error occurs during reception, WIF and BUSERR are set instead of RIF. Accessing the DATA register will clear the master interrupt flags and CLKHOLD. BAUD f sys 2 f TWI = ---------------- – 5 Bit 7 6 5 4 3 2 1 0 +0x05 ADDR[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x06 DATA[7:0] 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 XMEGA B [MANUAL] 249 Atmel-8291C-AVR-XMEGA B -09/2014 19.10 Register Description – TWI Slave 19.10.1 CTRLA – Control register A z Bit 7:6 – INTLVL[1:0]: Interrupt Level These bits select the interrupt level for the TWI master interrupt, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. z Bit 5 – DIEN: Data Interrupt Enable Setting the data interrupt enable (DIEN) bit enables the data interrupt when the data interrupt flag (DIF) in the STATUS register is set. The INTLVL bits must be nonzero for the interrupt to be generated. z Bit 4 – APIEN: Address/Stop Interrupt Enable Setting the address/stop interrupt enable (APIEN) bit enables the address/stop interrupt when the address/stop interrupt flag (APIF) in the STATUS register is set. The INTLVL bits must be nonzero for interrupt to be generated. z Bit 3 – ENABLE: Enable TWI Slave Setting this bit enables the TWI slave. z Bit 2 – PIEN: Stop Interrupt Enable Setting the this bit will cause APIF in the STATUS register to be set when a STOP condition is detected. z Bit 1 – PMEN: Promiscuous Mode Enable By setting the this bit, the slave address match logic responds to all received addresses. If this bit is cleared, the address match logic uses the ADDR register to determine which address to recognize as its own address. z Bit 0 – SMEN: Smart Mode Enable This bit enables smart mode. When Smart mode is enabled, the acknowledge action, as set by the ACKACT bit in the CTRLB register, is sent immediately after reading the DATA register. 19.10.2 CTRLB – Control register B z Bit 7:3 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 2 – ACKACT: Acknowledge Action This bit defines the slave's acknowledge behavior after an address or data byte is received from the master. The acknowledge action is executed when a command is written to the CMD bits. If the SMEN bit in the CTRLA register is set, the acknowledge action is performed when the DATA register is read. Table 19-7 lists the acknowledge actions. Bit 7 6 5 4 3 2 1 0 +0x00 INTLVL[1:0] DIEN APIEN ENABLE PIEN PMEN SMEN Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0000 0 0 Bit 7 6 5 4 3 2 1 0 +0x01 – – – – – ACKACT CMD[1:0] Read/Write R R R R R R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 250 Atmel-8291C-AVR-XMEGA B -09/2014 Table 19-7. TWI slave acknowledge actions. z Bit 1:0 – CMD[1:0]: Command Writing these bits trigger the slave operation as defined by Table 19-8. The CMD bits are strobe bits and always read as zero. The operation is dependent on the slave interrupt flags, DIF and APIF. The acknowledge action is only executed when the slave receives data bytes or address byte from the master. Table 19-8. TWI slave command. Writing the CMD bits will automatically clear the slave interrupt flags and CLKHOLD, and release the SCL line. The ACKACT bit and CMD bits can be written at the same time, and then the acknowledge action will be updated before the command is triggered. ACKACT Action 0 Send ACK 1 Send NACK CMD[1:0] Group Configuration DIR Operation 00 NOACT X No action 01 X Reserved 10 COMPLETE Used to complete transaction 0 Execute acknowledge action succeeded by waiting for any START (S/Sr) condition 1 Wait for any START (S/Sr) condition 11 RESPONSE Used in response to an address byte (APIF is set) 0 Execute acknowledge action succeeded by reception of next byte 1 Execute acknowledge action succeeded by DIF being set Used in response to a data byte (DIF is set) 0 Execute acknowledge action succeeded by waiting for the next byte 1 No operation XMEGA B [MANUAL] 251 Atmel-8291C-AVR-XMEGA B -09/2014 19.10.3 STATUS – Status register z Bit 7 – DIF: Data Interrupt Flag This flag is set when a data byte is successfully received; i.e., no bus error or collision occurred during the operation. Writing a one to this bit location will clear DIF. When this flag is set, the slave forces the SCL line low, stretching the TWI clock period. Clearing the interrupt flags will release the SCL line. This flag is also cleared automatically when writing a valid command to the CMD bits in the CTRLB register z Bit 6 – APIF: Address/Stop Interrupt Flag This flag is set when the slave detects that a valid address has been received, or when a transmit collision is detected. If the PIEN bit in the CTRLA register is set, a STOP condition on the bus will also set APIF. Writing a one to this bit location will clear APIF. When set for an address interrupt, the slave forces the SCL line low, stretching the TWI clock period. Clearing the interrupt flags will release the SCL line. The flag is also cleared automatically for the same condition as DIF. z Bit 5 – CLKHOLD: Clock Hold This flag is set when the slave is holding the SCL line low.This is a status flag and a read-only bit that is set when DIF or APIF is set. Clearing the interrupt flags and releasing the SCL line will indirectly clear this flag. z Bit 4 – RXACK: Received Acknowledge This flag contains the most recently received acknowledge bit from the master. This is a read-only flag. When read as zero, the most recent acknowledge bit from the maser was ACK, and when read as one, the most recent acknowledge bit was NACK. z Bit 3 – COLL: Collision This flag is set when a slave has not been able to transfer a high data bit or a NACK bit. If a collision is detected, the slave will commence its normal operation, disable data, and acknowledge output, and no low values will be shifted out onto the SDA line. Writing a one to this bit location will clear COLL. The flag is also cleared automatically when a START or repeated START condition is detected. z Bit 2 – BUSERR: TWI Slave Bus Error This flag is set when an illegal bus condition occurs during a transfer. An illegal bus condition occurs if a repeated START or a STOP condition is detected, and the number of bits from the previous START condition is not a multiple of nine. Writing a one to this bit location will clear BUSERR. For bus errors to be detected, the bus state logic must be enabled. This is done by enabling the TWI master. z Bit 1 – DIR: Read/Write Direction The R/W direction (DIR) flag reflects the direction bit from the last address packet received from a master. When this bit is read as one, a master read operation is in progress. When read as zero, a master write operation is in progress. z Bit 0 – AP: Slave Address or Stop This flag indicates whether a valid address or a STOP condition caused the last setting of APIF in the STATUS register. Table 19-9. TWI slave address or stop. Bit 7 6 5 4 3 2 1 0 +0x02 DIF APIF CLKHOLD RXACK COLL BUSERR DIR AP Read/Write R/W R/W R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 AP Description 0 A STOP condition generated the interrupt on APIF 1 Address detection generated the interrupt on APIF XMEGA B [MANUAL] 252 Atmel-8291C-AVR-XMEGA B -09/2014 19.10.4 ADDR – Address register The TWI slave address register should be loaded with the 7-bit slave address (in the seven most significant bits of ADDR) to which the TWI will respond. The lsb of ADDR is used to enable recognition of the general call address (0x00). z Bit 7:1 – ADDR[7:1]: TWI Slave Address This register contains the TWI slave address used by the slave address match logic to determine if a master has addressed the slave. The seven most-significant bits (ADDR[7:1]) represent the slave address. When using 10-bit addressing, the address match logic only supports hardware address recognition of the first byte of a 10-bit address. By setting ADDR[7:1] = 0b11110nn, ”nn” represents bits 9 and 8 of the slave address. The next byte received is bits 7 to 0 in the 10-bit address, and this must be handled by software. When the address match logic detects that a valid address byte is received, APIF is set and the DIR flag is updated. If the PMEN bit in CTRLA is set, the address match logic responds to all addresses transmitted on the TWI bus. The ADDR register is not used in this mode. z Bit 0 – ADDR: General Call Recognition Enable When ADDR[0] is set, this enables general call address recognition logic so the device can respond to a general address call that addresses all devices on the bus. 19.10.5 DATA – Data register The data (DATA) register is used when transmitting and received data. During data transfer, data are shifted from/to the DATA register and to/from the bus. This implies that the DATA register cannot be accessed during byte transfers, and this is prevented by hardware. The DATA register can be accessed only when the SCL line is held low by the slave; i.e., when CLKHOLD is set. When a master is reading data from the slave, data to send must be written to the DATA register. The byte transfer is started when the master starts to clock the data byte from the slave, followed by the slave receiving the acknowledge bit from the master. DIF and CLKHOLD are set. When a master writes data to the slave, DIF and CLKHOLD are set when one byte has been received in the DATA register. If smart mode is enabled, reading the DATA register will trigger the bus operation as set by the ACKACT bit. Accessing the DATA register will clear the slave interrupt flags and CLKHOLD. When an address match occurs, the received address will be stored in the DATA register. Bit 7 6 5 4 3 2 1 0 +0x03 ADDR[7:1] ADDR[0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 000000 Bit 7 6 5 4 3 2 1 0 +0x04 DATA[7:0] 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 XMEGA B [MANUAL] 253 Atmel-8291C-AVR-XMEGA B -09/2014 19.10.6 ADDRMASK – Address Mask register z Bit 7:1 – ADDRMASK[7:1]: Address Mask These bits can act as a second address match register or as an address mask register, depending on the ADDREN setting. If ADDREN is set to zero, ADDRMASK can be loaded with a 7-bit slave address mask. Each bit in ADDRMASK can mask (disable) the corresponding address bit in the ADDR register. If the mask bit is one, the address match between the incoming address bit and the corresponding bit in ADDR is ignored; i.e., masked bits will always match. If ADDREN is set to one, ADDRMASK can be loaded with a second slave address in addition to the ADDR register. In this mode, the slave will match on two unique addresses, one in ADDR and the other in ADDRMASK. z Bit 0 – ADDREN: Address Enable By default, this bit is zero, and the ADDRMASK bits acts as an address mask to the ADDR register. If this bit is set to one, the slave address match logic responds to the two unique addresses in ADDR and ADDRMASK. Bit 7 6 5 4 3 2 1 0 +0x05 ADDRMASK[7:1] ADDREN 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 XMEGA B [MANUAL] 254 Atmel-8291C-AVR-XMEGA B -09/2014 19.11 Register Summary - TWI 19.12 Register Summary - TWI Master 19.13 Register Summary - TWI Slave 19.14 Interrupt Vector Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL – – – – – SDAHOLD[1:0] EDIEN 243 +0x01 MASTER Offset address for TWI Master +0x08 SLAVE Offset address for TWI Slave Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRLA INTLVL[1:0] RIEN WIEN ENABLE – – – 244 +0x01 CTRLB – – – – TIMEOUT[1:0] QCEN SMEN 244 +0x02 CTRLC – – – – – ACKACT CMD[1:0] 245 +0x03 STATUS RIF WIF CLKHOLD RXACK ARBLOST BUSERR BUSSTATE[1:0] 246 +0x04 BAUD BAUD[7:0] 247 +0x05 ADDR ADDR[7:0] 248 +0x06 DATA DATA[7:0] 248 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRLA INTLVL[1:0] DIEN APIEN ENABLE PIEN TPMEN SMEN 249 +0x01 CTRLB – – – – – ACKACT CMD[1:0] 249 +0x02 STATUS DIF APIF CLKHOLD RXACK COLL BUSERR DIR AP 251 +0x03 ADDR ADDR[7:0] 252 +0x04 DATA DATA[7:0] 252 +0x05 ADDRMAS ADDRMASK[7:1] ADDREN 253 Offset Source Interrupt Description 0x00 SLAVE_vect TWI slave interrupt vector 0x02 MASTER_vect TWI master interrupt vector XMEGA B [MANUAL] 255 8291C–AVR–09/2014 20. SPI – Serial Peripheral Interface 20.1 Features z Full-duplex, three-wire synchronous data transfer z Master or slave operation z Lsb first or msb first data transfer z Eight programmable bit rates z Interrupt flag at the end of transmission z Write collision flag to indicate data collision z Wake up from idle sleep mode z Double speed master mode 20.2 Overview The Serial Peripheral Interface (SPI) is a high-speed synchronous data transfer interface using three or four pins. It allows fast communication between an XMEGA device and peripheral devices or between several microcontrollers. The SPI supports full-duplex communication. A device connected to the bus must act as a master or slave.The master initiates and controls all data transactions. The interconnection between master and slave devices with SPI is shown in Figure 20-1 on page 255. The system consists of two shift registers and a master clock generator. The SPI master initiates the communication cycle by pulling the slave select (SS) signal low for the desired slave. Master and slave prepare the data to be sent in their respective shift registers, and the master generates the required clock pulses on the SCK line to interchange data. Data are always shifted from master to slave on the master output, slave input (MOSI) line, and from slave to master on the master input, slave output (MISO) line. After each data packet, the master can synchronize the slave by pulling the SS line high. Figure 20-1. SPI master-slave interconnection. The SPI module is unbuffered in the transmit direction and single buffered in the receive direction. This means that bytes to be transmitted cannot be written to the SPI DATA register before the entire shift cycle is completed. When receiving data, a received character must be read from the DATA register before the next character has been completely shifted in. Otherwise, the first byte will be lost. In SPI slave mode, the control logic will sample the incoming signal on the SCK pin. To ensure correct sampling of this clock signal, the minimum low and high periods must each be longer than two CPU clock cycles. When the SPI module is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to Table 20-1. The pins with user-defined direction must be configured from software to have the correct direction according to the application. SHIFT ENABLE XMEGA B [MANUAL] 256 8291C–AVR–09/2014 Table 20-1. SPI pin override and directions. 20.3 Master Mode In master mode, the SPI interface has no automatic control of the SS line. If the SS pin is used, it must be configured as output and controlled by user software. If the bus consists of several SPI slaves and/or masters, a SPI master can use general purpose I/O pins to control the SS line to each of the slaves on the bus. Writing a byte to the DATA register starts the SPI clock generator and the hardware shifts the eight bits into the selected slave. After shifting one byte, the SPI clock generator stops and the SPI interrupt flag is set. The master may continue to shift the next byte by writing new data to the DATA register, or can signal the end of the transfer by pulling the SS line high. The last incoming byte will be kept in the buffer register. If the SS pin is not used and is configured as input, it must be held high to ensure master operation. If the SS pin is set as input and is being driven low, the SPI module will interpret this as another master trying to take control of the bus. To avoid bus contention, the master will take the following action: 1. The master enters slave mode. 2. The SPI interrupt flag is set. 20.4 Slave Mode In slave mode, the SPI module will remain sleeping with the MISO line tri-stated as long as the SS pin is driven high. In this state, software may update the contents of the DATA register, but the data will not be shifted out by incoming clock pulses on the SCK pin until the SS pin is driven low. If SS is driven low, the slave will start to shift out data on the first SCK clock pulse. When one byte has been completely shifted, the SPI interrupt flag is set. The slave may continue placing new data to be sent into the DATA register before reading the incoming data. The last incoming byte will be kept in the buffer register. When SS is driven high, the SPI logic is reset, and the SPI slave will not receive any new data. Any partially received packet in the shift register will be dropped. As the SS pin is used to signal the start and end of a transfer, it is also useful for doing packet/byte synchronization, keeping the slave bit counter synchronous with the master clock generator. 20.5 Data Modes There are four combinations of SCK phase and polarity with respect to serial data. The SPI data transfer formats are shown in Figure 20-2. Data bits are shifted out and latched in on opposite edges of the SCK signal, ensuring sufficient time for data signals to stabilize. The leading edge is the first clock edge of a clock cycle. The trailing edge is the last clock edge of a clock cycle. Pin Master Mode Slave Mode MOSI User defined Input MISO Input User defined SCK User defined Input SS User defined Input XMEGA B [MANUAL] 257 8291C–AVR–09/2014 Figure 20-2. SPI transfer modes. 20.6 DMA Support DMA support on the SPI module is available only in slave mode. The SPI slave can trigger a DMA transfer as one byte has been shifted into the DATA register. It is possible, however, to use the XMEGA USART in SPI mode and then have DMA support in master mode. For details, refer to “USART in Master SPI Mode” on page 273. Bit 1 Bit 6 LSB MSB Mode 0 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN Mode 2 SS MSB LSB Bit 6 Bit 1 Bit 5 Bit 2 Bit 4 Bit 3 Bit 3 Bit 4 Bit 2 Bit 5 MSB first (DORD = 0) LSB first (DORD = 1) Mode 1 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN Mode 3 SS MSB LSB Bit 6 Bit 1 Bit 5 Bit 2 Bit 4 Bit 3 Bit 3 Bit 4 Bit 2 Bit 5 Bit 1 Bit 6 LSB MSB MSB first (DORD = 0) LSB first (DORD = 1) XMEGA B [MANUAL] 258 8291C–AVR–09/2014 20.7 Register Description 20.7.1 CTRL – Control register z Bit 7 – CLK2X: Clock Double When this bit is set, the SPI speed (SCK frequency) will be doubled in master mode (see Table 20-3 on page 259). z Bit 6 – ENABLE: Enable Setting this bit enables the SPI module. This bit must be set to enable any SPI operations. z Bit 5 – DORD: Data Order DORD decides the data order when a byte is shifted out from the DATA register. When DORD is written to one, the leastsignificant bit (lsb) of the data byte is transmitted first, and when DORD is written to zero, the most-significant bit (msb) of the data byte is transmitted first. z Bit 4 – MASTER: Master Select This bit selects master mode when written to one, and slave mode when written to zero. If SS is configured as an input and driven low while master mode is set, master mode will be cleared. z Bit 3:2 – MODE[1:0]: Transfer Mode These bits select the transfer mode. The four combinations of SCK phase and polarity with respect to the serial data are shown in Table 20-2. These bits decide whether the first edge of a clock cycle (leading edge) is rising or falling, and whether data setup and sample occur on the leading or trailing edge. When the leading edge is rising, the SCK signal is low when idle, and when the leading edge is falling, the SCK signal is high when idle. Table 20-2. SPI transfer mode z Bits 1:0 – PRESCALER[1:0]: Clock Prescaler These two bits control the SPI clock rate configured in master mode. These bits have no effect in slave mode. The relationship between SCK and the peripheral clock frequency ( clkPER) is shown in Table 20-3. Bit 7 6 5 4 3 2 1 0 +0x00 CLK2X ENABLE DORD MASTER MODE[1:0] PRESCALER[1:0] 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 MODE[1:0] Group Configuration Leading Edge Trailing Edge 00 0 Rising, sample Falling, setup 01 1 Rising, setup Falling, sample 10 2 Falling, sample Rising, setup 11 3 Falling, setup Rising, sample XMEGA B [MANUAL] 259 8291C–AVR–09/2014 Table 20-3. Relationship between SCK and the peripheral clock (ClkPER) frequency. 20.7.2 INTCTRL – Interrupt Control register z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1:0 – INTLVL[1:0]: Interrupt Level These bits enable the SPI interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when IF in the STATUS register is set. 20.7.3 STATUS – Status register z Bit 7 – IF: Interrupt Flag This flag is set when a serial transfer is complete and one byte is completely shifted in/out of the DATA register. If SS is configured as input and is driven low when the SPI is in master mode, this will also set this flag. IF is cleared by hardware when executing the corresponding interrupt vector. Alternatively, the IF flag can be cleared by first reading the STATUS register when IF is set, and then accessing the DATA register. z Bit 6 – WRCOL: Write Collision Flag The WRCOL flag is set if the DATA register is written during a data transfer. This flag is cleared by first reading the STATUS register when WRCOL is set, and then accessing the DATA register. z Bit 5:0 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. CLK2X PRESCALER[1:0] SCK Frequency 0 00 ClkPER/4 0 01 ClkPER/16 0 10 ClkPER/64 0 11 ClkPER/128 1 00 ClkPER/2 1 01 ClkPER/8 1 10 ClkPER/32 1 11 ClkPER/64 Bit 7 6 5 4 3 2 1 0 +0x01 – – – – – – INTLVL[1:0] Read/Write R R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x02 IF WRCOL – – – – – – Read/Write R R R R R R R R Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 260 8291C–AVR–09/2014 20.7.4 DATA – Data register The DATA register is used for sending and receiving data. Writing to the register initiates the data transmission, and the byte written to the register will be shifted out on the SPI output line. Reading the register causes the shift register receive buffer to be read, returning the last byte successfully received. 20.8 Register Summary 20.9 Interrupt vector Summary Bit 7 6 5 4 3 2 1 0 +0x03 DATA[7:0] 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 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL CLK2X ENABLE DORD MASTER MODE[1:0] PRESCALER[1:0] 258 +0x01 INTCTRL – – – – – – INTLVL[1:0] 259 +0x02 STATUS IF WRCOL – – – – – – 259 +0x03 DATA DATA[7:0] 260 Offset Source Interrupt Description 0x00 SPI_vect SPI interrupt vector XMEGA B [MANUAL] 261 8291C–AVR–09/2014 21. USART 21.1 Features z Full-duplex operation z Asynchronous or synchronous operation z Synchronous clock rates up to 1/2 of the device clock frequency z Asynchronous clock rates up to 1/8 of the device clock frequency z Supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits z Fractional baud rate generator z Can generate desired baud rate from any system clock frequency z No need for external oscillator with certain frequencies z Built-in error detection and correction schemes z Odd or even parity generation and parity check z Data overrun and framing error detection z Noise filtering includes false start bit detection and digital low-pass filter z Separate interrupts for z Transmit complete z Transmit data register empty z Receive complete z Multiprocessor communication mode z Addressing scheme to address a specific devices on a multi-device bus z Enable unaddressed devices to automatically ignore all frames z Master SPI mode z Double buffered operation z Configurable data order z Operation up to 1/2 of the peripheral clock frequency z IRCOM module for IrDA compliant pulse modulation/demodulation 21.2 Overview The universal synchronous and asynchronous serial receiver and transmitter (USART) is a fast and flexible serial communication module. The USART supports full-duplex communication and asynchronous and synchronous operation. The USART can be configured to operate in SPI master mode and used for SPI communication. Communication is frame based, and the frame format can be customized to support a wide range of standards. The USART is buffered in both directions, enabling continued data transmission without any delay between frames. Separate interrupts for receive and transmit complete enable fully interrupt driven communication. Frame error and buffer overflow are detected in hardware and indicated with separate status flags. Even or odd parity generation and parity check can also be enabled. A block diagram of the USART is shown in Figure 21-1 on page 262. The main functional blocks are the clock generator, the transmitter, and the receiver, which are indicated in dashed boxes. XMEGA B [MANUAL] 262 8291C–AVR–09/2014 Figure 21-1. USART block diagram. The clock generator includes a fractional baud rate generator that is able to generate a wide range of USART baud rates from any system clock frequencies. This removes the need to use an external crystal oscillator with a specific frequency to achieve a required baud rate. It also supports external clock input in synchronous slave operation. The transmitter consists of a single write buffer (DATA), a shift register, and a parity generator. The write buffer allows continuous data transmission without any delay between frames. The receiver consists of a two-level receive buffer (DATA) and a shift register. Data and clock recovery units ensure robust synchronization and noise filtering during asynchronous data reception. It includes frame error, buffer overflow, and parity error detection. When the USART is set in master SPI mode, all USART-specific logic is disabled, leaving the transmit and receive buffers, shift registers, and baud rate generator enabled. Pin control and interrupt generation are identical in both modes. The registers are used in both modes, but their functionality differs for some control settings. An IRCOM module can be enabled for one USART to support IrDA 1.4 physical compliant pulse modulation and demodulation for baud rates up to 115.2kbps. For details, refer to “IRCOM - IR Communication Module” on page 282. 21.3 Clock Generation The clock used for baud rate generation and for shifting and sampling data bits is generated internally by the fractional baud rate generator or externally from the transfer clock (XCK) pin. Five modes of clock generation are supported: normal and double-speed asynchronous mode, master and slave synchronous mode, and master SPI mode. PARITY GENERATOR BSEL [H:L] DATA (Transmit) CTRLA CTRLB CTRLC BAUD RATE GENERATOR FRACTIONAL DIVIDE TRANSMIT SHIFT REGISTER RECEIVE SHIFT REGISTER RxD TxD PIN CONTROL DATA (Receive) PIN CONTROL XCK DATA RECOVERY CLOCK RECOVERY PIN CONTROL TX CONTROL RX CONTROL PARITY CHECKER DATA BUS OSC SYNC LOGIC Clock Generator Transmitter Receiver XMEGA B [MANUAL] 263 8291C–AVR–09/2014 Figure 21-2. Clock generation logic, block diagram. 21.3.1 Internal Clock Generation - The Fractional Baud Rate Generator The fractional baud rate generator is used for internal clock generation for asynchronous modes, synchronous master mode, and master SPI mode operation. The output frequency generated (fBAUD) is determined by the period setting (BSEL), an optional scale setting (BSCALE), and the peripheral clock frequency (fPER). Table 21-1 contains equations for calculating the baud rate (in bits per second) and for calculating the BSEL value for each mode of operation. It also shows the maximum baud rate versus peripheral clock frequency. BSEL can be set to any value between 0 and 4095. BSCALE can be set to any value between -7 and +7, and increases or decreases the baud rate slightly to provide the fractional baud rate scaling of the baud rate generator. When BSEL is 0, BSCALE must also be 0. Also, the value 2ABS(BSCALE) must at most be one half of the minimum number of clock cycles a frame requires. For more details, see “Fractional Baud Rate Generation” on page 271. Table 21-1. Equations for calculating baud rate register settings. Note: 1. The baud rate is defined to be the transfer rate in bits per second (bps) Baud Rate Generator /2 BSEL /4 /2 Sync Register fOSC XCK Pin txclk CLK2X UMSEL [1] DDR_XCK 0 1 0 1 xcki xcko DDR_XCK rxclk 0 1 1 0 Edge Detector PORT_INV fBAUD Operating Mode Conditions Baud Rate(1) Calculation BSEL Value Calculation Asynchronous normal speed mode (CLK2X = 0) BSCALE ≥ 0 BSCALE < 0 Asynchronous double speed mode (CLK2X = 1) BSCALE ≥ 0 BSCALE < 0 Synchronous and master SPI mode f BAUD f PER 16 ≤ ------------- f BAUD f PER 2 BSCALE ⋅ 16(BSEL + 1) = ------------------------------------------------------------ BSEL f PER 2 BSCALE ⋅ 16 f BAUD = -------------------------------------------------- – 1 f BAUD f PER 16 ≤ ------------- f BAUD f PER 16((2BSCALE ⋅ BSEL ) + 1) = ------------------------------------------------------------------ BSEL 1 2 BSCALE --------------------- f PER 16 f BAUD ----------------------- – 1 ⎝ ⎠ ⎛ ⎞ = f BAUD f PER 8 ≤ ------------- f BAUD f PER 2 BSCALE ⋅ ⋅ 8 ( ) BSEL + 1 = -------------------------------------------------------------- BSEL f PER 2 BSCALE ⋅ 8 f BAUD = ----------------------------------------------- – 1 f BAUD f PER 8 ≤ ------------- f BAUD f PER 8((2BSCALE ⋅ BSEL ) + 1) = --------------------------------------------------------------- BSEL 1 2 BSCALE --------------------- f PER 8 f BAUD -------------------- – 1 ⎝ ⎠ ⎛ ⎞ = f BAUD f PER 2 < ------------- f BAUD f PER 2 ⋅ ( ) BSEL + 1 = ------------------------------------ BSEL f PER 2 f BAUD = -------------------- – 1 XMEGA B [MANUAL] 264 8291C–AVR–09/2014 For BSEL=0, all baud rates must be achieved by changing BSEL instead of setting BSCALE: BSEL = (2 BSCALE-1) 21.3.2 External Clock External clock (XCK) is used in synchronous slave mode operation. The XCK clock input is sampled on the peripheral clock frequency (fPER), and the maximum XCK clock frequency (fXCK)is limited by the following: For each high and low period, XCK clock cycles must be sampled twice by the peripheral clock. If the XCK clock has jitter, or if the high/low period duty cycle is not 50/50, the maximum XCK clock speed must be reduced or the peripheral clock must be increased accordingly. 21.3.3 Double Speed Operation Double speed operation allows for higher baud rates under asynchronous operation with lower peripheral clock frequencies. When this is enabled, the baud rate for a given asynchronous baud rate setting shown in Table 21-1 on page 263 will be doubled. In this mode, the receiver will use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery. Due to the reduced sampling, a more accurate baud rate setting and peripheral clock are required. See “Asynchronous Data Reception” on page 268 for more details. 21.3.4 Synchronous Clock Operation When synchronous mode is used, the XCK pin controls whether the transmission clock is input (slave mode) or output (master mode). The corresponding port pin must be set to output for master mode or to input for slave mode. The normal port operation of the XCK pin will be overridden. The dependency between the clock edges and data sampling or data change is the same. Data input (on RxD) is sampled at the XCK clock edge which is opposite the edge where data output (TxD) is changed. BSCALE BSEL BSCALE BSEL 1 0 → 0 1 2 0 → 0 3 3 0 → 0 7 4 0 → 0 15 5 0 → 0 31 6 0 → 0 63 7 0 → 0 127 f XCK f PER 4 < ------------- XMEGA B [MANUAL] 265 8291C–AVR–09/2014 Figure 21-3. Synchronous mode XCK timing. Using the inverted I/O (INVEN) setting for the corresponding XCK port pin, the XCK clock edges used for data sampling and data change can be selected. If inverted I/O is disabled (INVEN=0), data will be changed at the rising XCK clock edge and sampled at the falling XCK clock edge. If inverted I/O is enabled (INVEN=1), data will be changed at the falling XCK clock edge and sampled at the rising XCK clock edge. For more details, see “I/O Ports” on page 123. 21.3.5 Master SPI Mode Clock Generation For master SPI mode operation, only internal clock generation is supported. This is identical to the USART synchronous master mode, and the baud rate or BSEL setting is calculated using the same equations (see Table 21-1 on page 263). There are four combinations of the SPI clock (SCK) phase and polarity with respect to the serial data, and these are determined by the clock phase (UCPHA) control bit and the inverted I/O pin (INVEN) settings. The data transfer timing diagrams are shown in Figure 21-4 on page 266. Data bits are shifted out and latched in on opposite edges of the XCK signal, ensuring sufficient time for data signals to stabilize. The UCPHA and INVEN settings are summarized in Table 21- 2. Changing the setting of any of these bits during transmission will corrupt both the receiver and transmitter Table 21-2. INVEN and UCPHA functionality. The leading edge is the first clock edge of a clock cycle. The trailing edge is the last clock edge of a clock cycle. RxD / TxD XCK RxD / TxD UCPOL = 0 XCK UCPOL = 1 Sample Sample SPI Mode INVEN UCPHA Leading Edge Trailing Edge 0 0 0 Rising, sample Falling, setup 1 0 1 Rising, setup Falling, sample 2 1 0 Falling, sample Rising, setup 3 1 1 Falling, setup Rising, sample XMEGA B [MANUAL] 266 8291C–AVR–09/2014 Figure 21-4. UCPHA and INVEN data transfer timing diagrams. 21.4 Frame Formats Data transfer is frame based, where a serial frame consists of one character of data bits with synchronization bits (start and stop bits) and an optional parity bit for error checking. Note that this does not apply to master SPI operation (See “SPI Frame Formats” on page 267). The USART accepts all combinations of the following as valid frame formats: z 1 start bit z 5, 6, 7, 8, or 9 data bits z no, even, or odd parity bit z 1 or 2 stop bits A frame starts with the start bit, followed by all the data bits (least-significant bit first and most-significant bit last). If enabled, the parity bit is inserted after the data bits, before the first stop bit. One frame can be directly followed by a start bit and a new frame, or the communication line can return to the idle (high) state. Figure 21-5 on page 266 illustrates the possible combinations of frame formats. Bits inside brackets are optional. Figure 21-5. Frame formats. 21.4.1 Parity Bit Calculation Even or odd parity can be selected for error checking. If even parity is selected, the parity bit is set to one if the number of logical one data bits is odd (making the total number of ones even). If odd parity is selected, the parity bit is set to one if the number of logical one data bits is even (making the total number of ones odd). XCK Data setup (TXD) Data sample (RXD) XCK Data setup (TXD) Data sample (RXD) XCK Data setup (TXD) Data sample (RXD) XCK Data setup (TXD) Data sample (RXD) UCPOL=0 UCPOL=1 UCPHA=0 UCPHA=1 St Start bit, always low. (n) Data bits (0 to 8). P Parity bit, may be odd or even. Sp Stop bit, always high. IDLE No transfers on the communication line (RxD or TxD). The IDLE state is always high. (IDLE) St Sp1 [Sp2] 0 2 3 4 [5] [6] [7] [8] [P] 1 (St / IDLE) FRAME XMEGA B [MANUAL] 267 8291C–AVR–09/2014 21.4.2 SPI Frame Formats The serial frame in SPI mode is defined to be one character of eight data bits. The USART in master SPI mode has two selectable frame formats: z 8-bit data, msb first z 8-bit data, lsb first After a complete, 8-bit frame is transmitted, a new frame can directly follow it, or the communication line can return to the idle (high) state. 21.5 USART Initialization USART initialization should use the following sequence: 1. Set the TxD pin value high, and optionally set the XCK pin low. 2. Set the TxD and optionally the XCK pin as output. 3. Set the baud rate and frame format. 4. Set the mode of operation (enables XCK pin output in synchronous mode). 5. Enable the transmitter or the receiver, depending on the usage. For interrupt-driven USART operation, global interrupts should be disabled during the initialization. Before doing a re-initialization with a changed baud rate or frame format, be sure that there are no ongoing transmissions while the registers are changed. 21.6 Data Transmission - The USART Transmitter When the transmitter has been enabled, the normal port operation of the TxD pin is overridden by the USART and given the function as the transmitter's serial output. The direction of the pin must be set as output using the direction register for the corresponding port. For details on port pin control and output configuration, refer to “I/O Ports” on page 123. 21.6.1 Sending Frames A data transmission is initiated by loading the transmit buffer (DATA) with the data to be sent. The data in the transmit buffer are moved to the shift register when the shift register is empty and ready to send a new frame. The shift register is loaded if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previous frame is transmitted. When the shift register is loaded with data, it will transfer one complete frame. The transmit complete interrupt flag (TXCIF) is set and the optional interrupt is generated when the entire frame in the shift register has been shifted out and there are no new data present in the transmit buffer. The transmit data register (DATA) can only be written when the data register empty flag (DREIF) is set, indicating that the register is empty and ready for new data. When using frames with fewer than eight bits, the most-significant bits written to DATA are ignored. If 9-bit characters are used, the ninth bit must be written to the TXB8 bit before the low byte of the character is written to DATA. 21.6.2 Disabling the Transmitter A disabling of the transmitter will not become effective until ongoing and pending transmissions are completed; i.e., when the transmit shift register and transmit buffer register do not contain data to be transmitted. When the transmitter is disabled, it will no longer override the TxDn pin, and the pin direction is set as input automatically by hardware, even if it was configured as output by the user. 21.7 Data Reception - The USART Receiver When the receiver is enabled, the RxD pin functions as the receiver's serial input. The direction of the pin must be set as input, which is the default pin setting. XMEGA B [MANUAL] 268 8291C–AVR–09/2014 21.7.1 Receiving Frames The receiver starts data reception when it detects a valid start bit. Each bit that follows the start bit will be sampled at the baud rate or XCK clock and shifted into the receive shift register until the first stop bit of a frame is received. A second stop bit will be ignored by the receiver. When the first stop bit is received and a complete serial frame is present in the receive shift register, the contents of the shift register will be moved into the receive buffer. The receive complete interrupt flag (RXCIF) is set, and the optional interrupt is generated. The receiver buffer can be read by reading the data register (DATA) location. DATA should not be read unless the receive complete interrupt flag is set. When using frames with fewer than eight bits, the unused most-significant bits are read as zero. If 9-bit characters are used, the ninth bit must be read from the RXB8 bit before the low byte of the character is read from DATA. 21.7.2 Receiver Error Flags The USART receiver has three error flags. The frame error (FERR), buffer overflow (BUFOVF) and parity error (PERR) flags are accessible from the status register. The error flags are located in the receive FIFO buffer together with their corresponding frame. Due to the buffering of the error flags, the status register must be read before the receive buffer (DATA), since reading the DATA location changes the FIFO buffer. 21.7.3 Parity Checker When enabled, the parity checker calculates the parity of the data bits in incoming frames and compares the result with the parity bit of the corresponding frame. If a parity error is detected, the parity error flag is set. 21.7.4 Disabling the Receiver A disabling of the receiver will be immediate. The receiver buffer will be flushed, and data from ongoing receptions will be lost. 21.7.5 Flushing the Receive Buffer If the receive buffer has to be flushed during normal operation, read the DATA location until the receive complete interrupt flag is cleared. 21.8 Asynchronous Data Reception The USART includes a clock recovery and a data recovery unit for handling asynchronous data reception. The clock recovery unit is used for synchronizing the incoming asynchronous serial frames at the RxD pin to the internally generated baud rate clock. It samples and low-pass filters each incoming bit, thereby improving the noise immunity of the receiver. The asynchronous reception operational range depends on the accuracy of the internal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. 21.8.1 Asynchronous Clock Recovery The clock recovery unit synchronizes the internal clock to the incoming serial frames. Figure 21-6 on page 269 illustrates the sampling process for the start bit of an incoming frame. The sample rate is 16 times the baud rate for normal mode, and eight times the baud rate for double speed mode. The horizontal arrows illustrate the synchronization variation due to the sampling process. Note the larger time variation when using the double speed mode of operation. Samples denoted as zero are samples done when the RxD line is idle; i.e., when there is no communication activity. XMEGA B [MANUAL] 269 8291C–AVR–09/2014 Figure 21-6. Start bit sampling. When the clock recovery logic detects a high (idle) to low (start) transition on the RxD line, the start bit detection sequence is initiated. Sample 1 denotes the first zero-sample, as shown in the figure. The clock recovery logic then uses samples 8, 9, and 10 for normal mode and samples 4, 5, and 6 for double speed mode to decide if a valid start bit is received. If two or three samples have a low level, the start bit is accepted. The clock recovery unit is synchronized, and the data recovery can begin. If two or three samples have a high level, the start bit is rejected as a noise spike, and the receiver looks for the next high-to-low transition. The process is repeated for each start bit. 21.8.2 Asynchronous Data Recovery The data recovery unit uses sixteen samples in normal mode and eight samples in double speed mode for each bit. Figure 21-7 on page 269 shows the sampling process of data and parity bits. Figure 21-7. Sampling of data and parity bits. As for start bit detection, an identical majority voting technique is used on the three center samples for deciding of the logic level of the received bit. The process is repeated for each bit until a complete frame is received. It includes the first stop bit, but excludes additional ones. If the sampled stop bit is a 0 value, the frame error (FERR) flag will be set. Figure 21-8 on page 269 shows the sampling of the stop bit in relation to the earliest possible beginning of the next frame's start bit. Figure 21-8. Stop bit and next start bit sampling. A new high-to-low transition indicating the start bit of a new frame can come right after the last of the bits used for majority voting. For normal speed mode, the first low level sample can be at the point marked (A) in Stop Bit Sampling and Next Start Bit Sampling. For double speed mode, the first low level must be delayed to point (B). Point (C) marks a stop bit of full length at nominal baud rate. The early start bit detection influences the operational range of the receiver. 1234567 8 9 10 11 12 13 14 15 16 1 2 IDLE START 0 0 BIT 0 3 0 123 4 5 678 1 2 RxD Sample (U2X = 0) Sample (U2X = 1) 1234567 8 9 10 11 12 13 14 15 16 1 BIT n 123 4 5 678 1 RxD Sample (CLK2X = 0) Sample (CLK2X = 1) 1234567 8 9 10 0/1 0/1 0/1 STOP 1 123 4 5 6 0/1 RxD Sample (CLK2X = 0) Sample (CLK2X = 1) (A) (B) (C) XMEGA B [MANUAL] 270 8291C–AVR–09/2014 21.8.3 Asynchronous Operational Range The operational range of the receiver is dependent on the mismatch between the received bit rate and the internally generated baud rate. If an external transmitter is sending using bit rates that are too fast or too slow, or if the internally generated baud rate of the receiver does not match the external source’s base frequency, the receiver will not be able to synchronize the frames to the start bit. The following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. Table 21-3 and Table 21-4 on page 270 list the maximum receiver baud rate error that can be tolerated. Normal speed mode has higher tolerance of baud rate variations. Table 21-3. Recommended maximum receiver baud rate error for normal speed mode. Table 21-4. Recommended maximum receiver baud rate error for double speed mode. D Sum of character size and parity size (D = 5 to 10 bits). S Samples per bit. S = 16 for normal speed mode and S = 8 for double speed mode. SF First sample number used for majority voting. SF = 8 for normal speed mode and SF = 4 for double speed mode. SM Middle sample number used for majority voting. SM = 9 for normal speed mode and SM = 5 for double speed mode. Rslow The ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate. Rfast The ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. D #(Data + Parity Bit) Rslow [%] Rfast [%] Max Total Error [%] Recommended Max Receiver Error [%] 5 93.20 106.67 +6.67/-6.80 ± 3.0 6 94.12 105.79 +5.79/-5.88 ± 2.5 7 94.81 105.11 +5.11/-5.19 ± 2.0 8 95.36 104.58 +4.58/-4.54 ± 2.0 9 95.81 104.14 +4.14/-4.19 ± 1.5 10 96.17 103.78 +3.78/-3.83 ± 1.5 D #(Data + Parity Bit) Rslow [%] Rfast [%] Max Total Error [%] Recommended Max Receiver Error [%] 5 94.12 105.66 +5.66/-5.88 ± 2.5 6 94.92 104.92 +4.92/-5.08 ± 2.0 7 95.52 104.35 +4.35/-4.48 ± 1.5 Rslow ( ) D + 1 S S – 1 D S⋅ SF + + = ------------------------------------------- R fast ( ) D + 2 S ( ) D + 1 S SM + = ------------------------------------ XMEGA B [MANUAL] 271 8291C–AVR–09/2014 The recommendations for the maximum receiver baud rate error assume that the receiver and transmitter equally divide the maximum total error. 21.9 Fractional Baud Rate Generation Fractional baud rate generation is possible for asynchronous operation due to the relatively high number of clock cycles for each frame. Each bit is sampled sixteen times, but only the three middle samples are of importance. The total number of samples for one frame is also relatively high. Given a 1-start, 8-data, no-parity, and 1-stop-bit frame format, and assuming that normal speed mode is used, the total number of samples for a frame is (1+8+1)×16 or 160. As stated earlier, the UART can tolerate some variation in clock cycles for each sample. The critical factor is the time from the falling edge of the start bit (i.e., the clock synchronization) until the last bit's (i.e., the first stop bit’s) value is recovered. Standard baud rate generators have the unwanted property of having large frequency steps between high baud rate settings. The worst case is found between the BSEL values 0x000 and 0x001. Going from a BSEL value of 0x000, which has a 10-bit frame of 160 clock cycles, to a BSEL value of 0x001, with 320 clock cycles, gives a 50% change in frequency. Ideally, the step size should be small even between the fastest baud rates. This is where the advantage of the fractional baud rate generator emerges. In principle, the fractional baud rate generator works by doing uneven counting and then distributing the error evenly over the entire frame. A typical count sequence for an ordinary baud rate generator is: 2, 1, 0, 2, 1, 0, 2, 1, 0, 2, … which has an even period time. A baud rate clock ticks each time the counter reaches zero, and a sample of the signal received on RxD is taken for every 16th baud rate clock tick. For the fractional baud rate generator, the count sequence can have an uneven period: 2, 1, 0, 2, 1-1, 0, 2, 1, 0, 2, 1-1, 0,... In this example, an extra cycle is added to every second baud clock. This gives a baud rate clock tick jitter, but the average period has been increased by a fraction of 0.5 clock cycles. Figure 21-9 on page 272 shows an example of how BSEL and BSCALE can be used to achieve baud rates in between what is possible by just changing BSEL. The impact of fractional baud rate generation is that the step size between baud rate settings has been reduced. Given a scale factor of -1, the worst-case step then becomes from 160 to 240 clock cycles per 10-bit frame, compared to the previous step of from 160 to 320. A higher negative scale factor gives even finer granularity. There is a limit, however, to how high the scale factor can be. The value 2|BSCALE| must be at most half the minimum number of clock cycles of a frame. For instance, for 10-bit frames, the minimum number of clock cycles is 160. This means that the highest applicable scale factor is -6 (2I-6I = 64 < (160/2) = 80). For higher BSEL settings, the scale factor can be increased. Table 21-5 on page 272 shows BSEL and BSCALE settings when using the internal oscillators to generate the most commonly used baud rates for asynchronous operation and how reducing the BSCALE can be used to reduce the baud rate error even further. 8 96.00 103.90 +3.90/-4.00 ± 1.5 9 96.39 103.53 +3.53/-3.61 ± 1.5 10 96.70 103.23 +3.23/-3.30 ± 1.0 D #(Data + Parity Bit) Rslow [%] Rfast [%] Max Total Error [%] Recommended Max Receiver Error [%] XMEGA B [MANUAL] 272 8291C–AVR–09/2014 Figure 21-9. Fractional baud rate example. Table 21-5. USART baud rate. BSEL=0 BSCALE=0 fBAUD=fPER/8 clkBAUD8 clkBAUD8 BSEL=3 BSCALE=-6 fBAUD=fPER/8.375 clkBAUD8 BSEL=3 BSCALE=-4 fBAUD=fPER/9.5 Extra clock cycle added Baud fOSC = 32.0000MHz rate (bps) CLK2X = 0 CLK2X = 1 BSEL BSCALE Error [%] BSEL BSCALE Error [%] 2400 12 6 0.2 12 7 0.2 4800 12 5 0.2 12 6 0.2 9600 12 4 0.2 12 5 0.2 14.4k 34 2 0.8 34 3 0.8 138 0 -0.1 138 1 -0.1 19.2k 12 3 0.2 12 4 0.2 28.8k 34 1 -0.8 34 2 -0.8 137 -1 -0.1 138 0 -0.1 38.4k 12 2 0.2 12 3 0.2 57.6k 34 0 -0.8 34 1 -0.8 135 -2 -0.1 137 -1 -0.1 76.8k 12 1 0.2 12 2 0.2 115.2k 33 -1 -0.8 34 0 -0.8 131 -3 -0.1 135 -2 -0.1 230.4k 31 -2 -0.8 33 -1 -0.8 123 -4 -0.1 131 -3 -0.1 460.8k 27 -3 -0.8 31 -2 -0.8 107 -5 -0.1 123 -4 -0.1 XMEGA B [MANUAL] 273 8291C–AVR–09/2014 21.10 USART in Master SPI Mode Using the USART in master SPI mode requires the transmitter to be enabled. The receiver can optionally be enabled to serve as the serial input. The XCK pin will be used as the transfer clock. As for the USART, a data transfer is initiated by writing to the DATA register. This is the case for both sending and receiving data, since the transmitter controls the transfer clock. The data written to DATA are moved from the transmit buffer to the shift register when the shift register is ready to send a new frame. The transmitter and receiver interrupt flags and corresponding USART interrupts used in master SPI mode are identical in function to their use in normal USART operation. The receiver error status flags are not in use and are always read as zero. Disabling of the USART transmitter or receiver in master SPI mode is identical to their disabling in normal USART operation. 21.11 USART SPI vs. SPI The USART in master SPI mode is fully compatible with the standalone SPI module in that: z Timing diagrams are the same z UCPHA bit functionality is identical to that of the SPI CPHA bit z UDORD bit functionality is identical to that of the SPI DORD bit When the USART is set in master SPI mode, configuration and use are in some cases different from those of the standalone SPI module. In addition, the following differences exist: 921.6k 19 -4 -0.8 27 -3 -0.8 75 -6 -0.1 107 -5 -0.1 1.382M 7 -4 0.6 15 -3 0.6 57 -7 0.1 121 -6 0.1 1.843M 3 -5 -0.8 19 -4 -0.8 11 -7 -0.1 75 -6 -0.1 2.00M 0 0 0.0 1 0 0.0 2.304M – – – 3 -2 -0.8 47 -6 -0.1 2.5M – – – 19 -4 0.4 77 -7 -0.1 3.0M – – – 11 -5 -0.8 43 -7 -0.2 4.0M – – – 0 0 0.0 Max 2.0Mbps 4.0Mbps Baud fOSC = 32.0000MHz rate (bps) CLK2X = 0 CLK2X = 1 BSEL BSCALE Error [%] BSEL BSCALE Error [%] XMEGA B [MANUAL] 274 8291C–AVR–09/2014 z The USART transmitter in master SPI mode includes buffering, but the SPI module has no transmit buffer z The USART receiver in master SPI mode includes an additional buffer level z The USART in master SPI mode does not include the SPI write collision feature z The USART in master SPI mode does not include the SPI double speed mode feature, but this can be achieved by configuring the baud rate generator accordingly z Interrupt timing is not compatible z Pin control differs due to the master-only operation of the USART in SPI master mode A comparison of the USART in master SPI mode and the SPI pins is shown Table 21-6. Table 21-6. Comparison of USART in master SPI mode and SPI pins. 21.12 Multiprocessor Communication Mode The multiprocessor communication mode effectively reduces the number of incoming frames that have to be handled by the receiver in a system with multiple microcontrollers communicating via the same serial bus. In this mode, a dedicated bit in the frames is used to indicate whether the frame is an address or data frame type. If the receiver is set up to receive frames that contain five to eight data bits, the first stop bit is used to indicate the frame type. If the receiver is set up for frames with nine data bits, the ninth bit is used. When the frame type bit is one, the frame contains an address. When the frame type bit is zero, the frame is a data frame. If 5-bit to 8-bit character frames are used, the transmitter must be set to use two stop bits, since the first stop bit is used for indicating the frame type. If a particular slave MCU has been addressed, it will receive the following data frames as usual, while the other slave MCUs will ignore the frames until another address frame is received. 21.12.1 Using Multiprocessor Communication Mode The following procedure should be used to exchange data in multiprocessor communication mode (MPCM): 1. All slave MCUs are in multiprocessor communication mode. 2. The master MCU sends an address frame, and all slaves receive and read this frame. 3. Each slave MCU determines if it has been selected. 4. The addressed MCU will disable MPCM and receive all data frames. The other slave MCUs will ignore the data frames. 5. When the addressed MCU has received the last data frame, it must enable MPCM again and wait for a new address frame from the master. The process then repeats from step 2. Using any of the 5-bit to 8-bit character frame formats is impractical, as the receiver must change between using n and n+1 character frame formats. This makes full-duplex operation difficult, since the transmitter and receiver must use the same character size setting. USART SPI Comment TxD MOSI Master out only RxD MISO Master in only XCK SCK Functionally identical N/A SS Not supported by USART in master SPI mode XMEGA B [MANUAL] 275 8291C–AVR–09/2014 21.13 IRCOM Mode of Operation IRCOM mode can be enabled to use the IRCOM module with the USART. This enables IrDA 1.4 compliant modulation and demodulation for baud rates up to 115.2kbps. When IRCOM mode is enabled, double speed mode cannot be used for the USART. For devices with more than one USART, IRCOM mode can be enabled for only one USART at a time. For details, refer to “IRCOM - IR Communication Module” on page 282. 21.14 DMA Support DMA support is available on UART, USRT, and master SPI mode peripherals. For details on different USART DMA transfer triggers, refer to “Transfer Triggers” on page 49. XMEGA B [MANUAL] 276 8291C–AVR–09/2014 21.15 Register Description 21.15.1 DATA – Data register The USART transmit data buffer register (TXB) and USART receive data buffer register (RXB) share the same I/O address and is referred to as USART data register (DATA). The TXB register is the destination for data written to the DATA register location. Reading the DATA register location returns the contents of the RXB register. For 5-bit, 6-bit, or 7-bit characters, the upper unused bits will be ignored by the transmitter and set to zero by the receiver. The transmit buffer can be written only when DREIF in the STATUS register is set. Data written to the DATA register when DREIF is not set will be ignored by the USART transmitter. When data are written to the transmit buffer and the transmitter is enabled, the transmitter will load the data into the transmit shift register when the shift register is empty. The data are then transmitted on the TxD pin. The receive buffer consists of a two-level FIFO. Always read STATUS before DATA in order to get the correct status of the receive buffer. 21.15.2 STATUS – Status register z Bit 7 – RXCIF: Receive Complete Interrupt Flag This flag is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). When the receiver is disabled, the receive buffer will be flushed, and consequently RXCIF will become zero. When interrupt-driven data reception is used, the receive complete interrupt routine must read the received data from DATA in order to clear RXCIF. If not, a new interrupt will occur directly after the return from the current interrupt. This flag can also be cleared by writing a one to its bit location. z Bit 6 – TXCIF: Transmit Complete Interrupt Flag This flag is set when the entire frame in the transmit shift register has been shifted out and there are no new data in the transmit buffer (DATA). TXCIF is automatically cleared when the transmit complete interrupt vector is executed. The flag can also be cleared by writing a one to its bit location. z Bit 5 – DREIF: Data Register Empty Flag This flag indicates whether the transmit buffer (DATA) is ready to receive new data. The flag is one when the transmit buffer is empty and zero when the transmit buffer contains data to be transmitted that has not yet been moved into the shift register. DREIF is set after a reset to indicate that the transmitter is ready. Always write this bit to zero when writing the STATUS register. DREIF is cleared by writing DATA. When interrupt-driven data transmission is used, the data register empty interrupt routine must either write new data to DATA in order to clear DREIF or disable the data register empty interrupt. If not, a new interrupt will occur directly after the return from the current interrupt. Bit 7 6 5 4 3 2 1 0 +0x00 RXB[[7:0] TXB[[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x01 RXCIF TXCIF DREIF FERR BUFOVF PERR – RXB8 Read/Write R R/W R R R R R R/W Initial Value 0 0 1 0 0 0 0 0 XMEGA B [MANUAL] 277 8291C–AVR–09/2014 z Bit 4 – FERR: Frame Error The FERR flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. The bit is set if the received character had a frame error, i.e., the first stop bit was zero, and cleared when the stop bit of the received data is one. This bit is valid until the receive buffer (DATA) is read. FERR is not affected by setting the number of stop bits used, as it always uses only the first stop bit. Always write this bit location to zero when writing the STATUS register. This flag is not used in master SPI mode operation. z Bit 3 – BUFOVF: Buffer Overflow This flag indicates data loss due to a receiver buffer full condition. This flag is set if a buffer overflow condition is detected. A buffer overflow occurs when the receive buffer is full (two characters) with a new character waiting in the receive shift register and a new start bit is detected. This flag is valid until the receive buffer (DATA) is read. Always write this bit location to zero when writing the STATUS register. This flag is not used in master SPI mode operation. z Bit 2 – PERR: Parity Error If parity checking is enabled and the next character in the receive buffer has a parity error, this flag is set. If parity check is not enabled, this flag will always be read as zero. This bit is valid until the receive buffer (DATA) is read. Always write this bit location to zero when writing the STATUS register. For details on parity calculation, refer to “Parity Bit Calculation” on page 266. This flag is not used in master SPI mode operation. z Bit 1 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 0 – RXB8: Receive Bit 8 RXB8 is the ninth data bit of the received character when operating with serial frames with nine data bits. When used, this bit must be read before reading the low bits from DATA. This bit is unused in master SPI mode operation. 21.15.3 CTRLA – Control register A z Bit 7:6 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 5:4 – RXCINTLVL[1:0]: Receive Complete Interrupt Level These bits enable the receive complete interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when the RXCIF flag in the STATUS register is set. z Bit 3:2 – TXCINTLVL[1:0]: Transmit Complete Interrupt Level These bits enable the transmit complete interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when the TXCIF flag in the STATUS register is set. z Bit 1:0 – DREINTLVL[1:0]: Data Register Empty Interrupt Level These bits enable the data register empty interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when the DREIF flag in the STATUS register is set. Bit 7 6 5 4 3 2 1 0 +0x03 – – RXCINTLVL[1:0] TXCINTLVL[1:0] DREINTLVL[1:0] Read/Write R R R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 00000 XMEGA B [MANUAL] 278 8291C–AVR–09/2014 21.15.4 CTRLB – Control register B z Bit 7:5 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 4 – RXEN: Receiver Enable Setting this bit enables the USART receiver. The receiver will override normal port operation for the RxD pin, when enabled. Disabling the receiver will flush the receive buffer, invalidating the FERR, BUFOVF, and PERR flags. z Bit 3 – TXEN: Transmitter Enable Setting this bit enables the USART transmitter. The transmitter will override normal port operation for the TxD pin, when enabled. Disabling the transmitter (writing TXEN to zero) will not become effective until ongoing and pending transmissions are completed; i.e., when the transmit shift register and transmit buffer register do not contain data to be transmitted. When disabled, the transmitter will no longer override the TxD port. z Bit 2 – CLK2X: Double Transmission Speed Setting this bit will reduce the divisor of the baud rate divider from16 to 8, effectively doubling the transfer rate for asynchronous communication modes. For synchronous operation, this bit has no effect and should always be written to zero. This bit must be zero when the USART communication mode is configured to IRCOM. This bit is unused in master SPI mode operation. z Bit 1 – MPCM: Multiprocessor Communication Mode This bit enables the multiprocessor communication mode. When the MPCM bit is written to one, the USART receiver ignores all the incoming frames that do not contain address information. The transmitter is unaffected by the MPCM setting. For more detailed information, see “Multiprocessor Communication Mode” on page 274. This bit is unused in master SPI mode operation. z Bit 0 – TXB8: Transmit Bit 8 TXB8 is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. When used, this bit must be written before writing the low bits to DATA. This bit is unused in master SPI mode operation. 21.15.5 CTRLC – Control register C Note: 1. Master SPI mode. z Bits 7:6 – CMODE[1:0]: Communication Mode These bits select the mode of operation of the USART as shown in Table 21-7. Bit 7 6 5 4 3 2 1 0 +0x04 – – – RXEN TXEN CLK2X MPCM TXB8 Read/Write R R R R/W R/W R/W R/W R/W Initial Value 0 0 0 00000 Bit 7 6 5 4 3 2 1 0 +0x05 CMODE[1:0] PMODE[1:0] SBMODE CHSIZE[2:0] +0x05(1) CMODE[1:0] – – – UDORD UCPHA – Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0000110 XMEGA B [MANUAL] 279 8291C–AVR–09/2014 Table 21-7. CMODE bit settings. Notes: 1. See “IRCOM - IR Communication Module” on page 282 for full description on using IRCOM mode. 2. See “USART in Master SPI Mode” on page 273 for full description of the master SPI operation. z Bits 5:4 – PMODE[1:0]: Parity Mode These bits enable and set the type of parity generation according to Table 21-8. When enabled, the transmitter will automatically generate and send the parity of the transmitted data bits within each frame. The receiver will generate a parity value for the incoming data and compare it to the PMODE setting, and if a mismatch is detected, the PERR flag in STATUS will be set. These bits are unused in master SPI mode operation. Table 21-8. PMODE bit settings. z Bit 3 – SBMODE: Stop Bit Mode This bit selects the number of stop bits to be inserted by the transmitter according to Table 21-9. The receiver ignores this setting. This bit is unused in master SPI mode operation. Table 21-9. SBODE bit settings. z Bit 2:0 – CHSIZE[2:0]: Character Size The CHSIZE[2:0] bits set the number of data bits in a frame according to Table 21-10 on page 280. The receiver and transmitter use the same setting. CMODE[1:0] Group Configuration Mode 00 ASYNCHRONOUS Asynchronous USART 01 SYNCHRONOUS Synchronous USART 10 IRCOM IRCOM(1) 11 MSPI Master SPI(2) PMODE[1:0] Group Configuration Parity Mode 00 DISABLED Disabled 01 Reserved 10 EVEN Enabled, even parity 11 ODD Enabled, odd parity SBMODE Stop Bit(s) 0 1 1 2 XMEGA B [MANUAL] 280 8291C–AVR–09/2014 Table 21-10. CHSIZE bit settings. z Bit 2 – UDORD: Data Order This bit is only for master SPI mode, and this bit sets the frame format. When written to one, the lsb of the data word is transmitted first. When written to zero, the msb of the data word is transmitted first. The receiver and transmitter use the same setting. Changing the setting of UDORD will corrupt all ongoing communication for both receiver and transmitter. z Bit 1 – UCPHA: Clock Phase This bit is only for master SPI mode, and the bit determine whether data are sampled on the leading (first) edge or tailing (last) edge of XCKn. Refer to the “Master SPI Mode Clock Generation” on page 265 for details. 21.15.6 BAUDCTRLA – Baud Rate register A z Bit 7:0 – BSEL[7:0]: Baud Rate bits These are the lower 8 bits of the 12-bit BSEL value used for USART baud rate setting. BAUDCTRLB contains the four most-significant bits. Ongoing transmissions by the transmitter and receiver will be corrupted if the baud rate is changed. Writing BSEL will trigger an immediate update of the baud rate prescaler. See the equations in Table 21-1 on page 263. 21.15.7 BAUDCTRLB – Baud Rate register B z Bit 7:4 – BSCALE[3:0]: Baud Rate Scale factor These bits select the baud rate generator scale factor. The scale factor is given in two's complement form from -7 (0b1001) to +7 (0b0111). The -8 (0b1000) setting is reserved. See the equations in Table 21-1 on page 263. z Bit 3:0 – BSEL[11:8]: Baud Rate bits These are the upper 4 bits of the 12-bit value used for USART baud rate setting. BAUDCTRLA contains the eight leastsignificant bits. Ongoing transmissions by the transmitter and receiver will be corrupted if the baud rate is changed. Writing BAUDCTRLA will trigger an immediate update of the baud rate prescaler. CHSIZE[2:0] Group Configuration Character Size 000 5BIT 5-bit 001 6BIT 6-bit 010 7BIT 7-bit 011 8BIT 8-bit 100 Reserved 101 Reserved 110 Reserved 111 9BIT 9-bit Bit 7 6 5 4 3 2 1 0 +0x06 BSEL[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x07 BSCALE[3:0] BSEL[11:8] 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 XMEGA B [MANUAL] 281 8291C–AVR–09/2014 21.16 Register Summary 21.16.1 Register Description - USART 21.16.2 Register Description - USART in SPI Master Mode 21.17 Interrupt Vector Summary Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 DATA DATA[7:0] 276 +0x01 STATUS RXCIF TXCIF DREIF FERR BUFOVF PERR – RXB8 276 +0x02 Reserved – – – – – – – – +0x03 CTRLA – – RXCINTLVL[1:0] TXCINTLVL[1:0] DREINTLVL[1:0] 277 +0x04 CTRLB – – – RXEN TXEN CLK2X MPCM TXB8 278 +0x05 CTRLC CMODE[1:0] PMODE[1:0] SBMODE CHSIZE[2:0] 278 +0x06 BAUDCTRL BSEL[7:0] 280 +0x07 BAUDCTRL BSCALE[3:0] BSEL[11:8] 280 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 DATA DATA[7:0] 276 +0x01 STATUS RXCIF TXCIF DREIF – – – – – 276 +0x02 Reserved – – – – – – – – +0x03 CTRLA – – RXCINTLVL[1:0] TXCINTLVL[1:0] DREINTLVL[1:0] 277 +0x04 CTRLB – – – RXEN TXEN – – – 278 +0x05 CTRLC CMODE[1:0] – – – UDORD UCPHA – 278 +0x06 BAUDCTRL BSEL[7:0] 280 +0x07 BAUDCTRL BSCALE[3:0] BSEL[11:8] 280 Offset Source Interrupt Description 0x00 RXC_vect USART receive complete interrupt vector 0x02 DRE_vect USART data register empty interrupt vector 0x04 TXC_vect USART transmit complete interrupt vector XMEGA B [MANUAL] 282 8291C–AVR–09/2014 22. IRCOM - IR Communication Module 22.1 Features z Pulse modulation/demodulation for infrared communication z IrDA compatible for baud rates up to 115.2kbps z Selectable pulse modulation scheme z 3/16 of the baud rate period z Fixed pulse period, 8-bit programmable z Pulse modulation disabled z Built-in filtering z Can be connected to and used by any USART 22.2 Overview XMEGA devices contain an infrared communication module (IRCOM) that is IrDA compatible for baud rates up to 115.2kbps. It can be connected to any USART to enable infrared pulse encoding/decoding for that USART. Figure 22-1. IRCOM connection to USARTs and associated port pins. The IRCOM is automatically enabled when a USART is set in IRCOM mode. The signals between the USART and the RX/TX pins are then routed through the module as shown in Figure 22-1 on page 282. The data on the TX/RX pins are the inverted value of the transmitted/received infrared pulse. It is also possible to select an event channel from the event system as input for the IRCOM receiver. This will disable the RX input from the USART pin. For transmission, three pulse modulation schemes are available: z 3/16 of the baud rate period z Fixed programmable pulse time based on the peripheral clock frequency z Pulse modulation disabled IRCOM Pulse Decoding DIF Event System RXDxn TXDxn USARTxn .... USARTD0 USARTC0 RXDD0 TXDD0 RXDC0 TXDC0 Pulse Encoding decoded RXD encoded TXD encoded RXD RXD... TXD... decoded TXD events XMEGA B [MANUAL] 283 8291C–AVR–09/2014 For reception, a fixed programmable minimum high-level pulse width for the pulse to be decoded as a logical 0 is used. Shorter pulses will then be discarded, and the bit will be decoded to logical 1 as if no pulse was received. The module can only be used in combination with one USART at a time. Thus, IRCOM mode must not be set for more than one USART at a time. This must be ensured in the user software. 22.2.1 Event System Filtering The event system can be used as the receiver input. This enables IRCOM or USART input from I/O pins or sources other than the corresponding RX pin. If event system input is enabled, input from the USART's RX pin is automatically disabled. The event system has a digital input filter (DIF) on the event channels that can be used for filtering. Refer to “Event System” on page 63” for details on using the event system. XMEGA B [MANUAL] 284 8291C–AVR–09/2014 22.3 Registers Description 22.3.1 TXPLCTRL – Transmitter Pulse Length Control Register z Bit 7:0 – TXPLCTRL[7:0]: Transmitter Pulse Length Control This 8-bit value sets the pulse modulation scheme for the transmitter. Setting this register will have no effect if IRCOM mode is not selected by a USART. By leaving this register value to zero, 3/16 of the baud rate period pulse modulation is used. Setting this value from 1 to 254 will give a fixed pulse length coding. The 8-bit value sets the number of system clock periods for the pulse. The start of the pulse will be synchronized with the rising edge of the baud rate clock. Setting the value to 255 (0xFF) will disable pulse coding, letting the RX and TX signals pass through the IRCOM module unaltered. This enables other features through the IRCOM module, such as half-duplex USART, loop-back testing, and USART RX input from an event channel. TXPCTRL must be configured before the USART transmitter is enabled (TXEN). 22.3.2 RXPLCTRL – Receiver Pulse Length Control Register z Bit 7:0 – RXPLCTRL[7:0]: Receiver Pulse Length Control This 8-bit value sets the filter coefficient for the IRCOM transceiver. Setting this register will have no effect if IRCOM mode is not selected by a USART. By leaving this register value at zero, filtering is disabled. Setting this value between 1 and 255 will enable filtering, where x+1 equal samples are required for the pulse to be accepted. RXPCTRL must be configured before the USART receiver is enabled (RXEN). 22.3.3 CTRL – Control Register z Bit 7:4 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 3:0 – EVSEL [3:0]: Event Channel Selection These bits select the event channel source for the IRCOM receiver according to Table 22-1. If event input is selected for the IRCOM receiver, the input from the USART’s RX pin is automatically disabled. Bit 7 6 5 4 3 2 1 0 +0x01 TXPLCTRL[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x02 RXPLCTRL[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x00 – – – – EVSEL[3:0] Read/Write R R R R R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 285 8291C–AVR–09/2014 Table 22-1. Event channel selection. 22.4 Register Summary EVSEL[3:0] Group Configuration Event Source 0000 – None 0001 – (Reserved) 0010 – (Reserved) 0011 – (Reserved) 0100 – (Reserved) 0101 – (Reserved) 0110 – (Reserved) 0111 – (Reserved) 1nnn CHn Event system channel n; n = {0, …,7} Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL – – – – EVSEL[3:0] 284 +0x01 TXPLCTRL TXPLCTRL[7:0] 284 +0x02 RXPLCTRL RXPLCTRL[7:0] 284 XMEGA B [MANUAL] 286 8291C–AVR–09/2014 23. AES and DES Crypto Engines 23.1 Features z Data Encryption Standard (DES) CPU instruction z Advanced Encryption Standard (AES) crypto module z DES Instruction z Encryption and decryption z DES supported z Encryption/decryption in 16 CPU clock cycles per 8-byte block z AES crypto module z Encryption and decryption z Supports 128-bit keys z Supports XOR data load mode to the state memory z Encryption/decryption in 375 clock cycles per 16-byte block 23.2 Overview The Advanced Encryption Standard (AES) and Data Encryption Standard (DES) are two commonly used standards for cryptography. These are supported through an AES peripheral module and a DES CPU instruction, and the communication interfaces and the CPU can use these for fast, encrypted communication and secure data storage. DES is supported by an instruction in the AVR CPU. The 8-byte key and 8-byte data blocks must be loaded into the register file, and then the DES instruction must be executed 16 times to encrypt/decrypt the data block. The AES crypto module encrypts and decrypts 128-bit data blocks with the use of a 128-bit key. The key and data must be loaded into the key and state memory in the module before encryption/decryption is started. It takes 375 peripheral clock cycles before the encryption/decryption is done. The encrypted/encrypted data can then be read out, and an optional interrupt can be generated. The AES crypto module also has DMA support with transfer triggers when encryption/decryption is done and optional auto-start of encryption/decryption when the state memory is fully loaded. 23.3 DES Instruction The DES instruction is a single cycle instruction. In order to decrypt or encrypt a 64-bit (8-byte) data block, the instruction has to be executed 16 times. The data and key blocks must be loaded into the register file before encryption/decryption is started. The 64-bit data block (plaintext or ciphertext) is placed in registers R0-R7, where the LSB of data is placed in R0 and the MSB of data is placed in R7. The full 64-bit key (including parity bits) is placed in registers R8-R15, with the LSB of the key in R8 and the MSB of the key in R15. XMEGA B [MANUAL] 287 8291C–AVR–09/2014 Figure 23-1. Register file usage during DES encryption/decryption. Executing one DES instruction performs one round in the DES algorithm. Sixteen rounds must be executed in increasing order to form the correct DES ciphertext or plaintext. Intermediate results are stored in the register file (R0-R15) after each DES instruction. After sixteen rounds, the key is located in R8-R16 and the encrypted/decrypted ciphertext/plaintext is located in R0-R7. The instruction's operand (K) determines which round is executed, and the half carry flag (H) in the CPU status register determines whether encryption or decryption is performed. If the half carry flag is set, decryption is performed, and if the flag is cleared, encryption is performed. For more details on the DES instruction, refer to the AVR instruction set manual. 23.4 AES Crypto Module The AES crypto module performs encryption and decryption according to the Advanced Encryption Standard (FIPS-197). The 128-bit key block and 128-bit data block (plaintext or ciphertext) must be loaded into the key and state memories in the AES crypto module. This is done by writing the AES KEY register and STATE register sequentially with 16 bytes. It is software selectable whether the module should perform encryption or decryption. It is also possible to enable XOR mode, where all new data loaded to the state key is XORed with the current data in the state memory. The AES module uses 375 clock cycles before the encrypted/decrypted plaintext/ciphertext is available for readout in the state memory. The following setup and use procedure is recommended: 1. Enable the AES interrupt (optional). 2. Select the AES direction to encryption or decryption. 3. Load the key data block into the AES key memory. 4. Load the data block into the AES state memory. 5. Start the encryption/decryption operation. If more than one block is to be encrypted or decrypted, repeat the procedure from step 3. When the encryption/decryption procedure is complete, the AES interrupt flag is set and an optional interrupt is generated. Register File R0 R1 R2 R3 R4 R5 R6 R7 R8 R9 R10 R11 R12 R13 R14 R15 R16 ... R31 data0 data1 data2 data3 data4 data5 data6 data7 key0 key1 key2 key3 key4 key5 key6 key7 data key XMEGA B [MANUAL] 288 8291C–AVR–09/2014 23.4.1 Key and State Memory The AES key and state memory are both 16 x 8-bit memories that are accessible through the KEY and STATE registers, respectively. Each memory has two 4-bit address pointers used to address the memory for read and write, respectively. The initial value of the pointers is zero. After a read or write operation to the STATE or KEY register, the appropriate pointer is automatically incremented. Accessing (read or write) the control register (CTRL) will reset all pointers to zero. A pointer overflow (a sequential read or write done more than 16 times) will also set the affected pointer to zero. The pointers are not accessible from software. Read and write memory pointers are both incremented during write operations in XOR mode. Access to the KEY and STATE registers is possible only when encryption/decryption is not in progress. Figure 23-2. The state memory with pointers and register. The state memory contains the AES state throughout the encryption/decryption process. The initial value of the state is the initial data (i.e., plaintext in the encryption mode, and ciphertext in the decryption mode). The last value of the state is the encrypted/decrypted data. Figure 23-3. The key memory with pointers and register. In the AES crypto module, the following definition of the key is used: z In encryption mode, the key is the one defined in the AES standard. 4-bit state write address pointer 1 - 14 15 STATE 0 4-bit state read address pointer Reset pointer Reset pointer reset or access to AES Control reset or access to AES Control STATE[read pointer] xor XOR I/O Data Bus 4-bit key write address pointer 1 - 14 15 KEY 0 4-bit key read address pointer Reset pointer Reset pointer reset or access to CTRL reset or access to CTRL XMEGA B [MANUAL] 289 8291C–AVR–09/2014 z In decryption mode, the key is the last subkey of the expanded key defined in the AES standard. In decryption mode, the key expansion procedure must be executed by software before operation with the AES crypto module so that the last subkey is ready to be loaded through the KEY register. Alternatively, this procedure can be run in hardware by using the AES crypto module to process a dummy data block in encryption mode using the same key. After the end of the encryption, reading from the key memory allows the last subkey to be obtained; i.e., get the result of the key expansion procedure. Table 23-1 shows the results of reading the key, depending on the mode (encryption or decryption) and status of the AES crypto module. Table 23-1. The result of reading the key memory at different stages. 23.4.2 DMA Support The AES module can trigger a DMA transfer when the encryption/decryption procedure is complete. For more details on DMA transfer triggers, refer to “Transfer Triggers” on page 49. Encryption Decryption Before data processing After data processing Before data processing After Data Processing Same key as loaded The last subkey generated from the loaded key Same key as loaded The initial key generated from the last loaded subkey XMEGA B [MANUAL] 290 8291C–AVR–09/2014 23.5 Register Description – AES 23.5.1 CTRL – Control register z Bit 7 – START: Start/Run Setting this bit starts the encryption/decryption procedure, and this bit remains set while the encryption/decryption is ongoing. Writing this bit to zero will stop/abort any ongoing encryption/decryption process. This bit is automatically cleared if the SRIF or the ERROR flags in STATUS are set. z Bit 6 – AUTO: Auto Start Trigger Setting this bit enables the auto-start mode. In auto-start mode, the START bit will trigger automatically and start the encryption/decryption when all of the following conditions are met: z The AUTO bit is set before the state memory is loaded z All memory pointers (state read/write and key read/write) are zero z State memory is fully loaded If all of these conditions are not met, the encryption/decryption will be started with an incorrect key. z Bit 5 – RESET: Software Reset Setting this bit will reset the AES crypto module to its initial status on the next positive edge of the peripheral clock. All registers, pointers, and memories in the module are set to their initial value. When written to one, the bit stays high for one clock cycle before it is reset to zero by hardware. z Bit 4 – DECRYPT: Decryption / Direction This bit sets the direction for the AES crypto module. Writing this bit to zero will set the module in encryption mode. Writing one to this bit sets the module in decryption mode. z Bit 3 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 2 – XOR: State XOR Load Enable Setting this bit enables a XOR data load to the state memory. When this bit is set, the data loaded to the state memory are bitwise XORed with the data currently in the state memory. Writing this bit to zero disables XOR load mode, and new data written to the state memory will overwrite the current data. z Bit 1:0 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. Bit 7 6 5 4 3 2 1 0 +0x00 START AUTO RESET DECRYPT – XOR – – Read/Write R/W R/W R/W R/W R R/W R R Initial Value 0 0 0 0 0 0 0 0 XMEGA B [MANUAL] 291 8291C–AVR–09/2014 23.5.2 STATUS – AES Status register z Bit 7 – ERROR: Error The ERROR flag indicates an illegal handling of the AES crypto module. The flag is set in the following cases: z Setting START in the control register while the state memory and/or key memory are not fully loaded or read. This error occurs when the total number of read/write operations from/to the STATE and KEY registers is not a multiple of 16 before an AES start. z Accessing (read or write) the control register while the START bit is one. This flag can be cleared by software by writing one to its bit location. z Bit 6:1 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 0 – SRIF: State Ready Interrupt flag This flag is the interrupt/DMA request flag, and is set when the encryption/decryption procedure is completed and the state memory contains valid data. As long as the flag is zero, this indicates that there is no valid encrypted/decrypted data in the state memory. The flag is cleared by hardware when a read access is made to the state memory (the first byte is read). Alternatively, the bit can be cleared by writing a one to its bit location. 23.5.3 STATE – AES State register The STATE register is used to access the state memory. Before encryption/decryption can take place, the state memory must be written sequentially, byte-by-byte, through the STATE register. After encryption/decryption is done, the ciphertext/plaintext can be read sequentially, byte-by-byte, through the STATE register. Loading the initial data to the STATE register should be done after setting the appropriate AES mode and direction. This register can not be accessed during encryption/decryption. 23.5.4 KEY – Key register The KEY register is used to access the key memory. Before encryption/decryption can take place, the key memory must be written sequentially, byte-by-byte, through the KEY register. After encryption/decryption is done, the last subkey can be read sequentially, byte-by-byte, through the KEY register. Loading the initial data to the KEY register should be done after setting the appropriate AES mode and direction. Bit 7 6 5 4 3 2 1 0 +0x01 ERROR – – – – – – SRIF Read/Write R/W R R R R R R R/W Initial Value 00000000 Bit 7 6 5 4 3 2 1 0 +0x02 STATE[7:0] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0000 Bit 7 6 5 4 3 2 1 0 +0x03 KEY[7:0] 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 XMEGA B [MANUAL] 292 8291C–AVR–09/2014 23.5.5 INTCTRL – Interrupt Control register z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1:0 – INTLVL[1:0]: Interrupt priority and enable These bits enable the AES interrupt and select the interrupt level, as described in “Interrupts and Programmable Multilevel Interrupt Controller” on page 115. The enabled interrupt will be triggered when the SRIF in the STATUS register is set. 23.6 Register summary – AES 23.7 Interrupt vector summary Table 23-2. AES interrupt vector and its offset word address. Bit 7 6 5 4 3 2 1 0 +0x04 – – – – – – INTLVL[1:0] Read/Write R R R R R R R/W R/W Initial Value 0 0 0 0 0 0 0 0 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 bit 0 Page +0x00 CTRL START AUTO RESET DECRYPT – XOR – – 290 +0x01 STATUS ERROR – – – – – – SRIF 291 +0x02 STATE STATE[7:0] 291 +0x03 KEY KEY[7:0] 291 +0x04 INTCTRL – – – – – – INTLVL[1:0] 292 +0x05 Reserved – – – – – – – – +0x06 Reserved – – – – – – – – +0x07 Reserved – – – – – – – – Offset Source Interrupt Description 0x00 AES_vect AES interrupt vector XMEGA B [MANUAL] 293 8291C–AVR–09/2014 24. CRC – Cyclic Redundancy Check Generator 24.1 Features z Cyclic redundancy check (CRC) generation and checking for z Communication data z Program or data in flash memory z Data in SRAM and I/O memory space z Integrated with flash memory, DMA controller and CPU z Continuous CRC on data going through a DMA channel z Automatic CRC of the complete or a selectable range of the flash memory z CPU can load data to the CRC generator through the I/O interface z CRC polynomial software selectable to z CRC-16 (CRC-CCITT) z CRC-32 (IEEE 802.3) z Zero remainder detection 24.2 Overview A cyclic redundancy check (CRC) is an error detection technique test algorithm used to find accidental errors in data, and it is commonly used to determine the correctness of a data transmission, and data present in the data and program memories. A CRC takes a data stream or a block of data as input and generates a 16- or 32-bit output that can be appended to the data and used as a checksum. When the same data are later received or read, the device or application repeats the calculation. If the new CRC result does not match the one calculated earlier, the block contains a data error. The application will then detect this and may take a corrective action, such as requesting the data to be sent again or simply not using the incorrect data. Typically, an n-bit CRC applied to a data block of arbitrary length will detect any single error burst not longer than n bits (any single alteration that spans no more than n bits of the data), and will detect the fraction 1-2-n of all longer error bursts. The CRC module in XMEGA devices supports two commonly used CRC polynomials; CRC-16 (CRC-CCITT) and CRC-32 (IEEE 802.3). z CRC-16: z CRC-32: Polynomial: x16+x12+x5 +1 Hex value: 0x1021 Polynomial: x32+x26+x23+x22+x16+x12+x11+x10+x8 +x7 +x5 +x4 +x2 +x+1 Hex value: 0x04C11DB7 XMEGA B [MANUAL] 294 8291C–AVR–09/2014 24.3 Operation The data source for the CRC module must be selected in software as either flash memory, the DMA channels, or the I/O interface. The CRC module then takes data input from the selected source and generates a checksum based on these data. The checksum is available in the CHECKSUM registers in the CRC module. When CRC-32 polynomial is used, the final checksum read is bit reversed and complemented (see Figure 24-1). For the I/O interface or DMA controller, which CRC polynomial is used is software selectable, but the default setting is CRC-16. CRC-32 is automatically used if Flash Memory is selected as the source. The CRC module operates on bytes only. Figure 24-1. CRC generator block diagram. 24.4 CRC on Flash memory A CRC-32 calculation can be performed on the entire flash memory, on only the application section, on only the boot section, or on a software selectable range of the flash memory. Other than selecting the flash as the source, all further control and setup are done from the NVM controller. This means that the NVM controller configures the memory range to perform the CRC on, and the CRC is started using NVM commands. Once completed, the result is available in the checksum registers in the CRC module. For further details on setting up and performing CRC on flash memory, refer to “Memory Programming” on page 375. 24.5 CRC on DMA Data CRC-16 or CRC-32 calculations can be performed on data passing through any DMA channel. Once a DMA channel is selected as the source, the CRC module will continuously generate the CRC on the data passing through the DMA channel. The checksum is available for readout once the DMA transaction is completed or aborted. A CRC can be DATAIN CTRL Flash Memory DMA Controller CRC-16 CRC-32 CHECKSUM bit-reverse + complement 8 16 8 32 Checksum read crc32 XMEGA B [MANUAL] 295 8291C–AVR–09/2014 performed not only on communication data, but also on data in SRAM or I/O memory by passing these data through a DMA channel. If the latter is done, the destination register for the DMA data can be the data input (DATAIN) register in the CRC module. 24.6 CRC using the I/O Interface CRC can be performed on any data by loading them into the CRC module using the CPU and writing the data to the DATAIN register. Using this method, an arbitrary number of bytes can be written to the register by the CPU, and CRC is done continuously for each byte. New data can be written for each cycle. The CRC complete is signaled by writing the BUSY bit in the STATUS register. XMEGA B [MANUAL] 296 8291C–AVR–09/2014 24.7 Register Description 24.7.1 CTRL – Control register z Bit 7:6 – RESET[1:0]: Reset These bits are used to reset the CRC module, and they will always be read as zero. The CRC registers will be reset one peripheral clock cycle after the RESET[1] bit is set Table 24-1. CRC reset. z Bit 5 – CRC32: CRC-32 Enable Setting this bit will enable CRC-32 instead of the default CRC-16. It cannot be changed while the BUSY flag is set. z Bit 4 – Reserved This bit is unused and reserved for future use. For compatibility with future devices, always write this bit to zero when this register is written. z Bit 3:0 – SOURCE[3:0]: Input Source These bits select the input source for generating the CRC. The selected source is locked until either the CRC generation is completed or the CRC module is reset. CRC generation complete is generated and signaled from the selected source when used with the DMA controller or flash memory. Table 24-2. CRC source select. Bit 7 6 5 4 3 2 1 0 +0x00 RESET[1:0] CRC32 – SOURCE[3:0] 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 RESET[1:0] Group configuration Description 00 NO No reset 01 – Reserved 10 RESET0 Reset CRC with CHECKSUM to all zeros 11 RESET1 Reset CRC with CHECKSUM to all ones SOURCE[3:0] Group configuration Description 0000 DISABLE CRC disabled 0001 IO I/O interface 0010 FLASH Flash 0011 – Reserved for future use 0100 DMACH0 DMA controller channel 0 0101 DMACH1 DMA controller channel 1 0110 DMACH2 DMA controller channel 2 0111 DMACH3 DMA controller channel 3 1xxx – Reserved for future use XMEGA B [MANUAL] 297 8291C–AVR–09/2014 24.7.2 STATUS – Status register z Bit 7:2 – Reserved These bits are unused and reserved for future use. For compatibility with future devices, always write these bits to zero when this register is written. z Bit 1 – ZERO: Checksum Zero This flag is set if the CHECKSUM is zero when the CRC generation is complete. It is automatically cleared when a new CRC source is selected. When running CRC-32 and appending the checksum at the end of the packet (as little endian), the final checksum should be 0x2144df1c, and not zero. However, if the checksum is complemented before it is appended (as little endian) to the data, the final result in the checksum register will be zero. See the description of CHECKSUM to read out different versions of the CHECKSUM. z Bit 0 – BUSY: Busy This flag is read as one when a source configuration is selected and as long as the source is using the CRC module. If the I/O interface is selected as the source, the flag can be cleared by writing a one this location. If a DMA channel if selected as the source, the flag is cleared when the DMA channel transaction is completed or aborted. If flash memory is selected as the source, the flag is cleared when the CRC generation is completed. 24.7.3 DATAIN – Data Input register z Bit 7:0 – DATAIN[7:0]: Data Input This register is used to store the data for which the CRC checksum is computed. A new CHECKSUM is ready one clock cycle after the DATAIN register is written. 24.7.4 CHECKSUM0 – Checksum register 0 CHECKSUM0, CHECKSUM1, CHECKSUM2, and CHECKSUM3 represent the 16- or 32-bit CHECKSUM value and the generated CRC. The registers are reset to zero by default, but it is possible to write RESET to reset all bits to one. It is possible to write these registers only when the CRC module is disabled. If NVM is selected as the source, reading CHECKSUM will return a zero value until the BUSY flag is cleared. If CRC-32 is selected and the BUSY flag is cleared (i.e., CRC generation is completed or aborted), the bit reversed (bit 31 is swapped with bit 0, bit 30 with bit 1, etc.) and complemented result will be read from CHECKSUM. If CRC-16 is selected or the BUSY flag is set (i.e., CRC generation is ongoing), CHECKSUM will contain the actual content. z Bit 7:0 – CHECKSUM[7:0]: Checksum byte 0 These bits hold byte 0 of the generated CRC. Bit 7 6 5 4 3 2 1 0 +0x02 – – – – – – ZERO BUSY Read/Write R R R R R R R R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x03 DATAIN[7:0] Read/Write WWWWWWWW Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x04 CHECKSUM[7:0] 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 XMEGA B [MANUAL] 298 8291C–AVR–09/2014 24.7.5 CHECKSUM1 – Checksum register 1 z Bit 7:0 – CHECKSUM[15:8]: Checksum byte 1 These bits hold byte 1 of the generated CRC. 24.7.6 CHECKSUM2 – Checksum register 2 z Bit 7:0 – CHECKSUM[23:16]: Checksum byte 2 These bits hold byte 2 of the generated CRC when CRC-32 is used. 24.7.7 CHECKSUM3 – CRC Checksum register 3 z Bit 7:0 – CHECKSUM[31:24]: Checksum byte 3 These bits hold byte 3 of the generated CRC when CRC-32 is used. 24.8 Register Summary Bit 7 6 5 4 3 2 1 0 +0x05 CHECKSUM[15:8] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x06 CHECKSUM[23:16] Read/Write R/W R/W R/W R/W R/W R/W R/W R/W Initial Value 0 0 0 0 0 0 0 0 Bit 7 6 5 4 3 2 1 0 +0x07 CHECKSUM[31:24] 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 Address Name Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0 Page +0x00 CTRL RESET[1:0] CRC32 – SOURCE[3:0] 296 +0x01 STATUS – – – – – – ZERO BUSY 297 +0x02 Reserved – – – – – – – – +0x03 DATAIN DATAIN[7:0] 297 +0x04 CHECKSU CHECKSUM[7:0] 298 +0x05 CHECKSU CHECKSUM[15:8] 298 +0x06 CHECKSU CHECKSUM[23:16] 298 +0x07 CHECKSU CHECKSUM[31:24] 298 XMEGA B [MANUAL] 299 8291C–AVR–09/2014 25. LCD – Liquid Crystal Display 25.1 Features z Display Capacity up to 40 Segment and up to 4 Common Terminals z Supports up to 16 GPIO's z Shadow Display Memory Gives Full Freedom in Segment Update z ASCII Character Mapping z Swap Capability Option on Common and/or Segment Terminal Buses z Supports from Static up to 1/4 Duty z Supports Static and 1/3 Bias z LCD Driver Active in Power Save Mode for Low Power Operation z Software Selectable Low Power Waveform z Flexible Selection of Frame Frequency z Programmable Blink Mode and Frequency z Blink on two Segment Terminals z Uses Only 32kHz RTC Clock Source z On-chip LCD Power Supply z Software Contrast Adjustment Control z Equal Source and Sink Capability to Increase LCD Life Time z Extended Interrupt Mode for Display Update or Wake-up from Sleep Mode 25.2 Overview An LCD display is made of several segments (pixels or complete symbols) which can be visible or invisible. A segment has two electrodes with liquid crystal between them. These electrodes are the common terminal (COM pin) and the segment terminal (SEG pin). When a voltage above a threshold voltage is applied across the liquid crystal, the segment becomes visible. The voltage must alternate to avoid an electrophoresis effect in the liquid crystal, this effect degrades the display. Hence the voltage waveform across a segment must not have a DC-component. The LCD controller is intended for monochrome passive liquid crystal display (LCD) with up to 4 Common terminals and up to 40 Segments terminals. If the application does not need all the LCD segments available on the XMEGA, up to 16 of the unused LCD pins can be used as general purpose I/O pins. The LCD controller can be clocked by an internal or an external asynchronous 32kHz clock source. This 32kHz oscillator source selection is the same as for the Real Time Counter (RTC). Dedicated Low Power Waveform, Contrast Control, Extended Interrupt Mode, Selectable Frame Frequency and Blink functionality are supported to offload the CPU, reduce interrupts and reduce power consumption. To reduce hardware design complexity, the LCD includes integrated LCD buffers, an integrated power supply voltage and an innovative SWAP mode. Using SWAP mode, the hardware designers have more flexibility during board layout as they can rearrange the pin sequence on Segment and/or Common Terminal Buses. XMEGA B [MANUAL] 300 8291C–AVR–09/2014 25.2.1 Definitions Several terms are used when describing LCD. The definitions in Table 25-1 are used throughout this document. Table 25-1. LCD definitions. Figure 25-1. LCD Typical Connections 25.2.2 LCD Clock Sources The LCD