Avr Libc User Manual 1.8.1
User Manual: Pdf
Open the PDF directly: View PDF .
Page Count: 368
Download | |
Open PDF In Browser | View PDF |
avr-libc 1.8.1 Generated by Doxygen 1.8.7 Tue Aug 12 2014 21:20:45 ii CONTENTS Contents 1 2 AVR Libc 1 1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.2 General information about this library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1.3 Supported Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 1.4 avr-libc License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Toolchain Overview 11 2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.2 FSF and GNU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.3 GCC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 2.4 GNU Binutils . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2.5 avr-libc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.6 Building Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.7 AVRDUDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.8 GDB / Insight / DDD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.9 AVaRICE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.10 SimulAVR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.11 Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.12 Toolchain Distributions (Distros) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.13 Open Source 3 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Memory Areas and Using malloc() 15 3.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 3.2 Internal vs. external RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.3 Tunables for malloc() 3.4 Implementation details Memory Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 18 4.1 The .text Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.2 The .data Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.3 The .bss Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.4 The .eeprom Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.5 The .noinit Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.6 The .initN Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 4.7 The .finiN Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 4.8 Using Sections in Assembler Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 4.9 Using Sections in C Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen CONTENTS iii 5 22 6 7 8 9 Data in Program Space 5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 5.2 A Note On const . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 5.3 Storing and Retrieving Data in the Program Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 5.4 Storing and Retrieving Strings in the Program Space . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 5.5 Caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 avr-libc and assembler programs 26 6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 6.2 Invoking the compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 6.3 Example program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 6.4 Pseudo-ops and operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 Inline Assembler Cookbook 30 7.1 GCC asm Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 7.2 Assembler Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 7.3 Input and Output Operands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 7.4 Clobbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 7.5 Assembler Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 7.6 C Stub Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 7.7 C Names Used in Assembler Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 7.8 Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 How to Build a Library 39 8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 8.2 How the Linker Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 8.3 How to Design a Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 8.4 Creating a Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 8.5 Using a Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Benchmarks 42 9.1 A few of libc functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 9.2 Math functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 10 Porting From IAR to AVR GCC 44 10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 10.2 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 10.3 Interrupt Service Routines (ISRs) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 10.4 Intrinsic Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen iv CONTENTS 10.5 Flash Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 10.6 Non-Returning main() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 10.7 Locking Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 11 Frequently Asked Questions 48 11.1 FAQ Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 11.2 My program doesn’t recognize a variable updated within an interrupt routine . . . . . . . . . . . . . . . 49 11.3 I get "undefined reference to..." for functions like "sin()" . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 11.4 How to permanently bind a variable to a register? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 11.5 How to modify MCUCR or WDTCR early? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 11.6 What is all this _BV() stuff about? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 11.7 Can I use C++ on the AVR? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 11.8 Shouldn’t I initialize all my variables? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 11.9 Why do some 16-bit timer registers sometimes get trashed? . . . . . . . . . . . . . . . . . . . . . . . . 52 11.10How do I use a #define’d constant in an asm statement? . . . . . . . . . . . . . . . . . . . . . . . . . . 52 11.11Why does the PC randomly jump around when single-stepping through my program in avr-gdb? . . . . . 53 11.12How do I trace an assembler file in avr-gdb? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 11.13How do I pass an IO port as a parameter to a function? . . . . . . . . . . . . . . . . . . . . . . . . . . 54 11.14What registers are used by the C compiler? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 11.15How do I put an array of strings completely in ROM? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 11.16How to use external RAM? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 11.17Which -O flag to use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 11.18How do I relocate code to a fixed address? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 11.19My UART is generating nonsense! My ATmega128 keeps crashing! Port F is completely broken! . . . . 60 11.20Why do all my "foo...bar" strings eat up the SRAM? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 11.21Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation in assembly? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 11.22How to detect RAM memory and variable overlap problems? . . . . . . . . . . . . . . . . . . . . . . . 61 11.23Is it really impossible to program the ATtinyXX in C? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 11.24What is this "clock skew detected" message? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 11.25Why are (many) interrupt flags cleared by writing a logical 1? . . . . . . . . . . . . . . . . . . . . . . . 62 11.26Why have "programmed" fuses the bit value 0? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 11.27Which AVR-specific assembler operators are available? . . . . . . . . . . . . . . . . . . . . . . . . . . 63 11.28Why are interrupts re-enabled in the middle of writing the stack pointer? . . . . . . . . . . . . . . . . . . 63 11.29Why are there five different linker scripts? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 11.30How to add a raw binary image to linker output? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 11.31How do I perform a software reset of the AVR? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 11.32I am using floating point math. Why is the compiled code so big? Why does my code not work? . . . . . 65 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen CONTENTS v 11.33What pitfalls exist when writing reentrant code? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 11.34Why are some addresses of the EEPROM corrupted (usually address zero)? . . . . . . . . . . . . . . . 68 11.35Why is my baud rate wrong? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 11.36On a device with more than 128 KiB of flash, how to make function pointers work? . . . . . . . . . . . . 68 11.37Why is assigning ports in a "chain" a bad idea? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 12 Building and Installing the GNU Tool Chain 69 12.1 Building and Installing under Linux, FreeBSD, and Others . . . . . . . . . . . . . . . . . . . . . . . . . 69 12.2 Required Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 12.3 Optional Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70 12.4 GNU Binutils for the AVR target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 12.5 GCC for the AVR target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 12.6 AVR LibC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 12.7 AVRDUDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 12.8 GDB for the AVR target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 12.9 SimulAVR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 12.10AVaRICE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 12.11Building and Installing under Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 12.12Tools Required for Building the Toolchain for Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 12.13Building the Toolchain for Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 13 Using the GNU tools 81 13.1 Options for the C compiler avr-gcc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 13.1.1 Machine-specific options for the AVR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 13.1.2 Selected general compiler options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 13.2 Options for the assembler avr-as . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 13.2.1 Machine-specific assembler options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 13.2.2 Examples for assembler options passed through the C compiler . . . . . . . . . . . . . . . . . 96 13.3 Controlling the linker avr-ld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 13.3.1 Selected linker options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96 13.3.2 Passing linker options from the C compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 14 Compiler optimization 98 14.1 Problems with reordering code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 15 Using the avrdude program 16 Release Numbering and Methodology 99 101 16.1 Release Version Numbering Scheme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen vi CONTENTS 16.2 Releasing AVR Libc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 16.2.1 Creating an SVN branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 16.2.2 Making a release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 17 Acknowledgments 103 18 Todo List 104 19 Deprecated List 104 20 Module Index 105 20.1 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105 21 Data Structure Index 106 21.1 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 22 File Index 107 22.1 File List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 23 Module Documentation 111 23.1: Allocate space in the stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 23.1.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 23.1.2 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 23.2 : Diagnostics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 23.2.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 23.2.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112 23.3 : Character Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 23.3.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 23.3.2 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 23.4 : System Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 23.4.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 23.4.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 23.5 : Integer Type conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 23.5.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 23.5.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118 23.5.3 Typedef Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 23.6 : Mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 23.6.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 23.6.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 23.6.3 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen CONTENTS vii 23.7 : Non-local goto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 23.7.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 23.7.2 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 23.8 : Standard Integer Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 23.8.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 23.8.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142 23.8.3 Typedef Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146 23.9 : Standard IO facilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149 23.9.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150 23.9.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 23.9.3 Typedef Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 23.9.4 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155 23.10 : General utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 23.10.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 23.10.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 23.10.3 Typedef Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 23.10.4 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 23.10.5 Variable Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 23.11 : Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172 23.11.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 23.11.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 23.11.3 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 23.12 : Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182 23.12.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 23.12.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 23.12.3 Typedef Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 23.12.4 Enumeration Type Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 23.12.5 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 23.13 : Bootloader Support Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 23.13.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 23.13.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 23.14 : Special AVR CPU functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 23.14.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 23.14.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 23.15 : EEPROM handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 23.15.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197 23.15.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen viii CONTENTS 23.15.3 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198 23.16 : Fuse Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 23.17 : Interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 23.17.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204 23.17.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219 23.18 : AVR device-specific IO definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 23.18.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222 23.18.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223 23.19 : Lockbit Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224 23.20 : Program Space Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226 23.20.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 23.20.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227 23.20.3 Typedef Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230 23.20.4 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233 23.21 : Power Reduction Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239 23.22Additional notes from . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 23.23 : Special function registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 23.23.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 23.23.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 23.24 : Signature Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255 23.25 : Power Management and Sleep Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 23.25.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256 23.25.2 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257 23.26 : avr-libc version macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 23.26.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 23.26.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258 23.27 : Watchdog timer handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 23.27.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 23.27.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 23.28 Atomically and Non-Atomically Executed Code Blocks . . . . . . . . . . . . . . . . . . 263 23.28.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 23.28.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264 23.29 : CRC Computations 23.29.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 23.29.2 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 23.30 : Convenience functions for busy-wait delay loops . . . . . . . . . . . . . . . . . . . . . . 270 23.30.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen CONTENTS ix 23.30.2 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 23.31 : Basic busy-wait delay loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 23.31.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 23.31.2 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 23.32 : Parity bit generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 23.32.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 23.32.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 23.33 : Helper macros for baud rate calculations . . . . . . . . . . . . . . . . . . . . . . . . 274 23.33.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274 23.33.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275 23.34 : TWI bit mask definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 23.34.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276 23.34.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277 23.35 : Deprecated items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 23.35.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280 23.35.2 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281 23.35.3 Function Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282 23.36 : Compatibility with IAR EWB 3.x . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 23.37Demo projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 23.37.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284 23.38Combining C and assembly source files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 23.38.1 Hardware setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 23.38.2 A code walkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285 23.38.3 The source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287 23.39A simple project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 23.39.1 The Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288 23.39.2 The Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289 23.39.3 Compiling and Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 23.39.4 Examining the Object File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291 23.39.5 Linker Map Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 23.39.6 Generating Intel Hex Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 23.39.7 Letting Make Build the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297 23.39.8 Reference to the source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299 23.40A more sophisticated project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 23.40.1 Hardware setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300 23.40.2 Functional overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 23.40.3 A code walkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen x CONTENTS 23.40.4 The source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305 23.41Using the standard IO facilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 23.41.1 Hardware setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306 23.41.2 Functional overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 23.41.3 A code walkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307 23.41.4 The source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311 23.42Example using the two-wire interface (TWI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 23.42.1 Introduction into TWI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 23.42.2 The TWI example project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 23.42.3 The Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312 24 Data Structure Documentation 316 24.1 atexit_s Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 24.2 div_t Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 24.2.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 24.2.2 Field Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 24.3 ldiv_t Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 24.3.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316 24.3.2 Field Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 24.4 tm Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 24.4.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317 24.5 week_date Struct Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 24.5.1 Detailed Description 25 File Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 318 25.1 assert.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 25.2 atoi.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 25.3 atol.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 25.4 atomic.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 25.5 boot.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318 25.5.1 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320 25.6 cpufunc.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 25.7 crc16.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323 25.8 ctype.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 25.9 delay.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 25.10delay_basic.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324 25.11errno.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 25.12fdevopen.c File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen CONTENTS xi 25.13ffs.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 25.14ffsl.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 25.15ffsll.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 25.16fuse.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 25.17interrupt.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326 25.17.1 Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 25.18inttypes.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327 25.19io.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 25.20lock.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 25.21math.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329 25.22memccpy.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.23memchr.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.24memchr_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.25memcmp.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.26memcmp_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.27memcmp_PF.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.28memcpy.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.29memcpy_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.30memmem.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.31memmove.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.32memrchr.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.33memrchr_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.34memset.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.35parity.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.36pgmspace.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332 25.36.1 Macro Definition Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335 25.37power.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340 25.38setbaud.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 25.39setjmp.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 25.40signature.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 25.41sleep.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341 25.42stdint.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342 25.43stdio.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344 25.44stdlib.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346 25.45strcasecmp.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.46strcasecmp_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.47strcasestr.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen xii CONTENTS 25.48strcat.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.49strcat_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.50strchr.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.51strchr_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.52strchrnul.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.53strchrnul_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.54strcmp.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.55strcmp_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.56strcpy.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.57strcpy_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.58strcspn.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.59strcspn_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.60strdup.c File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348 25.61string.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349 25.62strlcat.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.63strlcat_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.64strlcpy.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.65strlcpy_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.66strlen.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.67strlen_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.68strlwr.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.69strncasecmp.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.70strncasecmp_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.71strncat.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.72strncat_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.73strncmp.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.74strncmp_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.75strncpy.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.76strncpy_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.77strnlen.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.78strnlen_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.79strpbrk.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.80strpbrk_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.81strrchr.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.82strrchr_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.83strrev.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.84strsep.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 1 AVR Libc 1 25.85strsep_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350 25.86strspn.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.87strspn_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.88strstr.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.89strstr_P.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.90strtok.c File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.91strtok_P.c File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.92strtok_r.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.93strtok_rP.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.94strupr.S File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.95time.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351 25.96twi.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353 25.97wdt.h File Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 Index 1 1.1 355 AVR Libc Introduction The latest version of this document is always available from http://savannah.nongnu.org/projects/avr-libc/ The AVR Libc package provides a subset of the standard C library for Atmel AVR 8-bit RISC microcontrollers. In addition, the library provides the basic startup code needed by most applications. There is a wealth of information in this document which goes beyond simply describing the interfaces and routines provided by the library. We hope that this document provides enough information to get a new AVR developer up to speed quickly using the freely available development tools: binutils, gcc avr-libc and many others. If you find yourself stuck on a problem which this document doesn’t quite address, you may wish to post a message to the avr-gcc mailing list. Most of the developers of the AVR binutils and gcc ports in addition to the devleopers of avr-libc subscribe to the list, so you will usually be able to get your problem resolved. You can subscribe to the list at http://lists.nongnu.org/mailman/listinfo/avr-gcc-list . Before posting to the list, you might want to try reading the Frequently Asked Questions chapter of this document. Note If you think you’ve found a bug, or have a suggestion for an improvement, either in this documentation or in the library itself, please use the bug tracker at https://savannah.nongnu.org/bugs/?group=avr-libc to ensure the issue won’t be forgotten. 1.2 General information about this library In general, it has been the goal to stick as best as possible to established standards while implementing this library. Commonly, this refers to the C library as described by the ANSI X3.159-1989 and ISO/IEC 9899:1990 ("ANSI-C") standard, as well as parts of their successor ISO/IEC 9899:1999 ("C99"). Some additions have been inspired by other standards like IEEE Std 1003.1-1988 ("POSIX.1"), while other extensions are purely AVR-specific (like the entire program-space string interface). Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 2 CONTENTS Unless otherwise noted, functions of this library are not guaranteed to be reentrant. In particular, any functions that store local state are known to be non-reentrant, as well as functions that manipulate IO registers like the EEPROM access routines. If these functions are used within both standard and interrupt contexts undefined behaviour will result. See the FAQ for a more detailed discussion. 1.3 Supported Devices The following is a list of AVR devices currently supported by the library. Note that actual support for some newer devices depends on the ability of the compiler/assembler to support these devices at library compile-time. megaAVR Devices: • atmega103 • atmega128 • atmega128a • atmega1280 • atmega1281 • atmega1284 • atmega1284p • atmega16 • atmega161 • atmega162 • atmega163 • atmega164a • atmega164p • atmega164pa • atmega165 • atmega165a • atmega165p • atmega165pa • atmega168 • atmega168a • atmega168p • atmega168pa • atmega16a • atmega2560 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 1.3 Supported Devices • atmega2561 • atmega32 • atmega32a • atmega323 • atmega324a • atmega324p • atmega324pa • atmega325 • atmega325a • atmega325p • atmega325pa • atmega3250 • atmega3250a • atmega3250p • atmega3250pa • atmega328 • atmega328p • atmega48 • atmega48a • atmega48pa • atmega48p • atmega64 • atmega64a • atmega640 • atmega644 • atmega644a • atmega644p • atmega644pa • atmega645 • atmega645a • atmega645p • atmega6450 • atmega6450a Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 3 4 CONTENTS • atmega6450p • atmega8 • atmega8a • atmega88 • atmega88a • atmega88p • atmega88pa • atmega8515 • atmega8535 tinyAVR Devices: • attiny4 • attiny5 • attiny10 • attiny11 [1] • attiny12 [1] • attiny13 • attiny13a • attiny15 [1] • attiny20 • attiny22 • attiny24 • attiny24a • attiny25 • attiny26 • attiny261 • attiny261a • attiny28 [1] • attiny2313 • attiny2313a • attiny40 • attiny4313 • attiny43u Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 1.3 Supported Devices • attiny44 • attiny44a • attiny45 • attiny461 • attiny461a • attiny48 • attiny828 • attiny84 • attiny84a • attiny85 • attiny861 • attiny861a • attiny87 • attiny88 • attiny1634 Automotive AVR Devices: • atmega16m1 • atmega32c1 • atmega32m1 • atmega64c1 • atmega64m1 • attiny167 • ata5505 • ata5272 • ata5790 • ata5795 CAN AVR Devices: • at90can32 • at90can64 • at90can128 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 5 6 CONTENTS LCD AVR Devices: • atmega169 • atmega169a • atmega169p • atmega169pa • atmega329 • atmega329a • atmega329p • atmega329pa • atmega3290 • atmega3290a • atmega3290p • atmega3290pa • atmega649 • atmega649a • atmega6490 • atmega6490a • atmega6490p • atmega649p Lighting AVR Devices: • at90pwm1 • at90pwm2 • at90pwm2b • at90pwm216 • at90pwm3 • at90pwm3b • at90pwm316 • at90pwm161 • at90pwm81 Smart Battery AVR Devices: Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 1.3 Supported Devices • atmega8hva • atmega16hva • atmega16hva2 • atmega16hvb • atmega16hvbrevb • atmega32hvb • atmega32hvbrevb • atmega64hve • atmega406 USB AVR Devices: • at90usb82 • at90usb162 • at90usb646 • at90usb647 • at90usb1286 • at90usb1287 • atmega8u2 • atmega16u2 • atmega16u4 • atmega32u2 • atmega32u4 • atmega32u6 XMEGA Devices: • atxmega16a4 • atxmega16a4u • atxmega16c4 • atxmega16d4 • atxmega32a4 • atxmega32a4u • atxmega32c4 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 7 8 CONTENTS • atxmega32d4 • atxmega64a1 • atxmega64a1u • atxmega64a3 • atxmega64a3u • atxmega64a4u • atxmega64b1 • atxmega64b3 • atxmega64c3 • atxmega64d3 • atxmega64d4 • atxmega128a1 • atxmega128a1u • atxmega128a3 • atxmega128a3u • atxmega128a4u • atxmega128b1 • atxmega128b3 • atxmega128c3 • atxmega128d3 • atxmega128d4 • atxmega192a3 • atxmega192a3u • atxmega192c3 • atxmega192d3 • atxmega256a3 • atxmega256a3u • atxmega256a3b • atxmega256a3bu • atxmega256c3 • atxmega256d3 • atxmega384c3 • atxmega384d3 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 1.3 Supported Devices 9 Wireless AVR devices: -atmega644rfr2 -atmega64rfr2 -atmega128rfa1 -atmega1284rfr2 -atmega128rfr2 -atmega2564rfr2 -atmega256rfr2 Miscellaneous Devices: • at94K [2] • at76c711 [3] • at43usb320 • at43usb355 • at86rf401 • at90scr100 • ata6285 • ata6286 • ata6289 • m3000 [4] Classic AVR Devices: • at90s1200 [1] • at90s2313 • at90s2323 • at90s2333 • at90s2343 • at90s4414 • at90s4433 • at90s4434 • at90s8515 • at90c8534 • at90s8535 Note [1] Assembly only. There is no direct support for these devices to be programmed in C since they do not have a RAM based stack. Still, it could be possible to program them in C, see the FAQ for an option. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 10 CONTENTS Note [2] The at94K devices are a combination of FPGA and AVR microcontroller. [TRoth-2002/11/12: Not sure of the level of support for these. More information would be welcomed.] Note [3] The at76c711 is a USB to fast serial interface bridge chip using an AVR core. Note [4] The m3000 is a motor controller AVR ASIC from Intelligent Motion Systems (IMS) / Schneider Electric. 1.4 avr-libc License avr-libc can be freely used and redistributed, provided the following license conditions are met. Portions of avr-libc are Copyright (c) 1999-2010 Werner Boellmann, Dean Camera, Pieter Conradie, Brian Dean, Keith Gudger, Wouter van Gulik, Bjoern Haase, Steinar Haugen, Peter Jansen, Reinhard Jessich, Magnus Johansson, Harald Kipp, Carlos Lamas, Cliff Lawson, Artur Lipowski, Marek Michalkiewicz, Todd C. Miller, Rich Neswold, Colin O’Flynn, Bob Paddock, Andrey Pashchenko, Reiner Patommel, Florin-Viorel Petrov, Alexander Popov, Michael Rickman, Theodore A. Roth, Juergen Schilling, Philip Soeberg, Anatoly Sokolov, Nils Kristian Strom, Michael Stumpf, Stefan Swanepoel, Helmut Wallner, Eric B. Weddington, Joerg Wunsch, Dmitry Xmelkov, Atmel Corporation, egnite Software GmbH, The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 2 Toolchain Overview 11 notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holders nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 2 2.1 Toolchain Overview Introduction Welcome to the open source software development toolset for the Atmel AVR! There is not a single tool that provides everything needed to develop software for the AVR. It takes many tools working together. Collectively, the group of tools are called a toolset, or commonly a toolchain, as the tools are chained together to produce the final executable application for the AVR microcontroller. The following sections provide an overview of all of these tools. You may be used to cross-compilers that provide everything with a GUI front-end, and not know what goes on "underneath the hood". You may be coming from a desktop or server computer background and not used to embedded systems. Or you may be just learning about the most common software development toolchain available on Unix and Linux systems. Hopefully the following overview will be helpful in putting everything in perspective. 2.2 FSF and GNU According to its website, "the Free Software Foundation (FSF), established in 1985, is dedicated to promoting computer users’ rights to use, study, copy, modify, and redistribute computer programs. The FSF promotes the development and use of free software, particularly the GNU operating system, used widely in its GNU/Linux variant." The FSF remains the primary sponsor of the GNU project. The GNU Project was launched in 1984 to develop a complete Unix-like operating system which is free software: the GNU system. GNU is a recursive acronym for »GNU’s Not Unix«; it is pronounced guh-noo, approximately like canoe. One of the main projects of the GNU system is the GNU Compiler Collection, or GCC, and its sister project, GNU Binutils. These two open source projects provide a foundation for a software development toolchain. Note that these projects were designed to originally run on Unix-like systems. 2.3 GCC GCC stands for GNU Compiler Collection. GCC is highly flexible compiler system. It has different compiler front-ends for different languages. It has many back-ends that generate assembly code for many different processors and host Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 12 CONTENTS operating systems. All share a common "middle-end", containing the generic parts of the compiler, including a lot of optimizations. In GCC, a host system is the system (processor/OS) that the compiler runs on. A target system is the system that the compiler compiles code for. And, a build system is the system that the compiler is built (from source code) on. If a compiler has the same system for host and for target, it is known as a native compiler. If a compiler has different systems for host and target, it is known as a cross-compiler. (And if all three, build, host, and target systems are different, it is known as a Canadian cross compiler, but we won’t discuss that here.) When GCC is built to execute on a host system such as FreeBSD, Linux, or Windows, and it is built to generate code for the AVR microcontroller target, then it is a cross compiler, and this version of GCC is commonly known as "AVR GCC". In documentation, or discussion, AVR GCC is used when referring to GCC targeting specifically the AVR, or something that is AVR specific about GCC. The term "GCC" is usually used to refer to something generic about GCC, or about GCC as a whole. GCC is different from most other compilers. GCC focuses on translating a high-level language to the target assembly only. AVR GCC has three available compilers for the AVR: C language, C++, and Ada. The compiler itself does not assemble or link the final code. GCC is also known as a "driver" program, in that it knows about, and drives other programs seamlessly to create the final output. The assembler, and the linker are part of another open source project called GNU Binutils. GCC knows how to drive the GNU assembler (gas) to assemble the output of the compiler. GCC knows how to drive the GNU linker (ld) to link all of the object modules into a final executable. The two projects, GCC and Binutils, are very much interrelated and many of the same volunteers work on both open source projects. When GCC is built for the AVR target, the actual program names are prefixed with "avr-". So the actual executable name for AVR GCC is: avr-gcc. The name "avr-gcc" is used in documentation and discussion when referring to the program itself and not just the whole AVR GCC system. See the GCC Web Site and GCC User Manual for more information about GCC. 2.4 GNU Binutils The name GNU Binutils stands for "Binary Utilities". It contains the GNU assembler (gas), and the GNU linker (ld), but also contains many other utilities that work with binary files that are created as part of the software development toolchain. Again, when these tools are built for the AVR target, the actual program names are prefixed with "avr-". For example, the assembler program name, for a native assembler is "as" (even though in documentation the GNU assembler is commonly referred to as "gas"). But when built for an AVR target, it becomes "avr-as". Below is a list of the programs that are included in Binutils: avr-as The Assembler. avr-ld The Linker. avr-ar Create, modify, and extract from libraries (archives). avr-ranlib Generate index to library (archive) contents. avr-objcopy Copy and translate object files to different formats. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 2.5 avr-libc 13 avr-objdump Display information from object files including disassembly. avr-size List section sizes and total size. avr-nm List symbols from object files. avr-strings List printable strings from files. avr-strip Discard symbols from files. avr-readelf Display the contents of ELF format files. avr-addr2line Convert addresses to file and line. avr-c++filt Filter to demangle encoded C++ symbols. 2.5 avr-libc GCC and Binutils provides a lot of the tools to develop software, but there is one critical component that they do not provide: a Standard C Library. There are different open source projects that provide a Standard C Library depending upon your system time, whether for a native compiler (GNU Libc), for some other embedded system (newlib), or for some versions of Linux (uCLibc). The open source AVR toolchain has its own Standard C Library project: avr-libc. AVR-Libc provides many of the same functions found in a regular Standard C Library and many additional library functions that is specific to an AVR. Some of the Standard C Library functions that are commonly used on a PC environment have limitations or additional issues that a user needs to be aware of when used on an embedded system. AVR-Libc also contains the most documentation about the whole AVR toolchain. 2.6 Building Software Even though GCC, Binutils, and avr-libc are the core projects that are used to build software for the AVR, there is another piece of software that ties it all together: Make. GNU Make is a program that makes things, and mainly software. Make interprets and executes a Makefile that is written for a project. A Makefile contains dependency rules, showing which output files are dependent upon which input files, and instructions on how to build output files from input files. Some distributions of the toolchains, and other AVR tools such as MFile, contain a Makefile template written for the AVR toolchain and AVR applications that you can copy and modify for your application. See the GNU Make User Manual for more information. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 14 2.7 CONTENTS AVRDUDE After creating your software, you’ll want to program your device. You can do this by using the program AVRDUDE which can interface with various hardware devices to program your processor. AVRDUDE is a very flexible package. All the information about AVR processors and various hardware programmers is stored in a text database. This database can be modified by any user to add new hardware or to add an AVR processor if it is not already listed. 2.8 GDB / Insight / DDD The GNU Debugger (GDB) is a command-line debugger that can be used with the rest of the AVR toolchain. Insight is GDB plus a GUI written in Tcl/Tk. Both GDB and Insight are configured for the AVR and the main executables are prefixed with the target name: avr-gdb, and avr-insight. There is also a "text mode" GUI for GDB: avr-gdbtui. DDD (Data Display Debugger) is another popular GUI front end to GDB, available on Unix and Linux systems. 2.9 AVaRICE AVaRICE is a back-end program to AVR GDB and interfaces to the Atmel JTAG In-Circuit Emulator (ICE), to provide emulation capabilities. 2.10 SimulAVR SimulAVR is an AVR simulator used as a back-end with AVR GDB. Unfortunately, this project is currently unmaintained and could use some help. 2.11 Utilities There are also other optional utilities available that may be useful to add to your toolset. SRecord is a collection of powerful tools for manipulating EPROM load files. It reads and writes numerous EPROM file formats, and can perform many different manipulations. MFile is a simple Makefile generator is meant as an aid to quickly customize a Makefile to use for your AVR application. 2.12 Toolchain Distributions (Distros) All of the various open source projects that comprise the entire toolchain are normally distributed as source code. It is left up to the user to build the tool application from its source code. This can be a very daunting task to any potential user of these tools. Luckily there are people who help out in this area. Volunteers take the time to build the application from source code on particular host platforms and sometimes packaging the tools for convenient installation by the end user. These packages contain the binary executables of the tools, pre-made and ready to use. These packages are known as "distributions" of the AVR toolchain, or by a more shortened name, "distros". AVR toolchain distros are available on FreeBSD, Windows, Mac OS X, and certain flavors of Linux. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 2.13 Open Source 2.13 Open Source 15 All of these tools, from the original source code in the multitude of projects, to the various distros, are put together by many, many volunteers. All of these projects could always use more help from other people who are willing to volunteer some of their time. There are many different ways to help, for people with varying skill levels, abilities, and available time. You can help to answer questions in mailing lists such as the avr-gcc-list, or on forums at the AVR Freaks website. This helps many people new to the open source AVR tools. If you think you found a bug in any of the tools, it is always a big help to submit a good bug report to the proper project. A good bug report always helps other volunteers to analyze the problem and to get it fixed for future versions of the software. You can also help to fix bugs in various software projects, or to add desirable new features. Volunteers are always welcome! :-) 3 3.1 Memory Areas and Using malloc() Introduction Many of the devices that are possible targets of avr-libc have a minimal amount of RAM. The smallest parts supported by the C environment come with 128 bytes of RAM. This needs to be shared between initialized and uninitialized variables (sections .data and .bss), the dynamic memory allocator, and the stack that is used for calling subroutines and storing local (automatic) variables. Also, unlike larger architectures, there is no hardware-supported memory management which could help in separating the mentioned RAM regions from being overwritten by each other. The standard RAM layout is to place .data variables first, from the beginning of the internal RAM, followed by .bss. The stack is started from the top of internal RAM, growing downwards. The so-called "heap" available for the dynamic memory allocator will be placed beyond the end of .bss. Thus, there’s no risk that dynamic memory will ever collide with the RAM variables (unless there were bugs in the implementation of the allocator). There is still a risk that the heap and stack could collide if there are large requirements for either dynamic memory or stack space. The former can even happen if the allocations aren’t all that large but dynamic memory allocations get fragmented over time such that new requests don’t quite fit into the "holes" of previously freed regions. Large stack space requirements can arise in a C function containing large and/or numerous local variables or when recursively calling function. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 16 CONTENTS Note on−board RAM .data .bss variables variables heap ! external RAM 0xFFFF 0x10FF 0x1100 0x0100 The pictures shown in this document represent typical situations where the RAM locations refer to an ATmega128. The memory addresses used are not displayed in a linear scale. stack SP RAMEND *(__brkval) (<= *SP − *(__malloc_margin)) *(__malloc_heap_start) == __heap_start __bss_end __data_end == __bss_start __data_start Figure 1: RAM map of a device with internal RAM On a simple device like a microcontroller it is a challenge to implement a dynamic memory allocator that is simple enough so the code size requirements will remain low, yet powerful enough to avoid unnecessary memory fragmentation and to get it all done with reasonably few CPU cycles. Microcontrollers are often low on space and also run at much lower speeds than the typical PC these days. The memory allocator implemented in avr-libc tries to cope with all of these constraints, and offers some tuning options that can be used if there are more resources available than in the default configuration. 3.2 Internal vs. external RAM Obviously, the constraints are much harder to satisfy in the default configuration where only internal RAM is available. Extreme care must be taken to avoid a stack-heap collision, both by making sure functions aren’t nesting too deeply, and don’t require too much stack space for local variables, as well as by being cautious with allocating too much dynamic memory. If external RAM is available, it is strongly recommended to move the heap into the external RAM, regardless of whether or not the variables from the .data and .bss sections are also going to be located there. The stack should always be kept in internal RAM. Some devices even require this, and in general, internal RAM can be accessed faster since no extra wait states are required. When using dynamic memory allocation and stack and heap are separated in distinct memory areas, this is the safest way to avoid a stack-heap collision. 3.3 Tunables for malloc() There are a number of variables that can be tuned to adapt the behavior of malloc() to the expected requirements and constraints of the application. Any changes to these tunables should be made before the very first call to malloc(). Note that some library functions might also use dynamic memory (notably those from the : Standard IO facilities), so make sure the changes will be done early enough in the startup sequence. The variables __malloc_heap_start and __malloc_heap_end can be used to restrict the malloc() function to a certain memory region. These variables are statically initialized to point to __heap_start and __heap_end, respectively, where __heap_start is filled in by the linker to point just beyond .bss, and __heap_end is set to 0 which makes malloc() assume the heap is below the stack. If the heap is going to be moved to external RAM, __malloc_heap_end must be adjusted accordingly. This can Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 3.3 Tunables for malloc() 17 either be done at run-time, by writing directly to this variable, or it can be done automatically at link-time, by adjusting the value of the symbol __heap_end. The following example shows a linker command to relocate the entire .data and .bss segments, and the heap to location 0x1100 in external RAM. The heap will extend up to address 0xffff. avr-gcc ... -Wl,--section-start,.data=0x801100,--defsym=__heap_end=0x80ffff ... Note on−board RAM stack 0xFFFF 0x10FF 0x1100 0x0100 See explanation for offset 0x800000. See the chapter about using gcc for the -Wl options. The ld (linker) user manual states that using -Tdata= is equivalent to using –section-start,.data= . However, you have to use –section-start as above because the GCC frontend also sets the -Tdata option for all MCU types where the SRAM doesn’t start at 0x800060. Thus, the linker is being faced with two -Tdata options. Sarting with binutils 2.16, the linker changed the preference, and picks the "wrong" option in this situation. external RAM .data .bss variables variables heap SP *(__malloc_heap_end) == __heap_end RAMEND *(__brkval) *(__malloc_heap_start) == __heap_start __bss_end __data_end == __bss_start __data_start Figure 2: Internal RAM: stack only, external RAM: variables and heap If dynamic memory should be placed in external RAM, while keeping the variables in internal RAM, something like the following could be used. Note that for demonstration purposes, the assignment of the various regions has not been made adjacent in this example, so there are "holes" below and above the heap in external RAM that remain completely unaccessible by regular variables or dynamic memory allocations (shown in light bisque color in the picture below). avr-gcc ... -Wl,--defsym=__heap_start=0x802000,--defsym=__heap_end=0x803fff ... .bss .data variables variables stack SP RAMEND __bss_end 0xFFFF 0x3FFF on−board RAM 0x2000 0x10FF 0x1100 0x0100 external RAM heap *(__malloc_heap_end) == __heap_end *(__brkval) *(__malloc_heap_start) == __heap_start __data_end == __bss_start __data_start Figure 3: Internal RAM: variables and stack, external RAM: heap Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 18 CONTENTS If __malloc_heap_end is 0, the allocator attempts to detect the bottom of stack in order to prevent a stack-heap collision when extending the actual size of the heap to gain more space for dynamic memory. It will not try to go beyond the current stack limit, decreased by __malloc_margin bytes. Thus, all possible stack frames of interrupt routines that could interrupt the current function, plus all further nested function calls must not require more stack space, or they will risk colliding with the data segment. The default value of __malloc_margin is set to 32. 3.4 Implementation details Dynamic memory allocation requests will be returned with a two-byte header prepended that records the size of the allocation. This is later used by free(). The returned address points just beyond that header. Thus, if the application accidentally writes before the returned memory region, the internal consistency of the memory allocator is compromised. The implementation maintains a simple freelist that accounts for memory blocks that have been returned in previous calls to free(). Note that all of this memory is considered to be successfully added to the heap already, so no further checks against stack-heap collisions are done when recycling memory from the freelist. The freelist itself is not maintained as a separate data structure, but rather by modifying the contents of the freed memory to contain pointers chaining the pieces together. That way, no additional memory is reqired to maintain this list except for a variable that keeps track of the lowest memory segment available for reallocation. Since both, a chain pointer and the size of the chunk need to be recorded in each chunk, the minimum chunk size on the freelist is four bytes. When allocating memory, first the freelist is walked to see if it could satisfy the request. If there’s a chunk available on the freelist that will fit the request exactly, it will be taken, disconnected from the freelist, and returned to the caller. If no exact match could be found, the closest match that would just satisfy the request will be used. The chunk will normally be split up into one to be returned to the caller, and another (smaller) one that will remain on the freelist. In case this chunk was only up to two bytes larger than the request, the request will simply be altered internally to also account for these additional bytes since no separate freelist entry could be split off in that case. If nothing could be found on the freelist, heap extension is attempted. This is where __malloc_margin will be considered if the heap is operating below the stack, or where __malloc_heap_end will be verified otherwise. If the remaining memory is insufficient to satisfy the request, NULL will eventually be returned to the caller. When calling free(), a new freelist entry will be prepared. An attempt is then made to aggregate the new entry with possible adjacent entries, yielding a single larger entry available for further allocations. That way, the potential for heap fragmentation is hopefully reduced. When deallocating the topmost chunk of memory, the size of the heap is reduced. A call to realloc() first determines whether the operation is about to grow or shrink the current allocation. When shrinking, the case is easy: the existing chunk is split, and the tail of the region that is no longer to be used is passed to the standard free() function for insertion into the freelist. Checks are first made whether the tail chunk is large enough to hold a chunk of its own at all, otherwise realloc() will simply do nothing, and return the original region. When growing the region, it is first checked whether the existing allocation can be extended in-place. If so, this is done, and the original pointer is returned without copying any data contents. As a side-effect, this check will also record the size of the largest chunk on the freelist. If the region cannot be extended in-place, but the old chunk is at the top of heap, and the above freelist walk did not reveal a large enough chunk on the freelist to satisfy the new request, an attempt is made to quickly extend this topmost chunk (and thus the heap), so no need arises to copy over the existing data. If there’s no more space available in the heap (same check is done as in malloc()), the entire request will fail. Otherwise, malloc() will be called with the new request size, the existing data will be copied over, and free() will be called on the old region. 4 Memory Sections Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 4.1 The .text Section 19 Remarks Need to list all the sections which are available to the avr. Weak Bindings FIXME: need to discuss the .weak directive. The following describes the various sections available. 4.1 The .text Section The .text section contains the actual machine instructions which make up your program. This section is further subdivided by the .initN and .finiN sections dicussed below. Note The avr-size program (part of binutils), coming from a Unix background, doesn’t account for the .data initialization space added to the .text section, so in order to know how much flash the final program will consume, one needs to add the values for both, .text and .data (but not .bss), while the amount of pre-allocated SRAM is the sum of .data and .bss. 4.2 The .data Section This section contains static data which was defined in your code. Things like the following would end up in .data: char err_str[] = "Your program has died a horrible death!"; struct point pt = { 1, 1 }; It is possible to tell the linker the SRAM address of the beginning of the .data section. This is accomplished by adding -Wl,-Tdata,addr to the avr-gcc command used to the link your program. Not that addr must be offset by adding 0x800000 the to real SRAM address so that the linker knows that the address is in the SRAM memory space. Thus, if you want the .data section to start at 0x1100, pass 0x801100 at the address to the linker. [offset explained] Note When using malloc() in the application (which could even happen inside library calls), additional adjustments are required. 4.3 The .bss Section Uninitialized global or static variables end up in the .bss section. 4.4 The .eeprom Section This is where eeprom variables are stored. 4.5 The .noinit Section This sections is a part of the .bss section. What makes the .noinit section special is that variables which are defined as such: Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 20 CONTENTS int foo __attribute__ ((section (".noinit"))); will not be initialized to zero during startup as would normal .bss data. Only uninitialized variables can be placed in the .noinit section. Thus, the following code will cause avr-gcc to issue an error: int bar __attribute__ ((section (".noinit"))) = 0xaa; It is possible to tell the linker explicitly where to place the .noinit section by adding -Wl,-section-start=.noinit=0x802000 to the avr-gcc command line at the linking stage. For example, suppose you wish to place the .noinit section at SRAM address 0x2000: $ avr-gcc ... -Wl,--section-start=.noinit=0x802000 ... Note Because of the Harvard architecture of the AVR devices, you must manually add 0x800000 to the address you pass to the linker as the start of the section. Otherwise, the linker thinks you want to put the .noinit section into the .text section instead of .data/.bss and will complain. Alternatively, you can write your own linker script to automate this. [FIXME: need an example or ref to dox for writing linker scripts.] 4.6 The .initN Sections These sections are used to define the startup code from reset up through the start of main(). These all are subparts of the .text section. The purpose of these sections is to allow for more specific placement of code within your program. Note Sometimes, it is convenient to think of the .initN and .finiN sections as functions, but in reality they are just symbolic names which tell the linker where to stick a chunk of code which is not a function. Notice that the examples for asm and C can not be called as functions and should not be jumped into. The .initN sections are executed in order from 0 to 9. .init0: Weakly bound to __init(). If user defines __init(), it will be jumped into immediately after a reset. .init1: Unused. User definable. .init2: In C programs, weakly bound to initialize the stack, and to clear zero_reg (r1). .init3: Unused. User definable. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 4.7 The .finiN Sections 21 .init4: For devices with > 64 KB of ROM, .init4 defines the code which takes care of copying the contents of .data from the flash to SRAM. For all other devices, this code as well as the code to zero out the .bss section is loaded from libgcc.a. .init5: Unused. User definable. .init6: Unused for C programs, but used for constructors in C++ programs. .init7: Unused. User definable. .init8: Unused. User definable. .init9: Jumps into main(). 4.7 The .finiN Sections These sections are used to define the exit code executed after return from main() or a call to exit(). These all are subparts of the .text section. The .finiN sections are executed in descending order from 9 to 0. .finit9: Unused. User definable. This is effectively where _exit() starts. .fini8: Unused. User definable. .fini7: Unused. User definable. .fini6: Unused for C programs, but used for destructors in C++ programs. .fini5: Unused. User definable. .fini4: Unused. User definable. .fini3: Unused. User definable. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 22 CONTENTS .fini2: Unused. User definable. .fini1: Unused. User definable. .fini0: Goes into an infinite loop after program termination and completion of any _exit() code (execution of code in the .fini9 -> .fini1 sections). 4.8 Using Sections in Assembler Code Example: #include .section .init1,"ax",@progbits ldi r0, 0xff out _SFR_IO_ADDR(PORTB), r0 out _SFR_IO_ADDR(DDRB), r0 Note The ,"ax",@progbits tells the assembler that the section is allocatable ("a"), executable ("x") and contains data ("@progbits"). For more detailed information on the .section directive, see the gas user manual. 4.9 Using Sections in C Code Example: #include void my_init_portb (void) __attribute__ ((naked)) \ __attribute__ ((section (".init3"))); void my_init_portb (void) { PORTB = 0xff; DDRB = 0xff; } Note Section .init3 is used in this example, as this ensures the inernal __zero_reg__ has already been set up. The code generated by the compiler might blindly rely on __zero_reg__ being really 0. 5 5.1 Data in Program Space Introduction So you have some constant data and you’re running out of room to store it? Many AVRs have limited amount of RAM in which to store data, but may have more Flash space available. The AVR is a Harvard architecture processor, where Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 5.2 A Note On const 23 Flash is used for the program, RAM is used for data, and they each have separate address spaces. It is a challenge to get constant data to be stored in the Program Space, and to retrieve that data to use it in the AVR application. The problem is exacerbated by the fact that the C Language was not designed for Harvard architectures, it was designed for Von Neumann architectures where code and data exist in the same address space. This means that any compiler for a Harvard architecture processor, like the AVR, has to use other means to operate with separate address spaces. Some compilers use non-standard C language keywords, or they extend the standard syntax in ways that are nonstandard. The AVR toolset takes a different approach. GCC has a special keyword, attribute that is used to attach different attributes to things such as function declarations, variables, and types. This keyword is followed by an attribute specification in double parentheses. In AVR GCC, there is a special attribute called progmem. This attribute is use on data declarations, and tells the compiler to place the data in the Program Memory (Flash). AVR-Libc provides a simple macro PROGMEM that is defined as the attribute syntax of GCC with the progmem attribute. This macro was created as a convenience to the end user, as we will see below. The PROGMEM macro is defined in the system header file. It is difficult to modify GCC to create new extensions to the C language syntax, so instead, avr-libc has created macros to retrieve the data from the Program Space. These macros are also found in the system header file. 5.2 A Note On const Many users bring up the idea of using C’s keyword const as a means of declaring data to be in Program Space. Doing this would be an abuse of the intended meaning of the const keyword. const is used to tell the compiler that the data is to be "read-only". It is used to help make it easier for the compiler to make certain transformations, or to help the compiler check for incorrect usage of those variables. For example, the const keyword is commonly used in many functions as a modifier on the parameter type. This tells the compiler that the function will only use the parameter as read-only and will not modify the contents of the parameter variable. const was intended for uses such as this, not as a means to identify where the data should be stored. If it were used as a means to define data storage, then it loses its correct meaning (changes its semantics) in other situations such as in the function parameter example. 5.3 Storing and Retrieving Data in the Program Space Let’s say you have some global data: unsigned char mydata[11][10] = { {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09}, {0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13}, {0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D}, {0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27}, {0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31}, {0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B}, {0x3C,0x3D,0x3E,0x3F,0x40,0x41,0x42,0x43,0x44,0x45}, {0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F}, {0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59}, {0x5A,0x5B,0x5C,0x5D,0x5E,0x5F,0x60,0x61,0x62,0x63}, {0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D} }; and later in your code you access this data in a function and store a single byte into a variable like so: byte = mydata[i][j]; Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 24 CONTENTS Now you want to store your data in Program Memory. Use the PROGMEM macro found in and put it after the declaration of the variable, but before the initializer, like so: #include . . . unsigned char mydata[11][10] PROGMEM = { {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09}, {0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x13}, {0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D}, {0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27}, {0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31}, {0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B}, {0x3C,0x3D,0x3E,0x3F,0x40,0x41,0x42,0x43,0x44,0x45}, {0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F}, {0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59}, {0x5A,0x5B,0x5C,0x5D,0x5E,0x5F,0x60,0x61,0x62,0x63}, {0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D} }; That’s it! Now your data is in the Program Space. You can compile, link, and check the map file to verify that mydata is placed in the correct section. Now that your data resides in the Program Space, your code to access (read) the data will no longer work. The code that gets generated will retrieve the data that is located at the address of the mydata array, plus offsets indexed by the i and j variables. However, the final address that is calculated where to the retrieve the data points to the Data Space! Not the Program Space where the data is actually located. It is likely that you will be retrieving some garbage. The problem is that AVR GCC does not intrinsically know that the data resides in the Program Space. The solution is fairly simple. The "rule of thumb" for accessing data stored in the Program Space is to access the data as you normally would (as if the variable is stored in Data Space), like so: byte = mydata[i][j]; then take the address of the data: byte = &(mydata[i][j]); then use the appropriate pgm_read_∗ macro, and the address of your data becomes the parameter to that macro: byte = pgm_read_byte(&(mydata[i][j])); The pgm_read_∗ macros take an address that points to the Program Space, and retrieves the data that is stored at that address. This is why you take the address of the offset into the array. This address becomes the parameter to the macro so it can generate the correct code to retrieve the data from the Program Space. There are different pgm_read_∗ macros to read different sizes of data at the address given. 5.4 Storing and Retrieving Strings in the Program Space Now that you can successfully store and retrieve simple data from Program Space you want to store and retrive strings from Program Space. And specifically you want to store and array of strings to Program Space. So you start off with your array, like so: char *string_table[] = { "String 1", "String 2", "String 3", "String 4", "String 5" }; Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 5.4 Storing and Retrieving Strings in the Program Space 25 and then you add your PROGMEM macro to the end of the declaration: char *string_table[] PROGMEM = { "String 1", "String 2", "String 3", "String 4", "String 5" }; Right? WRONG! Unfortunately, with GCC attributes, they affect only the declaration that they are attached to. So in this case, we successfully put the string_table variable, the array itself, in the Program Space. This DOES NOT put the actual strings themselves into Program Space. At this point, the strings are still in the Data Space, which is probably not what you want. In order to put the strings in Program Space, you have to have explicit declarations for each string, and put each string in Program Space: char char char char char string_1[] string_2[] string_3[] string_4[] string_5[] PROGMEM PROGMEM PROGMEM PROGMEM PROGMEM = = = = = "String "String "String "String "String 1"; 2"; 3"; 4"; 5"; Then use the new symbols in your table, like so: PGM_P string_table[] PROGMEM = { string_1, string_2, string_3, string_4, string_5 }; Now this has the effect of putting string_table in Program Space, where string_table is an array of pointers to characters (strings), where each pointer is a pointer to the Program Space, where each string is also stored. The PGM_P type above is also a macro that defined as a pointer to a character in the Program Space. Retrieving the strings are a different matter. You probably don’t want to pull the string out of Program Space, byte by byte, using the pgm_read_byte() macro. There are other functions declared in the header file that work with strings that are stored in the Program Space. For example if you want to copy the string from Program Space to a buffer in RAM (like an automatic variable inside a function, that is allocated on the stack), you can do this: void foo(void) { char buffer[10]; for (unsigned char i = 0; i < 5; i++) { strcpy_P(buffer, (PGM_P)pgm_read_word(&(string_table[i]))); // Display buffer on LCD. } return; } Here, the string_table array is stored in Program Space, so we access it normally, as if were stored in Data Space, then take the address of the location we want to access, and use the address as a parameter to pgm_read_word. We use the pgm_read_word macro to read the string pointer out of the string_table array. Remember that Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 26 CONTENTS a pointer is 16-bits, or word size. The pgm_read_word macro will return a 16-bit unsigned integer. We then have to typecast it as a true pointer to program memory, PGM_P. This pointer is an address in Program Space pointing to the string that we want to copy. This pointer is then used as a parameter to the function strcpy_P. The function strcpy_P is just like the regular strcpy function, except that it copies a string from Program Space (the second parameter) to a buffer in the Data Space (the first parameter). There are many string functions available that work with strings located in Program Space. All of these special string functions have a suffix of _P in the function name, and are declared in the header file. 5.5 Caveats The macros and functions used to retrieve data from the Program Space have to generate some extra code in order to actually load the data from the Program Space. This incurs some extra overhead in terms of code space (extra opcodes) and execution time. Usually, both the space and time overhead is minimal compared to the space savings of putting data in Program Space. But you should be aware of this so you can minimize the number of calls within a single function that gets the same piece of data from Program Space. It is always instructive to look at the resulting disassembly from the compiler. 6 6.1 avr-libc and assembler programs Introduction There might be several reasons to write code for AVR microcontrollers using plain assembler source code. Among them are: • Code for devices that do not have RAM and are thus not supported by the C compiler. • Code for very time-critical applications. • Special tweaks that cannot be done in C. Usually, all but the first could probably be done easily using the inline assembler facility of the compiler. Although avr-libc is primarily targeted to support programming AVR microcontrollers using the C (and C++) language, there’s limited support for direct assembler usage as well. The benefits of it are: • Use of the C preprocessor and thus the ability to use the same symbolic constants that are available to C programs, as well as a flexible macro concept that can use any valid C identifier as a macro (whereas the assembler’s macro concept is basically targeted to use a macro in place of an assembler instruction). • Use of the runtime framework like automatically assigning interrupt vectors. For devices that have RAM, initializing the RAM variables can also be utilized. 6.2 Invoking the compiler For the purpose described in this document, the assembler and linker are usually not invoked manually, but rather using the C compiler frontend (avr-gcc) that in turn will call the assembler and linker as required. This approach has the following advantages: • There is basically only one program to be called directly, avr-gcc, regardless of the actual source language used. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 6.3 Example program 27 • The invokation of the C preprocessor will be automatic, and will include the appropriate options to locate required include files in the filesystem. • The invokation of the linker will be automatic, and will include the appropriate options to locate additional libraries as well as the application start-up code (crtXXX.o) and linker script. Note that the invokation of the C preprocessor will be automatic when the filename provided for the assembler file ends in .S (the capital letter "s"). This would even apply to operating systems that use case-insensitive filesystems since the actual decision is made based on the case of the filename suffix given on the command-line, not based on the actual filename from the file system. As an alternative to using .S, the suffix .sx is recognized for this purpose (starting with GCC 4.3.0). This is primarily meant to be compatible with other compiler environments that have been providing this variant before in order to cope with operating systems where filenames are case-insensitive (and, with some versions of make that could not distinguish between .s and .S on such systems). Alternatively, the language can explicitly be specified using the -x assembler-with-cpp option. 6.3 Example program The following annotated example features a simple 100 kHz square wave generator using an AT90S1200 clocked with a 10.7 MHz crystal. Pin PD6 will be used for the square wave output. #include ; Note [1] work tmp = = 16 17 ; Note [2] inttmp = 19 intsav = 0 SQUARE = PD6 tmconst= 10700000 / 200000 fuzz= 8 ; Note [3] ; Note [4]: ; 100 kHz => 200000 edges/s ; # clocks in ISR until TCNT0 is set .section .text .global main ; Note [5] main: rcall ioinit rjmp 1b 1: ; Note [6] .global TIMER0_OVF_vect TIMER0_OVF_vect: ldi inttmp, 256 - tmconst + fuzz out _SFR_IO_ADDR(TCNT0), inttmp 1: 2: in intsav, _SFR_IO_ADDR(SREG) sbic rjmp sbi rjmp cbi _SFR_IO_ADDR(PORTD), SQUARE 1f _SFR_IO_ADDR(PORTD), SQUARE 2f _SFR_IO_ADDR(PORTD), SQUARE out reti _SFR_IO_ADDR(SREG), intsav sbi _SFR_IO_ADDR(DDRD), SQUARE ldi out work, _BV(TOIE0) _SFR_IO_ADDR(TIMSK), work ldi work, _BV(CS00) ; Note [7] ; Note [8] ; Note [9] ioinit: ; tmr0: Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen CK/1 28 CONTENTS out _SFR_IO_ADDR(TCCR0), work ldi out work, 256 - tmconst _SFR_IO_ADDR(TCNT0), work sei ret .global __vector_default __vector_default: reti ; Note [10] .end Note [1] As in C programs, this includes the central processor-specific file containing the IO port definitions for the device. Note that not all include files can be included into assembler sources. Note [2] Assignment of registers to symbolic names used locally. Another option would be to use a C preprocessor macro instead: #define work 16 Note [3] Our bit number for the square wave output. Note that the right-hand side consists of a CPP macro which will be substituted by its value (6 in this case) before actually being passed to the assembler. Note [4] The assembler uses integer operations in the host-defined integer size (32 bits or longer) when evaluating expressions. This is in contrast to the C compiler that uses the C type int by default in order to calculate constant integer expressions. In order to get a 100 kHz output, we need to toggle the PD6 line 200000 times per second. Since we use timer 0 without any prescaling options in order to get the desired frequency and accuracy, we already run into serious timing considerations: while accepting and processing the timer overflow interrupt, the timer already continues to count. When pre-loading the TCCNT0 register, we therefore have to account for the number of clock cycles required for interrupt acknowledge and for the instructions to reload TCCNT0 (4 clock cycles for interrupt acknowledge, 2 cycles for the jump from the interrupt vector, 2 cycles for the 2 instructions that reload TCCNT0). This is what the constant fuzz is for. Note [5] External functions need to be declared to be .global. main is the application entry point that will be jumped to from the ininitalization routine in crts1200.o. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 6.4 Pseudo-ops and operators 29 Note [6] The main loop is just a single jump back to itself. Square wave generation itself is completely handled by the timer 0 overflow interrupt service. A sleep instruction (using idle mode) could be used as well, but probably would not conserve much energy anyway since the interrupt service is executed quite frequently. Note [7] Interrupt functions can get the usual names that are also available to C programs. The linker will then put them into the appropriate interrupt vector slots. Note that they must be declared .global in order to be acceptable for this purpose. This will only work if has been included. Note that the assembler or linker have no chance to check the correct spelling of an interrupt function, so it should be double-checked. (When analyzing the resulting object file using avr-objdump or avr-nm, a name like __vector_N should appear, with N being a small integer number.) Note [8] As explained in the section about special function registers, the actual IO port address should be obtained using the macro _SFR_IO_ADDR. (The AT90S1200 does not have RAM thus the memory-mapped approach to access the IO registers is not available. It would be slower than using in / out instructions anyway.) Since the operation to reload TCCNT0 is time-critical, it is even performed before saving SREG. Obviously, this requires that the instructions involved would not change any of the flag bits in SREG. Note [9] Interrupt routines must not clobber the global CPU state. Thus, it is usually necessary to save at least the state of the flag bits in SREG. (Note that this serves as an example here only since actually, all the following instructions would not modify SREG either, but that’s not commonly the case.) Also, it must be made sure that registers used inside the interrupt routine do not conflict with those used outside. In the case of a RAM-less device like the AT90S1200, this can only be done by agreeing on a set of registers to be used exclusively inside the interrupt routine; there would not be any other chance to "save" a register anywhere. If the interrupt routine is to be linked together with C modules, care must be taken to follow the register usage guidelines imposed by the C compiler. Also, any register modified inside the interrupt sevice needs to be saved, usually on the stack. Note [10] As explained in Interrupts, a global "catch-all" interrupt handler that gets all unassigned interrupt vectors can be installed using the name __vector_default. This must be .global, and obviously, should end in a reti instruction. (By default, a jump to location 0 would be implied instead.) 6.4 Pseudo-ops and operators The available pseudo-ops in the assembler are described in the GNU assembler (gas) manual. The manual can be found online as part of the current binutils release under http://sources.redhat.com/binutils/. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 30 CONTENTS As gas comes from a Unix origin, its pseudo-op and overall assembler syntax is slightly different than the one being used by other assemblers. Numeric constants follow the C notation (prefix 0x for hexadecimal constants), expressions use a C-like syntax. Some common pseudo-ops include: • .byte allocates single byte constants • .ascii allocates a non-terminated string of characters • .asciz allocates a \0-terminated string of characters (C string) • .data switches to the .data section (initialized RAM variables) • .text switches to the .text section (code and ROM constants) • .set declares a symbol as a constant expression (identical to .equ) • .global (or .globl) declares a public symbol that is visible to the linker (e. g. function entry point, global variable) • .extern declares a symbol to be externally defined; this is effectively a comment only, as gas treats all undefined symbols it encounters as globally undefined anyway Note that .org is available in gas as well, but is a fairly pointless pseudo-op in an assembler environment that uses relocatable object files, as it is the linker that determines the final position of some object in ROM or RAM. Along with the architecture-independent standard operators, there are some AVR-specific operators available which are unfortunately not yet described in the official documentation. The most notable operators are: • lo8 Takes the least significant 8 bits of a 16-bit integer • hi8 Takes the most significant 8 bits of a 16-bit integer • pm Takes a program-memory (ROM) address, and converts it into a RAM address. This implies a division by 2 as the AVR handles ROM addresses as 16-bit words (e.g. in an IJMP or ICALL instruction), and can also handle relocatable symbols on the right-hand side. Example: ldi ldi call r24, lo8(pm(somefunc)) r25, hi8(pm(somefunc)) something This passes the address of function somefunc as the first parameter to function something. 7 Inline Assembler Cookbook AVR-GCC Inline Assembler Cookbook About this Document The GNU C compiler for Atmel AVR RISC processors offers, to embed assembly language code into C programs. This cool feature may be used for manually optimizing time critical parts of the software or to use specific processor instruction, which are not available in the C language. Because of a lack of documentation, especially for the AVR version of the compiler, it may take some time to figure out the implementation details by studying the compiler and assembler source code. There are also a few sample programs available in the net. Hopefully this document will help to increase their number. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 7.1 GCC asm Statement 31 It’s assumed, that you are familiar with writing AVR assembler programs, because this is not an AVR assembler programming tutorial. It’s not a C language tutorial either. Note that this document does not cover file written completely in assembler language, refer to avr-libc and assembler programs for this. Copyright (C) 2001-2002 by egnite Software GmbH Permission is granted to copy and distribute verbatim copies of this manual provided that the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. This document describes version 3.3 of the compiler. There may be some parts, which hadn’t been completely understood by the author himself and not all samples had been tested so far. Because the author is German and not familiar with the English language, there are definitely some typos and syntax errors in the text. As a programmer the author knows, that a wrong documentation sometimes might be worse than none. Anyway, he decided to offer his little knowledge to the public, in the hope to get enough response to improve this document. Feel free to contact the author via e-mail. For the latest release check http://www.ethernut.de/. Herne, 17th of May 2002 Harald Kipp harald.kipp-at-egnite.de Note As of 26th of July 2002, this document has been merged into the documentation for avr-libc. The latest version is now available at http://savannah.nongnu.org/projects/avr-libc/. 7.1 GCC asm Statement Let’s start with a simple example of reading a value from port D: asm("in %0, %1" : "=r" (value) : "I" (_SFR_IO_ADDR(PORTD)) ); Each asm statement is devided by colons into (up to) four parts: 1. The assembler instructions, defined as a single string constant: "in %0, %1" 2. A list of output operands, separated by commas. Our example uses just one: "=r" (value) 3. A comma separated list of input operands. Again our example uses one operand only: "I" (_SFR_IO_ADDR(PORTD)) 4. Clobbered registers, left empty in our example. You can write assembler instructions in much the same way as you would write assembler programs. However, registers and constants are used in a different way if they refer to expressions of your C program. The connection between registers and C operands is specified in the second and third part of the asm instruction, the list of input and output operands, respectively. The general form is asm(code : output operand list : input operand list [: clobber list]); Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 32 CONTENTS In the code section, operands are referenced by a percent sign followed by a single digit. %0 refers to the first %1 to the second operand and so forth. From the above example: %0 refers to "=r" (value) and %1 refers to "I" (_SFR_IO_ADDR(PORTD)). This may still look a little odd now, but the syntax of an operand list will be explained soon. Let us first examine the part of a compiler listing which may have been generated from our example: lds r24,value /* #APP */ in r24, 12 /* #NOAPP */ sts value,r24 The comments have been added by the compiler to inform the assembler that the included code was not generated by the compilation of C statements, but by inline assembler statements. The compiler selected register r24 for storage of the value read from PORTD. The compiler could have selected any other register, though. It may not explicitely load or store the value and it may even decide not to include your assembler code at all. All these decisions are part of the compiler’s optimization strategy. For example, if you never use the variable value in the remaining part of the C program, the compiler will most likely remove your code unless you switched off optimization. To avoid this, you can add the volatile attribute to the asm statement: asm volatile("in %0, %1" : "=r" (value) : "I" (_SFR_IO_ADDR(PORTD))); Alternatively, operands can be given names. The name is prepended in brackets to the constraints in the operand list, and references to the named operand use the bracketed name instead of a number after the % sign. Thus, the above example could also be written as asm("in %[retval], %[port]" : [retval] "=r" (value) : [port] "I" (_SFR_IO_ADDR(PORTD)) ); The last part of the asm instruction, the clobber list, is mainly used to tell the compiler about modifications done by the assembler code. This part may be omitted, all other parts are required, but may be left empty. If your assembler routine won’t use any input or output operand, two colons must still follow the assembler code string. A good example is a simple statement to disable interrupts: asm volatile("cli"::); 7.2 Assembler Code You can use the same assembler instruction mnemonics as you’d use with any other AVR assembler. And you can write as many assembler statements into one code string as you like and your flash memory is able to hold. Note The available assembler directives vary from one assembler to another. To make it more readable, you should put each statement on a seperate line: asm volatile("nop\n\t" "nop\n\t" "nop\n\t" "nop\n\t" ::); The linefeed and tab characters will make the assembler listing generated by the compiler more readable. It may look a bit odd for the first time, but that’s the way the compiler creates it’s own assembler code. You may also make use of some special registers. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 7.3 Input and Output Operands 33 Symbol Register Status register at address 0x3F Stack pointer high byte at address 0x3E Stack pointer low byte at address 0x3D Register r0, used for temporary storage Register r1, always zero __SREG__ __SP_H__ __SP_L__ __tmp_reg__ __zero_reg__ Register r0 may be freely used by your assembler code and need not be restored at the end of your code. It’s a good idea to use tmp_reg and zero_reg instead of r0 or r1, just in case a new compiler version changes the register usage definitions. 7.3 Input and Output Operands Each input and output operand is described by a constraint string followed by a C expression in parantheses. AVR-GCC 3.3 knows the following constraint characters: Note The most up-to-date and detailed information on contraints for the avr can be found in the gcc manual. The x register is r27:r26, the y register is r29:r28, and the z register is r31:r30 Constraint a b d e q r t w x y z G I J K L l M N O P Q Used for Simple upper registers Base pointer registers pairs Upper register Pointer register pairs Stack pointer register Any register Temporary register Special upper register pairs Pointer register pair X Pointer register pair Y Pointer register pair Z Floating point constant 6-bit positive integer constant 6-bit negative integer constant Integer constant Integer constant Lower registers 8-bit integer constant Integer constant Integer constant Integer constant (GCC >= 4.2.x) A memory address based on Y or Z pointer with displacement. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen Range r16 to r23 y, z r16 to r31 x, y, z SPH:SPL r0 to r31 r0 r24, r26, r28, r30 x (r27:r26) y (r29:r28) z (r31:r30) 0.0 0 to 63 -63 to 0 2 0 r0 to r15 0 to 255 -1 8, 16, 24 1 34 CONTENTS (GCC >= 4.3.x) Integer constant. R -6 to 5 The selection of the proper contraint depends on the range of the constants or registers, which must be acceptable to the AVR instruction they are used with. The C compiler doesn’t check any line of your assembler code. But it is able to check the constraint against your C expression. However, if you specify the wrong constraints, then the compiler may silently pass wrong code to the assembler. And, of course, the assembler will fail with some cryptic output or internal errors. For example, if you specify the constraint "r" and you are using this register with an "ori" instruction in your assembler code, then the compiler may select any register. This will fail, if the compiler chooses r2 to r15. (It will never choose r0 or r1, because these are uses for special purposes.) That’s why the correct constraint in that case is "d". On the other hand, if you use the constraint "M", the compiler will make sure that you don’t pass anything else but an 8-bit value. Later on we will see how to pass multibyte expression results to the assembler code. The following table shows all AVR assembler mnemonics which require operands, and the related contraints. Because of the improper constraint definitions in version 3.3, they aren’t strict enough. There is, for example, no constraint, which restricts integer constants to the range 0 to 7 for bit set and bit clear operations. Mnemonic adc adiw andi bclr brbc bset cbi com cpc cpse elpm in ld ldi lpm lsr movw neg ori pop rol sbc sbi sbiw sbrc ser std sub swap Constraints r,r w,I d,M I I,label I I,I r r,r r,r t,z r,I r,e d,M t,z r r,r r d,M r r r,r I,I w,I r,I d b,r r,r r Mnemonic add and asr bld brbs bst cbr cp cpi dec eor inc ldd lds lsl mov mul or out push ror sbci sbic sbr sbrs st sts subi Constraints r,r r,r r r,I I,label r,I d,I r,r d,M r r,r r r,b r,label r r,r r,r r,r I,r r r d,M I,I d,M r,I e,r label,r d,M Constraint characters may be prepended by a single constraint modifier. Contraints without a modifier specify read-only operands. Modifiers are: Modifier = Specifies Write-only operand, usually used for all output operands. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 7.3 Input and Output Operands 35 + & Read-write operand Register should be used for output only Output operands must be write-only and the C expression result must be an lvalue, which means that the operands must be valid on the left side of assignments. Note, that the compiler will not check if the operands are of reasonable type for the kind of operation used in the assembler instructions. Input operands are, you guessed it, read-only. But what if you need the same operand for input and output? As stated above, read-write operands are not supported in inline assembler code. But there is another solution. For input operators it is possible to use a single digit in the constraint string. Using digit n tells the compiler to use the same register as for the n-th operand, starting with zero. Here is an example: asm volatile("swap %0" : "=r" (value) : "0" (value)); This statement will swap the nibbles of an 8-bit variable named value. Constraint "0" tells the compiler, to use the same input register as for the first operand. Note however, that this doesn’t automatically imply the reverse case. The compiler may choose the same registers for input and output, even if not told to do so. This is not a problem in most cases, but may be fatal if the output operator is modified by the assembler code before the input operator is used. In the situation where your code depends on different registers used for input and output operands, you must add the & constraint modifier to your output operand. The following example demonstrates this problem: asm volatile("in %0,%1" "\n\t" "out %1, %2" "\n\t" : "=&r" (input) : "I" (_SFR_IO_ADDR(port)), "r" (output) ); In this example an input value is read from a port and then an output value is written to the same port. If the compiler would have choosen the same register for input and output, then the output value would have been destroyed on the first assembler instruction. Fortunately, this example uses the & constraint modifier to instruct the compiler not to select any register for the output value, which is used for any of the input operands. Back to swapping. Here is the code to swap high and low byte of a 16-bit value: asm volatile("mov __tmp_reg__, %A0" "\n\t" "mov %A0, %B0" "\n\t" "mov %B0, __tmp_reg__" "\n\t" : "=r" (value) : "0" (value) ); First you will notice the usage of register __tmp_reg__, which we listed among other special registers in the Assembler Code section. You can use this register without saving its contents. Completely new are those letters A and B in %A0 and %B0. In fact they refer to two different 8-bit registers, both containing a part of value. Another example to swap bytes of a 32-bit value: asm volatile("mov __tmp_reg__, %A0" "mov %A0, %D0" "mov %D0, __tmp_reg__" "mov __tmp_reg__, %B0" "mov %B0, %C0" "mov %C0, __tmp_reg__" : "=r" (value) : "0" (value) ); "\n\t" "\n\t" "\n\t" "\n\t" "\n\t" "\n\t" Instead of listing the same operand as both, input and output operand, it can also be declared as a read-write operand. This must be applied to an output operand, and the respective input operand list remains empty: asm volatile("mov __tmp_reg__, %A0" "\n\t" "mov %A0, %D0" "\n\t" "mov %D0, __tmp_reg__" "\n\t" Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 36 CONTENTS "mov __tmp_reg__, %B0" "\n\t" "mov %B0, %C0" "\n\t" "mov %C0, __tmp_reg__" "\n\t" : "+r" (value)); If operands do not fit into a single register, the compiler will automatically assign enough registers to hold the entire operand. In the assembler code you use %A0 to refer to the lowest byte of the first operand, %A1 to the lowest byte of the second operand and so on. The next byte of the first operand will be %B0, the next byte %C0 and so on. This also implies, that it is often neccessary to cast the type of an input operand to the desired size. A final problem may arise while using pointer register pairs. If you define an input operand "e" (ptr) and the compiler selects register Z (r30:r31), then %A0 refers to r30 and %B0 refers to r31. But both versions will fail during the assembly stage of the compiler, if you explicitely need Z, like in ld r24,Z If you write ld r24, %a0 with a lower case a following the percent sign, then the compiler will create the proper assembler line. 7.4 Clobbers As stated previously, the last part of the asm statement, the list of clobbers, may be omitted, including the colon seperator. However, if you are using registers, which had not been passed as operands, you need to inform the compiler about this. The following example will do an atomic increment. It increments an 8-bit value pointed to by a pointer variable in one go, without being interrupted by an interrupt routine or another thread in a multithreaded environment. Note, that we must use a pointer, because the incremented value needs to be stored before interrupts are enabled. asm volatile( "cli" "ld r24, %a0" "inc r24" "st %a0, r24" "sei" : : "e" (ptr) : "r24" ); "\n\t" "\n\t" "\n\t" "\n\t" "\n\t" The compiler might produce the following code: cli ld r24, Z inc r24 st Z, r24 sei One easy solution to avoid clobbering register r24 is, to make use of the special temporary register tmp_reg defined by the compiler. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 7.4 Clobbers asm volatile( "cli" "ld __tmp_reg__, %a0" "inc __tmp_reg__" "st %a0, __tmp_reg__" "sei" : : "e" (ptr) ); 37 "\n\t" "\n\t" "\n\t" "\n\t" "\n\t" The compiler is prepared to reload this register next time it uses it. Another problem with the above code is, that it should not be called in code sections, where interrupts are disabled and should be kept disabled, because it will enable interrupts at the end. We may store the current status, but then we need another register. Again we can solve this without clobbering a fixed, but let the compiler select it. This could be done with the help of a local C variable. { uint8_t s; asm volatile( "in %0, __SREG__" "cli" "ld __tmp_reg__, %a1" "inc __tmp_reg__" "st %a1, __tmp_reg__" "out __SREG__, %0" : "=&r" (s) : "e" (ptr) ); "\n\t" "\n\t" "\n\t" "\n\t" "\n\t" "\n\t" } Now every thing seems correct, but it isn’t really. The assembler code modifies the variable, that ptr points to. The compiler will not recognize this and may keep its value in any of the other registers. Not only does the compiler work with the wrong value, but the assembler code does too. The C program may have modified the value too, but the compiler didn’t update the memory location for optimization reasons. The worst thing you can do in this case is: { uint8_t s; asm volatile( "in %0, __SREG__" "cli" "ld __tmp_reg__, %a1" "inc __tmp_reg__" "st %a1, __tmp_reg__" "out __SREG__, %0" : "=&r" (s) : "e" (ptr) : "memory" ); "\n\t" "\n\t" "\n\t" "\n\t" "\n\t" "\n\t" } The special clobber "memory" informs the compiler that the assembler code may modify any memory location. It forces the compiler to update all variables for which the contents are currently held in a register before executing the assembler code. And of course, everything has to be reloaded again after this code. In most situations, a much better solution would be to declare the pointer destination itself volatile: volatile uint8_t *ptr; This way, the compiler expects the value pointed to by ptr to be changed and will load it whenever used and store it whenever modified. Situations in which you need clobbers are very rare. In most cases there will be better ways. Clobbered registers will force the compiler to store their values before and reload them after your assembler code. Avoiding clobbers gives the compiler more freedom while optimizing your code. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 38 7.5 CONTENTS Assembler Macros In order to reuse your assembler language parts, it is useful to define them as macros and put them into include files. AVR Libc comes with a bunch of them, which could be found in the directory avr/include. Using such include files may produce compiler warnings, if they are used in modules, which are compiled in strict ANSI mode. To avoid that, you can write asm instead of asm and volatile instead of volatile. These are equivalent aliases. Another problem with reused macros arises if you are using labels. In such cases you may make use of the special pattern %=, which is replaced by a unique number on each asm statement. The following code had been taken from avr/include/iomacros.h: #define loop_until_bit_is_clear(port,bit) \ __asm__ __volatile__ ( \ "L_%=: " "sbic %0, %1" "\n\t" \ "rjmp L_%=" \ : /* no outputs */ : "I" (_SFR_IO_ADDR(port)), "I" (bit) ) When used for the first time, L_%= may be translated to L_1404, the next usage might create L_1405 or whatever. In any case, the labels became unique too. Another option is to use Unix-assembler style numeric labels. They are explained in How do I trace an assembler file in avr-gdb?. The above example would then look like: #define loop_until_bit_is_clear(port,bit) __asm__ __volatile__ ( "1: " "sbic %0, %1" "\n\t" "rjmp 1b" : /* no outputs */ : "I" (_SFR_IO_ADDR(port)), "I" (bit) ) 7.6 C Stub Functions Macro definitions will include the same assembler code whenever they are referenced. This may not be acceptable for larger routines. In this case you may define a C stub function, containing nothing other than your assembler code. void delay(uint8_t ms) { uint16_t cnt; asm volatile ( "\n" "L_dl1%=:" "\n\t" "mov %A0, %A2" "\n\t" "mov %B0, %B2" "\n" "L_dl2%=:" "\n\t" "sbiw %A0, 1" "\n\t" "brne L_dl2%=" "\n\t" "dec %1" "\n\t" "brne L_dl1%=" "\n\t" : "=&w" (cnt) : "r" (ms), "r" (delay_count) ); } The purpose of this function is to delay the program execution by a specified number of milliseconds using a counting loop. The global 16 bit variable delay_count must contain the CPU clock frequency in Hertz divided by 4000 and must have been set before calling this routine for the first time. As described in the clobber section, the routine uses a local variable to hold a temporary value. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 7.7 C Names Used in Assembler Code 39 Another use for a local variable is a return value. The following function returns a 16 bit value read from two successive port addresses. uint16_t inw(uint8_t port) { uint16_t result; asm volatile ( "in %A0,%1" "\n\t" "in %B0,(%1) + 1" : "=r" (result) : "I" (_SFR_IO_ADDR(port)) ); return result; } Note inw() is supplied by avr-libc. 7.7 C Names Used in Assembler Code By default AVR-GCC uses the same symbolic names of functions or variables in C and assembler code. You can specify a different name for the assembler code by using a special form of the asm statement: unsigned long value asm("clock") = 3686400; This statement instructs the compiler to use the symbol name clock rather than value. This makes sense only for external or static variables, because local variables do not have symbolic names in the assembler code. However, local variables may be held in registers. With AVR-GCC you can specify the use of a specific register: void Count(void) { register unsigned char counter asm("r3"); ... some code... asm volatile("clr r3"); ... more code... } The assembler instruction, "clr r3", will clear the variable counter. AVR-GCC will not completely reserve the specified register. If the optimizer recognizes that the variable will not be referenced any longer, the register may be re-used. But the compiler is not able to check wether this register usage conflicts with any predefined register. If you reserve too many registers in this way, the compiler may even run out of registers during code generation. In order to change the name of a function, you need a prototype declaration, because the compiler will not accept the asm keyword in the function definition: extern long Calc(void) asm ("CALCULATE"); Calling the function Calc() will create assembler instructions to call the function CALCULATE. 7.8 Links For a more thorough discussion of inline assembly usage, see the gcc user manual. The latest version of the gcc manual is always available here: http://gcc.gnu.org/onlinedocs/ Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 40 8 8.1 CONTENTS How to Build a Library Introduction So you keep reusing the same functions that you created over and over? Tired of cut and paste going from one project to the next? Would you like to reduce your maintenance overhead? Then you’re ready to create your own library! Code reuse is a very laudable goal. With some upfront investment, you can save time and energy on future projects by having ready-to-go libraries. This chapter describes some background information, design considerations, and practical knowledge that you will need to create and use your own libraries. 8.2 How the Linker Works The compiler compiles a single high-level language file (C language, for example) into a single object module file. The linker (ld) can only work with object modules to link them together. Object modules are the smallest unit that the linker works with. Typically, on the linker command line, you will specify a set of object modules (that has been previously compiled) and then a list of libraries, including the Standard C Library. The linker takes the set of object modules that you specify on the command line and links them together. Afterwards there will probably be a set of "undefined references". A reference is essentially a function call. An undefined reference is a function call, with no defined function to match the call. The linker will then go through the libraries, in order, to match the undefined references with function definitions that are found in the libraries. If it finds the function that matches the call, the linker will then link in the object module in which the function is located. This part is important: the linker links in THE ENTIRE OBJECT MODULE in which the function is located. Remember, the linker knows nothing about the functions internal to an object module, other than symbol names (such as function names). The smallest unit the linker works with is object modules. When there are no more undefined references, the linker has linked everything and is done and outputs the final application. 8.3 How to Design a Library How the linker behaves is very important in designing a library. Ideally, you want to design a library where only the functions that are called are the only functions to be linked into the final application. This helps keep the code size to a minimum. In order to do this, with the way the linker works, is to only write one function per code module. This will compile to one function per object module. This is usually a very different way of doing things than writing an application! There are always exceptions to the rule. There are generally two cases where you would want to have more than one function per object module. The first is when you have very complementary functions that it doesn’t make much sense to split them up. For example, malloc() and free(). If someone is going to use malloc(), they will very likely be using free() (or at least should be using free()). In this case, it makes more sense to aggregate those two functions in the same object module. The second case is when you want to have an Interrupt Service Routine (ISR) in your library that you want to link in. The problem in this case is that the linker looks for unresolved references and tries to resolve them with code in libraries. A reference is the same as a function call. But with ISRs, there is no function call to initiate the ISR. The ISR is placed in the Interrupt Vector Table (IVT), hence no call, no reference, and no linking in of the ISR. In order to do this, you have to trick the linker in a way. Aggregate the ISR, with another function in the same object module, but have the other function be something that is required for the user to call in order to use the ISR, like perhaps an initialization function for the subsystem, or perhaps a function that enables the ISR in the first place. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 8.4 Creating a Library 8.4 Creating a Library 41 The librarian program is called ar (for "archiver") and is found in the GNU Binutils project. This program will have been built for the AVR target and will therefore be named avr-ar. The job of the librarian program is simple: aggregate a list of object modules into a single library (archive) and create an index for the linker to use. The name that you create for the library filename must follow a specific pattern: libname.a. The name part is the unique part of the filename that you create. It makes it easier if the name part relates to what the library is about. This name part must be prefixed by "lib", and it must have a file extension of .a, for "archive". The reason for the special form of the filename is for how the library gets used by the toolchain, as we will see later on. Note The filename is case-sensitive. Use a lowercase "lib" prefix, and a lowercase ".a" as the file extension. The command line is fairly simple: avr-ar rcs The r command switch tells the program to insert the object modules into the archive with replacement. The c command line switch tells the program to create the archive. And the s command line switch tells the program to write an object-file index into the archive, or update an existing one. This last switch is very important as it helps the linker to find what it needs to do its job. Note The command line switches are case sensitive! There are uppercase switches that have completely different actions. MFile and the WinAVR distribution contain a Makefile Template that includes the necessary command lines to build a library. You will have to manually modify the template to switch it over to build a library instead of an application. See the GNU Binutils manual for more information on the ar program. 8.5 Using a Library To use a library, use the -l switch on your linker command line. The string immediately following the -l is the unique part of the library filename that the linker will link in. For example, if you use: -lm this will expand to the library filename: libm.a which happens to be the math library included in avr-libc. If you use this on your linker command line: -lprintf_flt then the linker will look for a library called: libprintf_flt.a Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 42 CONTENTS This is why naming your library is so important when you create it! The linker will search libraries in the order that they appear on the command line. Whichever function is found first that matches the undefined reference, it will be linked in. There are also command line switches that tell GCC which directory to look in (-L) for the libraries that are specified to be linke in with -l. See the GNU Binutils manual for more information on the GNU linker (ld) program. 9 Benchmarks The results below can only give a rough estimate of the resources necessary for using certain library functions. There is a number of factors which can both increase or reduce the effort required: • Expenses for preparation of operands and their stack are not considered. • In the table, the size includes all additional functions (for example, function to multiply two integers) but they are only linked from the library. • Expenses of time of performance of some functions essentially depend on parameters of a call, for example, qsort() is recursive, and sprintf() receives parameters in a stack. • Different versions of the compiler can give a significant difference in code size and execution time. For example, the dtostre() function, compiled with avr-gcc 3.4.6, requires 930 bytes. After transition to avr-gcc 4.2.3, the size become 1088 bytes. 9.1 A few of libc functions. Avr-gcc version is 4.7.1 The size of function is given in view of all picked up functions. By default Avr-libc is compiled with -mcall-prologues option. In brackets the size without taking into account modules of a prologue and an epilogue is resulted. Both of the size can coincide, if function does not cause a prologue/epilogue. Function atoi ("12345") atol ("12345") dtostre (1.2345, s, 6, 0) dtostrf (1.2345, 15, 6, s) itoa (12345, s, 10) Units Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Avr2 82 (82) 2 155 122 (122) 2 221 1116 (1004) 17 1247 1616 (1616) 38 1634 110 (110) 2 879 Avr25 78 (78) 2 149 118 (118) 2 219 1048 (938) 17 1105 1508 (1508) 38 1462 102 (102) 2 875 Avr4 74 (74) 2 149 118 (118) 2 219 1048 (938) 17 1105 1508 (1508) 38 1462 102 (102) 2 875 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 9.2 Math functions. ltoa (12345L, s, 10) malloc (1) realloc ((void ∗)0, 1) qsort (s, sizeof(s), 1, cmp) sprintf_min (s, "%d", 12345) sprintf (s, "%d", 12345) sprintf_flt (s, "%e", 1.2345) sscanf_min ("12345", "%d", &i) sscanf ("12345", "%d", &i) sscanf ("point,color", "%[a-z]", s) sscanf_flt ("1.2345", "%e", &x) strtod ("1.2345", &p) strtol ("12345", &p, 0) 9.2 43 Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks Flash bytes Stack bytes MCU clocks 134 (134) 2 1597 768 (712) 6 215 1284 (1172) 18 305 1252 (1140) 42 21996 1224 (1112) 53 1841 1614 (1502) 58 1647 3228 (3116) 67 2573 1532 (1420) 55 1607 2008 (1896) 55 1610 2008 (1896) 86 3067 3464 (3352) 71 2497 1632 (1520) 20 1235 918 (806) 22 956 126 (126) 2 1593 714 (660) 6 201 1174 (1064) 18 286 1022 (912) 42 19905 1092 (982) 53 1694 1476 (1366) 58 1552 2990 (2880) 67 2311 1328 (1218) 55 1446 1748 (1638) 55 1449 1748 (1638) 86 2806 3086 (2976) 71 2281 1536 (1426) 20 1177 834 (724) 22 891 126 (126) 2 1593 714 (660) 6 201 1174 (1064) 18 286 1028 (918) 42 17541 1088 (978) 53 1689 1454 (1344) 58 1547 2968 (2858) 67 2311 1328 (1218) 55 1446 1748 (1638) 55 1449 1748 (1638) 86 2806 3070 (2960) 71 2078 1480 (1480) 21 1124 792 (792) 28 794 Math functions. The table contains the number of MCU clocks to calculate a function with a given argument(s). The main reason of a big difference between Avr2 and Avr4 is a hardware multiplication. Function __addsf3 (1.234, 5.678) __mulsf3 (1.234, 5.678) __divsf3 (1.234, 5.678) acos (0.54321) asin (0.54321) atan (0.54321) atan2 (1.234, 5.678) cbrt (1.2345) ceil (1.2345) cos (1.2345) cosh (1.2345) Avr2 113 375 466 4411 4517 4710 5270 2684 177 3387 4922 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen Avr4 108 138 465 2455 2556 2271 2857 2555 177 1671 2979 44 CONTENTS exp (1.2345) fdim (5.678, 1.234) floor (1.2345) fmax (1.234, 5.678) fmin (1.234, 5.678) fmod (5.678, 1.234) frexp (1.2345, 0) hypot (1.234, 5.678) ldexp (1.2345, 6) log (1.2345) log10 (1.2345) modf (1.2345, 0) pow (1.234, 5.678) round (1.2345) sin (1.2345) sinh (1.2345) sqrt (1.2345) tan (1.2345) tanh (1.2345) trunc (1.2345) 10 10.1 4708 111 180 39 35 131 42 1341 42 4142 4498 433 9293 150 3353 4946 494 4381 5126 178 2765 111 180 37 35 131 41 866 42 2134 2260 429 5047 150 1653 3003 492 2426 3173 178 Porting From IAR to AVR GCC Introduction C language was designed to be a portable language. There two main types of porting activities: porting an application to a different platform (OS and/or processor), and porting to a different compiler. Porting to a different compiler can be exacerbated when the application is an embedded system. For example, the C language Standard, strangely, does not specify a standard for declaring and defining Interrupt Service Routines (ISRs). Different compilers have different ways of defining registers, some of which use non-standard language constructs. This chapter describes some methods and pointers on porting an AVR application built with the IAR compiler to the GNU toolchain (AVR GCC). Note that this may not be an exhaustive list. 10.2 Registers IO header files contain identifiers for all the register names and bit names for a particular processor. IAR has individual header files for each processor and they must be included when registers are being used in the code. For example: #include
Note IAR does not always use the same register names or bit names that are used in the AVR datasheet. AVR GCC also has individual IO header files for each processor. However, the actual processor type is specified as a command line flag to the compiler. (Using the -mmcu=processor flag.) This is usually done in the Makefile. This allows you to specify only a single header file for any processor type: #include Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 10.3 Interrupt Service Routines (ISRs) 45 Note The forward slash in the file name that is used to separate subdirectories can be used on Windows distributions of the toolchain and is the recommended method of including this file. The compiler knows the processor type and through the single header file above, it can pull in and include the correct individual IO header file. This has the advantage that you only have to specify one generic header file, and you can easily port your application to another processor type without having to change every file to include the new IO header file. The AVR toolchain tries to adhere to the exact names of the registers and names of the bits found in the AVR datasheet. There may be some descrepencies between the register names found in the IAR IO header files and the AVR GCC IO header files. 10.3 Interrupt Service Routines (ISRs) As mentioned above, the C language Standard, strangely, does not specify a standard way of declaring and defining an ISR. Hence, every compiler seems to have their own special way of doing so. IAR declares an ISR like so: #pragma vector=TIMER0_OVF_vect __interrupt void MotorPWMBottom() { // code } In AVR GCC, you declare an ISR like so: ISR(PCINT1_vect) { //code } AVR GCC uses the ISR macro to define an ISR. This macro requries the header file: #include The names of the various interrupt vectors are found in the individual processor IO header files that you must include with . Note The names of the interrupt vectors in AVR GCC has been changed to match the names of the vectors in IAR. This significantly helps in porting applications from IAR to AVR GCC. 10.4 Intrinsic Routines IAR has a number of intrinsic routine such as __enable_interrupts() __disable_interrupts() __watchdog_reset() These intrinsic functions compile to specific AVR opcodes (SEI, CLI, WDR). There are equivalent macros that are used in AVR GCC, however they are not located in a single include file. AVR GCC has sei() for __enable_interrupts(), and cli() for __disable_interrupts(). Both of these macros are located in . AVR GCC has the macro wdt_reset() in place of __watchdog_reset(). However, there is a whole Watchdog Timer API available in AVR GCC that can be found in . Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 46 10.5 CONTENTS Flash Variables The C language was not designed for Harvard architecture processors with separate memory spaces. This means that there are various non-standard ways to define a variable whose data resides in the Program Memory (Flash). IAR uses a non-standard keyword to declare a variable in Program Memory: __flash int mydata[] = .... AVR GCC uses Variable Attributes to achieve the same effect: int mydata[] __attribute__((progmem)) Note See the GCC User Manual for more information about Variable Attributes. avr-libc provides a convenience macro for the Variable Attribute: #include . . . int mydata[] PROGMEM = .... Note The PROGMEM macro expands to the Variable Attribute of progmem. This macro requires that you include . This is the canonical method for defining a variable in Program Space. To read back flash data, use the pgm_read_∗() macros defined in . All Program Memory handling macros are defined there. There is also a way to create a method to define variables in Program Memory that is common between the two compilers (IAR and AVR GCC). Create a header file that has these definitions: #if defined(__ICCAVR__) // IAR C Compiler #define FLASH_DECLARE(x) __flash x #endif #if defined(__GNUC__) // GNU Compiler #define FLASH_DECLARE(x) x __attribute__((__progmem__)) #endif This code snippet checks for the IAR compiler or for the GCC compiler and defines a macro FLASH_DECLARE(x) that will declare a variable in Program Memory using the appropriate method based on the compiler that is being used. Then you would used it like so: FLASH_DECLARE(int mydata[] = ...); 10.6 Non-Returning main() To declare main() to be a non-returning function in IAR, it is done like this: __C_task void main(void) { // code } Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 10.7 Locking Registers 47 To do the equivalent in AVR GCC, do this: void main(void) __attribute__((noreturn)); void main(void) { //... } Note See the GCC User Manual for more information on Function Attributes. In AVR GCC, a prototype for main() is required so you can declare the function attribute to specify that the main() function is of type "noreturn". Then, define main() as normal. Note that the return type for main() is now void. 10.7 Locking Registers The IAR compiler allows a user to lock general registers from r15 and down by using compiler options and this keyword syntax: __regvar __no_init volatile unsigned int filteredTimeSinceCommutation @14; This line locks r14 for use only when explicitly referenced in your code thorugh the var name "filteredTimeSince←Commutation". This means that the compiler cannot dispose of it at its own will. To do this in AVR GCC, do this: register unsigned char counter asm("r3"); Typically, it should be possible to use r2 through r15 that way. Note Do not reserve r0 or r1 as these are used internally by the compiler for a temporary register and for a zero value. Locking registers is not recommended in AVR GCC as it removes this register from the control of the compiler, which may make code generation worse. Use at your own risk. 11 Frequently Asked Questions 11.1 FAQ Index 1. My program doesn’t recognize a variable updated within an interrupt routine 2. I get "undefined reference to..." for functions like "sin()" 3. How to permanently bind a variable to a register? 4. How to modify MCUCR or WDTCR early? 5. What is all this _BV() stuff about? 6. Can I use C++ on the AVR? 7. Shouldn’t I initialize all my variables? Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 48 CONTENTS 8. Why do some 16-bit timer registers sometimes get trashed? 9. How do I use a #define’d constant in an asm statement? 10. Why does the PC randomly jump around when single-stepping through my program in avr-gdb? 11. How do I trace an assembler file in avr-gdb? 12. How do I pass an IO port as a parameter to a function? 13. What registers are used by the C compiler? 14. How do I put an array of strings completely in ROM? 15. How to use external RAM? 16. Which -O flag to use? 17. How do I relocate code to a fixed address? 18. My UART is generating nonsense! My ATmega128 keeps crashing! Port F is completely broken! 19. Why do all my "foo...bar" strings eat up the SRAM? 20. Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation in assembly? 21. How to detect RAM memory and variable overlap problems? 22. Is it really impossible to program the ATtinyXX in C? 23. What is this "clock skew detected" message? 24. Why are (many) interrupt flags cleared by writing a logical 1? 25. Why have "programmed" fuses the bit value 0? 26. Which AVR-specific assembler operators are available? 27. Why are interrupts re-enabled in the middle of writing the stack pointer? 28. Why are there five different linker scripts? 29. How to add a raw binary image to linker output? 30. How do I perform a software reset of the AVR? 31. I am using floating point math. Why is the compiled code so big? Why does my code not work? 32. What pitfalls exist when writing reentrant code? 33. Why are some addresses of the EEPROM corrupted (usually address zero)? 34. Why is my baud rate wrong? 35. On a device with more than 128 KiB of flash, how to make function pointers work? 36. Why is assigning ports in a "chain" a bad idea? Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.2 My program doesn’t recognize a variable updated within an interrupt routine 11.2 My program doesn’t recognize a variable updated within an interrupt routine 49 When using the optimizer, in a loop like the following one: uint8_t flag; ... ISR(SOME_vect) { flag = 1; } ... while (flag == 0) { ... } the compiler will typically access flag only once, and optimize further accesses completely away, since its code path analysis shows that nothing inside the loop could change the value of flag anyway. To tell the compiler that this variable could be changed outside the scope of its code path analysis (e. g. from within an interrupt routine), the variable needs to be declared like: volatile uint8_t flag; Back to FAQ Index. 11.3 I get "undefined reference to..." for functions like "sin()" In order to access the mathematical functions that are declared in , the linker needs to be told to also link the mathematical library, libm.a. Typically, system libraries like libm.a are given to the final C compiler command line that performs the linking step by adding a flag -lm at the end. (That is, the initial lib and the filename suffix from the library are written immediately after a -l flag. So for a libfoo.a library, -lfoo needs to be provided.) This will make the linker search the library in a path known to the system. An alternative would be to specify the full path to the libm.a file at the same place on the command line, i. e. after all the object files (∗.o). However, since this requires knowledge of where the build system will exactly find those library files, this is deprecated for system libraries. Back to FAQ Index. 11.4 How to permanently bind a variable to a register? This can be done with register unsigned char counter asm("r3"); Typically, it should be safe to use r2 through r7 that way. Registers r8 through r15 can be used for argument passing by the compiler in case many or long arguments are being passed to callees. If this is not the case throughout the entire application, these registers could be used for register variables as well. Extreme care should be taken that the entire application is compiled with a consistent set of register-allocated variables, including possibly used library functions. See C Names Used in Assembler Code for more details. Back to FAQ Index. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 50 11.5 CONTENTS How to modify MCUCR or WDTCR early? The method of early initialization (MCUCR, WDTCR or anything else) is different (and more flexible) in the current version. Basically, write a small assembler file which looks like this: ;; begin xram.S #include .section .init1,"ax",@progbits ldi r16,_BV(SRE) | _BV(SRW) out _SFR_IO_ADDR(MCUCR),r16 ;; end xram.S Assemble it, link the resulting xram.o with other files in your program, and this piece of code will be inserted in initialization code, which is run right after reset. See the linker script for comments about the new .initN sections (which one to use, etc.). The advantage of this method is that you can insert any initialization code you want (just remember that this is very early startup – no stack and no __zero_reg__ yet), and no program memory space is wasted if this feature is not used. There should be no need to modify linker scripts anymore, except for some very special cases. It is best to leave __←stack at its default value (end of internal SRAM – faster, and required on some devices like ATmega161 because of errata), and add -Wl,-Tdata,0x801100 to start the data section above the stack. For more information on using sections, see Memory Sections. There is also an example for Using Sections in C Code. Note that in C code, any such function would preferably be placed into section .init3 as the code in .init2 ensures the internal register __zero_reg__ is already cleared. Back to FAQ Index. 11.6 What is all this _BV() stuff about? When performing low-level output work, which is a very central point in microcontroller programming, it is quite common that a particular bit needs to be set or cleared in some IO register. While the device documentation provides mnemonic names for the various bits in the IO registers, and the AVR device-specific IO definitions reflect these names in definitions for numerical constants, a way is needed to convert a bit number (usually within a byte register) into a byte value that can be assigned directly to the register. However, sometimes the direct bit numbers are needed as well (e. g. in an SBI() instruction), so the definitions cannot usefully be made as byte values in the first place. So in order to access a particular bit number as a byte value, use the _BV() macro. Of course, the implementation of this macro is just the usual bit shift (which is done by the compiler anyway, thus doesn’t impose any run-time penalty), so the following applies: _BV(3) => 1 << 3 => 0x08 However, using the macro often makes the program better readable. "BV" stands for "bit value", in case someone might ask you. :-) Example: clock timer 2 with full IO clock (CS2x = 0b001), toggle OC2 output on compare match (COM2x = 0b01), and clear timer on compare match (CTC2 = 1). Make OC2 (PD7) an output. TCCR2 = _BV(COM20)|_BV(CTC2)|_BV(CS20); DDRD = _BV(PD7); Back to FAQ Index. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.7 Can I use C++ on the AVR? 11.7 Can I use C++ on the AVR? 51 Basically yes, C++ is supported (assuming your compiler has been configured and compiled to support it, of course). Source files ending in .cc, .cpp or .C will automatically cause the compiler frontend to invoke the C++ compiler. Alternatively, the C++ compiler could be explicitly called by the name avr-c++. However, there’s currently no support for libstdc++, the standard support library needed for a complete C++ implementation. This imposes a number of restrictions on the C++ programs that can be compiled. Among them are: • Obviously, none of the C++ related standard functions, classes, and template classes are available. • The operators new and delete are not implemented, attempting to use them will cause the linker to complain about undefined external references. (This could perhaps be fixed.) • Some of the supplied include files are not C++ safe, i. e. they need to be wrapped into extern "C" { . . . } (This could certainly be fixed, too.) • Exceptions are not supported. Since exceptions are enabled by default in the C++ frontend, they explicitly need to be turned off using -fno-exceptions in the compiler options. Failing this, the linker will complain about an undefined external reference to __gxx_personality_sj0. Constructors and destructors are supported though, including global ones. When programming C++ in space- and runtime-sensitive environments like microcontrollers, extra care should be taken to avoid unwanted side effects of the C++ calling conventions like implied copy constructors that could be called upon function invocation etc. These things could easily add up into a considerable amount of time and program memory wasted. Thus, casual inspection of the generated assembler code (using the -S compiler option) seems to be warranted. Back to FAQ Index. 11.8 Shouldn’t I initialize all my variables? Global and static variables are guaranteed to be initialized to 0 by the C standard. avr-gcc does this by placing the appropriate code into section .init4 (see The .initN Sections). With respect to the standard, this sentence is somewhat simplified (because the standard allows for machines where the actual bit pattern used differs from all bits being 0), but for the AVR target, in general, all integer-type variables are set to 0, all pointers to a NULL pointer, and all floating-point variables to 0.0. As long as these variables are not initialized (i. e. they don’t have an equal sign and an initialization expression to the right within the definition of the variable), they go into the .bss section of the file. This section simply records the size of the variable, but otherwise doesn’t consume space, neither within the object file nor within flash memory. (Of course, being a variable, it will consume space in the target’s SRAM.) In contrast, global and static variables that have an initializer go into the .data section of the file. This will cause them to consume space in the object file (in order to record the initializing value), and in the flash ROM of the target device. The latter is needed since the flash ROM is the only way that the compiler can tell the target device the value this variable is going to be initialized to. Now if some programmer "wants to make doubly sure" their variables really get a 0 at program startup, and adds an initializer just containing 0 on the right-hand side, they waste space. While this waste of space applies to virtually any platform C is implemented on, it’s usually not noticeable on larger machines like PCs, while the waste of flash ROM storage can be very painful on a small microcontroller like the AVR. So in general, variables should only be explicitly initialized if the initial value is non-zero. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 52 CONTENTS Note Recent versions of GCC are now smart enough to detect this situation, and revert variables that are explicitly initialized to 0 to the .bss section. Still, other compilers might not do that optimization, and as the C standard guarantees the initialization, it is safe to rely on it. Back to FAQ Index. 11.9 Why do some 16-bit timer registers sometimes get trashed? Some of the timer-related 16-bit IO registers use a temporary register (called TEMP in the Atmel datasheet) to guarantee an atomic access to the register despite the fact that two separate 8-bit IO transfers are required to actually move the data. Typically, this includes access to the current timer/counter value register (TCNTn), the input capture register (I←CRn), and write access to the output compare registers (OCRnM). Refer to the actual datasheet for each device’s set of registers that involves the TEMP register. When accessing one of the registers that use TEMP from the main application, and possibly any other one from within an interrupt routine, care must be taken that no access from within an interrupt context could clobber the TEMP register data of an in-progress transaction that has just started elsewhere. To protect interrupt routines against other interrupt routines, it’s usually best to use the ISR() macro when declaring the interrupt function, and to ensure that interrupts are still disabled when accessing those 16-bit timer registers. Within the main program, access to those registers could be encapsulated in calls to the cli() and sei() macros. If the status of the global interrupt flag before accessing one of those registers is uncertain, something like the following example code can be used. uint16_t read_timer1(void) { uint8_t sreg; uint16_t val; sreg = SREG; cli(); val = TCNT1; SREG = sreg; return val; } Back to FAQ Index. 11.10 How do I use a #define’d constant in an asm statement? So you tried this: asm volatile("sbi 0x18,0x07;"); Which works. When you do the same thing but replace the address of the port by its macro name, like this: asm volatile("sbi PORTB,0x07;"); you get a compilation error: "Error: constant value required". PORTB is a precompiler definition included in the processor specific file included in avr/io.h. As you may know, the precompiler will not touch strings and PORTB, instead of 0x18, gets passed to the assembler. One way to avoid this problem is: asm volatile("sbi %0, 0x07" : "I" (_SFR_IO_ADDR(PORTB)):); Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.11 Why does the PC randomly jump around when single-stepping through my program in avr-gdb? 53 Note For C programs, rather use the standard C bit operators instead, so the above would be expressed as PORTB |= (1 << 7). The optimizer will take care to transform this into a single SBI instruction, assuming the operands allow for this. Back to FAQ Index. 11.11 Why does the PC randomly jump around when single-stepping through my program in avr-gdb? When compiling a program with both optimization (-O) and debug information (-g) which is fortunately possible in avr-gcc, the code watched in the debugger is optimized code. While it is not guaranteed, very often this code runs with the exact same optimizations as it would run without the -g switch. This can have unwanted side effects. Since the compiler is free to reorder code execution as long as the semantics do not change, code is often rearranged in order to make it possible to use a single branch instruction for conditional operations. Branch instructions can only cover a short range for the target PC (-63 through +64 words from the current PC). If a branch instruction cannot be used directly, the compiler needs to work around it by combining a skip instruction together with a relative jump (rjmp) instruction, which will need one additional word of ROM. Another side effect of optimization is that variable usage is restricted to the area of code where it is actually used. So if a variable was placed in a register at the beginning of some function, this same register can be re-used later on if the compiler notices that the first variable is no longer used inside that function, even though the variable is still in lexical scope. When trying to examine the variable in avr-gdb, the displayed result will then look garbled. So in order to avoid these side effects, optimization can be turned off while debugging. However, some of these optimizations might also have the side effect of uncovering bugs that would otherwise not be obvious, so it must be noted that turning off optimization can easily change the bug pattern. In most cases, you are better off leaving optimizations enabled while debugging. Back to FAQ Index. 11.12 How do I trace an assembler file in avr-gdb? When using the -g compiler option, avr-gcc only generates line number and other debug information for C (and C++) files that pass the compiler. Functions that don’t have line number information will be completely skipped by a single step command in gdb. This includes functions linked from a standard library, but by default also functions defined in an assembler source file, since the -g compiler switch does not apply to the assembler. So in order to debug an assembler input file (possibly one that has to be passed through the C preprocessor), it’s the assembler that needs to be told to include line-number information into the output file. (Other debug information like data types and variable allocation cannot be generated, since unlike a compiler, the assembler basically doesn’t know about this.) This is done using the (GNU) assembler option -gstabs. Example: $ avr-as -mmcu=atmega128 --gstabs -o foo.o foo.s When the assembler is not called directly but through the C compiler frontend (either implicitly by passing a source file ending in .S, or explicitly using -x assembler-with-cpp), the compiler frontend needs to be told to pass the -gstabs option down to the assembler. This is done using -Wa,-gstabs. Please take care to only pass this option when compiling an assembler input file. Otherwise, the assembler code that results from the C compilation stage will also get line number information, which confuses the debugger. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 54 CONTENTS Note You can also use -Wa,-gstabs since the compiler will add the extra ’-’ for you. Example: $ EXTRA_OPTS="-Wall -mmcu=atmega128 -x assembler-with-cpp" $ avr-gcc -Wa,--gstabs ${EXTRA_OPTS} -c -o foo.o foo.S Also note that the debugger might get confused when entering a piece of code that has a non-local label before, since it then takes this label as the name of a new function that appears to have been entered. Thus, the best practice to avoid this confusion is to only use non-local labels when declaring a new function, and restrict anything else to local labels. Local labels consist just of a number only. References to these labels consist of the number, followed by the letter b for a backward reference, or f for a forward reference. These local labels may be re-used within the source file, references will pick the closest label with the same number and given direction. Example: myfunc: push push push push push ... eor ldi ldi rjmp 1: ld ... breq ... inc 2: cmp brlo r16 r17 r18 YL YH 1: YH YL r18 r17 r16 pop pop pop pop pop ret r16, r16 ; start loop YL, lo8(sometable) YH, hi8(sometable) 2f ; jump to loop test at end r17, Y+ ; loop continues here 1f ; return from myfunc prematurely r16 r16, r18 1b ; jump back to top of loop Back to FAQ Index. 11.13 How do I pass an IO port as a parameter to a function? Consider this example code: #include #include void set_bits_func_wrong (volatile uint8_t port, uint8_t mask) { port |= mask; } void set_bits_func_correct (volatile uint8_t *port, uint8_t mask) { *port |= mask; } #define set_bits_macro(port,mask) ((port) |= (mask)) int main (void) { Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.13 How do I pass an IO port as a parameter to a function? 55 set_bits_func_wrong (PORTB, 0xaa); set_bits_func_correct (&PORTB, 0x55); set_bits_macro (PORTB, 0xf0); return (0); } The first function will generate object code which is not even close to what is intended. The major problem arises when the function is called. When the compiler sees this call, it will actually pass the value of the PORTB register (using an IN instruction), instead of passing the address of PORTB (e.g. memory mapped io addr of 0x38, io port 0x18 for the mega128). This is seen clearly when looking at the disassembly of the call: set_bits_func_wrong 10a: 6a ea 10c: 88 b3 10e: 0e 94 65 00 (PORTB, ldi in call 0xaa); r22, 0xAA r24, 0x18 0xca ; 170 ; 24 So, the function, once called, only sees the value of the port register and knows nothing about which port it came from. At this point, whatever object code is generated for the function by the compiler is irrelevant. The interested reader can examine the full disassembly to see that the function’s body is completely fubar. The second function shows how to pass (by reference) the memory mapped address of the io port to the function so that you can read and write to it in the function. Here’s the object code generated for the function call: set_bits_func_correct (&PORTB, 0x55); 112: 65 e5 ldi r22, 0x55 114: 88 e3 ldi r24, 0x38 116: 90 e0 ldi r25, 0x00 118: 0e 94 7c 00 call 0xf8 ; 85 ; 56 ; 0 You can clearly see that 0x0038 is correctly passed for the address of the io port. Looking at the disassembled object code for the body of the function, we can see that the function is indeed performing the operation we intended: void set_bits_func_correct (volatile uint8_t *port, uint8_t mask) { f8: fc 01 movw r30, r24 *port |= mask; fa: 80 81 ld r24, Z fc: 86 2b or r24, r22 fe: 80 83 st Z, r24 } 100: 08 95 ret Notice that we are accessing the io port via the LD and ST instructions. The port parameter must be volatile to avoid a compiler warning. Note Because of the nature of the IN and OUT assembly instructions, they can not be used inside the function when passing the port in this way. Readers interested in the details should consult the Instruction Set datasheet. Finally we come to the macro version of the operation. In this contrived example, the macro is the most efficient method with respect to both execution speed and code size: set_bits_macro (PORTB, 0xf0); 11c: 88 b3 in r24, 0x18 11e: 80 6f ori r24, 0xF0 120: 88 bb out 0x18, r24 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen ; 24 ; 240 ; 24 56 CONTENTS Of course, in a real application, you might be doing a lot more in your function which uses a passed by reference io port address and thus the use of a function over a macro could save you some code space, but still at a cost of execution speed. Care should be taken when such an indirect port access is going to one of the 16-bit IO registers where the order of write access is critical (like some timer registers). All versions of avr-gcc up to 3.3 will generate instructions that use the wrong access order in this situation (since with normal memory operands where the order doesn’t matter, this sometimes yields shorter code). See http://mail.nongnu.org/archive/html/avr-libc-dev/2003-01/msg00044.html for a possible workaround. avr-gcc versions after 3.3 have been fixed in a way where this optimization will be disabled if the respective pointer variable is declared to be volatile, so the correct behaviour for 16-bit IO ports can be forced that way. Back to FAQ Index. 11.14 What registers are used by the C compiler? • Data types: char is 8 bits, int is 16 bits, long is 32 bits, long long is 64 bits, float and double are 32 bits (this is the only supported floating point format), pointers are 16 bits (function pointers are word addresses, to allow addressing up to 128K program memory space). There is a -mint8 option (see Options for the C compiler avr-gcc) to make int 8 bits, but that is not supported by avr-libc and violates C standards (int must be at least 16 bits). It may be removed in a future release. • Call-used registers (r18-r27, r30-r31): May be allocated by gcc for local data. You may use them freely in assembler subroutines. Calling C subroutines can clobber any of them - the caller is responsible for saving and restoring. • Call-saved registers (r2-r17, r28-r29): May be allocated by gcc for local data. Calling C subroutines leaves them unchanged. Assembler subroutines are responsible for saving and restoring these registers, if changed. r29:r28 (Y pointer) is used as a frame pointer (points to local data on stack) if necessary. The requirement for the callee to save/preserve the contents of these registers even applies in situations where the compiler assigns them for argument passing. • Fixed registers (r0, r1): Never allocated by gcc for local data, but often used for fixed purposes: r0 - temporary register, can be clobbered by any C code (except interrupt handlers which save it), may be used to remember something for a while within one piece of assembler code r1 - assumed to be always zero in any C code, may be used to remember something for a while within one piece of assembler code, but must then be cleared after use (clr r1). This includes any use of the [f]mul[s[u]] instructions, which return their result in r1:r0. Interrupt handlers save and clear r1 on entry, and restore r1 on exit (in case it was non-zero). • Function call conventions: Arguments - allocated left to right, r25 to r8. All arguments are aligned to start in even-numbered registers (oddsized arguments, including char, have one free register above them). This allows making better use of the movw instruction on the enhanced core. If too many, those that don’t fit are passed on the stack. Return values: 8-bit in r24 (not r25!), 16-bit in r25:r24, up to 32 bits in r22-r25, up to 64 bits in r18-r25. 8-bit return values are zero/sign-extended to 16 bits by the called function (unsigned char is more efficient than signed char just clr r25). Arguments to functions with variable argument lists (printf etc.) are all passed on stack, and char is extended to int. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.15 How do I put an array of strings completely in ROM? 57 Warning There was no such alignment before 2000-07-01, including the old patches for gcc-2.95.2. Check your old assembler subroutines, and adjust them accordingly. Back to FAQ Index. 11.15 How do I put an array of strings completely in ROM? There are times when you may need an array of strings which will never be modified. In this case, you don’t want to waste ram storing the constant strings. The most obvious (and incorrect) thing to do is this: #include PGM_P array[2] PROGMEM = { "Foo", "Bar" }; int main (void) { char buf[32]; strcpy_P (buf, array[1]); return 0; } The result is not what you want though. What you end up with is the array stored in ROM, while the individual strings end up in RAM (in the .data section). To work around this, you need to do something like this: #include const char foo[] PROGMEM = "Foo"; const char bar[] PROGMEM = "Bar"; PGM_P array[2] PROGMEM = { foo, bar }; int main (void) { char buf[32]; PGM_P p; int i; memcpy_P(&p, &array[i], sizeof(PGM_P)); strcpy_P(buf, p); return 0; } Looking at the disassembly of the resulting object file we see that array is in flash as such: 00000026 : 26: 2e 00 28: 2a 00 .word .word 0x002e 0x002a ; ???? ; ???? 0000002a : 2a: 42 61 72 00 Bar. 0000002e : 2e: 46 6f 6f 00 Foo. foo is at addr 0x002e. bar is at addr 0x002a. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 58 CONTENTS array is at addr 0x0026. Then in main we see this: memcpy_P(&p, &array[i], sizeof(PGM_P)); 70: 66 0f add r22, r22 72: 77 1f adc r23, r23 74: 6a 5d subi r22, 0xDA 76: 7f 4f sbci r23, 0xFF 78: 42 e0 ldi r20, 0x02 7a: 50 e0 ldi r21, 0x00 7c: ce 01 movw r24, r28 7e: 81 96 adiw r24, 0x21 80: 08 d0 rcall .+16 ; ; ; ; 218 255 2 0 ; 33 ; 0x92 This code reads the pointer to the desired string from the ROM table array into a register pair. The value of i (in r22:r23) is doubled to accommodate for the word offset required to access array[], then the address of array (0x26) is added, by subtracting the negated address (0xffda). The address of variable p is computed by adding its offset within the stack frame (33) to the Y pointer register, and memcpy_P is called. strcpy_P(buf, p); 82: 69 a1 84: 7a a1 86: ce 01 88: 01 96 8a: 0c d0 ldd ldd movw adiw rcall r22, r23, r24, r24, .+24 Y+33 Y+34 r28 0x01 ; 0x21 ; 0x22 ; 1 ; 0xa4 This will finally copy the ROM string into the local buffer buf. Variable p (located at Y+33) is read, and passed together with the address of buf (Y+1) to strcpy_P. This will copy the string from ROM to buf. Note that when using a compile-time constant index, omitting the first step (reading the pointer from ROM via memcpy←_P) usually remains unnoticed, since the compiler would then optimize the code for accessing array at compile-time. Back to FAQ Index. 11.16 How to use external RAM? Well, there is no universal answer to this question; it depends on what the external RAM is going to be used for. Basically, the bit SRE (SRAM enable) in the MCUCR register needs to be set in order to enable the external memory interface. Depending on the device to be used, and the application details, further registers affecting the external memory operation like XMCRA and XMCRB, and/or further bits in MCUCR might be configured. Refer to the datasheet for details. If the external RAM is going to be used to store the variables from the C program (i. e., the .data and/or .bss segment) in that memory area, it is essential to set up the external memory interface early during the device initialization so the initialization of these variable will take place. Refer to How to modify MCUCR or WDTCR early? for a description how to do this using few lines of assembler code, or to the chapter about memory sections for an example written in C. The explanation of malloc() contains a discussion about the use of internal RAM vs. external RAM in particular with respect to the various possible locations of the heap (area reserved for malloc()). It also explains the linker commandline options that are required to move the memory regions away from their respective standard locations in internal RAM. Finally, if the application simply wants to use the additional RAM for private data storage kept outside the domain of the C compiler (e. g. through a char ∗ variable initialized directly to a particular address), it would be sufficient to defer the initialization of the external RAM interface to the beginning of main(), so no tweaking of the .init3 section is necessary. The same applies if only the heap is going to be located there, since the application start-up code does not affect the heap. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.17 Which -O flag to use? 59 It is not recommended to locate the stack in external RAM. In general, accessing external RAM is slower than internal RAM, and errata of some AVR devices even prevent this configuration from working properly at all. Back to FAQ Index. 11.17 Which -O flag to use? There’s a common misconception that larger numbers behind the -O option might automatically cause "better" optimization. First, there’s no universal definition for "better", with optimization often being a speed vs. code size trade off. See the detailed discussion for which option affects which part of the code generation. A test case was run on an ATmega128 to judge the effect of compiling the library itself using different optimization levels. The following table lists the results. The test case consisted of around 2 KB of strings to sort. Test #1 used qsort() using the standard library strcmp(), test #2 used a function that sorted the strings by their size (thus had two calls to strlen() per invocation). When comparing the resulting code size, it should be noted that a floating point version of fvprintf() was linked into the binary (in order to print out the time elapsed) which is entirely not affected by the different optimization levels, and added about 2.5 KB to the code. Optimization flags -O3 -O2 -Os -Os -mcall-prologues Size of .text 6898 6666 6618 6474 Time for test #1 903 µs 972 µs 955 µs 972 µs Time for test #2 19.7 ms 20.1 ms 20.1 ms 20.1 ms (The difference between 955 µs and 972 µs was just a single timer-tick, so take this with a grain of salt.) So generally, it seems -Os -mcall-prologues is the most universal "best" optimization level. Only applications that need to get the last few percent of speed benefit from using -O3. Back to FAQ Index. 11.18 How do I relocate code to a fixed address? First, the code should be put into a new named section. This is done with a section attribute: __attribute__ ((section (".bootloader"))) In this example, .bootloader is the name of the new section. This attribute needs to be placed after the prototype of any function to force the function into the new section. void boot(void) __attribute__ ((section (".bootloader"))); To relocate the section to a fixed address the linker flag -section-start is used. This option can be passed to the linker using the -Wl compiler option: -Wl,--section-start=.bootloader=0x1E000 The name after section-start is the name of the section to be relocated. The number after the section name is the beginning address of the named section. Back to FAQ Index. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 60 CONTENTS 11.19 My UART is generating nonsense! My ATmega128 keeps crashing! Port F is completely broken! Well, certain odd problems arise out of the situation that the AVR devices as shipped by Atmel often come with a default fuse bit configuration that doesn’t match the user’s expectations. Here is a list of things to care for: • All devices that have an internal RC oscillator ship with the fuse enabled that causes the device to run off this oscillator, instead of an external crystal. This often remains unnoticed until the first attempt is made to use something critical in timing, like UART communication. • The ATmega128 ships with the fuse enabled that turns this device into ATmega103 compatibility mode. This means that some ports are not fully usable, and in particular that the internal SRAM is located at lower addresses. Since by default, the stack is located at the top of internal SRAM, a program compiled for an ATmega128 running on such a device will immediately crash upon the first function call (or rather, upon the first function return). • Devices with a JTAG interface have the JTAGEN fuse programmed by default. This will make the respective port pins that are used for the JTAG interface unavailable for regular IO. Back to FAQ Index. 11.20 Why do all my "foo...bar" strings eat up the SRAM? By default, all strings are handled as all other initialized variables: they occupy RAM (even though the compiler might warn you when it detects write attempts to these RAM locations), and occupy the same amount of flash ROM so they can be initialized to the actual string by startup code. The compiler can optimize multiple identical strings into a single one, but obviously only for one compilation unit (i. e., a single C source file). That way, any string literal will be a valid argument to any C function that expects a const char ∗ argument. Of course, this is going to waste a lot of SRAM. In Program Space String Utilities, a method is described how such constant data can be moved out to flash ROM. However, a constant string located in flash ROM is no longer a valid argument to pass to a function that expects a const char ∗-type string, since the AVR processor needs the special instruction LPM to access these strings. Thus, separate functions are needed that take this into account. Many of the standard C library functions have equivalents available where one of the string arguments can be located in flash ROM. Private functions in the applications need to handle this, too. For example, the following can be used to implement simple debugging messages that will be sent through a UART: #include #include #include int uart_putchar(char c) { if (c == ’\n’) uart_putchar(’\r’); loop_until_bit_is_set(USR, UDRE); UDR = c; return 0; /* so it could be used for fdevopen(), too */ } void debug_P(const char *addr) { char c; while ((c = pgm_read_byte(addr++))) uart_putchar(c); } int main(void) { ioinit(); /* initialize UART, ... */ Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.21 Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation in assembly? 61 debug_P(PSTR("foo was here\n")); return 0; } Note By convention, the suffix _P to the function name is used as an indication that this function is going to accept a "program-space string". Note also the use of the PSTR() macro. Back to FAQ Index. 11.21 Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation in assembly? Bitwise operations in Standard C will automatically promote their operands to an int, which is (by default) 16 bits in avr-gcc. To work around this use typecasts on the operands, including literals, to declare that the values are to be 8 bit operands. This may be especially important when clearing a bit: var &= ~mask; /* wrong way! */ The bitwise "not" operator (∼) will also promote the value in mask to an int. To keep it an 8-bit value, typecast before the "not" operator: var &= (unsigned char)~mask; Back to FAQ Index. 11.22 How to detect RAM memory and variable overlap problems? You can simply run avr-nm on your output (ELF) file. Run it with the -n option, and it will sort the symbols numerically (by default, they are sorted alphabetically). Look for the symbol _end, that’s the first address in RAM that is not allocated by a variable. (avr-gcc internally adds 0x800000 to all data/bss variable addresses, so please ignore this offset.) Then, the run-time initialization code initializes the stack pointer (by default) to point to the last available address in (internal) SRAM. Thus, the region between _end and the end of SRAM is what is available for stack. (If your application uses malloc(), which e. g. also can happen inside printf(), the heap for dynamic memory is also located there. See Memory Areas and Using malloc().) The amount of stack required for your application cannot be determined that easily. For example, if you recursively call a function and forget to break that recursion, the amount of stack required is infinite. :-) You can look at the generated assembler code (avr-gcc ... -S), there’s a comment in each generated assembler file that tells you the frame size for each generated function. That’s the amount of stack required for this function, you have to add up that for all functions where you know that the calls could be nested. Back to FAQ Index. 11.23 Is it really impossible to program the ATtinyXX in C? While some small AVRs are not directly supported by the C compiler since they do not have a RAM-based stack (and some do not even have RAM at all), it is possible anyway to use the general-purpose registers as a RAM replacement since they are mapped into the data memory region. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 62 CONTENTS Bruce D. Lightner wrote an excellent description of how to do this, and offers this together with a toolkit on his web page: http://lightner.net/avr/ATtinyAvrGcc.html Back to FAQ Index. 11.24 What is this "clock skew detected" message? It’s a known problem of the MS-DOS FAT file system. Since the FAT file system has only a granularity of 2 seconds for maintaining a file’s timestamp, and it seems that some MS-DOS derivative (Win9x) perhaps rounds up the current time to the next second when calculating the timestamp of an updated file in case the current time cannot be represented in FAT’s terms, this causes a situation where make sees a "file coming from the future". Since all make decisions are based on file timestamps, and their dependencies, make warns about this situation. Solution: don’t use inferior file systems / operating systems. Neither Unix file systems nor HPFS (aka NTFS) do experience that problem. Workaround: after saving the file, wait a second before starting make. Or simply ignore the warning. If you are paranoid, execute a make clean all to make sure everything gets rebuilt. In networked environments where the files are accessed from a file server, this message can also happen if the file server’s clock differs too much from the network client’s clock. In this case, the solution is to use a proper time keeping protocol on both systems, like NTP. As a workaround, synchronize the client’s clock frequently with the server’s clock. Back to FAQ Index. 11.25 Why are (many) interrupt flags cleared by writing a logical 1? Usually, each interrupt has its own interrupt flag bit in some control register, indicating the specified interrupt condition has been met by representing a logical 1 in the respective bit position. When working with interrupt handlers, this interrupt flag bit usually gets cleared automatically in the course of processing the interrupt, sometimes by just calling the handler at all, sometimes (e. g. for the U[S]ART) by reading a particular hardware register that will normally happen anyway when processing the interrupt. From the hardware’s point of view, an interrupt is asserted as long as the respective bit is set, while global interrupts are enabled. Thus, it is essential to have the bit cleared before interrupts get re-enabled again (which usually happens when returning from an interrupt handler). Only few subsystems require an explicit action to clear the interrupt request when using interrupt handlers. (The notable exception is the TWI interface, where clearing the interrupt indicates to proceed with the TWI bus hardware handshake, so it’s never done automatically.) However, if no normal interrupt handlers are to be used, or in order to make extra sure any pending interrupt gets cleared before re-activating global interrupts (e. g. an external edge-triggered one), it can be necessary to explicitly clear the respective hardware interrupt bit by software. This is usually done by writing a logical 1 into this bit position. This seems to be illogical at first, the bit position already carries a logical 1 when reading it, so why does writing a logical 1 to it clear the interrupt bit? The solution is simple: writing a logical 1 to it requires only a single OUT instruction, and it is clear that only this single interrupt request bit will be cleared. There is no need to perform a read-modify-write cycle (like, an SBI instruction), since all bits in these control registers are interrupt bits, and writing a logical 0 to the remaining bits (as it is done by the simple OUT instruction) will not alter them, so there is no risk of any race condition that might accidentally clear another interrupt request bit. So instead of writing TIFR |= _BV(TOV0); /* wrong! */ simply use Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.26 Why have "programmed" fuses the bit value 0? 63 TIFR = _BV(TOV0); Back to FAQ Index. 11.26 Why have "programmed" fuses the bit value 0? Basically, fuses are just a bit in a special EEPROM area. For technical reasons, erased E[E]PROM cells have all bits set to the value 1, so unprogrammed fuses also have a logical 1. Conversely, programmed fuse cells read out as bit value 0. Back to FAQ Index. 11.27 Which AVR-specific assembler operators are available? See Pseudo-ops and operators. Back to FAQ Index. 11.28 Why are interrupts re-enabled in the middle of writing the stack pointer? When setting up space for local variables on the stack, the compiler generates code like this: /* prologue: frame size=20 */ push r28 push r29 in r28,__SP_L__ in r29,__SP_H__ sbiw r28,20 in __tmp_reg__,__SREG__ cli out __SP_H__,r29 out __SREG__,__tmp_reg__ out __SP_L__,r28 /* prologue end (size=10) */ It reads the current stack pointer value, decrements it by the required amount of bytes, then disables interrupts, writes back the high part of the stack pointer, writes back the saved SREG (which will eventually re-enable interrupts if they have been enabled before), and finally writes the low part of the stack pointer. At the first glance, there’s a race between restoring SREG, and writing SPL. However, after enabling interrupts (either explicitly by setting the I flag, or by restoring it as part of the entire SREG), the AVR hardware executes (at least) the next instruction still with interrupts disabled, so the write to SPL is guaranteed to be executed with interrupts disabled still. Thus, the emitted sequence ensures interrupts will be disabled only for the minimum time required to guarantee the integrity of this operation. Back to FAQ Index. 11.29 Why are there five different linker scripts? From a comment in the source code: Which one of the five linker script files is actually used depends on command line options given to ld. A .x script file is the default script A .xr script is for linking without relocation (-r flag) A .xu script is like .xr but do create constructors (-Ur flag) A .xn script is for linking with -n flag (mix text and data on same page). A .xbn script is for linking with -N flag (mix text and data on same page). Back to FAQ Index. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 64 11.30 CONTENTS How to add a raw binary image to linker output? The GNU linker avr-ld cannot handle binary data directly. However, there’s a companion tool called avr-objcopy. This is already known from the output side: it’s used to extract the contents of the linked ELF file into an Intel Hex load file. avr-objcopy can create a relocatable object file from arbitrary binary input, like avr-objcopy -I binary -O elf32-avr foo.bin foo.o This will create a file named foo.o, with the contents of foo.bin. The contents will default to section .data, and two symbols will be created named _binary_foo_bin_start and _binary_foo_bin_end. These symbols can be referred to inside a C source to access these data. If the goal is to have those data go to flash ROM (similar to having used the PROGMEM attribute in C source code), the sections have to be renamed while copying, and it’s also useful to set the section flags: avr-objcopy --rename-section .data=.progmem.data,contents,alloc,load,readonly,data -I binary -O elf32-avr foo.bin foo.o Note that all this could be conveniently wired into a Makefile, so whenever foo.bin changes, it will trigger the recreation of foo.o, and a subsequent relink of the final ELF file. Below are two Makefile fragments that provide rules to convert a .txt file to an object file, and to convert a .bin file to an object file: $(OBJDIR)/%.o : %.txt @echo Converting $< @cp $(<) $(*).tmp @echo -n 0 | tr 0 ’\000’ >> $(*).tmp @$(OBJCOPY) -I binary -O elf32-avr \ --rename-section .data=.progmem.data,contents,alloc,load,readonly,data \ --redefine-sym _binary_$*_tmp_start=$* \ --redefine-sym _binary_$*_tmp_end=$*_end \ --redefine-sym _binary_$*_tmp_size=$*_size_sym \ $(*).tmp $(@) @echo "extern const char" $(*)"[] PROGMEM;" > $(*).h @echo "extern const char" $(*)_end"[] PROGMEM;" >> $(*).h @echo "extern const char" $(*)_size_sym"[];" >> $(*).h @echo "#define $(*)_size ((int)$(*)_size_sym)" >> $(*).h @rm $(*).tmp $(OBJDIR)/%.o : %.bin @echo Converting $< @$(OBJCOPY) -I binary -O elf32-avr \ --rename-section .data=.progmem.data,contents,alloc,load,readonly,data \ --redefine-sym _binary_$*_bin_start=$* \ --redefine-sym _binary_$*_bin_end=$*_end \ --redefine-sym _binary_$*_bin_size=$*_size_sym \ $(<) $(@) @echo "extern const char" $(*)"[] PROGMEM;" > $(*).h @echo "extern const char" $(*)_end"[] PROGMEM;" >> $(*).h @echo "extern const char" $(*)_size_sym"[];" >> $(*).h @echo "#define $(*)_size ((int)$(*)_size_sym)" >> $(*).h Back to FAQ Index. 11.31 How do I perform a software reset of the AVR? The canonical way to perform a software reset of non-XMega AVR’s is to use the watchdog timer. Enable the watchdog timer to the shortest timeout setting, then go into an infinite, do-nothing loop. The watchdog will then reset the processor. XMega parts have a specific bit RST_SWRST_bm in the RST.CTRL register, that generates a hardware reset. RST←_SWRST_bm is protected by the XMega Configuration Change Protection system. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.32 I am using floating point math. Why is the compiled code so big? Why does my code not work? 65 The reason why using the watchdog timer or RST_SWRST_bm is preferable over jumping to the reset vector, is that when the watchdog or RST_SWRST_bm resets the AVR, the registers will be reset to their known, default settings. Whereas jumping to the reset vector will leave the registers in their previous state, which is generally not a good idea. CAUTION! Older AVRs will have the watchdog timer disabled on a reset. For these older AVRs, doing a soft reset by enabling the watchdog is easy, as the watchdog will then be disabled after the reset. On newer AVRs, once the watchdog is enabled, then it stays enabled, even after a reset! For these newer AVRs a function needs to be added to the .init3 section (i.e. during the startup code, before main()) to disable the watchdog early enough so it does not continually reset the AVR. Here is some example code that creates a macro that can be called to perform a soft reset: #include ... #define soft_reset() do { wdt_enable(WDTO_15MS); for(;;) { } } while(0) \ \ \ \ \ \ \ For newer AVRs (such as the ATmega1281) also add this function to your code to then disable the watchdog after a reset (e.g., after a soft reset): #include ... // Function Pototype void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3"))); ... // Function Implementation void wdt_init(void) { MCUSR = 0; wdt_disable(); return; } Back to FAQ Index. 11.32 I am using floating point math. Why is the compiled code so big? Why does my code not work? You are not linking in the math library from AVR-LibC. GCC has a library that is used for floating point operations, but it is not optimized for the AVR, and so it generates big code, or it could be incorrect. This can happen even when you are not using any floating point math functions from the Standard C library, but you are just doing floating point math operations. When you link in the math library from AVR-LibC, those routines get replaced by hand-optimized AVR assembly and it produces much smaller code. See I get "undefined reference to..." for functions like "sin()" for more details on how to link in the math library. Back to FAQ Index. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 66 11.33 CONTENTS What pitfalls exist when writing reentrant code? Reentrant code means the ability for a piece of code to be called simultaneously from two or more threads. Attention to re-enterability is needed when using a multi-tasking operating system, or when using interrupts since an interrupt is really a temporary thread. The code generated natively by gcc is reentrant. But, only some of the libraries in avr-libc are explicitly reentrant, and some are known not to be reentrant. In general, any library call that reads and writes global variables (including I/O registers) is not reentrant. This is because more than one thread could read or write the same storage at the same time, unaware that other threads are doing the same, and create inconsistent and/or erroneous results. A library call that is known not to be reentrant will work if it is used only within one thread and no other thread makes use of a library call that shares common storage with it. Below is a table of library calls with known issues. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.33 What pitfalls exist when writing reentrant code? Library call rand(), random() strtod(), strtol(), strtoul() Reentrant Issue Uses global variables to keep state information. Uses the global variable errno to return success/failure. malloc(), realloc(), calloc(), free() Uses the stack pointer and global variables to allocate and free memory. fdevopen(), fclose() Uses calloc() and free(). eeprom_∗(), boot_∗() Accesses I/O registers. pgm_∗_far() Accesses I/O register RAMPZ. printf(), printf_P(), vprintf(), vprintf_P(), puts(), puts_P() Alters flags and character count in global FILE stdout. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 67 Workaround/Alternative Use special reentrant versions: rand_r(), random_r(). Ignore errno, or protect calls with cli()/sei() or ATOMIC_BLOCK() if the application can tolerate it. Or use sccanf() or sccanf_P() if possible. Protect calls with cli()/sei() or ATOMIC_BLOCK() if the application can tolerate it. If using an OS, use the OS provided memory allocator since the OS is likely modifying the stack pointer anyway. Protect calls with cli()/sei() or ATOMIC_BLOCK() if the application can tolerate it. Or use fdev_setup_stream() or FDEV_SETUP_STREAM(). Note: fclose() will only call free() if the stream has been opened with fdevopen(). Protect calls with cli()/sei(), ATOMIC_BLOCK(), or use OS locking. Starting with GCC 4.3, RAMPZ is automatically saved for ISRs, so nothing further is needed if only using interrupts. Some OSes may automatically preserve RAMPZ during context switching. Check the OS documentation before assuming it does. Otherwise, protect calls with cli()/sei(), ATOMIC_BLOCK(), or use explicit OS locking. Use only in one thread. Or if returned character count is unimportant, do not use the ∗_P versions. Note: Formatting to a string output, e.g. sprintf(), sprintf_P(), snprintf(), snprintf_P(), vsprintf(), vsprintf_P(), vsnprintf(), vsnprintf_P(), is thread safe. The formatted string could then be followed by an fwrite() which simply calls the lower layer to send the string. 68 CONTENTS fprintf(), fprintf_P(), vfprintf(), vfprintf_P(), fputs(), fputs_P() assert() clearerr() getchar(), gets() fgetc(), ungetc(), fgets(), scanf(), scanf_P(), fscanf(), fscanf_P(), vscanf(), vfscanf(), vfscanf_P(), fread() Alters flags and character count in the FILE argument. Problems can occur if a global FILE is used from multiple threads. Contains an embedded fprintf(). See above for fprintf(). Alters flags in the FILE argument. Assign each thread its own FILE for output. Or if returned character count is unimportant, do not use the ∗_P versions. See above for fprintf(). Alters flags, character count, and unget buffer in global FILE stdin. Alters flags, character count, and unget buffer in the FILE argument. Use only in one thread. ∗∗∗ Assign each thread its own FILE for output. Assign each thread its own FILE for input. ∗∗∗ Note: Scanning from a string, e.g. sscanf() and sscanf_P(), are thread safe. Note It’s not clear one would ever want to do character input simultaneously from more than one thread anyway, but these entries are included for completeness. An effort will be made to keep this table up to date if any new issues are discovered or introduced. Back to FAQ Index. 11.34 Why are some addresses of the EEPROM corrupted (usually address zero)? The two most common reason for EEPROM corruption is either writing to the EEPROM beyond the datasheet endurance specification, or resetting the AVR while an EEPROM write is in progress. EEPROM writes can take up to tens of milliseconds to complete. So that the CPU is not tied up for that long of time, an internal state-machine handles EEPROM write requests. The EEPROM state-machine expects to have all of the EEPROM registers setup, then an EEPROM write request to start the process. Once the EEPROM state-machine has started, changing EEPROM related registers during an EEPROM write is guaranteed to corrupt the EEPROM write process. The datasheet always shows the proper way to tell when a write is in progress, so that the registers are not changed by the user’s program. The EEPROM state-machine will always complete the write in progress unless power is removed from the device. As with all EEPROM technology, if power fails during an EEPROM write the state of the byte being written is undefined. In older generation AVRs the EEPROM Address Register (EEAR) is initialized to zero on reset, be it from Brown Out Detect, Watchdog or the Reset Pin. If an EEPROM write has just started at the time of the reset, the write will be completed, but now at address zero instead of the requested address. If the reset occurs later in the write process both the requested address and address zero may be corrupted. To distinguish which AVRs may exhibit the corrupt of address zero while a write is in process during a reset, look at the "initial value" section for the EEPROM Address Register. If EEAR shows the initial value as 0x00 or 0x0000, then address zero and possibly the one being written will be corrupted. Newer parts show the initial value as "undefined", these will not corrupt address zero during a reset (unless it was address zero that was being written). EEPROMs have limited write endurance. The datasheet specifies the number of EEPROM writes that are guaranteed to function across the full temperature specification of the AVR, for a given byte. A read should always be performed before a write, to see if the value in the EEPROM actually needs to be written, so not to cause unnecessary EEPROM wear. The failure mechanism for an overwritten byte is generally one of "stuck" bits, i. e. a bit will stay at a one or zero state Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 11.35 Why is my baud rate wrong? 69 regardless of the byte written. Also a write followed by a read may return the correct data, but the data will change with the passage of time, due the EEPROM’s inability to hold a charge from the excessive write wear. Back to FAQ Index. 11.35 Why is my baud rate wrong? Some AVR datasheets give the following formula for calculating baud rates: (F_CPU/(UART_BAUD_RATE*16L)-1) Unfortunately that formula does not work with all combinations of clock speeds and baud rates due to integer truncation during the division operator. When doing integer division it is usually better to round to the nearest integer, rather than to the lowest. To do this add 0.5 (i. e. half the value of the denominator) to the numerator before the division, resulting in the formula: ((F_CPU + UART_BAUD_RATE * 8L) / (UART_BAUD_RATE * 16L) - 1) This is also the way it is implemented in : Helper macros for baud rate calculations. Back to FAQ Index. 11.36 On a device with more than 128 KiB of flash, how to make function pointers work? Function pointers beyond the "magical" 128 KiB barrier(s) on larger devices are supposed to be resolved through socalled trampolines by the linker, so the actual pointers used in the code can remain 16 bits wide. In order for this to work, the option -mrelax must be given on the compiler command-line that is used to link the final ELF file. (Older compilers did not implement this option for the AVR, use -Wl,-relax instead.) Back to FAQ Index. 11.37 Why is assigning ports in a "chain" a bad idea? Suppose a number of IO port registers should get the value 0xff assigned. Conveniently, it is implemented like this: DDRB = DDRD = 0xff; According to the rules of the C language, this causes 0xff to be assigned to DDRD, then DDRD is read back, and the value is assigned to DDRB. The compiler stands no chance to optimize the readback away, as an IO port register is declared "volatile". Thus, chaining that kind of IO port assignments would better be avoided, using explicit assignments instead: DDRB = 0xff; DDRD = 0xff; Even worse ist this, e. g. on an ATmega1281: DDRA = DDRB = DDRC = DDRD = DDRE = DDRF = DDRG = 0xff; The same happens as outlined above. However, when reading back register DDRG, this register only implements 6 out of the 8 bits, so the two topmost (unimplemented) bits read back as 0! Consequently, all remaining DDRx registers get assigned the value 0x3f, which does not match the intention of the developer in any way. Back to FAQ Index. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 70 CONTENTS 12 Building and Installing the GNU Tool Chain This chapter shows how to build and install, from source code, a complete development environment for the AVR processors using the GNU toolset. There are two main sections, one for Linux, FreeBSD, and other Unix-like operating systems, and another section for Windows. 12.1 Building and Installing under Linux, FreeBSD, and Others The default behaviour for most of these tools is to install every thing under the /usr/local directory. In order to keep the AVR tools separate from the base system, it is usually better to install everything into /usr/local/avr. If the /usr/local/avr directory does not exist, you should create it before trying to install anything. You will need root access to install there. If you don’t have root access to the system, you can alternatively install in your home directory, for example, in $HOME/local/avr. Where you install is a completely arbitrary decision, but should be consistent for all the tools. You specify the installation directory by using the -prefix=dir option with the configure script. It is important to install all the AVR tools in the same directory or some of the tools will not work correctly. To ensure consistency and simplify the discussion, we will use $PREFIX to refer to whatever directory you wish to install in. You can set this as an environment variable if you wish as such (using a Bourne-like shell): $ PREFIX=$HOME/local/avr $ export PREFIX Note Be sure that you have your PATH environment variable set to search the directory you install everything in before you start installing anything. For example, if you use -prefix=$PREFIX, you must have $PREFIX/bin in your exported PATH. As such: $ PATH=$PATH:$PREFIX/bin $ export PATH Warning If you have CC set to anything other than avr-gcc in your environment, this will cause the configure script to fail. It is best to not have CC set at all. Note It is usually the best to use the latest released version of each of the tools. 12.2 Required Tools • GNU Binutils http://sources.redhat.com/binutils/ Installation • GCC http://gcc.gnu.org/ Installation • AVR LibC http://savannah.gnu.org/projects/avr-libc/ Installation Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 12.3 Optional Tools 12.3 Optional Tools 71 You can develop programs for AVR devices without the following tools. They may or may not be of use for you. • AVRDUDE http://savannah.nongnu.org/projects/avrdude/ Installation Usage Notes • GDB http://sources.redhat.com/gdb/ Installation • SimulAVR http://savannah.gnu.org/projects/simulavr/ Installation • AVaRICE http://avarice.sourceforge.net/ Installation 12.4 GNU Binutils for the AVR target The binutils package provides all the low-level utilities needed in building and manipulating object files. Once installed, your environment will have an AVR assembler (avr-as), linker (avr-ld), and librarian (avr-ar and avr-ranlib). In addition, you get tools which extract data from object files (avr-objcopy), dissassemble object file information (avr-objdump), and strip information from object files (avr-strip). Before we can build the C compiler, these tools need to be in place. Download and unpack the source files: $ bunzip2 -c binutils- .tar.bz2 | tar xf $ cd binutils- Note Replace with the version of the package you downloaded. If you obtained a gzip compressed file (.gz), use gunzip instead of bunzip2. It is usually a good idea to configure and build binutils in a subdirectory so as not to pollute the source with the compiled files. This is recommended by the binutils developers. $ mkdir obj-avr $ cd obj-avr The next step is to configure and build the tools. This is done by supplying arguments to the configure script that enable the AVR-specific options. $ ../configure --prefix=$PREFIX --target=avr --disable-nls Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 72 CONTENTS If you don’t specify the -prefix option, the tools will get installed in the /usr/local hierarchy (i.e. the binaries will get installed in /usr/local/bin, the info pages get installed in /usr/local/info, etc.) Since these tools are changing frequently, It is preferrable to put them in a location that is easily removed. When configure is run, it generates a lot of messages while it determines what is available on your operating system. When it finishes, it will have created several Makefiles that are custom tailored to your platform. At this point, you can build the project. $ make Note BSD users should note that the project’s Makefile uses GNU make syntax. This means FreeBSD users may need to build the tools by using gmake. If the tools compiled cleanly, you’re ready to install them. If you specified a destination that isn’t owned by your account, you’ll need root access to install them. To install: $ make install You should now have the programs from binutils installed into $PREFIX/bin. Don’t forget to set your PATH environment variable before going to build avr-gcc. 12.5 GCC for the AVR target Warning You must install avr-binutils and make sure your path is set properly before installing avr-gcc. The steps to build avr-gcc are essentially same as for binutils: $ $ $ $ $ bunzip2 -c gcc- .tar.bz2 | tar xf cd gcc- mkdir obj-avr cd obj-avr ../configure --prefix=$PREFIX --target=avr --enable-languages=c,c++ \ --disable-nls --disable-libssp --with-dwarf2 $ make $ make install To save your self some download time, you can alternatively download only the gcc-core- .tar.bz2 and gcc-c++- .tar.bz2 parts of the gcc. Also, if you don’t need C++ support, you only need the core part and should only enable the C language support. (Starting with GCC 4.7 releases, these split files are no longer available though.) Note Early versions of these tools did not support C++. The stdc++ libs are not included with C++ for AVR due to the size limitations of the devices. 12.6 AVR LibC Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 12.7 AVRDUDE 73 Warning You must install avr-binutils, avr-gcc and make sure your path is set properly before installing avr-libc. Note If you have obtained the latest avr-libc from cvs, you will have to run the bootstrap script before using either of the build methods described below. To build and install avr-libc: $ $ $ $ $ gunzip -c avr-libc- .tar.gz | tar xf cd avr-libc- ./configure --prefix=$PREFIX --build=‘./config.guess‘ --host=avr make make install Optionally, generation of debug information can be requested with: $ gunzip -c avr-libc- .tar.gz | tar xf $ cd avr-libc- $ ./configure --prefix=$PREFIX --build=‘./config.guess‘ --host=avr \ --with-debug-info=DEBUG_INFO $ make $ make install where DEBUG_INFO can be one of stabs, dwarf-2, or dwarf-4. The default is to not generate any debug information, which is suitable for binary distributions of avr-libc, where the user does not have the source code installed the debug information would refer to. 12.7 AVRDUDE Note It has been ported to windows (via MinGW or cygwin), Linux and Solaris. Other Unix systems should be trivial to port to. avrdude is part of the FreeBSD ports system. To install it, simply do the following: # cd /usr/ports/devel/avrdude # make install Note Installation into the default location usually requires root permissions. However, running the program only requires access permissions to the appropriate ppi(4) device. Building and installing on other systems should use the configure system, as such: $ $ $ $ $ $ $ gunzip -c avrdude- .tar.gz | tar xf cd avrdude- mkdir obj-avr cd obj-avr ../configure --prefix=$PREFIX make make install Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 74 12.8 CONTENTS GDB for the AVR target GDB also uses the configure system, so to build and install: $ $ $ $ $ $ $ bunzip2 -c gdb- .tar.bz2 | tar xf cd gdb- mkdir obj-avr cd obj-avr ../configure --prefix=$PREFIX --target=avr make make install Note If you are planning on using avr-gdb, you will probably want to install either simulavr or avarice since avr-gdb needs one of these to run as a a remote target backend. 12.9 SimulAVR SimulAVR also uses the configure system, so to build and install: $ $ $ $ $ $ $ gunzip -c simulavr- .tar.gz | tar xf cd simulavr- mkdir obj-avr cd obj-avr ../configure --prefix=$PREFIX make make install Note You might want to have already installed avr-binutils, avr-gcc and avr-libc if you want to have the test programs built in the simulavr source. 12.10 AVaRICE Note These install notes are not applicable to avarice-1.5 or older. You probably don’t want to use anything that old anyways since there have been many improvements and bug fixes since the 1.5 release. AVaRICE also uses the configure system, so to build and install: $ $ $ $ $ $ $ gunzip -c avarice- .tar.gz | tar xf cd avarice- mkdir obj-avr cd obj-avr ../configure --prefix=$PREFIX make make install Note AVaRICE uses the BFD library for accessing various binary file formats. You may need to tell the configure script where to find the lib and headers for the link to work. This is usually done by invoking the configure script like this (Replace with the path to the bfd.h file on your system. Replace with the path to libbfd.a on your system.): $ CPPFLAGS=-I LDFLAGS=-L ../configure --prefix=$PREFIX Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 12.11 Building and Installing under Windows 12.11 Building and Installing under Windows 75 Building and installing the toolchain under Windows requires more effort because all of the tools required for building, and the programs themselves, are mainly designed for running under a POSIX environment such as Unix and Linux. Windows does not natively provide such an environment. There are two projects available that provide such an environment, Cygwin and MinGW. There are advantages and disadvantages to both. Cygwin provides a very complete POSIX environment that allows one to build many Linux based tools from source with very little or no source modifications. However, POSIX functionality is provided in the form of a DLL that is linked to the application. This DLL has to be redistributed with your application and there are issues if the Cygwin DLL already exists on the installation system and different versions of the DLL. On the other hand, MinGW can compile code as native Win32 applications. However, this means that programs designed for Unix and Linux (i.e. that use POSIX functionality) will not compile as MinGW does not provide that POSIX layer for you. Therefore most programs that compile on both types of host systems, usually must provide some sort of abstraction layer to allow an application to be built cross-platform. MinGW does provide somewhat of a POSIX environment, called MSYS, that allows you to build Unix and Linux applications as they woud normally do, with a configure step and a make step. Cygwin also provides such an environment. This means that building the AVR toolchain is very similar to how it is built in Linux, described above. The main differences are in what the PATH environment variable gets set to, pathname differences, and the tools that are required to build the projects under Windows. We’ll take a look at the tools next. 12.12 Tools Required for Building the Toolchain for Windows These are the tools that are currently used to build an AVR tool chain. This list may change, either the version of the tools, or the tools themselves, as improvements are made. • MinGW Download the MinGW Automated Installer, 20100909 (or later) http://sourceforge.net/projects/mingw/files/←- Automated%20MinGW%20Installer/mingw-get-inst/mingw-get-inst-20100909/mingw-get-inst-201 exe/download – Run mingw-get-inst-20100909.exe – In the installation wizard, keep the default values and press the "Next" button for all installer pages except for the pages explicitly listed below. In the installer page "Repository Catalogues", select the "Download latest repository catalogues" radio button, and press the "Next" button • In the installer page "License Agreement", select the "I accept the agreement" radio button, and press the "Next" button • In the installer page "Select Components", be sure to select these items: – C compiler (default checked) – C++ compiler – Ada compiler – MinGW Developer Toolkit (which includes "MSYS Basic System"). • Install. Install Cygwin Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 76 CONTENTS • Install everything, all users, UNIX line endings. This will take a long time. A fat internet pipe is highly recommended. It is also recommended that you download all to a directory first, and then install from that directory to your machine. Note GMP, MPFR, and MPC are required to build GCC. GMP is a prequisite for building MPFR. Build GMP first. MPFR is a prerequisite for building MPC. Build MPFR second. • Build GMP for MinGW – Latest Version – http://gmplib.org/ – Build script: ./configure make make check make install 2>&1 2>&1 2>&1 2>&1 | | | | tee tee tee tee gmp-configure.log gmp-make.log gmp-make-check.log gmp-make-install.log – GMP headers will be installed under /usr/local/include and library installed under /usr/local/lib. • Build MPFR for MinGW – Latest Version – http://www.mpfr.org/ – Build script: ./configure --with-gmp=/usr/local --disable-shared 2>&1 | tee mpfr-configure.log make 2>&1 | tee mpfr-make.log make check 2>&1 | tee mpfr-make-check.log make install 2>&1 | tee mpfr-make-install.log – MPFR headers will be installed under /usr/local/include and library installed under /usr/local/lib. • Build MPC for MinGW – Latest Version – http://www.multiprecision.org/ – Build script: ./configure --with-gmp=/usr/local --with-mpfr=/usr/local --disable-shared 2>&1 | tee mpfr-config make 2>&1 | tee mpfr-make.log make check 2>&1 | tee mpfr-make-check.log make install 2>&1 | tee mpfr-make-install.log – MPFR headers will be installed under /usr/local/include and library installed under /usr/local/lib. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 12.13 Building the Toolchain for Windows 77 Note Doxygen is required to build AVR-LibC documentation. • Install Doxygen – Version 1.7.2 – http://www.stack.nl/∼dimitri/doxygen/ – Download and install. NetPBM is required to build graphics in the AVR-LibC documentation. • Install NetPBM – Version 10.27.0 – From the GNUWin32 project: http://gnuwin32.sourceforge.net/packages.html – Download and install. fig2dev is required to build graphics in the AVR-LibC documentation. • Install fig2dev – Version 3.2 patchlevel 5c – From WinFig 4.62: http://www.schmidt-web-berlin.de/winfig/ – Download the zip file version of WinFig – Unzip the download file and install fig2dev.exe in a location of your choice, somewhere in the PATH. – You may have to unzip and install related DLL files for fig2dev. In the version above, you have to install QtCore4.dll and QtGui4.dll. MikTeX is required to build various documentation. • Install MiKTeX – Version 2.9 – http://miktex.org/ – Download and install. Ghostscript is required to build various documentation. • Install Ghostscript – Version 9.00 – http://www.ghostscript.com – Download and install. – In the \bin subdirectory of the installaion, copy gswin32c.exe to gs.exe. • Set the TEMP and TMP environment variables to c:\temp or to the short filename version. This helps to avoid NTVDM errors during building. 12.13 Building the Toolchain for Windows All directories in the PATH enviornment variable should be specified using their short filename (8.3) version. This will also help to avoid NTVDM errors during building. These short filenames can be specific to each machine. Build the tools below in MinGW/MSYS. • Binutils Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 78 CONTENTS – Open source code pacakge and patch as necessary. – Configure and build in a directory outside of the source code tree. – Set PATH, in order: * · * /usr/local/bin * /usr/bin * /bin * /mingw/bin * c:/cygwin/bin * /bin – Configure CFLAGS=-D__USE_MINGW_ACCESS \ ../$archivedir/configure \ --prefix=$installdir \ --target=avr \ --disable-nls \ --enable-doc \ --datadir=$installdir/doc/binutils \ --with-gmp=/usr/local \ --with-mpfr=/usr/local \ 2>&1 | tee binutils-configure.log – Make make all html install install-html 2>&1 | tee binutils-make.log – Manually change documentation location. • GCC – Open source code pacakge and patch as necessary. – Configure and build in a directory outside of the source code tree. – Set PATH, in order: * · * /usr/local/bin * /usr/bin * /bin * /mingw/bin * c:/cygwin/bin * /bin – Configure LDFLAGS=’-L /usr/local/lib -R /usr/local/lib’ \ CFLAGS=’-D__USE_MINGW_ACCESS’ \ ../gcc-$version/configure \ --with-gmp=/usr/local \ --with-mpfr=/usr/local \ --with-mpc=/usr/local \ --prefix=$installdir \ --target=$target \ --enable-languages=c,c++ \ --with-dwarf2 \ --enable-doc \ --with-docdir=$installdir/doc/$project \ Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 12.13 Building the Toolchain for Windows --disable-shared \ --disable-libada \ --disable-libssp \ 2>&1 | tee $project-configure.log – Make make all html install 2>&1 | tee $package-make.log • avr-libc – Open source code package. – Configure and build at the top of the source code tree. – Set PATH, in order: * /usr/local/bin * /mingw/bin * /bin * * /bin * * * * * c:/cygwin/bin – Configure ./configure \ --host=avr \ --prefix=$installdir \ --enable-doc \ --disable-versioned-doc \ --enable-html-doc \ --enable-pdf-doc \ --enable-man-doc \ --mandir=$installdir/man \ --datadir=$installdir \ 2>&1 | tee $package-configure.log – Make make all install 2>&1 | tee $package-make.log – Manually change location of man page documentation. – Move the examples to the top level of the install tree. – Convert line endings in examples to Windows line endings. – Convert line endings in header files to Windows line endings. • AVRDUDE – Open source code package. – Configure and build at the top of the source code tree. – Set PATH, in order: * * /usr/local/bin * /usr/bin Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 79 80 CONTENTS * /bin * /mingw/bin * c:/cygwin/bin * /bin – Set location of LibUSB headers and libraries export CPPFLAGS="-I../../libusb-win32-device-bin-$libusb_version/include" export CFLAGS="-I../../libusb-win32-device-bin-$libusb_version/include" export LDFLAGS="-L../../libusb-win32-device-bin-$libusb_version/lib/gcc" – Configure ./configure \ --prefix=$installdir \ --datadir=$installdir \ --sysconfdir=$installdir/bin \ --enable-doc \ --disable-versioned-doc \ 2>&1 | tee $package-configure.log – Make make -k all install 2>&1 | tee $package-make.log – Convert line endings in avrdude config file to Windows line endings. – Delete backup copy of avrdude config file in install directory if exists. • Insight/GDB – Open source code pacakge and patch as necessary. – Configure and build in a directory outside of the source code tree. – Set PATH, in order: * * /usr/local/bin * /usr/bin * /bin * /mingw/bin * c:/cygwin/bin * /bin – Configure CFLAGS=-D__USE_MINGW_ACCESS \ LDFLAGS=’-static’ \ ../$archivedir/configure \ --prefix=$installdir \ --target=avr \ --with-gmp=/usr/local \ --with-mpfr=/usr/local \ --enable-doc \ 2>&1 | tee insight-configure.log – Make make all install 2>&1 | tee $package-make.log • SRecord – Open source code package. – Configure and build at the top of the source code tree. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 12.13 Building the Toolchain for Windows 81 – Set PATH, in order: * * /usr/local/bin * /usr/bin * /bin * /mingw/bin * c:/cygwin/bin * /bin – Configure ./configure \ --prefix=$installdir \ --infodir=$installdir/info \ --mandir=$installdir/man \ 2>&1 | tee $package-configure.log – Make make all install 2>&1 | tee $package-make.log Build the tools below in Cygwin. • AVaRICE – Open source code package. – Configure and build in a directory outside of the source code tree. – Set PATH, in order: * * /usr/local/bin * /usr/bin * /bin * /bin – Set location of LibUSB headers and libraries export CPPFLAGS=-I$startdir/libusb-win32-device-bin-$libusb_version/include export CFLAGS=-I$startdir/libusb-win32-device-bin-$libusb_version/include export LDFLAGS="-static -L$startdir/libusb-win32-device-bin-$libusb_version/lib/gcc " – Configure ../$archivedir/configure \ --prefix=$installdir \ --datadir=$installdir/doc \ --mandir=$installdir/man \ --infodir=$installdir/info \ 2>&1 | tee avarice-configure.log – Make make all install 2>&1 | tee avarice-make.log • SimulAVR – Open source code package. – Configure and build in a directory outside of the source code tree. – Set PATH, in order: * Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 82 CONTENTS * /usr/local/bin * /usr/bin * /bin * /bin – Configure export LDFLAGS="-static" ../$archivedir/configure \ --prefix=$installdir \ --datadir=$installdir \ --disable-tests \ --disable-versioned-doc \ 2>&1 | tee simulavr-configure.log – Make make -k all install 2>&1 | tee simulavr-make.log make pdf install-pdf 2>&1 | tee simulavr-pdf-make.log 13 Using the GNU tools This is a short summary of the AVR-specific aspects of using the GNU tools. Normally, the generic documentation of these tools is fairly large and maintained in texinfo files. Command-line options are explained in detail in the manual page. 13.1 Options for the C compiler avr-gcc 13.1.1 Machine-specific options for the AVR The following machine-specific options are recognized by the C compiler frontend. In addition to the preprocessor macros indicated in the tables below, the preprocessor will define the macros AVR and __AVR (to the value 1) when compiling for an AVR target. The macro AVR will be defined as well when using the standard levels gnu89 (default) and gnu99 but not with c89 and c99. • -mmcu=architecture Compile code for architecture. Currently known architectures are Architecture avr1 avr2 avr25 [1] avr3 PBSMacros PBSAVR_ARCH=1 AVR_ASM_ONLY AVR_2_BYTE_PC [2] PBSAVR_ARCH=2 AVR_2_BYTE_PC [2] PBSAVR_ARCH=25 AVR_HAVE_MOVW [1] AVR_HAVE_LPMX [1] AVR_2_BYTE_PC [2] PBSAVR_ARCH=3 AVR_MEGA [5] AVR_HAVE_JMP_CALL [4] AVR_2_BYTE_PC [2] PBSDescription PBSSimple CPU core, only assembler support PBS"Classic" CPU core, up to 8 KB of ROM PBS"Classic" CPU core with ’MOVW’ and ’LPM Rx, Z[+]’ instruction, up to 8 KB of ROM PBS"Classic" CPU core, 16 KB to 64 KB of ROM Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 13.1 Options for the C compiler avr-gcc avr31 avr35 [3] avr4 avr5 avr51 avr6 [2] PBSAVR_ARCH=31 AVR_MEGA [5] AVR_HAVE_JMP_CALL [4] AVR_HAVE_RAMPZ [4] AVR_HAVE_ELPM [4] AVR_2_BYTE_PC [2] PBSAVR_ARCH=35 AVR_MEGA [5] AVR_HAVE_JMP_CALL [4] AVR_HAVE_MOVW [1] AVR_HAVE_LPMX [1] AVR_2_BYTE_PC [2] PBSAVR_ARCH=4 AVR_ENHANCED [5] AVR_HAVE_MOVW [1] AVR_HAVE_LPMX [1] AVR_HAVE_MUL [1] AVR_2_BYTE_PC [2] PBSAVR_ARCH=5 AVR_MEGA [5] AVR_ENHANCED [5] AVR_HAVE_JMP_CALL [4] AVR_HAVE_MOVW [1] AVR_HAVE_LPMX [1] AVR_HAVE_MUL [1] AVR_2_BYTE_PC [2] PBSAVR_ARCH=51 AVR_MEGA [5] AVR_ENHANCED [5] AVR_HAVE_JMP_CALL [4] AVR_HAVE_MOVW [1] AVR_HAVE_LPMX [1] AVR_HAVE_MUL [1] AVR_HAVE_RAMPZ [4] AVR_HAVE_ELPM [4] AVR_HAVE_ELPMX [4] AVR_2_BYTE_PC [2] PBSAVR_ARCH=6 AVR_MEGA [5] AVR_ENHANCED [5] AVR_HAVE_JMP_CALL [4] AVR_HAVE_MOVW [1] AVR_HAVE_LPMX [1] AVR_HAVE_MUL [1] AVR_HAVE_RAMPZ [4] AVR_HAVE_ELPM [4] AVR_HAVE_ELPMX [4] AVR_3_BYTE_PC [2] [1] New in GCC 4.2 [2] Unofficial patch for GCC 4.1 [3] New in GCC 4.2.3 [4] New in GCC 4.3 [5] Obsolete. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 83 PBS"Classic" CPU core, 128 KB of ROM PBS"Classic" CPU core with ’MOVW’ and ’LPM Rx, Z[+]’ instruction, 16 KB to 64 KB of ROM PBS"Enhanced" CPU core, up to 8 KB of ROM PBS"Enhanced" CPU core, 16 KB to 64 KB of ROM PBS"Enhanced" CPU core, 128 KB of ROM PBS"Enhanced" CPU core, 256 KB of ROM 84 CONTENTS By default, code is generated for the avr2 architecture. Note that when only using -mmcu=architecture but no -mmcu=MCU type, including the file cannot work since it cannot decide which device’s definitions to select. • -mmcu=MCU type The following MCU types are currently understood by avr-gcc. The table matches them against the corresponding avr-gcc architecture name, and shows the preprocessor symbol declared by the -mmcu option. Architecture PBSMCU name PBSMacro avr1 PBSat90s1200 avr1 PBSattiny11 avr1 PBSattiny12 avr1 PBSattiny15 avr1 PBSattiny28 PBS__AVR_AT90←S1200__ PBS__AVR_ATtiny11←__ PBS__AVR_ATtiny12←__ PBS__AVR_ATtiny15←__ PBS__AVR_ATtiny28←__ avr2 PBSat90s2313 avr2 PBSat90s2323 avr2 PBSat90s2333 avr2 PBSat90s2343 avr2 PBSattiny22 avr2 PBSattiny26 avr2 PBSat90s4414 avr2 PBSat90s4433 avr2 PBSat90s4434 avr2 PBSat90s8515 avr2 PBSat90c8534 avr2 PBSat90s8535 avr2/avr25 [1] PBSat86rf401 avr2/avr25 [1] PBSata5272 avr2/avr25 [1] PBSattiny13 PBS__AVR_AT90←S2313__ PBS__AVR_AT90←S2323__ PBS__AVR_AT90←S2333__ PBS__AVR_AT90←S2343__ PBS__AVR_ATtiny22←__ PBS__AVR_ATtiny26←__ PBS__AVR_AT90←S4414__ PBS__AVR_AT90←S4433__ PBS__AVR_AT90←S4434__ PBS__AVR_AT90←S8515__ PBS__AVR_AT90←C8534__ PBS__AVR_AT90←S8535__ PBS__AVR_AT86R←F401__ PBS__AVR_ATA5272←__ PBS__AVR_ATtiny13←__ Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 13.1 Options for the C compiler avr-gcc avr2/avr25 [1] PBSattiny13a avr2/avr25 [1] PBSattiny2313 avr2/avr25 [1] PBSattiny2313a avr2/avr25 [1] PBSattiny24 avr2/avr25 [1] PBSattiny24a avr2/avr25 [1] PBSattiny25 avr2/avr25 [1] PBSattiny261 avr2/avr25 [1] PBSattiny261a avr2/avr25 [1] PBSattiny4313 avr2/avr25 [1] PBSattiny43u avr2/avr25 [1] PBSattiny44 avr2/avr25 [1] PBSattiny44a avr2/avr25 [1] PBSattiny45 avr2/avr25 [1] PBSattiny461 avr2/avr25 [1] PBSattiny461a avr2/avr25 [1] PBSattiny48 avr2/avr25 [1] PBSattiny828 avr2/avr25 [1] PBSattiny84 avr2/avr25 [1] PBSattiny84a avr2/avr25 [1] PBSattiny85 avr2/avr25 [1] PBSattiny861 avr2/avr25 [1] PBSattiny861a avr2/avr25 [1] PBSattiny87 avr2/avr25 [1] PBSattiny88 avr3 PBSatmega603 avr3 PBSat43usb355 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 85 PBS__AVR_ATtiny13←A__ PBS__AVR_A←Ttiny2313__ PBS__AVR_A←Ttiny2313A__ PBS__AVR_ATtiny24←__ PBS__AVR_ATtiny24←A__ PBS__AVR_ATtiny25←__ PBS__AVR_A←Ttiny261__ PBS__AVR_A←Ttiny261A__ PBS__AVR_A←Ttiny4313__ PBS__AVR_ATtiny43←U__ PBS__AVR_ATtiny44←__ PBS__AVR_ATtiny44←A__ PBS__AVR_ATtiny45←__ PBS__AVR_A←Ttiny461__ PBS__AVR_A←Ttiny461A__ PBS__AVR_ATtiny48←__ PBS__AVR_A←Ttiny828__ PBS__AVR_ATtiny84←__ PBS__AVR_ATtiny84←A__ PBS__AVR_ATtiny85←__ PBS__AVR_A←Ttiny861__ PBS__AVR_A←Ttiny861A__ PBS__AVR_ATtiny87←__ PBS__AVR_ATtiny88←__ PBS__AVR_A←Tmega603__ PBS__AVR_AT43US←B355__ 86 CONTENTS avr3/avr31 [3] PBSatmega103 avr3/avr31 [3] PBSat43usb320 avr3/avr35 [2] PBSat90usb82 avr3/avr35 [2] PBSat90usb162 avr3/avr35 [2] PBSata5505 avr3/avr35 [2] PBSatmega8u2 avr3/avr35 [2] PBSatmega16u2 avr3/avr35 [2] PBSatmega32u2 avr3/avr35 [2] PBSattiny167 avr3/avr35 [2] PBSattiny1634 avr3 PBSat76c711 avr4 PBSata6285 avr4 PBSata6286 avr4 PBSata6289 avr4 PBSatmega48 avr4 PBSatmega48a avr4 PBSatmega48pa avr4 PBSatmega48p avr4 PBSatmega8 avr4 PBSatmega8a avr4 PBSatmega8515 avr4 PBSatmega8535 avr4 PBSatmega88 avr4 PBSatmega88a avr4 PBSatmega88p avr4 PBSatmega88pa PBS__AVR_A←Tmega103__ PBS__AVR_AT43US←B320__ PBS__AVR_AT90US←B82__ PBS__AVR_AT90US←B162__ PBS__AVR_ATA5505←__ PBS__AVR_ATmega8←U2__ PBS__AVR_A←Tmega16U2__ PBS__AVR_A←Tmega32U2__ PBS__AVR_A←Ttiny167__ PBS__AVR_A←Ttiny1634__ PBS__AVR_AT76←C711__ PBS__AVR_ATA6285←__ PBS__AVR_ATA6286←__ PBS__AVR_ATA6289←__ PBS__AVR_A←Tmega48__ PBS__AVR_A←Tmega48A__ PBS__AVR_A←Tmega48PA__ PBS__AVR_A←Tmega48P__ PBS__AVR_ATmega8←__ PBS__AVR_ATmega8←A__ PBS__AVR_A←Tmega8515__ PBS__AVR_A←Tmega8535__ PBS__AVR_A←Tmega88__ PBS__AVR_A←Tmega88A__ PBS__AVR_A←Tmega88P__ PBS__AVR_A←Tmega88PA__ Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 13.1 Options for the C compiler avr-gcc avr4 PBSatmega8hva avr4 PBSat90pwm1 avr4 PBSat90pwm2 avr4 PBSat90pwm2b avr4 PBSat90pwm3 avr4 PBSat90pwm3b avr4 PBSat90pwm81 avr5 PBSat90can32 avr5 PBSat90can64 avr5 PBSat90pwm161 avr5 PBSat90pwm216 avr5 PBSat90pwm316 avr5 PBSat90scr100 avr5 PBSat90usb646 avr5 PBSat90usb647 avr5 avr5 PBSat94k PBSatmega16 avr5 PBSata5790 avr5 PBSata5795 avr5 PBSatmega161 avr5 PBSatmega162 avr5 PBSatmega163 avr5 PBSatmega164a avr5 PBSatmega164p avr5 PBSatmega164pa avr5 PBSatmega165 avr5 PBSatmega165a Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 87 PBS__AVR_ATmega8←HVA__ PBS__AVR_AT90PW←M1__ PBS__AVR_AT90PW←M2__ PBS__AVR_AT90PW←M2B__ PBS__AVR_AT90PW←M3__ PBS__AVR_AT90PW←M3B__ PBS__AVR_AT90PW←M81__ PBS__AVR_AT90CA←N32__ PBS__AVR_AT90CA←N64__ PBS__AVR_AT90PW←M161__ PBS__AVR_AT90PW←M216__ PBS__AVR_AT90PW←M316__ PBS__AVR_AT90SC←R100__ PBS__AVR_AT90US←B646__ PBS__AVR_AT90US←B647__ PBS__AVR_AT94K__ PBS__AVR_A←Tmega16__ PBS__AVR_ATA5790←__ PBS__AVR_ATA5795←__ PBS__AVR_A←Tmega161__ PBS__AVR_A←Tmega162__ PBS__AVR_A←Tmega163__ PBS__AVR_A←Tmega164A__ PBS__AVR_A←Tmega164P__ PBS__AVR_A←Tmega164PA__ PBS__AVR_A←Tmega165__ PBS__AVR_A←Tmega165A__ 88 CONTENTS avr5 PBSatmega165p avr5 PBSatmega165pa avr5 PBSatmega168 avr5 PBSatmega168a avr5 PBSatmega168p avr5 PBSatmega168pa avr5 PBSatmega169 avr5 PBSatmega169a avr5 PBSatmega169p avr5 PBSatmega169pa avr5 PBSatmega16a avr5 PBSatmega16hva avr5 PBSatmega16hva2 avr5 PBSatmega16hvb avr5 PBSatmega16hvbrevb avr5 PBSatmega16m1 avr5 PBSatmega16u4 avr5 PBSatmega32 avr5 PBSatmega32a avr5 PBSatmega323 avr5 PBSatmega324a avr5 PBSatmega324p avr5 PBSatmega324pa avr5 PBSatmega325 avr5 PBSatmega325a avr5 PBSatmega325p avr5 PBSatmega325pa PBS__AVR_A←Tmega165P__ PBS__AVR_A←Tmega165PA__ PBS__AVR_A←Tmega168__ PBS__AVR_A←Tmega168A__ PBS__AVR_A←Tmega168P__ PBS__AVR_A←Tmega168PA__ PBS__AVR_A←Tmega169__ PBS__AVR_A←Tmega169A__ PBS__AVR_A←Tmega169P__ PBS__AVR_A←Tmega169PA__ PBS__AVR_A←Tmega16A__ PBS__AVR_A←Tmega16HVA__ PBS__AVR_A←Tmega16HVA2__ PBS__AVR_A←Tmega16HVB__ PBS__AVR_A←Tmega16HVBREVB__ PBS__AVR_A←Tmega16M1__ PBS__AVR_A←Tmega16U4__ PBS__AVR_A←Tmega32__ PBS__AVR_A←Tmega32A__ PBS__AVR_A←Tmega323__ PBS__AVR_A←Tmega324A__ PBS__AVR_A←Tmega324P__ PBS__AVR_A←Tmega324PA__ PBS__AVR_A←Tmega325__ PBS__AVR_A←Tmega325A__ PBS__AVR_A←Tmega325P__ PBS__AVR_A←Tmega325PA__ Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 13.1 Options for the C compiler avr-gcc avr5 PBSatmega3250 avr5 PBSatmega3250a avr5 PBSatmega3250p avr5 PBSatmega3250pa avr5 PBSatmega328 avr5 PBSatmega328p avr5 PBSatmega329 avr5 PBSatmega329a avr5 PBSatmega329p avr5 PBSatmega329pa avr5 PBSatmega3290 avr5 PBSatmega3290a avr5 PBSatmega3290p avr5 PBSatmega3290pa avr5 PBSatmega32c1 avr5 PBSatmega32hvb avr5 PBSatmega32hvbrevb avr5 PBSatmega32m1 avr5 PBSatmega32u4 avr5 PBSatmega32u6 avr5 PBSatmega406 avr5 PBSatmega644rfr2 avr5 PBSatmega64rfr2 avr5 PBSatmega64 avr5 PBSatmega64a avr5 PBSatmega640 avr5 PBSatmega644 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 89 PBS__AVR_A←Tmega3250__ PBS__AVR_A←Tmega3250A__ PBS__AVR_A←Tmega3250P__ PBS__AVR_A←Tmega3250PA__ PBS__AVR_A←Tmega328__ PBS__AVR_A←Tmega328P__ PBS__AVR_A←Tmega329__ PBS__AVR_A←Tmega329A__ PBS__AVR_A←Tmega329P__ PBS__AVR_A←Tmega329PA__ PBS__AVR_A←Tmega3290__ PBS__AVR_A←Tmega3290A__ PBS__AVR_A←Tmega3290P__ PBS__AVR_A←Tmega3290PA__ PBS__AVR_A←Tmega32C1__ PBS__AVR_A←Tmega32HVB__ PBS__AVR_A←Tmega32HVBREVB__ PBS__AVR_A←Tmega32M1__ PBS__AVR_A←Tmega32U4__ PBS__AVR_A←Tmega32U6__ PBS__AVR_A←Tmega406__ PBS__AVR_A←Tmega644RFR2__ PBS__AVR_A←Tmega64RFR2__ PBS__AVR_A←Tmega64__ PBS__AVR_A←Tmega64A__ PBS__AVR_A←Tmega640__ PBS__AVR_A←Tmega644__ 90 CONTENTS avr5 PBSatmega644a avr5 PBSatmega644p avr5 PBSatmega644pa avr5 PBSatmega645 avr5 PBSatmega645a avr5 PBSatmega645p avr5 PBSatmega6450 avr5 PBSatmega6450a avr5 PBSatmega6450p avr5 PBSatmega649 avr5 PBSatmega649a avr5 PBSatmega6490 avr5 PBSatmega6490a avr5 PBSatmega6490p avr5 PBSatmega649p avr5 PBSatmega64c1 avr5 PBSatmega64hve avr5 PBSatmega64m1 avr5 PBSm3000 avr5/avr51 [3] PBSat90can128 avr5/avr51 [3] PBSat90usb1286 avr5/avr51 [3] PBSat90usb1287 avr5/avr51 [3] PBSatmega128 avr5/avr51 [3] PBSatmega128a avr5/avr51 [3] PBSatmega1280 avr5/avr51 [3] PBSatmega1281 avr5/avr51 [3] PBSatmega1284 PBS__AVR_A←Tmega644A__ PBS__AVR_A←Tmega644P__ PBS__AVR_A←Tmega644PA__ PBS__AVR_A←Tmega645__ PBS__AVR_A←Tmega645A__ PBS__AVR_A←Tmega645P__ PBS__AVR_A←Tmega6450__ PBS__AVR_A←Tmega6450A__ PBS__AVR_A←Tmega6450P__ PBS__AVR_A←Tmega649__ PBS__AVR_A←Tmega649A__ PBS__AVR_A←Tmega6490__ PBS__AVR_A←Tmega6490A__ PBS__AVR_A←Tmega6490P__ PBS__AVR_A←Tmega649P__ PBS__AVR_A←Tmega64C1__ PBS__AVR_A←Tmega64HVE__ PBS__AVR_A←Tmega64M1__ PBS__AVR_M3000__ PBS__AVR_AT90CA←N128__ PBS__AVR_AT90US←B1286__ PBS__AVR_AT90US←B1287__ PBS__AVR_A←Tmega128__ PBS__AVR_A←Tmega128A__ PBS__AVR_A←Tmega1280__ PBS__AVR_A←Tmega1281__ PBS__AVR_A←Tmega1284__ Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 13.1 Options for the C compiler avr-gcc avr5/avr51 [3] PBSatmega1284p avr5/avr51 [3] PBSatmega1284rfr2 avr5/avr51 [3] PBSatmega128rfr2 avr6 PBSatmega2560 avr6 PBSatmega2561 avr6 PBSatmega2564rfr2 avr6 PBSatmega256rfr2 avrxmega2 PBSatxmega16a4 avrxmega2 PBSatxmega16a4u avrxmega2 PBSatxmega16c4 avrxmega2 PBSatxmega16d4 avrxmega2 PBSatxmega32a4 avrxmega2 PBSatxmega32a4u avrxmega2 PBSatxmega32c4 avrxmega2 PBSatxmega32d4 avrxmega4 PBSatxmega64a3 avrxmega4 PBSatxmega64a3u avrxmega4 PBSatxmega64a4u avrxmega4 PBSatxmega64b1 avrxmega4 PBSatxmega64b3 avrxmega4 PBSatxmega64c3 avrxmega4 PBSatxmega64d3 avrxmega4 PBSatxmega64d4 avrxmega5 PBSatxmega64a1 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 91 PBS__AVR_A←Tmega1284P__ PBS__AVR_A←Tmega1284RFR2__ PBS__AVR_A←Tmega128RFR2__ PBS__AVR_A←Tmega2560__ PBS__AVR_A←Tmega2561__ PBS__AVR_A←Tmega2564RFR2__ PBS__AVR_A←Tmega256RFR2__ PBS__AVR_A←Txmega16A4__ PBS__AVR_A←Txmega16A4U__ PBS__AVR_A←Txmega16C4__ PBS__AVR_A←Txmega16D4__ PBS__AVR_A←Txmega32A4__ PBS__AVR_A←Txmega32A4U__ PBS__AVR_A←Txmega32C4__ PBS__AVR_A←Txmega32D4__ PBS__AVR_A←Txmega64A3__ PBS__AVR_A←Txmega64A3U__ PBS__AVR_A←Txmega64A4U__ PBS__AVR_A←Txmega64B1__ PBS__AVR_A←Txmega64B3__ PBS__AVR_A←Txmega64C3__ PBS__AVR_A←Txmega64D3__ PBS__AVR_A←Txmega64D4__ PBS__AVR_A←Txmega64A1__ 92 CONTENTS avrxmega5 PBSatxmega64a1u PBS__AVR_A←Txmega64A1U__ avrxmega6 PBSatxmega128a3 avrxmega6 PBSatxmega128a3u avrxmega6 PBSatxmega128b1 avrxmega6 PBSatxmega128b3 avrxmega6 PBSatxmega128c3 avrxmega6 PBSatxmega128d3 avrxmega6 PBSatxmega128d4 avrxmega6 PBSatxmega192a3 avrxmega6 PBSatxmega192a3u avrxmega6 PBSatxmega192c3 avrxmega6 PBSatxmega192d3 avrxmega6 PBSatxmega256a3 avrxmega6 PBSatxmega256a3u avrxmega6 PBSatxmega256a3b avrxmega6 PBSatxmega256a3bu avrxmega6 PBSatxmega256c3 avrxmega6 PBSatxmega256d3 avrxmega6 PBSatxmega384c3 avrxmega6 PBSatxmega384d3 PBS__AVR_A←Txmega128A3__ PBS__AVR_A←Txmega128A3U__ PBS__AVR_A←Txmega128B1__ PBS__AVR_A←Txmega128B3__ PBS__AVR_A←Txmega128C3__ PBS__AVR_A←Txmega128D3__ PBS__AVR_A←Txmega128D4__ PBS__AVR_A←Txmega192A3__ PBS__AVR_A←Txmega192A3U__ PBS__AVR_A←Txmega192C3__ PBS__AVR_A←Txmega192D3__ PBS__AVR_A←Txmega256A3__ PBS__AVR_A←Txmega256A3U__ PBS__AVR_A←Txmega256A3B__ PBS__AVR_A←Txmega256A3BU__ PBS__AVR_A←Txmega256C3__ PBS__AVR_A←Txmega256D3__ PBS__AVR_A←Txmega384C3__ PBS__AVR_A←Txmega384D3__ avrxmega7 PBSatxmega128a1 avrxmega7 PBSatxmega128a1u avrxmega7 PBSatxmega128a4u avrtiny10 PBSattiny4 avrtiny10 PBSattiny5 PBS__AVR_A←Txmega128A1__ PBS__AVR_A←Txmega128A1U__ PBS__AVR_A←Txmega128A4U__ PBS__AVR_ATtiny4_←_ PBS__AVR_ATtiny5_←_ Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 13.1 Options for the C compiler avr-gcc avrtiny10 PBSattiny9 avrtiny10 PBSattiny10 avrtiny10 PBSattiny20 avrtiny10 PBSattiny40 93 PBS__AVR_ATtiny9_←_ PBS__AVR_ATtiny10←__ PBS__AVR_ATtiny20←__ PBS__AVR_ATtiny40←__ [1] ’avr25’ architecture is new in GCC 4.2 [2] ’avr35’ architecture is new in GCC 4.2.3 [3] ’avr31’ and ’avr51’ architectures is new in GCC 4.3 • -morder1 • -morder2 Change the order of register assignment. The default is r24, r25, r18, r19, r20, r21, r22, r23, r30, r31, r26, r27, r28, r29, r17, r16, r15, r14, r13, r12, r11, r10, r9, r8, r7, r6, r5, r4, r3, r2, r0, r1 Order 1 uses r18, r19, r20, r21, r22, r23, r24, r25, r30, r31, r26, r27, r28, r29, r17, r16, r15, r14, r13, r12, r11, r10, r9, r8, r7, r6, r5, r4, r3, r2, r0, r1 Order 2 uses r25, r24, r23, r22, r21, r20, r19, r18, r30, r31, r26, r27, r28, r29, r17, r16, r15, r14, r13, r12, r11, r10, r9, r8, r7, r6, r5, r4, r3, r2, r1, r0 • -mint8 Assume int to be an 8-bit integer. Note that this is not really supported by avr-libc, so it should normally not be used. The default is to use 16-bit integers. • -mno-interrupts Generates code that changes the stack pointer without disabling interrupts. Normally, the state of the status register SREG is saved in a temporary register, interrupts are disabled while changing the stack pointer, and SREG is restored. Specifying this option will define the preprocessor macro NO_INTERRUPTS to the value 1. • -mcall-prologues Use subroutines for function prologue/epilogue. For complex functions that use many registers (that needs to be saved/restored on function entry/exit), this saves some space at the cost of a slightly increased execution time. • -mtiny-stack Change only the low 8 bits of the stack pointer. • -mno-tablejump Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 94 CONTENTS Deprecated, use -fno-jump-tables instead. • -mshort-calls Use rjmp/rcall (limited range) on >8K devices. On avr2 and avr4 architectures (less than 8 KB or flash memory), this is always the case. On avr3 and avr5 architectures, calls and jumps to targets outside the current function will by default use jmp/call instructions that can cover the entire address range, but that require more flash ROM and execution time. • -mrtl Dump the internal compilation result called "RTL" into comments in the generated assembler code. Used for debugging avr-gcc. • -msize Dump the address, size, and relative cost of each statement into comments in the generated assembler code. Used for debugging avr-gcc. • -mdeb Generate lots of debugging information to stderr. 13.1.2 Selected general compiler options The following general gcc options might be of some interest to AVR users. • -On Optimization level n. Increasing n is meant to optimize more, an optimization level of 0 means no optimization at all, which is the default if no -O option is present. The special option -Os is meant to turn on all -O2 optimizations that are not expected to increase code size. Note that at -O3, gcc attempts to inline all "simple" functions. For the AVR target, this will normally constitute a large pessimization due to the code increasement. The only other optimization turned on with -O3 is -frename-registers, which could rather be enabled manually instead. A simple -O option is equivalent to -O1. Note also that turning off all optimizations will prevent some warnings from being issued since the generation of those warnings depends on code analysis steps that are only performed when optimizing (unreachable code, unused variables). See also the appropriate FAQ entry for issues regarding debugging optimized code. • -Wa,assembler-options • -Wl,linker-options Pass the listed options to the assembler, or linker, respectively. • -g Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 13.2 Options for the assembler avr-as 95 Generate debugging information that can be used by avr-gdb. • -ffreestanding Assume a "freestanding" environment as per the C standard. This turns off automatic builtin functions (though they can still be reached by prepending __builtin_ to the actual function name). It also makes the compiler not complain when main() is declared with a void return type which makes some sense in a microcontroller environment where the application cannot meaningfully provide a return value to its environment (in most cases, main() won’t even return anyway). However, this also turns off all optimizations normally done by the compiler which assume that functions known by a certain name behave as described by the standard. E. g., applying the function strlen() to a literal string will normally cause the compiler to immediately replace that call by the actual length of the string, while with -ffreestanding, it will always call strlen() at run-time. • -funsigned-char Make any unqualfied char type an unsigned char. Without this option, they default to a signed char. • -funsigned-bitfields Make any unqualified bitfield type unsigned. By default, they are signed. • -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. • -fpack-struct Pack all structure members together without holes. • -fno-jump-tables Do not generate tablejump instructions. By default, jump tables can be used to optimize switch statements. When turned off, sequences of compare statements are used instead. Jump tables are usually faster to execute on average, but in particular for switch statements, where most of the jumps would go to the default label, they might waste a bit of flash memory. NOTE: The tablejump instructions use the LPM assembler instruction for access to jump tables. Always use -fno-jump-tables switch, if compiling a bootloader for devices with more than 64 KB of code memory. 13.2 Options for the assembler avr-as 13.2.1 Machine-specific assembler options • -mmcu=architecture • -mmcu=MCU name avr-as understands the same -mmcu= options as avr-gcc. By default, avr2 is assumed, but this can be altered by using the appropriate .arch pseudo-instruction inside the assembler source file. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 96 CONTENTS • -mall-opcodes Turns off opcode checking for the actual MCU type, and allows any possible AVR opcode to be assembled. • -mno-skip-bug Don’t emit a warning when trying to skip a 2-word instruction with a CPSE/SBIC/SBIS/SBRC/SBRS instruction. Early AVR devices suffered from a hardware bug where these instructions could not be properly skipped. • -mno-wrap For RJMP/RCALL instructions, don’t allow the target address to wrap around for devices that have more than 8 KB of memory. • -gstabs Generate .stabs debugging symbols for assembler source lines. This enables avr-gdb to trace through assembler source files. This option must not be used when assembling sources that have been generated by the C compiler; these files already contain the appropriate line number information from the C source files. • -a[cdhlmns=file] Turn on the assembler listing. The sub-options are: • c omit false conditionals • d omit debugging directives • h include high-level source • l include assembly • m include macro expansions • n omit forms processing • s include symbols • =file set the name of the listing file The various sub-options can be combined into a single -a option list; =file must be the last one in that case. 13.2.2 Examples for assembler options passed through the C compiler Remember that assembler options can be passed from the C compiler frontend using -Wa (see above), so in order to include the C source code into the assembler listing in file foo.lst, when compiling foo.c, the following compiler command-line can be used: $ avr-gcc -c -O foo.c -o foo.o -Wa,-ahls=foo.lst In order to pass an assembler file through the C preprocessor first, and have the assembler generate line number debugging information for it, the following command can be used: $ avr-gcc -c -x assembler-with-cpp -o foo.o foo.S -Wa,--gstabs Note that on Unix systems that have case-distinguishing file systems, specifying a file name with the suffix .S (uppercase letter S) will make the compiler automatically assume -x assembler-with-cpp, while using .s would pass the file directly to the assembler (no preprocessing done). Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 13.3 Controlling the linker avr-ld 13.3 Controlling the linker avr-ld 13.3.1 Selected linker options 97 While there are no machine-specific options for avr-ld, a number of the standard options might be of interest to AVR users. • -lname Locate the archive library named libname.a, and use it to resolve currently unresolved symbols from it. The library is searched along a path that consists of builtin pathname entries that have been specified at compile time (e. g. /usr/local/avr/lib on Unix systems), possibly extended by pathname entries as specified by -L options (that must precede the -l options on the command-line). • -Lpath Additional location to look for archive libraries requested by -l options. • -defsym symbol=expr Define a global symbol symbol using expr as the value. • -M Print a linker map to stdout. • -Map mapfile Print a linker map to mapfile. • -cref Output a cross reference table to the map file (in case -Map is also present), or to stdout. • -section-start sectionname=org Start section sectionname at absolute address org. • -Tbss org • -Tdata org • -Ttext org Start the bss, data, or text section at org, respectively. • -T scriptfile Use scriptfile as the linker script, replacing the default linker script. Default linker scripts are stored in a system-specific location (e. g. under /usr/local/avr/lib/ldscripts on Unix systems), and consist of the AVR architecture name (avr2 through avr5) with the suffix .x appended. They describe how the various memory sections will be linked together. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 98 13.3.2 CONTENTS Passing linker options from the C compiler By default, all unknown non-option arguments on the avr-gcc command-line (i. e., all filename arguments that don’t have a suffix that is handled by avr-gcc) are passed straight to the linker. Thus, all files ending in .o (object files) and .a (object libraries) are provided to the linker. System libraries are usually not passed by their explicit filename but rather using the -l option which uses an abbreviated form of the archive filename (see above). avr-libc ships two system libraries, libc.a, and libm.a. While the standard library libc.a will always be searched for unresolved references when the linker is started using the C compiler frontend (i. e., there’s always at least one implied -lc option), the mathematics library libm.a needs to be explicitly requested using -lm. See also the entry in the FAQ explaining this. Conventionally, Makefiles use the make macro LDLIBS to keep track of -l (and possibly -L) options that should only be appended to the C compiler command-line when linking the final binary. In contrast, the macro LDFLAGS is used to store other command-line options to the C compiler that should be passed as options during the linking stage. The difference is that options are placed early on the command-line, while libraries are put at the end since they are to be used to resolve global symbols that are still unresolved at this point. Specific linker flags can be passed from the C compiler command-line using the -Wl compiler option, see above. This option requires that there be no spaces in the appended linker option, while some of the linker options above (like -Map or -defsym) would require a space. In these situations, the space can be replaced by an equal sign as well. For example, the following command-line can be used to compile foo.c into an executable, and also produce a link map that contains a cross-reference list in the file foo.map: $ avr-gcc -O -o foo.out -Wl,-Map=foo.map -Wl,--cref foo.c Alternatively, a comma as a placeholder will be replaced by a space before passing the option to the linker. So for a device with external SRAM, the following command-line would cause the linker to place the data segment at address 0x2000 in the SRAM: $ avr-gcc -mmcu=atmega128 -o foo.out -Wl,-Tdata,0x802000 See the explanation of the data section for why 0x800000 needs to be added to the actual value. Note that the stack will still remain in internal RAM, through the symbol __stack that is provided by the run-time startup code. This is probably a good idea anyway (since internal RAM access is faster), and even required for some early devices that had hardware bugs preventing them from using a stack in external RAM. Note also that the heap for malloc() will still be placed after all the variables in the data section, so in this situation, no stack/heap collision can occur. In order to relocate the stack from its default location at the top of interns RAM, the value of the symbol __stack can be changed on the linker command-line. As the linker is typically called from the compiler frontend, this can be achieved using a compiler option like -Wl,--defsym=__stack=0x8003ff The above will make the code use stack space from RAM address 0x3ff downwards. The amount of stack space available then depends on the bottom address of internal RAM for a particular device. It is the responsibility of the application to ensure the stack does not grow out of bounds, as well as to arrange for the stack to not collide with variable allocations made by the compiler (sections .data and .bss). 14 14.1 Compiler optimization Problems with reordering code Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 14.1 Problems with reordering code 99 Author Jan Waclawek Programs contain sequences of statements, and a naive compiler would execute them exactly in the order as they are written. But an optimizing compiler is free to reorder the statements - or even parts of them - if the resulting "net effect" is the same. The "measure" of the "net effect" is what the standard calls "side effects", and is accomplished exclusively through accesses (reads and writes) to variables qualified as volatile. So, as long as all volatile reads and writes are to the same addresses and in the same order (and writes write the same values), the program is correct, regardless of other operations in it. (One important point to note here is, that time duration between consecutive volatile accesses is not considered at all.) Unfortunately, there are also operations which are not covered by volatile accesses. An example of this in avr-gcc/avr-libc are the cli() and sei() macros defined in , which convert directly to the respective assembler mnemonics through the asm() statement. These don’t constitute a variable access at all, not even volatile, so the compiler is free to move them around. Although there is a "volatile" qualifier which can be attached to the asm() statement, its effect on (re)ordering is not clear from the documentation (and is more likely only to prevent complete removal by the optimiser), as it (among other) states: Note that even a volatile asm instruction can be moved relative to other code, including across jump instructions. [...] Similarly, you can’t expect a sequence of volatile asm instructions to remain perfectly consecutive. See also http://gcc.gnu.org/onlinedocs/gcc-4.3.4/gcc/Extended-Asm.html There is another mechanism which can be used to achieve something similar: memory barriers. This is accomplished through adding a special "memory" clobber to the inline asm statement, and ensures that all variables are flushed from registers to memory before the statement, and then re-read after the statement. The purpose of memory barriers is slightly different than to enforce code ordering: it is supposed to ensure that there are no variables "cached" in registers, so that it is safe to change the content of registers e.g. when switching context in a multitasking OS (on "big" processors with out-of-order execution they also imply usage of special instructions which force the processor into "in-order" state (this is not the case of AVRs)). However, memory barrier works well in ensuring that all volatile accesses before and after the barrier occur in the given order with respect to the barrier. However, it does not ensure the compiler moving non-volatile-related statements across the barrier. Peter Dannegger provided a nice example of this effect: #define cli() __asm volatile( "cli" ::: "memory" ) #define sei() __asm volatile( "sei" ::: "memory" ) unsigned int ivar; void test2( unsigned int val ) { val = 65535U / val; cli(); ivar = val; sei(); } compiles with optimisations switched on (-Os) to 00000112 : 112: bc 01 114: f8 94 116: 8f ef 118: 9f ef 11a: 0e 94 96 00 movw cli ldi ldi call r22, r24 r24, 0xFF ; 255 r25, 0xFF ; 255 0x12c ; 0x12c <__udivmodhi4> Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 100 CONTENTS 11e: 122: 126: 128: 70 60 78 08 93 01 02 93 00 02 94 95 sts sts sei ret 0x0201, r23 0x0200, r22 where the potentially slow division is moved across cli(), resulting in interrupts to be disabled longer than intended. Note, that the volatile access occurs in order with respect to cli() or sei(); so the "net effect" required by the standard is achieved as intended, it is "only" the timing which is off. However, for most of embedded applications, timing is an important, sometimes critical factor. See also https://www.mikrocontroller.net/topic/65923 Unfortunately, at the moment, in avr-gcc (nor in the C standard), there is no mechanism to enforce complete match of written and executed code ordering - except maybe of switching the optimization completely off (-O0), or writing all the critical code in assembly. To sum it up: • memory barriers ensure proper ordering of volatile accesses • memory barriers don’t ensure statements with no volatile accesses to be reordered across the barrier 15 Using the avrdude program Note This section was contributed by Brian Dean [ bsd@bsdhome.com ]. The avrdude program was previously called avrprog. The name was changed to avoid confusion with the avrprog program that Atmel ships with AvrStudio. avrdude is a program that is used to update or read the flash and EEPROM memories of Atmel AVR microcontrollers on FreeBSD Unix. It supports the Atmel serial programming protocol using the PC’s parallel port and can upload either a raw binary file or an Intel Hex format file. It can also be used in an interactive mode to individually update EEPROM cells, fuse bits, and/or lock bits (if their access is supported by the Atmel serial programming protocol.) The main flash instruction memory of the AVR can also be programmed in interactive mode, however this is not very useful because one can only turn bits off. The only way to turn flash bits on is to erase the entire memory (using avrdude’s -e option). avrdude is part of the FreeBSD ports system. To install it, simply do the following: # cd /usr/ports/devel/avrdude # make install Once installed, avrdude can program processors using the contents of the .hex file specified on the command line. In this example, the file main.hex is burned into the flash memory: # avrdude -p 2313 -e -m flash -i main.hex avrdude: AVR device initialized and ready to accept instructions avrdude: Device signature = 0x1e9101 avrdude: erasing chip avrdude: done. avrdude: reading input file "main.hex" Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 16 Release Numbering and Methodology 101 avrdude: input file main.hex auto detected as Intel Hex avrdude: writing flash: 1749 0x00 avrdude: 1750 bytes of flash written avrdude: verifying flash memory against main.hex: avrdude: reading on-chip flash data: 1749 0x00 avrdude: verifying ... avrdude: 1750 bytes of flash verified avrdude done. Thank you. The -p 2313 option lets avrdude know that we are operating on an AT90S2313 chip. This option specifies the device id and is matched up with the device of the same id in avrdude’s configuration file ( /usr/local/etc/avrdude.conf ). To list valid parts, specify the -v option. The -e option instructs avrdude to perform a chip-erase before programming; this is almost always necessary before programming the flash. The -m flash option indicates that we want to upload data into the flash memory, while -i main.hex specifies the name of the input file. The EEPROM is uploaded in the same way, the only difference is that you would use -m eeprom instead of -m flash. To use interactive mode, use the -t option: # avrdude -p 2313 -t avrdude: AVR device initialized and ready to accept instructions avrdude: Device signature = 0x1e9101 avrdude> The ’?’ command displays a list of valid commands: avrdude> ? >>> ? Valid commands: dump read write erase sig part send help ? quit : : : : : : : : : : dump memory : dump alias for dump write memory : write ... perform a chip erase display device signature bytes display the current part information send a raw command : send help help quit Use the ’part’ command to display valid memory types for use with the ’dump’ and ’write’ commands. avrdude> 16 16.1 Release Numbering and Methodology Release Version Numbering Scheme Release numbers consist of three parts, a major number, a minor number, and a revision number, each separated by a dot. The major number is currently 1 (and has always been). It will only be bumped in case a new version offers a major change in the API that is not backwards compatible. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 102 CONTENTS In the past (up to 1.6.x), even minor numbers have been used to indicate "stable" releases, and odd minor numbers have been reserved for development branches/versions. As the latter has never really been used, and maintaining a stable branch that eventually became effectively the same as the development version has proven to be just a cumbersome and tedious job, this scheme has given up in early 2010, so starting with 1.7.0, every minor number will be used. Minor numbers will be bumped upon judgement of the development team, whenever it seems appropriate, but at least in cases where some API was changed. Starting with version 1.4.0, a file indicates the library version of an installed library tree. 16.2 Releasing AVR Libc The information in this section is only relevant to AVR Libc developers and can be ignored by end users. Note In what follows, I assume you know how to use SVN and how to checkout multiple source trees in a single directory without having them clobber each other. If you don’t know how to do this, you probably shouldn’t be making releases or cutting branches. 16.2.1 Creating an SVN branch The following steps should be taken to cut a branch in SVN (assuming $username is set to your savannah username): 1. Check out a fresh source tree from SVN trunk. 2. Update the NEWS file with pending release number and commit to SVN trunk: Change Changes since avr-libc- : to Changes in avr-libc- . 3. Set the branch-point tag (setting and accordingly): svn copy svn+ssh://$username@svn.savannah.nongnu.org/avr-libc/trunk svn+ssh←://$username@svn.savannah.nongnu.org/avr-libc/tags/avr-libc- _ -branchpoint 4. Create the branch: svn copy svn+ssh://$username@svn.savannah.nongnu.org/avr-libc/trunk svn+ssh←://$username@svn.savannah.nongnu.org/avr-libc/branches/avr-libc- _← -branch 5. Update the package version in configure.ac and commit configure.ac to SVN trunk: Change minor number to next odd value. 6. Update the NEWS file and commit to SVN trunk: Add Changes since avr-libc- : 7. Check out a new tree for the branch: svn co svn+ssh://$username@svn.savannah.nongnu.org/avr-libc/branches/avr-libc- ←_ -branch 8. Update the package version in configure.ac and commit configure.ac to SVN branch: Change the patch number to 90 to denote that this now a branch leading up to a release. Be sure to leave the part of the version. 9. Bring the build system up to date by running bootstrap and configure. 10. Perform a ’make distcheck’ and make sure it succeeds. This will create the snapshot source tarball. This should be considered the first release candidate. 11. Upload the snapshot tarball to savannah. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 16.2 Releasing AVR Libc 103 12. Update the bug tracker interface on Savannah: Bugs —> Edit field values —> Release / Fixed Release 13. Announce the branch and the branch tag to the avr-libc-dev list so other developers can checkout the branch. 16.2.2 Making a release A stable release will only be done on a branch, not from the SVN trunk. The following steps should be taken when making a release: 1. Make sure the source tree you are working from is on the correct branch: svn switch svn+ssh://$username@svn.savannah.nongnu.org/avr-libc/branches/avr-libc- -branch 2. Update the package version in configure.ac and commit it to SVN. 3. Update the gnu tool chain version requirements in the README and commit to SVN. 4. Update the ChangeLog file to note the release and commit to SVN on the branch: Add Released avr-libc- . 5. Update the NEWS file with pending release number and commit to SVN: Change Changes since avr-libc- : to Changes in avr-libc- :. 6. Bring the build system up to date by running bootstrap and configure. 7. Perform a ’make distcheck’ and make sure it succeeds. This will create the source tarball. 8. Tag the release: svn copy . svn+ssh://$username@svn.savannah.nongnu.org/avr-libc/tags/avr-libc- ←_ _ -release or svn copy svn+ssh://$username@svn.savannah.nongnu.org/avr-libc/branches/avr-libc- ← _ -branch svn+ssh://$username@svn.savannah.nongnu.org/avr-libc/tags/avr-libc- _ -release 9. Upload the tarball to savannah. 10. Update the NEWS file, and commit to SVN: Add Changes since avr-libc- _ _ : 11. Update the bug tracker interface on Savannah: Bugs —> Edit field values —> Release / Fixed Release 12. Generate the latest documentation and upload to savannah. 13. Announce the release. The following hypothetical diagram should help clarify version and branch relationships. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 104 CONTENTS HEAD 1.0 Branch 1.2 Branch cvs tag avr−libc−1_0−branchpoint set version to 1.1.0. cvs tag −b avr−libc−1_0−branch set version to 0.90.90. set version to 1.0 cvs tag avr−libc−1_0−release set version to 1.0.0. set version to 1.0.1 cvs tag avr−libc−1_0_1−release cvs tag avr−libc−1_2−branchpoint set version to 1.3.0. cvs tag −b avr−libc−1_2−branch set version to 1.1.90. set version to 1.2 cvs tag avr−libc−1_2−release cvs tag avr−libc−2.0−branchpoint set version to 2.1.0. Figure 4: Release tree 17 Acknowledgments This document tries to tie together the labors of a large group of people. Without these individuals’ efforts, we wouldn’t have a terrific, free set of tools to develop AVR projects. We all owe thanks to: - The GCC Team, which produced a very capable set of development tools for an amazing number of platforms and processors. - Denis Chertykov [ denisc@overta.ru ] for making the AVR-specific changes to the GNU tools. - Denis Chertykov and Marek Michalkiewicz [ marekm@linux.org.pl ] for developing the standard libraries and startup code for \b AVR-GCC. - Uros Platise for developing the AVR programmer tool, \b uisp. - Joerg Wunsch [ joerg@FreeBSD.ORG ] for adding all the AVR development tools to the FreeBSD [ http://www.freebsd.org ] ports tree and for providing the basics for the \ref demo_project "demo project". - Brian Dean [ bsd@bsdhome.com ] for developing \b avrdude (an alternative to uisp) and for contributing \ref using_avrprog "documentation" which describes how to use it. \b Avrdude was previously called \b avrprog. - Eric Weddington [ eweddington@cso.atmel.com ] for maintaining the \b WinAVR package and thus making the continued improvements to the open source AVR toolchain available to many users. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 18 Todo List 105 - Rich Neswold for writing the original avr-tools document (which he graciously allowed to be merged into this document) and his improvements to the \ref demo_project "demo project". - Theodore A. Roth for having been a long-time maintainer of many of the tools (\b AVR-Libc, the AVR port of \b GDB, \b AVaRICE, \b uisp, \b avrdude). - All the people who currently maintain the tools, and/or have submitted suggestions, patches and bug reports. (See the AUTHORS files of the various tools.) - And lastly, all the users who use the software. If nobody used the software, we would probably not be very motivated to continue to develop it. Keep those bug reports coming. ;-) 18 Todo List Group avr_boot From email with Marek: On smaller devices (all except ATmega64/128), __SPM_REG is in the I/O space, accessible with the shorter "in" and "out" instructions - since the boot loader has a limited size, this could be an important optimization. 19 Deprecated List Global cbi (port, bit) Global enable_external_int (mask) Global inb (port) Global inp (port) Global INTERRUPT (signame) Global ISR_ALIAS (vector, target_vector) For new code, the use of ISR(..., ISR_ALIASOF(...)) is recommended. Global outb (port, val) Global outp (val, port) Global sbi (port, bit) Global SIGNAL (vector) Do not use SIGNAL() in new code. Use ISR() instead. Global timer_enable_int (unsigned char ints) Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 106 20 CONTENTS Module Index 20.1 Modules Here is a list of all modules: : Allocate space in the stack 111 : Diagnostics 112 : Character Operations 113 : System Errors 115 : Integer Type conversions 116 : Mathematics 127 : Non-local goto 137 : Standard Integer Types 139 : Standard IO facilities 149 : General utilities 163 : Strings 172 : Time 182 : Bootloader Support Utilities 190 : Special AVR CPU functions 196 : EEPROM handling 197 : Fuse Support 201 : Interrupts 204 : AVR device-specific IO definitions 222 : Lockbit Support 224 : Program Space Utilities 226 : Power Reduction Management 239 : Special function registers 253 Additional notes from 252 : Signature Support 255 : Power Management and Sleep Modes 256 : avr-libc version macros 258 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 21 Data Structure Index 107 : Watchdog timer handling 260 Atomically and Non-Atomically Executed Code Blocks 263 : CRC Computations 266 : Convenience functions for busy-wait delay loops 270 : Basic busy-wait delay loops 272 : Parity bit generation 273 : Helper macros for baud rate calculations 274 : TWI bit mask definitions 276 : Deprecated items 280 : Compatibility with IAR EWB 3.x 283 Demo projects 284 21 Combining C and assembly source files 285 A simple project 288 A more sophisticated project 300 Using the standard IO facilities 306 Example using the two-wire interface (TWI) 312 Data Structure Index 21.1 Data Structures Here are the data structures with brief descriptions: atexit_s 316 div_t 316 ldiv_t 316 tm 317 week_date 318 22 22.1 File Index File List Here is a list of all documented files with brief descriptions: Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 108 CONTENTS alloca.h ?? assert.h 318 atoi.S 318 atol.S 318 atomic.h 318 boot.h 318 cpufunc.h 323 crc16.h 323 ctype.h 324 defines.h ?? delay.h 324 delay_basic.h 324 deprecated.h ?? dtoa_conv.h ?? eedef.h ?? eeprom.h ?? ephemera_common.h ?? errno.h eu_dst.h 325 ?? fdevopen.c 326 ffs.S 326 ffsl.S 326 ffsll.S 326 fuse.h 326 hd44780.h ?? ina90.h ?? interrupt.h 326 inttypes.h 327 io.h 329 iocompat.h ?? Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 22.1 File List 109 lcd.h ?? lock.h 329 math.h 329 memccpy.S 332 memchr.S 332 memchr_P.S 332 memcmp.S 332 memcmp_P.S 332 memcmp_PF.S 332 memcpy.S 332 memcpy_P.S 332 memmem.S 332 memmove.S 332 memrchr.S 332 memrchr_P.S 332 memset.S 332 parity.h 332 pgmspace.h 332 portpins.h ?? power.h 340 project.h ?? setbaud.h 341 setjmp.h 341 sfr_defs.h ?? signal.h ?? signature.h 341 sleep.h 341 stdint.h 342 stdio.h 344 stdio_private.h Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen ?? 110 stdlib.h stdlib_private.h CONTENTS 346 ?? strcasecmp.S 348 strcasecmp_P.S 348 strcasestr.S 348 strcat.S 348 strcat_P.S 348 strchr.S 348 strchr_P.S 348 strchrnul.S 348 strchrnul_P.S 348 strcmp.S 348 strcmp_P.S 348 strcpy.S 348 strcpy_P.S 348 strcspn.S 348 strcspn_P.S 348 strdup.c 348 string.h 349 strlcat.S 350 strlcat_P.S 350 strlcpy.S 350 strlcpy_P.S 350 strlen.S 350 strlen_P.S 350 strlwr.S 350 strncasecmp.S 350 strncasecmp_P.S 350 strncat.S 350 strncat_P.S 350 Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 22.1 File List 111 strncmp.S 350 strncmp_P.S 350 strncpy.S 350 strncpy_P.S 350 strnlen.S 350 strnlen_P.S 350 strpbrk.S 350 strpbrk_P.S 350 strrchr.S 350 strrchr_P.S 350 strrev.S 350 strsep.S 350 strsep_P.S 350 strspn.S 351 strspn_P.S 351 strstr.S 351 strstr_P.S 351 strtok.c 351 strtok_P.c 351 strtok_r.S 351 strtok_rP.S 351 strupr.S 351 time.h 351 util/twi.h 353 compat/twi.h ?? uart.h ?? usa_dst.h ?? version.h ?? wdt.h xmega.h Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 354 ?? 112 CONTENTS xtoa_fast.h 23 ?? Module Documentation : Allocate space in the stack 23.1 Functions • void ∗ alloca (size_t __size) 23.1.1 Detailed Description 23.1.2 Function Documentation 23.1.2.1 void∗ alloca ( size_t __size ) Allocate __size bytes of space in the stack frame of the caller. This temporary space is automatically freed when the function that called alloca() returns to its caller. Avr-libc defines the alloca() as a macro, which is translated into the inlined __builtin_alloca() function. The fact that the code is inlined, means that it is impossible to take the address of this function, or to change its behaviour by linking with a different library. Returns alloca() returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow, program behaviour is undefined. Warning Avoid use alloca() inside the list of arguments of a function call. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.2 : Diagnostics 23.2 : Diagnostics 113 Macros • #define assert(expression) 23.2.1 Detailed Description #include This header file defines a debugging aid. As there is no standard error output stream available for many applications using this library, the generation of a printable error message is not enabled by default. These messages will only be generated if the application defines the macro __ASSERT_USE_STDERR before including the header file. By default, only abort() will be called to halt the application. 23.2.2 23.2.2.1 Macro Definition Documentation #define assert( expression ) Parameters expression Expression to test for. The assert() macro tests the given expression and if it is false, the calling process is terminated. A diagnostic message is written to stderr and the function abort() is called, effectively terminating the program. If expression is true, the assert() macro does nothing. The assert() macro may be removed at compile time by defining NDEBUG as a macro (e.g., by using the compiler option -DNDEBUG). Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 114 CONTENTS 23.3 : Character Operations Character classification routines These functions perform character classification. They return true or false status depending whether the character passed to the function falls into the function’s classification (i.e. isdigit() returns true if its argument is any value ’0’ though ’9’, inclusive). If the input is not an unsigned char value, all of this function return false. • int isalnum (int __c) • int isalpha (int __c) • int isascii (int __c) • int isblank (int __c) • int iscntrl (int __c) • int isdigit (int __c) • int isgraph (int __c) • int islower (int __c) • int isprint (int __c) • int ispunct (int __c) • int isspace (int __c) • int isupper (int __c) • int isxdigit (int __c) Character convertion routines This realization permits all possible values of integer argument. The toascii() function clears all highest bits. The tolower() and toupper() functions return an input argument as is, if it is not an unsigned char value. • int toascii (int __c) • int tolower (int __c) • int toupper (int __c) 23.3.1 Detailed Description These functions perform various operations on characters. #include 23.3.2 23.3.2.1 Function Documentation int isalnum ( int __c ) Checks for an alphanumeric character. It is equivalent to (isalpha(c) || isdigit(c)). 23.3.2.2 int isalpha ( int __c ) Checks for an alphabetic character. It is equivalent to (isupper(c) || islower(c)). 23.3.2.3 int isascii ( int __c ) Checks whether c is a 7-bit unsigned char value that fits into the ASCII character set. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.3 : Character Operations 23.3.2.4 115 int isblank ( int __c ) Checks for a blank character, that is, a space or a tab. 23.3.2.5 int iscntrl ( int __c ) Checks for a control character. 23.3.2.6 int isdigit ( int __c ) Checks for a digit (0 through 9). 23.3.2.7 int isgraph ( int __c ) Checks for any printable character except space. 23.3.2.8 int islower ( int __c ) Checks for a lower-case character. 23.3.2.9 int isprint ( int __c ) Checks for any printable character including space. 23.3.2.10 int ispunct ( int __c ) Checks for any printable character which is not a space or an alphanumeric character. 23.3.2.11 int isspace ( int __c ) Checks for white-space characters. For the avr-libc library, these are: space, form-feed (’\f’), newline (’\n’), carriage return (’\r’), horizontal tab (’\t’), and vertical tab (’\v’). 23.3.2.12 int isupper ( int __c ) Checks for an uppercase letter. 23.3.2.13 int isxdigit ( int __c ) Checks for a hexadecimal digits, i.e. one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F. 23.3.2.14 int toascii ( int __c ) Converts c to a 7-bit unsigned char value that fits into the ASCII character set, by clearing the high-order bits. Warning Many people will be unhappy if you use this function. This function will convert accented letters into random characters. 23.3.2.15 int tolower ( int __c ) Converts the letter c to lower case, if possible. 23.3.2.16 int toupper ( int __c ) Converts the letter c to upper case, if possible. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 116 CONTENTS : System Errors 23.4 Macros • #define EDOM 33 • #define ERANGE 34 23.4.1 Detailed Description #include Some functions in the library set the global variable errno when an error occurs. The file, , provides symbolic names for various error codes. Warning The errno global variable is not safe to use in a threaded or multi-task system. A race condition can occur if a task is interrupted between the call which sets error and when the task examines errno. If another task changes errno during this time, the result will be incorrect for the interrupted task. 23.4.2 23.4.2.1 Macro Definition Documentation #define EDOM 33 Domain error. 23.4.2.2 #define ERANGE 34 Range error. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.5 : Integer Type conversions 23.5 : Integer Type conversions Far pointers for memory access >64K • typedef int32_t int_farptr_t • typedef uint32_t uint_farptr_t macros for printf and scanf format specifiers For C++, these are only included if __STDC_LIMIT_MACROS is defined before including . • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • #define PRId8 "d" #define PRIdLEAST8 "d" #define PRIdFAST8 "d" #define PRIi8 "i" #define PRIiLEAST8 "i" #define PRIiFAST8 "i" #define PRId16 "d" #define PRIdLEAST16 "d" #define PRIdFAST16 "d" #define PRIi16 "i" #define PRIiLEAST16 "i" #define PRIiFAST16 "i" #define PRId32 "ld" #define PRIdLEAST32 "ld" #define PRIdFAST32 "ld" #define PRIi32 "li" #define PRIiLEAST32 "li" #define PRIiFAST32 "li" #define PRIdPTR PRId16 #define PRIiPTR PRIi16 #define PRIo8 "o" #define PRIoLEAST8 "o" #define PRIoFAST8 "o" #define PRIu8 "u" #define PRIuLEAST8 "u" #define PRIuFAST8 "u" #define PRIx8 "x" #define PRIxLEAST8 "x" #define PRIxFAST8 "x" #define PRIX8 "X" #define PRIXLEAST8 "X" #define PRIXFAST8 "X" #define PRIo16 "o" #define PRIoLEAST16 "o" #define PRIoFAST16 "o" #define PRIu16 "u" #define PRIuLEAST16 "u" #define PRIuFAST16 "u" #define PRIx16 "x" Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 117 118 CONTENTS • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • #define PRIxLEAST16 "x" #define PRIxFAST16 "x" #define PRIX16 "X" #define PRIXLEAST16 "X" #define PRIXFAST16 "X" #define PRIo32 "lo" #define PRIoLEAST32 "lo" #define PRIoFAST32 "lo" #define PRIu32 "lu" #define PRIuLEAST32 "lu" #define PRIuFAST32 "lu" #define PRIx32 "lx" #define PRIxLEAST32 "lx" #define PRIxFAST32 "lx" #define PRIX32 "lX" #define PRIXLEAST32 "lX" #define PRIXFAST32 "lX" #define PRIoPTR PRIo16 #define PRIuPTR PRIu16 #define PRIxPTR PRIx16 #define PRIXPTR PRIX16 #define SCNd8 "hhd" #define SCNdLEAST8 "hhd" #define SCNdFAST8 "hhd" #define SCNi8 "hhi" #define SCNiLEAST8 "hhi" #define SCNiFAST8 "hhi" #define SCNd16 "d" #define SCNdLEAST16 "d" #define SCNdFAST16 "d" #define SCNi16 "i" #define SCNiLEAST16 "i" #define SCNiFAST16 "i" #define SCNd32 "ld" #define SCNdLEAST32 "ld" #define SCNdFAST32 "ld" #define SCNi32 "li" #define SCNiLEAST32 "li" #define SCNiFAST32 "li" #define SCNdPTR SCNd16 #define SCNiPTR SCNi16 #define SCNo8 "hho" #define SCNoLEAST8 "hho" #define SCNoFAST8 "hho" #define SCNu8 "hhu" #define SCNuLEAST8 "hhu" #define SCNuFAST8 "hhu" #define SCNx8 "hhx" #define SCNxLEAST8 "hhx" #define SCNxFAST8 "hhx" #define SCNo16 "o" Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.5 : Integer Type conversions 119 • #define SCNoLEAST16 "o" • #define SCNoFAST16 "o" • #define SCNu16 "u" • #define SCNuLEAST16 "u" • #define SCNuFAST16 "u" • #define SCNx16 "x" • #define SCNxLEAST16 "x" • #define SCNxFAST16 "x" • #define SCNo32 "lo" • #define SCNoLEAST32 "lo" • #define SCNoFAST32 "lo" • #define SCNu32 "lu" • #define SCNuLEAST32 "lu" • #define SCNuFAST32 "lu" • #define SCNx32 "lx" • #define SCNxLEAST32 "lx" • #define SCNxFAST32 "lx" • #define SCNoPTR SCNo16 • #define SCNuPTR SCNu16 • #define SCNxPTR SCNx16 23.5.1 Detailed Description #include This header file includes the exact-width integer definitions from , and extends them with additional facilities provided by the implementation. Currently, the extensions include two additional integer types that could hold a "far" pointer (i.e. a code pointer that can address more than 64 KB), as well as standard names for all printf and scanf formatting options that are supported by the : Standard IO facilities. As the library does not support the full range of conversion specifiers from ISO 9899:1999, only those conversions that are actually implemented will be listed here. The idea behind these conversion macros is that, for each of the types defined by , a macro will be supplied that portably allows formatting an object of that type in printf() or scanf() operations. Example: #include uint8_t smallval; int32_t longval; ... printf("The hexadecimal value of smallval is %" PRIx8 ", the decimal value of longval is %" PRId32 ".\n", smallval, longval); 23.5.2 23.5.2.1 Macro Definition Documentation #define PRId16 "d" decimal printf format for int16_t 23.5.2.2 #define PRId32 "ld" decimal printf format for int32_t Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 120 23.5.2.3 CONTENTS #define PRId8 "d" decimal printf format for int8_t 23.5.2.4 #define PRIdFAST16 "d" decimal printf format for int_fast16_t 23.5.2.5 #define PRIdFAST32 "ld" decimal printf format for int_fast32_t 23.5.2.6 #define PRIdFAST8 "d" decimal printf format for int_fast8_t 23.5.2.7 #define PRIdLEAST16 "d" decimal printf format for int_least16_t 23.5.2.8 #define PRIdLEAST32 "ld" decimal printf format for int_least32_t 23.5.2.9 #define PRIdLEAST8 "d" decimal printf format for int_least8_t 23.5.2.10 #define PRIdPTR PRId16 decimal printf format for intptr_t 23.5.2.11 #define PRIi16 "i" integer printf format for int16_t 23.5.2.12 #define PRIi32 "li" integer printf format for int32_t 23.5.2.13 #define PRIi8 "i" integer printf format for int8_t 23.5.2.14 #define PRIiFAST16 "i" integer printf format for int_fast16_t 23.5.2.15 #define PRIiFAST32 "li" integer printf format for int_fast32_t 23.5.2.16 #define PRIiFAST8 "i" integer printf format for int_fast8_t Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.5 : Integer Type conversions 23.5.2.17 #define PRIiLEAST16 "i" integer printf format for int_least16_t 23.5.2.18 #define PRIiLEAST32 "li" integer printf format for int_least32_t 23.5.2.19 #define PRIiLEAST8 "i" integer printf format for int_least8_t 23.5.2.20 #define PRIiPTR PRIi16 integer printf format for intptr_t 23.5.2.21 #define PRIo16 "o" octal printf format for uint16_t 23.5.2.22 #define PRIo32 "lo" octal printf format for uint32_t 23.5.2.23 #define PRIo8 "o" octal printf format for uint8_t 23.5.2.24 #define PRIoFAST16 "o" octal printf format for uint_fast16_t 23.5.2.25 #define PRIoFAST32 "lo" octal printf format for uint_fast32_t 23.5.2.26 #define PRIoFAST8 "o" octal printf format for uint_fast8_t 23.5.2.27 #define PRIoLEAST16 "o" octal printf format for uint_least16_t 23.5.2.28 #define PRIoLEAST32 "lo" octal printf format for uint_least32_t 23.5.2.29 #define PRIoLEAST8 "o" octal printf format for uint_least8_t 23.5.2.30 #define PRIoPTR PRIo16 octal printf format for uintptr_t Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 121 122 23.5.2.31 CONTENTS #define PRIu16 "u" decimal printf format for uint16_t 23.5.2.32 #define PRIu32 "lu" decimal printf format for uint32_t 23.5.2.33 #define PRIu8 "u" decimal printf format for uint8_t 23.5.2.34 #define PRIuFAST16 "u" decimal printf format for uint_fast16_t 23.5.2.35 #define PRIuFAST32 "lu" decimal printf format for uint_fast32_t 23.5.2.36 #define PRIuFAST8 "u" decimal printf format for uint_fast8_t 23.5.2.37 #define PRIuLEAST16 "u" decimal printf format for uint_least16_t 23.5.2.38 #define PRIuLEAST32 "lu" decimal printf format for uint_least32_t 23.5.2.39 #define PRIuLEAST8 "u" decimal printf format for uint_least8_t 23.5.2.40 #define PRIuPTR PRIu16 decimal printf format for uintptr_t 23.5.2.41 #define PRIx16 "x" hexadecimal printf format for uint16_t 23.5.2.42 #define PRIX16 "X" uppercase hexadecimal printf format for uint16_t 23.5.2.43 #define PRIx32 "lx" hexadecimal printf format for uint32_t 23.5.2.44 #define PRIX32 "lX" uppercase hexadecimal printf format for uint32_t Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.5 : Integer Type conversions 23.5.2.45 #define PRIx8 "x" hexadecimal printf format for uint8_t 23.5.2.46 #define PRIX8 "X" uppercase hexadecimal printf format for uint8_t 23.5.2.47 #define PRIxFAST16 "x" hexadecimal printf format for uint_fast16_t 23.5.2.48 #define PRIXFAST16 "X" uppercase hexadecimal printf format for uint_fast16_t 23.5.2.49 #define PRIxFAST32 "lx" hexadecimal printf format for uint_fast32_t 23.5.2.50 #define PRIXFAST32 "lX" uppercase hexadecimal printf format for uint_fast32_t 23.5.2.51 #define PRIxFAST8 "x" hexadecimal printf format for uint_fast8_t 23.5.2.52 #define PRIXFAST8 "X" uppercase hexadecimal printf format for uint_fast8_t 23.5.2.53 #define PRIxLEAST16 "x" hexadecimal printf format for uint_least16_t 23.5.2.54 #define PRIXLEAST16 "X" uppercase hexadecimal printf format for uint_least16_t 23.5.2.55 #define PRIxLEAST32 "lx" hexadecimal printf format for uint_least32_t 23.5.2.56 #define PRIXLEAST32 "lX" uppercase hexadecimal printf format for uint_least32_t 23.5.2.57 #define PRIxLEAST8 "x" hexadecimal printf format for uint_least8_t 23.5.2.58 #define PRIXLEAST8 "X" uppercase hexadecimal printf format for uint_least8_t Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 123 124 23.5.2.59 CONTENTS #define PRIxPTR PRIx16 hexadecimal printf format for uintptr_t 23.5.2.60 #define PRIXPTR PRIX16 uppercase hexadecimal printf format for uintptr_t 23.5.2.61 #define SCNd16 "d" decimal scanf format for int16_t 23.5.2.62 #define SCNd32 "ld" decimal scanf format for int32_t 23.5.2.63 #define SCNd8 "hhd" decimal scanf format for int8_t 23.5.2.64 #define SCNdFAST16 "d" decimal scanf format for int_fast16_t 23.5.2.65 #define SCNdFAST32 "ld" decimal scanf format for int_fast32_t 23.5.2.66 #define SCNdFAST8 "hhd" decimal scanf format for int_fast8_t 23.5.2.67 #define SCNdLEAST16 "d" decimal scanf format for int_least16_t 23.5.2.68 #define SCNdLEAST32 "ld" decimal scanf format for int_least32_t 23.5.2.69 #define SCNdLEAST8 "hhd" decimal scanf format for int_least8_t 23.5.2.70 #define SCNdPTR SCNd16 decimal scanf format for intptr_t 23.5.2.71 #define SCNi16 "i" generic-integer scanf format for int16_t 23.5.2.72 #define SCNi32 "li" generic-integer scanf format for int32_t Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.5 : Integer Type conversions 23.5.2.73 #define SCNi8 "hhi" generic-integer scanf format for int8_t 23.5.2.74 #define SCNiFAST16 "i" generic-integer scanf format for int_fast16_t 23.5.2.75 #define SCNiFAST32 "li" generic-integer scanf format for int_fast32_t 23.5.2.76 #define SCNiFAST8 "hhi" generic-integer scanf format for int_fast8_t 23.5.2.77 #define SCNiLEAST16 "i" generic-integer scanf format for int_least16_t 23.5.2.78 #define SCNiLEAST32 "li" generic-integer scanf format for int_least32_t 23.5.2.79 #define SCNiLEAST8 "hhi" generic-integer scanf format for int_least8_t 23.5.2.80 #define SCNiPTR SCNi16 generic-integer scanf format for intptr_t 23.5.2.81 #define SCNo16 "o" octal scanf format for uint16_t 23.5.2.82 #define SCNo32 "lo" octal scanf format for uint32_t 23.5.2.83 #define SCNo8 "hho" octal scanf format for uint8_t 23.5.2.84 #define SCNoFAST16 "o" octal scanf format for uint_fast16_t 23.5.2.85 #define SCNoFAST32 "lo" octal scanf format for uint_fast32_t 23.5.2.86 #define SCNoFAST8 "hho" octal scanf format for uint_fast8_t Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 125 126 23.5.2.87 CONTENTS #define SCNoLEAST16 "o" octal scanf format for uint_least16_t 23.5.2.88 #define SCNoLEAST32 "lo" octal scanf format for uint_least32_t 23.5.2.89 #define SCNoLEAST8 "hho" octal scanf format for uint_least8_t 23.5.2.90 #define SCNoPTR SCNo16 octal scanf format for uintptr_t 23.5.2.91 #define SCNu16 "u" decimal scanf format for uint16_t 23.5.2.92 #define SCNu32 "lu" decimal scanf format for uint32_t 23.5.2.93 #define SCNu8 "hhu" decimal scanf format for uint8_t 23.5.2.94 #define SCNuFAST16 "u" decimal scanf format for uint_fast16_t 23.5.2.95 #define SCNuFAST32 "lu" decimal scanf format for uint_fast32_t 23.5.2.96 #define SCNuFAST8 "hhu" decimal scanf format for uint_fast8_t 23.5.2.97 #define SCNuLEAST16 "u" decimal scanf format for uint_least16_t 23.5.2.98 #define SCNuLEAST32 "lu" decimal scanf format for uint_least32_t 23.5.2.99 #define SCNuLEAST8 "hhu" decimal scanf format for uint_least8_t 23.5.2.100 #define SCNuPTR SCNu16 decimal scanf format for uintptr_t Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.5 : Integer Type conversions 23.5.2.101 #define SCNx16 "x" hexadecimal scanf format for uint16_t 23.5.2.102 #define SCNx32 "lx" hexadecimal scanf format for uint32_t 23.5.2.103 #define SCNx8 "hhx" hexadecimal scanf format for uint8_t 23.5.2.104 #define SCNxFAST16 "x" hexadecimal scanf format for uint_fast16_t 23.5.2.105 #define SCNxFAST32 "lx" hexadecimal scanf format for uint_fast32_t 23.5.2.106 #define SCNxFAST8 "hhx" hexadecimal scanf format for uint_fast8_t 23.5.2.107 #define SCNxLEAST16 "x" hexadecimal scanf format for uint_least16_t 23.5.2.108 #define SCNxLEAST32 "lx" hexadecimal scanf format for uint_least32_t 23.5.2.109 #define SCNxLEAST8 "hhx" hexadecimal scanf format for uint_least8_t 23.5.2.110 #define SCNxPTR SCNx16 hexadecimal scanf format for uintptr_t 23.5.3 23.5.3.1 Typedef Documentation typedef int32_t int_farptr_t signed integer type that can hold a pointer > 64 KB 23.5.3.2 typedef uint32_t uint_farptr_t unsigned integer type that can hold a pointer > 64 KB Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 127 128 CONTENTS : Mathematics 23.6 Macros • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • #define M_E 2.7182818284590452354 #define M_LOG2E 1.4426950408889634074 /∗ log_2 e ∗/ #define M_LOG10E 0.43429448190325182765 /∗ log_10 e ∗/ #define M_LN2 0.69314718055994530942 /∗ log_e 2 ∗/ #define M_LN10 2.30258509299404568402 /∗ log_e 10 ∗/ #define M_PI 3.14159265358979323846 /∗ pi ∗/ #define M_PI_2 1.57079632679489661923 /∗ pi/2 ∗/ #define M_PI_4 0.78539816339744830962 /∗ pi/4 ∗/ #define M_1_PI 0.31830988618379067154 /∗ 1/pi ∗/ #define M_2_PI 0.63661977236758134308 /∗ 2/pi ∗/ #define M_2_SQRTPI 1.12837916709551257390 /∗ 2/sqrt(pi) ∗/ #define M_SQRT2 1.41421356237309504880 /∗ sqrt(2) ∗/ #define M_SQRT1_2 0.70710678118654752440 /∗ 1/sqrt(2) ∗/ #define NAN __builtin_nan("") #define INFINITY __builtin_inf() #define cosf cos #define sinf sin #define tanf tan #define fabsf fabs #define fmodf fmod #define cbrtf cbrt #define hypotf hypot #define squaref square #define floorf floor #define ceilf ceil #define frexpf frexp #define ldexpf ldexp #define expf exp #define coshf cosh #define sinhf sinh #define tanhf tanh #define acosf acos #define asinf asin #define atanf atan #define atan2f atan2 #define logf log #define log10f log10 #define powf pow #define isnanf isnan #define isinff isinf #define isfinitef isfinite #define copysignf copysign #define signbitf signbit #define fdimf fdim #define fmaf fma #define fmaxf fmax #define fminf fmin Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.6 : Mathematics • #define truncf trunc • #define roundf round • #define lroundf lround • #define lrintf lrint Functions • double cos (double __x) • double sin (double __x) • double tan (double __x) • double fabs (double __x) • double fmod (double __x, double __y) • double modf (double __x, double ∗__iptr) • float modff (float __x, float ∗__iptr) • double sqrt (double __x) • float sqrtf (float) • double cbrt (double __x) • double hypot (double __x, double __y) • double square (double __x) • double floor (double __x) • double ceil (double __x) • double frexp (double __x, int ∗__pexp) • double ldexp (double __x, int __exp) • double exp (double __x) • double cosh (double __x) • double sinh (double __x) • double tanh (double __x) • double acos (double __x) • double asin (double __x) • double atan (double __x) • double atan2 (double __y, double __x) • double log (double __x) • double log10 (double __x) • double pow (double __x, double __y) • int isnan (double __x) • int isinf (double __x) • static int isfinite (double __x) • static double copysign (double __x, double __y) • int signbit (double __x) • double fdim (double __x, double __y) • double fma (double __x, double __y, double __z) • double fmax (double __x, double __y) • double fmin (double __x, double __y) • double trunc (double __x) • double round (double __x) • long lround (double __x) • long lrint (double __x) Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 129 130 23.6.1 CONTENTS Detailed Description #include This header file declares basic mathematics constants and functions. Notes: • In order to access the functions declared herein, it is usually also required to additionally link against the library libm.a. See also the related FAQ entry. • Math functions do not raise exceptions and do not change the errno variable. Therefore the majority of them are declared with const attribute, for better optimization by GCC. 23.6.2 Macro Definition Documentation 23.6.2.1 #define acosf acos The alias for acos(). 23.6.2.2 #define asinf asin The alias for asin(). 23.6.2.3 #define atan2f atan2 The alias for atan2(). 23.6.2.4 #define atanf atan The alias for atan(). 23.6.2.5 #define cbrtf cbrt The alias for cbrt(). 23.6.2.6 #define ceilf ceil The alias for ceil(). 23.6.2.7 #define copysignf copysign The alias for copysign(). 23.6.2.8 #define cosf cos The alias for cos(). 23.6.2.9 #define coshf cosh The alias for cosh(). 23.6.2.10 #define expf exp The alias for exp(). Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.6 : Mathematics 23.6.2.11 #define fabsf fabs The alias for fabs(). 23.6.2.12 #define fdimf fdim The alias for fdim(). 23.6.2.13 #define floorf floor The alias for floor(). 23.6.2.14 #define fmaf fma The alias for fma(). 23.6.2.15 #define fmaxf fmax The alias for fmax(). 23.6.2.16 #define fminf fmin The alias for fmin(). 23.6.2.17 #define fmodf fmod The alias for fmod(). 23.6.2.18 #define frexpf frexp The alias for frexp(). 23.6.2.19 #define hypotf hypot The alias for hypot(). 23.6.2.20 #define INFINITY __builtin_inf() INFINITY constant. 23.6.2.21 #define isfinitef isfinite The alias for isfinite(). 23.6.2.22 #define isinff isinf The alias for isinf(). 23.6.2.23 #define isnanf isnan The alias for isnan(). 23.6.2.24 #define ldexpf ldexp The alias for ldexp(). Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 131 132 23.6.2.25 CONTENTS #define log10f log10 The alias for log10(). 23.6.2.26 #define logf log The alias for log(). 23.6.2.27 #define lrintf lrint The alias for lrint(). 23.6.2.28 #define lroundf lround The alias for lround(). 23.6.2.29 #define M_1_PI 0.31830988618379067154 /∗ 1/pi ∗/ The constant 1/pi. 23.6.2.30 #define M_2_PI 0.63661977236758134308 /∗ 2/pi ∗/ The constant 2/pi. 23.6.2.31 #define M_2_SQRTPI 1.12837916709551257390 /∗ 2/sqrt(pi) ∗/ The constant 2/sqrt(pi). 23.6.2.32 #define M_E 2.7182818284590452354 The constant e. 23.6.2.33 #define M_LN10 2.30258509299404568402 /∗ log_e 10 ∗/ The natural logarithm of the 10. 23.6.2.34 #define M_LN2 0.69314718055994530942 /∗ log_e 2 ∗/ The natural logarithm of the 2. 23.6.2.35 #define M_LOG10E 0.43429448190325182765 /∗ log_10 e ∗/ The logarithm of the e to base 10. 23.6.2.36 #define M_LOG2E 1.4426950408889634074 /∗ log_2 e ∗/ The logarithm of the e to base 2. 23.6.2.37 #define M_PI 3.14159265358979323846 /∗ pi ∗/ The constant pi. 23.6.2.38 #define M_PI_2 1.57079632679489661923 /∗ pi/2 ∗/ The constant pi/2. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.6 : Mathematics 23.6.2.39 #define M_PI_4 0.78539816339744830962 /∗ pi/4 ∗/ The constant pi/4. 23.6.2.40 #define M_SQRT1_2 0.70710678118654752440 /∗ 1/sqrt(2) ∗/ The constant 1/sqrt(2). 23.6.2.41 #define M_SQRT2 1.41421356237309504880 /∗ sqrt(2) ∗/ The square root of 2. 23.6.2.42 #define NAN __builtin_nan("") NAN constant. 23.6.2.43 #define powf pow The alias for pow(). 23.6.2.44 #define roundf round The alias for round(). 23.6.2.45 #define signbitf signbit The alias for signbit(). 23.6.2.46 #define sinf sin The alias for sin(). 23.6.2.47 #define sinhf sinh The alias for sinh(). 23.6.2.48 #define squaref square The alias for square(). 23.6.2.49 #define tanf tan The alias for tan(). 23.6.2.50 #define tanhf tanh The alias for tanh(). 23.6.2.51 #define truncf trunc The alias for trunc(). 23.6.3 Function Documentation Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 133 134 23.6.3.1 CONTENTS double acos ( double __x ) The acos() function computes the principal value of the arc cosine of __x. The returned value is in the range [0, pi] radians. A domain error occurs for arguments not in the range [-1, +1]. 23.6.3.2 double asin ( double __x ) The asin() function computes the principal value of the arc sine of __x. The returned value is in the range [-pi/2, pi/2] radians. A domain error occurs for arguments not in the range [-1, +1]. 23.6.3.3 double atan ( double __x ) The atan() function computes the principal value of the arc tangent of __x. The returned value is in the range [-pi/2, pi/2] radians. 23.6.3.4 double atan2 ( double __y, double __x ) The atan2() function computes the principal value of the arc tangent of __y / __x, using the signs of both arguments to determine the quadrant of the return value. The returned value is in the range [-pi, +pi] radians. 23.6.3.5 double cbrt ( double __x ) The cbrt() function returns the cube root of __x. 23.6.3.6 double ceil ( double __x ) The ceil() function returns the smallest integral value greater than or equal to __x, expressed as a floating-point number. 23.6.3.7 static double copysign ( double __x, double __y ) [static] The copysign() function returns __x but with the sign of __y. They work even if __x or __y are NaN or zero. 23.6.3.8 double cos ( double __x ) The cos() function returns the cosine of __x, measured in radians. 23.6.3.9 double cosh ( double __x ) The cosh() function returns the hyperbolic cosine of __x. 23.6.3.10 double exp ( double __x ) The exp() function returns the exponential value of __x. 23.6.3.11 double fabs ( double __x ) The fabs() function computes the absolute value of a floating-point number __x. 23.6.3.12 double fdim ( double __x, double __y ) The fdim() function returns max(__x - __y, 0). If __x or __y or both are NaN, NaN is returned. 23.6.3.13 double floor ( double __x ) The floor() function returns the largest integral value less than or equal to __x, expressed as a floating-point number. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.6 : Mathematics 23.6.3.14 135 double fma ( double __x, double __y, double __z ) The fma() function performs floating-point multiply-add. This is the operation (__x ∗ __y) + __z, but the intermediate result is not rounded to the destination type. This can sometimes improve the precision of a calculation. 23.6.3.15 double fmax ( double __x, double __y ) The fmax() function returns the greater of the two values __x and __y. If an argument is NaN, the other argument is returned. If both arguments are NaN, NaN is returned. 23.6.3.16 double fmin ( double __x, double __y ) The fmin() function returns the lesser of the two values __x and __y. If an argument is NaN, the other argument is returned. If both arguments are NaN, NaN is returned. 23.6.3.17 double fmod ( double __x, double __y ) The function fmod() returns the floating-point remainder of __x / __y. 23.6.3.18 double frexp ( double __x, int ∗ __pexp ) The frexp() function breaks a floating-point number into a normalized fraction and an integral power of 2. It stores the integer in the int object pointed to by __pexp. If __x is a normal float point number, the frexp() function returns the value v, such that v has a magnitude in the interval [1/2, 1) or zero, and __x equals v times 2 raised to the power __pexp. If __x is zero, both parts of the result are zero. If __x is not a finite number, the frexp() returns __x as is and stores 0 by __pexp. Note This implementation permits a zero pointer as a directive to skip a storing the exponent. 23.6.3.19 double hypot ( double __x, double __y ) The hypot() function returns sqrt(__x∗__x + __y∗__y). This is the length of the hypotenuse of a right triangle with sides of length __x and __y, or the distance of the point (__x, __y) from the origin. Using this function instead of the direct formula is wise, since the error is much smaller. No underflow with small __x and __y. No overflow if result is in range. 23.6.3.20 static int isfinite ( double __x ) [static] The isfinite() function returns a nonzero value if __x is finite: not plus or minus infinity, and not NaN. 23.6.3.21 int isinf ( double __x ) The function isinf() returns 1 if the argument __x is positive infinity, -1 if __x is negative infinity, and 0 otherwise. Note The GCC 4.3 can replace this function with inline code that returns the 1 value for both infinities (gcc bug #35509). 23.6.3.22 int isnan ( double __x ) The function isnan() returns 1 if the argument __x represents a "not-a-number" (NaN) object, otherwise 0. 23.6.3.23 double ldexp ( double __x, int __exp ) The ldexp() function multiplies a floating-point number by an integral power of 2. It returns the value of __x times 2 raised to the power __exp. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 136 CONTENTS 23.6.3.24 double log ( double __x ) The log() function returns the natural logarithm of argument __x. 23.6.3.25 double log10 ( double __x ) The log10() function returns the logarithm of argument __x to base 10. 23.6.3.26 long lrint ( double __x ) The lrint() function rounds __x to the nearest integer, rounding the halfway cases to the even integer direction. (That is both 1.5 and 2.5 values are rounded to 2). This function is similar to rint() function, but it differs in type of return value and in that an overflow is possible. Returns The rounded long integer value. If __x is not a finite number or an overflow was, this realization returns the LONG_MIN value (0x80000000). 23.6.3.27 long lround ( double __x ) The lround() function rounds __x to the nearest integer, but rounds halfway cases away from zero (instead of to the nearest even integer). This function is similar to round() function, but it differs in type of return value and in that an overflow is possible. Returns The rounded long integer value. If __x is not a finite number or an overflow was, this realization returns the LONG_MIN value (0x80000000). 23.6.3.28 double modf ( double __x, double ∗ __iptr ) The modf() function breaks the argument __x into integral and fractional parts, each of which has the same sign as the argument. It stores the integral part as a double in the object pointed to by __iptr. The modf() function returns the signed fractional part of __x. Note This implementation skips writing by zero pointer. However, the GCC 4.3 can replace this function with inline code that does not permit to use NULL address for the avoiding of storing. 23.6.3.29 float modff ( float __x, float ∗ __iptr ) The alias for modf(). 23.6.3.30 double pow ( double __x, double __y ) The function pow() returns the value of __x to the exponent __y. 23.6.3.31 double round ( double __x ) The round() function rounds __x to the nearest integer, but rounds halfway cases away from zero (instead of to the nearest even integer). Overflow is impossible. Returns The rounded value. If __x is an integral or infinite, __x itself is returned. If __x is NaN, then NaN is returned. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.6 : Mathematics 23.6.3.32 137 int signbit ( double __x ) The signbit() function returns a nonzero value if the value of __x has its sign bit set. This is not the same as ‘__x < 0.0’, because IEEE 754 floating point allows zero to be signed. The comparison ‘-0.0 < 0.0’ is false, but ‘signbit (-0.0)’ will return a nonzero value. 23.6.3.33 double sin ( double __x ) The sin() function returns the sine of __x, measured in radians. 23.6.3.34 double sinh ( double __x ) The sinh() function returns the hyperbolic sine of __x. 23.6.3.35 double sqrt ( double __x ) The sqrt() function returns the non-negative square root of __x. 23.6.3.36 double square ( double __x ) The function square() returns __x ∗ __x. Note This function does not belong to the C standard definition. 23.6.3.37 double tan ( double __x ) The tan() function returns the tangent of __x, measured in radians. 23.6.3.38 double tanh ( double __x ) The tanh() function returns the hyperbolic tangent of __x. 23.6.3.39 double trunc ( double __x ) The trunc() function rounds __x to the nearest integer not larger in absolute value. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 138 CONTENTS : Non-local goto 23.7 Functions • int setjmp (jmp_buf __jmpb) • void longjmp (jmp_buf __jmpb, int __ret) __ATTR_NORETURN__ 23.7.1 Detailed Description While the C language has the dreaded goto statement, it can only be used to jump to a label in the same (local) function. In order to jump directly to another (non-local) function, the C library provides the setjmp() and longjmp() functions. setjmp() and longjmp() are useful for dealing with errors and interrupts encountered in a low-level subroutine of a program. Note setjmp() and longjmp() make programs hard to understand and maintain. If possible, an alternative should be used. longjmp() can destroy changes made to global register variables (see How to permanently bind a variable to a register?). For a very detailed discussion of setjmp()/longjmp(), see Chapter 7 of Advanced Programming in the UNIX Environment, by W. Richard Stevens. Example: #include jmp_buf env; int main (void) { if (setjmp (env)) { ... handle error ... } while (1) { ... main processing loop which calls foo() some where ... } } ... void foo (void) { ... blah, blah, blah ... if (err) { longjmp (env, 1); } } 23.7.2 23.7.2.1 Function Documentation void longjmp ( jmp_buf __jmpb, int __ret ) Non-local jump to a saved stack context. #include Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.7 : Non-local goto 139 longjmp() restores the environment saved by the last call of setjmp() with the corresponding __jmpb argument. After longjmp() is completed, program execution continues as if the corresponding call of setjmp() had just returned the value __ret. Note longjmp() cannot cause 0 to be returned. If longjmp() is invoked with a second argument of 0, 1 will be returned instead. Parameters __jmpb __ret Information saved by a previous call to setjmp(). Value to return to the caller of setjmp(). Returns This function never returns. 23.7.2.2 int setjmp ( jmp_buf __jmpb ) Save stack context for non-local goto. #include setjmp() saves the stack context/environment in __jmpb for later use by longjmp(). The stack context will be invalidated if the function which called setjmp() returns. Parameters __jmpb Variable of type jmp_buf which holds the stack information such that the environment can be restored. Returns setjmp() returns 0 if returning directly, and non-zero when returning from longjmp() using the saved context. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 140 CONTENTS 23.8 : Standard Integer Types Exact-width integer types Integer types having exactly the specified width • typedef signed char int8_t • typedef unsigned char uint8_t • typedef signed int int16_t • typedef unsigned int uint16_t • typedef signed long int int32_t • typedef unsigned long int uint32_t • typedef signed long long int int64_t • typedef unsigned long long int uint64_t Integer types capable of holding object pointers These allow you to declare variables of the same size as a pointer. • typedef int16_t intptr_t • typedef uint16_t uintptr_t Minimum-width integer types Integer types having at least the specified width • typedef int8_t int_least8_t • typedef uint8_t uint_least8_t • typedef int16_t int_least16_t • typedef uint16_t uint_least16_t • typedef int32_t int_least32_t • typedef uint32_t uint_least32_t • typedef int64_t int_least64_t • typedef uint64_t uint_least64_t Fastest minimum-width integer types Integer types being usually fastest having at least the specified width • typedef int8_t int_fast8_t • typedef uint8_t uint_fast8_t • typedef int16_t int_fast16_t • typedef uint16_t uint_fast16_t • typedef int32_t int_fast32_t • typedef uint32_t uint_fast32_t • typedef int64_t int_fast64_t • typedef uint64_t uint_fast64_t Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.8 : Standard Integer Types 141 Greatest-width integer types Types designating integer data capable of representing any value of any integer type in the corresponding signed or unsigned category • typedef int64_t intmax_t • typedef uint64_t uintmax_t Limits of specified-width integer types C++ implementations should define these macros only when __STDC_LIMIT_MACROS is defined before is included • • • • • • • • • • • • #define INT8_MAX 0x7f #define INT8_MIN (-INT8_MAX - 1) #define UINT8_MAX (INT8_MAX ∗ 2 + 1) #define INT16_MAX 0x7fff #define INT16_MIN (-INT16_MAX - 1) #define UINT16_MAX (__CONCAT(INT16_MAX, U) ∗ 2U + 1U) #define INT32_MAX 0x7fffffffL #define INT32_MIN (-INT32_MAX - 1L) #define UINT32_MAX (__CONCAT(INT32_MAX, U) ∗ 2UL + 1UL) #define INT64_MAX 0x7fffffffffffffffLL #define INT64_MIN (-INT64_MAX - 1LL) #define UINT64_MAX (__CONCAT(INT64_MAX, U) ∗ 2ULL + 1ULL) Limits of minimum-width integer types • • • • • • • • • • • • #define INT_LEAST8_MAX INT8_MAX #define INT_LEAST8_MIN INT8_MIN #define UINT_LEAST8_MAX UINT8_MAX #define INT_LEAST16_MAX INT16_MAX #define INT_LEAST16_MIN INT16_MIN #define UINT_LEAST16_MAX UINT16_MAX #define INT_LEAST32_MAX INT32_MAX #define INT_LEAST32_MIN INT32_MIN #define UINT_LEAST32_MAX UINT32_MAX #define INT_LEAST64_MAX INT64_MAX #define INT_LEAST64_MIN INT64_MIN #define UINT_LEAST64_MAX UINT64_MAX Limits of fastest minimum-width integer types • • • • • • • #define INT_FAST8_MAX INT8_MAX #define INT_FAST8_MIN INT8_MIN #define UINT_FAST8_MAX UINT8_MAX #define INT_FAST16_MAX INT16_MAX #define INT_FAST16_MIN INT16_MIN #define UINT_FAST16_MAX UINT16_MAX #define INT_FAST32_MAX INT32_MAX Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 142 CONTENTS • • • • • #define INT_FAST32_MIN INT32_MIN #define UINT_FAST32_MAX UINT32_MAX #define INT_FAST64_MAX INT64_MAX #define INT_FAST64_MIN INT64_MIN #define UINT_FAST64_MAX UINT64_MAX Limits of integer types capable of holding object pointers • #define INTPTR_MAX INT16_MAX • #define INTPTR_MIN INT16_MIN • #define UINTPTR_MAX UINT16_MAX Limits of greatest-width integer types • #define INTMAX_MAX INT64_MAX • #define INTMAX_MIN INT64_MIN • #define UINTMAX_MAX UINT64_MAX Limits of other integer types C++ implementations should define these macros only when __STDC_LIMIT_MACROS is defined before is included • • • • • • • • • #define PTRDIFF_MAX INT16_MAX #define PTRDIFF_MIN INT16_MIN #define SIG_ATOMIC_MAX INT8_MAX #define SIG_ATOMIC_MIN INT8_MIN #define SIZE_MAX UINT16_MAX #define WCHAR_MAX __WCHAR_MAX__ #define WCHAR_MIN __WCHAR_MIN__ #define WINT_MAX __WINT_MAX__ #define WINT_MIN __WINT_MIN__ Macros for integer constants C++ implementations should define these macros only when __STDC_CONSTANT_MACROS is defined before is included. These definitions are valid for integer constants without suffix and for macros defined as integer constant without suffix • • • • • • • • • • #define INT8_C(value) ((int8_t) value) #define UINT8_C(value) ((uint8_t) __CONCAT(value, U)) #define INT16_C(value) value #define UINT16_C(value) __CONCAT(value, U) #define INT32_C(value) __CONCAT(value, L) #define UINT32_C(value) __CONCAT(value, UL) #define INT64_C(value) __CONCAT(value, LL) #define UINT64_C(value) __CONCAT(value, ULL) #define INTMAX_C(value) __CONCAT(value, LL) #define UINTMAX_C(value) __CONCAT(value, ULL) Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.8 : Standard Integer Types 23.8.1 Detailed Description #include Use [u]intN_t if you need exactly N bits. Since these typedefs are mandated by the C99 standard, they are preferred over rolling your own typedefs. 23.8.2 Macro Definition Documentation 23.8.2.1 #define INT16_C( value ) value define a constant of type int16_t 23.8.2.2 #define INT16_MAX 0x7fff largest positive value an int16_t can hold. 23.8.2.3 #define INT16_MIN (-INT16_MAX - 1) smallest negative value an int16_t can hold. 23.8.2.4 #define INT32_C( value ) __CONCAT(value, L) define a constant of type int32_t 23.8.2.5 #define INT32_MAX 0x7fffffffL largest positive value an int32_t can hold. 23.8.2.6 #define INT32_MIN (-INT32_MAX - 1L) smallest negative value an int32_t can hold. 23.8.2.7 #define INT64_C( value ) __CONCAT(value, LL) define a constant of type int64_t 23.8.2.8 #define INT64_MAX 0x7fffffffffffffffLL largest positive value an int64_t can hold. 23.8.2.9 #define INT64_MIN (-INT64_MAX - 1LL) smallest negative value an int64_t can hold. 23.8.2.10 #define INT8_C( value ) ((int8_t) value) define a constant of type int8_t 23.8.2.11 #define INT8_MAX 0x7f largest positive value an int8_t can hold. 23.8.2.12 #define INT8_MIN (-INT8_MAX - 1) smallest negative value an int8_t can hold. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 143 144 23.8.2.13 CONTENTS #define INT_FAST16_MAX INT16_MAX largest positive value an int_fast16_t can hold. 23.8.2.14 #define INT_FAST16_MIN INT16_MIN smallest negative value an int_fast16_t can hold. 23.8.2.15 #define INT_FAST32_MAX INT32_MAX largest positive value an int_fast32_t can hold. 23.8.2.16 #define INT_FAST32_MIN INT32_MIN smallest negative value an int_fast32_t can hold. 23.8.2.17 #define INT_FAST64_MAX INT64_MAX largest positive value an int_fast64_t can hold. 23.8.2.18 #define INT_FAST64_MIN INT64_MIN smallest negative value an int_fast64_t can hold. 23.8.2.19 #define INT_FAST8_MAX INT8_MAX largest positive value an int_fast8_t can hold. 23.8.2.20 #define INT_FAST8_MIN INT8_MIN smallest negative value an int_fast8_t can hold. 23.8.2.21 #define INT_LEAST16_MAX INT16_MAX largest positive value an int_least16_t can hold. 23.8.2.22 #define INT_LEAST16_MIN INT16_MIN smallest negative value an int_least16_t can hold. 23.8.2.23 #define INT_LEAST32_MAX INT32_MAX largest positive value an int_least32_t can hold. 23.8.2.24 #define INT_LEAST32_MIN INT32_MIN smallest negative value an int_least32_t can hold. 23.8.2.25 #define INT_LEAST64_MAX INT64_MAX largest positive value an int_least64_t can hold. 23.8.2.26 #define INT_LEAST64_MIN INT64_MIN smallest negative value an int_least64_t can hold. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.8 : Standard Integer Types 23.8.2.27 #define INT_LEAST8_MAX INT8_MAX largest positive value an int_least8_t can hold. 23.8.2.28 #define INT_LEAST8_MIN INT8_MIN smallest negative value an int_least8_t can hold. 23.8.2.29 #define INTMAX_C( value ) __CONCAT(value, LL) define a constant of type intmax_t 23.8.2.30 #define INTMAX_MAX INT64_MAX largest positive value an intmax_t can hold. 23.8.2.31 #define INTMAX_MIN INT64_MIN smallest negative value an intmax_t can hold. 23.8.2.32 #define INTPTR_MAX INT16_MAX largest positive value an intptr_t can hold. 23.8.2.33 #define INTPTR_MIN INT16_MIN smallest negative value an intptr_t can hold. 23.8.2.34 #define PTRDIFF_MAX INT16_MAX largest positive value a ptrdiff_t can hold. 23.8.2.35 #define PTRDIFF_MIN INT16_MIN smallest negative value a ptrdiff_t can hold. 23.8.2.36 #define SIG_ATOMIC_MAX INT8_MAX largest positive value a sig_atomic_t can hold. 23.8.2.37 #define SIG_ATOMIC_MIN INT8_MIN smallest negative value a sig_atomic_t can hold. 23.8.2.38 #define SIZE_MAX UINT16_MAX largest value a size_t can hold. 23.8.2.39 #define UINT16_C( value ) __CONCAT(value, U) define a constant of type uint16_t 23.8.2.40 #define UINT16_MAX (__CONCAT(INT16_MAX, U) ∗ 2U + 1U) largest value an uint16_t can hold. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 145 146 23.8.2.41 CONTENTS #define UINT32_C( value ) __CONCAT(value, UL) define a constant of type uint32_t 23.8.2.42 #define UINT32_MAX (__CONCAT(INT32_MAX, U) ∗ 2UL + 1UL) largest value an uint32_t can hold. 23.8.2.43 #define UINT64_C( value ) __CONCAT(value, ULL) define a constant of type uint64_t 23.8.2.44 #define UINT64_MAX (__CONCAT(INT64_MAX, U) ∗ 2ULL + 1ULL) largest value an uint64_t can hold. 23.8.2.45 #define UINT8_C( value ) ((uint8_t) __CONCAT(value, U)) define a constant of type uint8_t 23.8.2.46 #define UINT8_MAX (INT8_MAX ∗ 2 + 1) largest value an uint8_t can hold. 23.8.2.47 #define UINT_FAST16_MAX UINT16_MAX largest value an uint_fast16_t can hold. 23.8.2.48 #define UINT_FAST32_MAX UINT32_MAX largest value an uint_fast32_t can hold. 23.8.2.49 #define UINT_FAST64_MAX UINT64_MAX largest value an uint_fast64_t can hold. 23.8.2.50 #define UINT_FAST8_MAX UINT8_MAX largest value an uint_fast8_t can hold. 23.8.2.51 #define UINT_LEAST16_MAX UINT16_MAX largest value an uint_least16_t can hold. 23.8.2.52 #define UINT_LEAST32_MAX UINT32_MAX largest value an uint_least32_t can hold. 23.8.2.53 #define UINT_LEAST64_MAX UINT64_MAX largest value an uint_least64_t can hold. 23.8.2.54 #define UINT_LEAST8_MAX UINT8_MAX largest value an uint_least8_t can hold. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.8 : Standard Integer Types 23.8.2.55 #define UINTMAX_C( value ) __CONCAT(value, ULL) define a constant of type uintmax_t 23.8.2.56 #define UINTMAX_MAX UINT64_MAX largest value an uintmax_t can hold. 23.8.2.57 #define UINTPTR_MAX UINT16_MAX largest value an uintptr_t can hold. 23.8.3 Typedef Documentation 23.8.3.1 typedef signed int int16_t 16-bit signed type. 23.8.3.2 typedef signed long int int32_t 32-bit signed type. 23.8.3.3 typedef signed long long int int64_t 64-bit signed type. Note This type is not available when the compiler option -mint8 is in effect. 23.8.3.4 typedef signed char int8_t 8-bit signed type. 23.8.3.5 typedef int16_t int_fast16_t fastest signed int with at least 16 bits. 23.8.3.6 typedef int32_t int_fast32_t fastest signed int with at least 32 bits. 23.8.3.7 typedef int64_t int_fast64_t fastest signed int with at least 64 bits. Note This type is not available when the compiler option -mint8 is in effect. 23.8.3.8 typedef int8_t int_fast8_t fastest signed int with at least 8 bits. 23.8.3.9 typedef int16_t int_least16_t signed int with at least 16 bits. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 147 148 CONTENTS 23.8.3.10 typedef int32_t int_least32_t signed int with at least 32 bits. 23.8.3.11 typedef int64_t int_least64_t signed int with at least 64 bits. Note This type is not available when the compiler option -mint8 is in effect. 23.8.3.12 typedef int8_t int_least8_t signed int with at least 8 bits. 23.8.3.13 typedef int64_t intmax_t largest signed int available. 23.8.3.14 typedef int16_t intptr_t Signed pointer compatible type. 23.8.3.15 typedef unsigned int uint16_t 16-bit unsigned type. 23.8.3.16 typedef unsigned long int uint32_t 32-bit unsigned type. 23.8.3.17 typedef unsigned long long int uint64_t 64-bit unsigned type. Note This type is not available when the compiler option -mint8 is in effect. 23.8.3.18 typedef unsigned char uint8_t 8-bit unsigned type. 23.8.3.19 typedef uint16_t uint_fast16_t fastest unsigned int with at least 16 bits. 23.8.3.20 typedef uint32_t uint_fast32_t fastest unsigned int with at least 32 bits. 23.8.3.21 typedef uint64_t uint_fast64_t fastest unsigned int with at least 64 bits. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 23.8 : Standard Integer Types Note This type is not available when the compiler option -mint8 is in effect. 23.8.3.22 typedef uint8_t uint_fast8_t fastest unsigned int with at least 8 bits. 23.8.3.23 typedef uint16_t uint_least16_t unsigned int with at least 16 bits. 23.8.3.24 typedef uint32_t uint_least32_t unsigned int with at least 32 bits. 23.8.3.25 typedef uint64_t uint_least64_t unsigned int with at least 64 bits. Note This type is not available when the compiler option -mint8 is in effect. 23.8.3.26 typedef uint8_t uint_least8_t unsigned int with at least 8 bits. 23.8.3.27 typedef uint64_t uintmax_t largest unsigned int available. 23.8.3.28 typedef uint16_t uintptr_t Unsigned pointer compatible type. Generated on Tue Aug 12 2014 21:20:45 for avr-libc by Doxygen 149 150 CONTENTS