Avr Libc User Manual 2.0.0 PDF
Avr Libc User Manual 2.0.0 PDF
2.0.0
Contents
1 AVR Libc 1
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 General information about this library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Supported Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.4 avr-libc License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2 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 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.8 GDB / Insight / DDD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.9 AVaRICE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.10 SimulAVR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.11 Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.12 Toolchain Distributions (Distros) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.13 Open Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
4 Memory Sections 17
4.1 The .text Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.2 The .data Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.3 The .bss Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.4 The .eeprom Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.5 The .noinit Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.6 The .initN Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.7 The .finiN Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.8 The .note.gnu.avr.deviceinfo Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4.9 Using Sections in Assembler Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4.10 Using Sections in C Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
5.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
5.5 Caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
6.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
7.4 Clobbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
7.8 Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
9 Benchmarks 40
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
10.2 Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
11.11Why does the PC randomly jump around when single-stepping through my program in avr-gdb? . . 50
11.19My UART is generating nonsense! My ATmega128 keeps crashing! Port F is completely broken! . 56
11.21Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation
in assembly? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
11.28Why are interrupts re-enabled in the middle of writing the stack pointer? . . . . . . . . . . . . . . . 60
11.32I am using floating point math. Why is the compiled code so big? Why does my code not work? . . 62
11.34Why are some addresses of the EEPROM corrupted (usually address zero)? . . . . . . . . . . . . 64
11.36On a device with more than 128 KiB of flash, how to make function pointers work? . . . . . . . . . 65
12.7 AVRDUDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
12.9 SimulAVR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
12.10AVaRICE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
14 Compiler optimization 93
17 Acknowledgments 98
18 Todo List 99
19 Deprecated List 99
Index 313
1 AVR Libc
1.1 Introduction
Note
If you think you've found a bug, or have a suggestion for an improvement, either in this documen-
tation 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.
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).
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.
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
• atmega2561
• atmega32
• atmega32a
• atmega323
• atmega324a
• atmega324p
• atmega324pa
• atmega325
• atmega325a
• atmega325p
• atmega325pa
• atmega3250
• atmega3250a
• atmega3250p
• atmega3250pa
• atmega328
• atmega328p
• atmega48
• atmega48a
• atmega48pa
• atmega48pb
• atmega48p
• atmega64
• atmega64a
• atmega640
• atmega644
• atmega644a
• atmega644p
• atmega644pa
• atmega645
• atmega645a
• atmega645p
• atmega6450
• atmega6450a
• atmega6450p
• atmega8
• atmega8a
• atmega88
• atmega88a
• atmega88p
• atmega88pa
• atmega88pb
• 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
• attiny44
• attiny44a
• attiny441
• attiny45
• attiny461
• attiny461a
• attiny48
• attiny828
• attiny84
• attiny84a
• attiny841
• attiny85
• attiny861
• attiny861a
• attiny87
• attiny88
• attiny1634
• atmega16m1
• atmega32c1
• atmega32m1
• atmega64c1
• atmega64m1
• attiny167
• ata5505
• ata5272
• ata5702m322
• ata5782
• ata5790
• ata5790n
• ata5831
• ata5795
• ata6612c
• ata6613c
• ata6614q
• ata6616c
• ata6617c
• ata664251
• at90can32
• at90can64
• at90can128
• atmega169
• atmega169a
• atmega169p
• atmega169pa
• atmega329
• atmega329a
• atmega329p
• atmega329pa
• atmega3290
• atmega3290a
• atmega3290p
• atmega3290pa
• atmega649
• atmega649a
• atmega6490
• atmega6490a
• atmega6490p
• atmega649p
• at90pwm1
• at90pwm2
• at90pwm2b
• at90pwm216
• at90pwm3
• at90pwm3b
• at90pwm316
• at90pwm161
• at90pwm81
• atmega8hva
• atmega16hva
• atmega16hva2
• atmega16hvb
• atmega16hvbrevb
• atmega32hvb
• atmega32hvbrevb
• atmega64hve
• atmega64hve2
• atmega406
• at90usb82
• at90usb162
• at90usb646
• at90usb647
• at90usb1286
• at90usb1287
• atmega8u2
• atmega16u2
• atmega16u4
• atmega32u2
• atmega32u4
• atmega32u6
XMEGA Devices:
• atxmega8e5
• atxmega16a4
• atxmega16a4u
• atxmega16c4
• atxmega16d4
• atxmega32a4
• atxmega32a4u
• atxmega32c3
• atxmega32c4
• atxmega32d3
• atxmega32d4
• atxmega32e5
• 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
• atmega644rfr2
• atmega64rfr2
• atmega128rfa1
• atmega1284rfr2
• atmega128rfr2
• atmega2564rfr2
• atmega256rfr2
Miscellaneous Devices:
• at94K [2]
• at76c711 [3]
• at43usb320
• at43usb355
• at86rf401
• at90scr100
• ata6285
• ata6286
• ata6289
• m3000 [4]
• 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.
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.
avr-libc can be freely used and redistributed, provided the following license conditions are met.
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 Toolchain Overview
2.1 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.
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 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.
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
avr-ranlib
avr-objcopy
avr-objdump
avr-size
avr-nm
avr-strings
avr-strip
avr-readelf
avr-addr2line
avr-c++filt
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.
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.
2.7 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.
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
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.
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.
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.1 Introduction
Many of the devices that are possible targets of avr-libc have a minimal amount of RAM. The smallest parts sup-
ported by the C environment come with 128 bytes of RAM. This needs to be shared between initialized and unini-
tialized 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 sepa-
rating 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.
Note
The pictures shown in this document represent typical situations where the RAM locations refer to an A←-
Tmega128. The memory addresses used are not displayed in a linear scale.
0x0100
0xFFFF
0x10FF
0x1100
on−board RAM external RAM
.data .bss
variables variables heap
! stack
SP RAMEND
*(__brkval) (<= *SP − *(__malloc_margin))
*(__malloc_heap_start) == __heap_start
__bss_end
__data_end == __bss_start
__data_start
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 fragmen-
tation 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.
Obviously, the constraints are much harder to satisfy in the default configuration where only internal RAM is avail-
able. 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.
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 <stdio.h>:
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() func-
tion 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 either be done at run-time, by writing directly to this variable, or it can be done automatically at link-time, by
Note
See explanation for offset 0x800000. See the chapter about using gcc for the -Wl options.
The ld (linker) user manual states that using -Tdata=<x> is equivalent to using –section-start,.data=<x>.
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.
0x0100
0xFFFF
0x10FF
0x1100
.data .bss
stack 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).
external RAM
0x0100
0xFFFF
0x3FFF
0x10FF
0x1100
0x2000
on−board RAM
.data .bss
variables variables stack heap
SP *(__malloc_heap_end) == __heap_end
RAMEND *(__brkval)
__bss_end *(__malloc_heap_start) == __heap_start
__data_end == __bss_start
__data_start
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.
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
Remarks
Need to list all the sections which are available to the avr.
Weak Bindings
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.
This section contains static data which was defined in your code. Things like the following would end up in .data:
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 adjust-
ments are required.
This sections is a part of the .bss section. What makes the .noinit section special is that variables which are defined
as such:
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:
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:
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.]
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.
.init0:
Weakly bound to __init(). If user defines __init(), it will be jumped into immediately after a reset.
.init1:
.init2:
In C programs, weakly bound to initialize the stack, and to clear __zero_reg__ (r1).
.init3:
.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:
.init6:
.init7:
.init8:
.init9:
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:
.fini8:
.fini7:
.fini6:
.fini5:
.fini4:
.fini3:
.fini2:
.fini1:
.fini0:
Goes into an infinite loop after program termination and completion of any _exit() code (execution of code in
the .fini9 -> .fini1 sections).
This section contains device specific information picked up from the device header file and compiler builtin macros.
The layout conforms to the standard ELF note section layout (http://docs.oracle.com/cd/E23824_←-
01/html/819-0690/chapter6-18048.html).
The section contents are laid out as below.
#define __NOTE_NAME_LEN 4
struct __note_gnu_avr_deviceinfo
{
struct
{
uint32_t namesz; /* = __NOTE_NAME_LEN */
uint32_t descsz; /* = size of avr_desc */
uint32_t type; /* = 1 - no other AVR note types exist */
char note_name[__NOTE_NAME_LEN]; /* = "AVR\0" */
}
note_header;
struct
{
uint32_t flash_start;
uint32_t flash_size;
uint32_t sram_start;
uint32_t sram_size;
uint32_t eeprom_start;
uint32_t eeprom_size;
uint32_t offset_table_size;
uint32_t offset_table[1]; /* Offset table containing byte offsets into
string table that immediately follows it.
index 0: Device name byte offset
*/
char str_table [2 +
strlen(__AVR_DEVICE_NAME__)]; /* Standard ELF string table.
index 0 : NULL
index 1 : Device name
index 2 : NULL
*/
}
avr_desc;
};
Example:
#include <avr/io.h>
.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 con-
tains data ("@progbits"). For more detailed information on the .section directive, see the gas user manual.
Example:
#include <avr/io.h>
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. __attribute←-
__ ((used)) tells the compiler that code must be generated for this function even if it appears that the
function is not referenced - this is necessary to prevent compiler optimizations (like LTO) from eliminating the
function.
5.1 Introduction
So you have some constant data and you're running out of room to store it? Many AVRs have limited amount of R←-
AM in which to store data, but may have more Flash space available. The AVR is a Harvard architecture processor,
where 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
non-standard. 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 <avr/pgmspace.h> 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 <avr/pgmspace.h>
system header file.
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.
{
{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];
Now you want to store your data in Program Memory. Use the PROGMEM macro found in <avr/pgmspace.h>
and put it after the declaration of the variable, but before the initializer, like so:
#include <avr/pgmspace.h>
.
.
.
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];
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.
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"
};
and then you add your PROGMEM macro to the end of the declaration:
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:
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 <avr/pgmspace.h> 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];
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 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 <avr/pgmspace.h> 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.1 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.
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++) lan-
guage, 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.
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.
• There is basically only one program to be called directly, avr-gcc, regardless of the actual source language
used.
• 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.
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.
inttmp = 19
intsav = 0
; Note [4]:
tmconst= 10700000 / 200000 ; 100 kHz => 200000 edges/s
fuzz= 8 ; # clocks in ISR until TCNT0 is set
.section .text
ioinit:
sbi _SFR_IO_ADDR(DDRD), SQUARE
sei
ret
.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 expres-
sions. 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.
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 <avr/io.h> 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.)
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/.
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:
• .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 unde-
fined 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:
• 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:
This passes the address of function somefunc as the first parameter to function something.
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.
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/.
Each asm statement is devided by colons into (up to) four parts:
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))
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
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:
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
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"::);
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
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.
Symbol Register
__SREG__ Status register at address 0x3F
__SP_H__ Stack pointer high byte at address 0x3E
__SP_L__ Stack pointer low byte at address 0x3D
__tmp_reg__ Register r0, used for temporary storage
__zero_reg__ Register r1, always zero
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.
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
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:
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:
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:
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:
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)
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" "\n\t"
"ld r24, %a0" "\n\t"
"inc r24" "\n\t"
"st %a0, r24" "\n\t"
"sei" "\n\t"
:
: "e" (ptr)
: "r24"
);
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.
asm volatile(
"cli" "\n\t"
"ld __tmp_reg__, %a0" "\n\t"
"inc __tmp_reg__" "\n\t"
"st %a0, __tmp_reg__" "\n\t"
"sei" "\n\t"
:
: "e" (ptr)
);
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__" "\n\t"
"cli" "\n\t"
"ld __tmp_reg__, %a1" "\n\t"
"inc __tmp_reg__" "\n\t"
"st %a1, __tmp_reg__" "\n\t"
"out __SREG__, %0" "\n\t"
: "=&r" (s)
: "e" (ptr)
);
}
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__" "\n\t"
"cli" "\n\t"
"ld __tmp_reg__, %a1" "\n\t"
"inc __tmp_reg__" "\n\t"
"st %a1, __tmp_reg__" "\n\t"
"out __SREG__, %0" "\n\t"
: "=&r" (s)
: "e" (ptr)
: "memory"
);
}
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:
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.
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)
)
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.
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.
Another use for a local variable is a return value. The following function returns a 16 bit value read from two
successive port addresses.
Note
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:
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");
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:
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/
8.1 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.
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 refer-
ences". 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.
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.
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 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.
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
libm.a
-lprintf_flt
libprintf_flt.a
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.
realloc ((void ∗)0, 1) Flash bytes 1284 (1172) 1174 (1064) 1174 (1064)
Stack bytes 18 18 18
MCU clocks 305 286 286
qsort (s, sizeof(s), 1, Flash bytes 1252 (1140) 1022 (912) 1028 (918)
cmp) Stack bytes 42 42 42
MCU clocks 21996 19905 17541
sprintf_min (s, "%d", Flash bytes 1224 (1112) 1092 (982) 1088 (978)
12345) Stack bytes 53 53 53
MCU clocks 1841 1694 1689
sprintf (s, "%d", 12345) Flash bytes 1614 (1502) 1476 (1366) 1454 (1344)
Stack bytes 58 58 58
MCU clocks 1647 1552 1547
sprintf_flt (s, "%e", Flash bytes 3228 (3116) 2990 (2880) 2968 (2858)
1.2345) Stack bytes 67 67 67
MCU clocks 2573 2311 2311
sscanf_min ("12345", Flash bytes 1532 (1420) 1328 (1218) 1328 (1218)
"%d", &i) Stack bytes 55 55 55
MCU clocks 1607 1446 1446
sscanf ("12345", "%d", Flash bytes 2008 (1896) 1748 (1638) 1748 (1638)
&i) Stack bytes 55 55 55
MCU clocks 1610 1449 1449
sscanf ("point,color", Flash bytes 2008 (1896) 1748 (1638) 1748 (1638)
"%[a-z]", s) Stack bytes 86 86 86
MCU clocks 3067 2806 2806
sscanf_flt ("1.2345", Flash bytes 3464 (3352) 3086 (2976) 3070 (2960)
"%e", &x) Stack bytes 71 71 71
MCU clocks 2497 2281 2078
strtod ("1.2345", &p) Flash bytes 1632 (1520) 1536 (1426) 1480 (1480)
Stack bytes 20 20 21
MCU clocks 1235 1177 1124
strtol ("12345", &p, 0) Flash bytes 918 (806) 834 (724) 792 (792)
Stack bytes 22 22 28
MCU clocks 956 891 794
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 Avr2 Avr4
__addsf3 (1.234, 5.678) 113 108
__mulsf3 (1.234, 5.678) 375 138
__divsf3 (1.234, 5.678) 466 465
acos (0.54321) 4411 2455
asin (0.54321) 4517 2556
atan (0.54321) 4710 2271
atan2 (1.234, 5.678) 5270 2857
cbrt (1.2345) 2684 2555
ceil (1.2345) 177 177
cos (1.2345) 3387 1671
cosh (1.2345) 4922 2979
exp (1.2345) 4708 2765
fdim (5.678, 1.234) 111 111
floor (1.2345) 180 180
fmax (1.234, 5.678) 39 37
fmin (1.234, 5.678) 35 35
fmod (5.678, 1.234) 131 131
frexp (1.2345, 0) 42 41
hypot (1.234, 5.678) 1341 866
ldexp (1.2345, 6) 42 42
log (1.2345) 4142 2134
log10 (1.2345) 4498 2260
modf (1.2345, 0) 433 429
pow (1.234, 5.678) 9293 5047
round (1.2345) 150 150
sin (1.2345) 3353 1653
sinh (1.2345) 4946 3003
sqrt (1.2345) 494 492
tan (1.2345) 4381 2426
tanh (1.2345) 5126 3173
trunc (1.2345) 178 178
10.1 Introduction
C language was designed to be a portable language. There two main types of porting activities: porting an ap-
plication 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 Stan-
dard, 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 <iom169.h>
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 <avr/io.h>
Note
The forward slash in the <avr/io.h> 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.
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
}
ISR(PCINT1_vect)
{
//code
}
AVR GCC uses the ISR macro to define an ISR. This macro requries the header file:
#include <avr/interrupt.h>
The names of the various interrupt vectors are found in the individual processor IO header files that you must include
with <avr/io.h>.
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.
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:
Note
See the GCC User Manual for more information about Variable Attributes.
#include <avr/pgmspace.h>
.
.
.
int mydata[] PROGMEM = ....
Note
The PROGMEM macro expands to the Variable Attribute of progmem. This macro requires that you include
<avr/pgmspace.h>. This is the canonical method for defining a variable in Program Space.
To read back flash data, use the pgm_read_∗() macros defined in <avr/pgmspace.h>. 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:
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:
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.
The IAR compiler allows a user to lock general registers from r15 and down by using compiler options and this
keyword syntax:
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:
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.
10. Why does the PC randomly jump around when single-stepping through my program in avr-gdb?
18. My UART is generating nonsense! My ATmega128 keeps crashing! Port F is completely broken!
20. Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation in as-
sembly?
27. Why are interrupts re-enabled in the middle of writing the stack pointer?
31. I am using floating point math. Why is the compiled code so big? Why does my code not work?
33. Why are some addresses of the EEPROM corrupted (usually address zero)?
35. On a device with more than 128 KiB of flash, how to make function pointers work?
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:
In order to access the mathematical functions that are declared in <math.h>, 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.
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 <avr/io.h>
.section .init1,"ax",@progbits
;; 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.
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:
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);
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 com-
plain 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" { . . . }
• 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.
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.
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.
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 (ICRn), 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;
}
Which works. When you do the same thing but replace the address of the port by its macro name, like this:
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.
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.
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:
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.
Note
You can also use -Wa,-gstabs since the compiler will add the extra '-' for you.
Example:
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:
1: pop YH
pop YL
pop r18
pop r17
pop r16
ret
#include <inttypes.h>
#include <avr/io.h>
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;
}
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:
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:
You can clearly see that 0x0038 is correctly passed for the address of the io port. Looking at the disassem-
bled 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:
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.
• 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.
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).
(odd-sized 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.
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.
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 <avr/pgmspace.h>
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 <avr/pgmspace.h>
Looking at the disassembly of the resulting object file we see that array is in flash as such:
00000026 <array>:
26: 2e 00 .word 0x002e ; ????
28: 2a 00 .word 0x002a ; ????
0000002a <bar>:
2a: 42 61 72 00 Bar.
0000002e <foo>:
2e: 46 6f 6f 00 Foo.
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 ldd r22, Y+33 ; 0x21
84: 7a a1 ldd r23, Y+34 ; 0x22
86: ce 01 movw r24, r28
88: 01 96 adiw r24, 0x01 ; 1
8a: 0c d0 rcall .+24 ; 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.
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
command-line 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.
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.
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 Size of .text Time for test #1 Time for test #2
-O3 6898 903 µs 19.7 ms
-O2 6666 972 µs 20.1 ms
-Os 6618 955 µs 20.1 ms
-Os -mcall-prologues 6474 972 µs 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 applica-
tions that need to get the last few percent of speed benefit from using -O3.
Back to FAQ Index.
First, the code should be put into a new named section. This is done with a section attribute:
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.
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.
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.
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 <inttypes.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
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;
int
main(void)
{
ioinit(); /* initialize UART, ... */
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.
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:
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:
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.
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.
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.
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.
Usually, each interrupt has its own interrupt flag bit in some control register, indicating the specified interrupt condi-
tion 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
simply use
TIFR = _BV(TOV0);
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.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:
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.
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
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:
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
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.
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 <avr/wdt.h>
...
#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 <avr/wdt.h>
...
// Function Pototype
void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3")));
...
// Function Implementation
void wdt_init(void)
{
MCUSR = 0;
wdt_disable();
return;
}
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.
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.
Library call Reentrant Issue Workaround/Alternative
rand(), random() Uses global variables to keep state Use special reentrant versions:
information. rand_r(), random_r().
strtod(), strtol(), strtoul() Uses the global variable errno to Ignore errno, or protect calls
return success/failure. with cli()/sei() or
ATOMIC_BLOCK() if the
application can tolerate it. Or use
sccanf() or sccanf_P() if possible.
malloc(), realloc(), calloc(), free() Uses the stack pointer and global Protect calls with cli()/sei() or
variables to allocate and free ATOMIC_BLOCK() if the
memory. application can tolerate it. If using
an OS, use the OS provided
memory allocator since the OS is
likely modifying the stack pointer
anyway.
fdevopen(), fclose() Uses calloc() and free(). 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().
eeprom_∗(), boot_∗() Accesses I/O registers. Protect calls with cli()/sei(),
ATOMIC_BLOCK(), or use OS
locking.
pgm_∗_far() Accesses I/O register RAMPZ. 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.
printf(), printf_P(), vprintf(), Alters flags and character count in Use only in one thread. Or if
vprintf_P(), puts(), puts_P() global FILE stdout. 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.
fprintf(), fprintf_P(), vfprintf(), Alters flags and character count in Assign each thread its own FILE
vfprintf_P(), fputs(), fputs_P() the FILE argument. Problems can for output. Or if returned character
occur if a global FILE is used from count is unimportant, do not use
multiple threads. the ∗_P versions.
assert() Contains an embedded fprintf(). See above for fprintf().
See above for fprintf().
clearerr() Alters flags in the FILE argument. Assign each thread its own FILE
for output.
getchar(), gets() Alters flags, character count, and Use only in one thread. ∗∗∗
unget buffer in global FILE stdin.
fgetc(), ungetc(), fgets(), scanf(), Alters flags, character count, and Assign each thread its own FILE
scanf_P(), fscanf(), fscanf_P(), unget buffer in the FILE argument. for input. ∗∗∗
vscanf(), vfscanf(), vfscanf_P(), Note: Scanning from a string, e.g.
fread() 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 guar-
anteed 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 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.
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:
This is also the way it is implemented in <util/setbaud.h>: 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
so-called 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.
Suppose a number of IO port registers should get the value 0xff assigned. Conveniently, it is implemented like
this:
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;
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.
This chapter shows how to build and install, from source code, a complete development environment for the A←-
VR 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.
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 $PREF←-
IX/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.
• GNU Binutils
http://sources.redhat.com/binutils/
Installation
• GCC
http://gcc.gnu.org/
Installation
• AVR LibC
http://savannah.gnu.org/projects/avr-libc/
Installation
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
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:
Note
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.
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.
Warning
You must install avr-binutils and make sure your path is set properly before installing avr-gcc.
To save your self some download time, you can alternatively download only the gcc-core-<version>.tar.←-
bz2 and gcc-c++-<version>.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
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.
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:
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
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.
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 <hdr_path> with the path to the bfd.h file on your system. Replace <lib_path>
with the path to libbfd.a on your system.):
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.
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-
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:
• Install Cygwin
– 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
– Latest Version
– http://gmplib.org/
– Build script:
./configure 2>&1 | tee gmp-configure.log
make 2>&1 | tee gmp-make.log
make check 2>&1 | tee gmp-make-check.log
make install 2>&1 | tee gmp-make-install.log
– GMP headers will be installed under /usr/local/include and library installed under /usr/local/lib.
– Latest Version
– http://www.mpfr.org/
– Build script:
– MPFR headers will be installed under /usr/local/include and library installed under /usr/local/lib.
– Latest Version
– http://www.multiprecision.org/
– Build script:
./configure --with-gmp=/usr/local --with-mpfr=/usr/local --disable-shared 2>&1 | tee mpfr-co
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.
Note
– 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 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.
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
* <MikTex executables>
* <ghostscript executables>
* /usr/local/bin
* /usr/bin
* /bin
* /mingw/bin
* c:/cygwin/bin
* <install directory>/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
• GCC
* <MikTex executables>
* <ghostscript executables>
* /usr/local/bin
* /usr/bin
* /bin
* /mingw/bin
* c:/cygwin/bin
* <install directory>/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 \
--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
* /usr/local/bin
* /mingw/bin
* /bin
* <MikTex executables>
* <install directory>/bin
* <Doxygen executables>
* <NetPBM executables>
* <fig2dev executable>
* <Ghostscript executables>
* 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
• AVRDUDE
* <MikTex executables>
* /usr/local/bin
* /usr/bin
* /bin
* /mingw/bin
* c:/cygwin/bin
* <install directory>/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
• Insight/GDB
* <MikTex executables>
* /usr/local/bin
* /usr/bin
* /bin
* /mingw/bin
* c:/cygwin/bin
* <install directory>/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
* <MikTex executables>
* /usr/local/bin
* /usr/bin
* /bin
* /mingw/bin
* c:/cygwin/bin
* <install directory>/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
• AVaRICE
* <MikTex executables>
* /usr/local/bin
* /usr/bin
* /bin
* <install directory>/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
* <MikTex executables>
* /usr/local/bin
* /usr/bin
* /bin
* <install directory>/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
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.
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
• -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.
• -morder1
• -morder2
• -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
• -mno-tablejump
• -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 de-
bugging 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
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 consti-
tute 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
• -g
• -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
• -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.
• -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.
• -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]
• l include assembly
• s include symbols
The various sub-options can be combined into a single -a option list; =file must be the last one in that case.
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:
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:
Note that on Unix systems that have case-distinguishing file systems, specifying a file name with the suffix .S (upper-
case 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).
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
• -defsym symbol=expr
• -M
• -Map mapfile
• -cref
Output a cross reference table to the map file (in case -Map is also present), or to stdout.
• -section-start sectionname=org
• -Tbss org
• -Tdata org
• -Ttext org
• -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.
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:
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:
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 Compiler optimization
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 <avr/interrupt.h>, 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 accom-
plished 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 mem-
ory 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 multitask-
ing 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:
cli();
ivar = val;
sei();
}
00000112 <test2>:
112: bc 01 movw r22, r24
114: f8 94 cli
116: 8f ef ldi r24, 0xFF ; 255
118: 9f ef ldi r25, 0xFF ; 255
11a: 0e 94 96 00 call 0x12c ; 0x12c <__udivmodhi4>
11e: 70 93 01 02 sts 0x0201, r23
122: 60 93 00 02 sts 0x0200, r22
126: 78 94 sei
128: 08 95 ret
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 don't ensure statements with no volatile accesses to be reordered across the barrier
Note
avrdude is a program that is used to update or read the flash and EEPROM memories of Atmel AVR microcon-
trollers 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:
The -p 2313 option lets avrdude know that we are operating on an AT90S2313 chip. This option spec-
ifies 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>
avrdude> ?
>>> ?
Valid commands:
Use the ’part’ command to display valid memory types for use with the
’dump’ and ’write’ commands.
avrdude>
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 2, to indicate the multilib layout has been adapted to the fairly different one used
starting with AVR-GCC version 5. Nevertheless, it is still believed to be generally API-compatible with release
versions 1.x.
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 <avr/version.h> indicates the library version of an installed library tree.
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.
The following steps should be taken to cut a branch in SVN (assuming $username is set to your savannah
username):
2. Update the NEWS file with pending release number and commit to SVN trunk:
Change Changes since avr-libc-<last_release>: to Changes in avr-libc-<this_relelase>.
svn+ssh://$username@svn.savannah.nongnu.org/avr-libc/tags/avr-libc-<major>←-
_<minor>-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-<major>←-
_<minor>-branch
5. Update the package version in configure.ac and commit configure.ac to SVN trunk:
Change minor number to next odd value.
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.
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.
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-<m
_<minor>-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-<this_release>.
5. Update the NEWS file with pending release number and commit to SVN:
Change Changes since avr-libc-<last_release>: to Changes in avr-libc-<this_relelase>:.
7. Perform a 'make distcheck' and make sure it succeeds. This will create the source tarball.
11. Update the bug tracker interface on Savannah: Bugs —> Edit field values —> Release / Fixed Release
The following hypothetical diagram should help clarify version and branch relationships.
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 li-
braries and startup code for AVR-GCC.
• 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 demo project.
• Brian Dean [ bsd@bsdhome.com ] for developing avrdude (an alternative to uisp) and for contributing
documentation which describes how to use it. Avrdude was previously called avrprog.
• Eric Weddington [ eweddington@cso.atmel.com ] for maintaining the WinAVR package and thus
making the continued improvements to the open source AVR toolchain available to many users.
• Rich Neswold for writing the original avr-tools document (which he graciously allowed to be merged into this
document) and his improvements to the demo project.
• Theodore A. Roth for having been a long-time maintainer of many of the tools (AVR-Libc, the AVR port of
GDB, AVaRICE, uisp, 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
Module avr_boot
From email with Marek: On smaller devices (all except ATmega64/128), __SPM_REG is in the I/O space, ac-
cessible with the shorter "in" and "out" instructions - since the boot loader has a limited size, this could be an
important optimization.
19 Deprecated List
20 Module Index
20.1 Modules
div_t 291
ldiv_t 291
tm 292
week_date 293
22 File Index
alloca.h ??
assert.h 293
atomic.h 293
boot.h 294
cpufunc.h 294
crc16.h 294
ctype.h 295
defines.h ??
delay.h 295
delay_basic.h 295
deprecated.h ??
dtoa_conv.h ??
eedef.h ??
eeprom.h ??
ephemera_common.h ??
errno.h 295
eu_dst.h ??
fdevopen.c 296
fuse.h 296
hd44780.h ??
ina90.h ??
interrupt.h 296
inttypes.h 296
io.h 298
iocompat.h ??
lcd.h ??
lock.h 298
math.h 298
parity.h 300
pgmspace.h 301
portpins.h ??
power.h 302
project.h ??
setbaud.h 303
setjmp.h 303
sfr_defs.h ??
signal.h ??
signature.h 303
sleep.h 303
stdint.h 303
stdio.h 306
stdio_private.h ??
stdlib.h 307
stdlib_private.h ??
string.h 308
time.h 309
util/twi.h 310
compat/twi.h ??
uart.h ??
usa_dst.h ??
version.h ??
wdt.h 311
xmega.h ??
xtoa_fast.h ??
23 Module Documentation
Functions
Returns
alloca() returns a pointer to the beginning of the allocated space. If the allocation causes stack overflow,
program behaviour is undefined.
Warning
Macros
• #define assert(expression)
#include <assert.h>
__ASSERT_USE_STDERR
before including the <assert.h> header file. By default, only abort() will be called to halt the application.
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 mes-
sage 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).
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.
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.
#include <ctype.h>
Checks whether c is a 7-bit unsigned char value that fits into the ASCII character set.
Checks for any printable character which is not a space or an alphanumeric character.
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').
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.
Macros
• #define EDOM 33
• #define ERANGE 34
Variables
• int errno
#include <errno.h>
Some functions in the library set the global variable errno when an error occurs. The file, <errno.h>, provides
symbolic names for various error codes.
Domain error.
Range error.
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.
For C++, these are only included if __STDC_LIMIT_MACROS is defined before including <inttypes.h>.
#include <inttypes.h>
This header file includes the exact-width integer definitions from <stdint.h>, 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 <stdio.h>: 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 <stdint.h>, a macro will be
supplied that portably allows formatting an object of that type in printf() or scanf() operations. Example:
#include <inttypes.h>
uint8_t smallval;
int32_t longval;
...
printf("The hexadecimal value of smallval is %" PRIx8
", the decimal value of longval is %" PRId32 ".\n",
smallval, longval);
Macros
Functions
#include <math.h>
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.
INFINITY constant.
The constant e.
NAN constant.
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].
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].
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.
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.
The ceil() function returns the smallest integral value greater than or equal to __x, expressed as a floating-point
number.
The copysign() function returns __x but with the sign of __y. They work even if __x or __y are NaN or zero.
The fabs() function computes the absolute value of a floating-point number __x.
The fdim() function returns max(__x - __y, 0). If __x or __y or both are NaN, NaN is returned.
The floor() function returns the largest integral value less than or equal to __x, expressed as a floating-point number.
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.
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.
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.
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.
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.
The isfinite() function returns a nonzero value if __x is finite: not plus or minus infinity, and not NaN.
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).
The function isnan() returns 1 if the argument __x represents a "not-a-number" (NaN) object, otherwise 0.
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.
The log10() function returns the logarithm of argument __x to base 10.
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).
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).
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.
The function pow() returns the value of __x to the exponent __y.
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.
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.
Note
The trunc() function rounds __x to the nearest integer not larger in absolute value.
Functions
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 sub-
routine 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 Environ-
ment, by W. Richard Stevens.
Example:
#include <setjmp.h>
jmp_buf env;
while (1)
{
... main processing loop which calls foo() some where ...
}
}
...
if (err)
{
longjmp (env, 1);
}
}
1 #include <setjmp.h>
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 Information saved by a previous call to setjmp().
__ret Value to return to the caller of setjmp().
Returns
1 #include <setjmp.h>
setjmp() saves the stack context/environment in __jmpb for later use by longjmp(). The stack context will be invali-
dated 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.
Integer types being usually fastest having at least the specified width
Types designating integer data capable of representing any value of any integer type in the corresponding signed
or unsigned category
C++ implementations should define these macros only when __STDC_LIMIT_MACROS is defined before <stdint.←-
h> is included
C++ implementations should define these macros only when __STDC_LIMIT_MACROS is defined before <stdint.←-
h> is included
C++ implementations should define these macros only when __STDC_CONSTANT_MACROS is defined before
<stdint.h> is included.
These definitions are valid for integer constants without suffix and for macros defined as integer constant without
suffix
#include <stdint.h>
Note
This type is not available when the compiler option -mint8 is in effect.
Note
This type is not available when the compiler option -mint8 is in effect.
Note
This type is not available when the compiler option -mint8 is in effect.
Note
This type is not available when the compiler option -mint8 is in effect.
Note
This type is not available when the compiler option -mint8 is in effect.
Note
This type is not available when the compiler option -mint8 is in effect.
Macros
Typedefs
Functions
#include <stdio.h>
This file declares the standard IO facilities that are implemented in avr-libc. Due to the nature of the underlying
hardware, only a limited subset of standard IO is implemented. There is no actual file implementation available,
so only device IO can be performed. Since there's no operating system, the application needs to provide enough
details about their devices in order to make them usable by the standard IO facilities.
Due to space constraints, some functionality has not been implemented at all (like some of the printf conversions
that have been left out). Nevertheless, potential users of this implementation should be warned: the printf and
scanf families of functions, although usually associated with presumably simple things like the famous "Hello,
world!" program, are actually fairly complex which causes their inclusion to eat up a fair amount of code space.
Also, they are not fast due to the nature of interpreting the format string at run-time. Whenever possible, resorting to
the (sometimes non-standard) predetermined conversion facilities that are offered by avr-libc will usually cost much
less in terms of speed and code size.
In order to allow programmers a code size vs. functionality tradeoff, the function vfprintf() which is the heart of
the printf family can be selected in different flavours using linker options. See the documentation of vfprintf() for a
detailed description. The same applies to vfscanf() and the scanf family of functions.
The standard streams stdin, stdout, and stderr are provided, but contrary to the C standard, since avr-libc
has no knowledge about applicable devices, these streams are not already pre-initialized at application startup.
Also, since there is no notion of "file" whatsoever to avr-libc, there is no function fopen() that could be used to
associate a stream to some device. (See note 1.) Instead, the function fdevopen() is provided to associate a
stream to a device, where the device needs to provide a function to send a character, to receive a character, or both.
There is no differentiation between "text" and "binary" streams inside avr-libc. Character \n is sent literally down to
the device's put() function. If the device requires a carriage return (\r) character to be sent before the linefeed,
its put() routine must implement this (see note 2).
As an alternative method to fdevopen(), the macro fdev_setup_stream() might be used to setup a user-supplied
FILE structure.
It should be noted that the automatic conversion of a newline character into a carriage return - newline sequence
breaks binary transfers. If binary transfers are desired, no automatic conversion should be performed, but instead
any string that aims to issue a CR-LF sequence must use "\r\n" explicitly.
For convenience, the first call to fdevopen() that opens a stream for reading will cause the resulting stream to be
aliased to stdin. Likewise, the first call to fdevopen() that opens a stream for writing will cause the resulting
stream to be aliased to both, stdout, and stderr. Thus, if the open was done with both, read and write intent, all
three standard streams will be identical. Note that these aliases are indistinguishable from each other, thus calling
fclose() on such a stream will also effectively close all of its aliases (note 3).
It is possible to tie additional user data to a stream, using fdev_set_udata(). The backend put and get functions can
then extract this user data using fdev_get_udata(), and act appropriately. For example, a single put function could
be used to talk to two different UARTs that way, or the put and get functions could keep internal state between calls
there.
All the printf and scanf family functions come in two flavours: the standard name, where the format string is
expected to be in SRAM, as well as a version with the suffix "_P" where the format string is expected to reside in
the flash ROM. The macro PSTR (explained in <avr/pgmspace.h>: Program Space Utilities) becomes very handy
for declaring these format strings.
By default, fdevopen() requires malloc(). As this is often not desired in the limited environment of a microcontroller,
an alternative option is provided to run completely without malloc().
The macro fdev_setup_stream() is provided to prepare a user-supplied FILE buffer for operation with stdio.
Example
#include <stdio.h>
static int
uart_putchar(char c, FILE *stream)
{
if (c == ’\n’)
uart_putchar(’\r’, stream);
loop_until_bit_is_set(UCSRA, UDRE);
UDR = c;
return 0;
}
int
main(void)
{
init_uart();
stdout = &mystdout;
printf("Hello, world!\n");
return 0;
}
This example uses the initializer form FDEV_SETUP_STREAM() rather than the function-like fdev_setup_stream(),
so all data initialization happens during C start-up.
If streams initialized that way are no longer needed, they can be destroyed by first calling the macro fdev_close(),
and then destroying the object itself. No call to fclose() should be issued for these streams. While calling fclose()
itself is harmless, it will cause an undefined reference to free() and thus cause the linker to link the malloc module
into the application.
Notes
Note 1:
It might have been possible to implement a device abstraction that is compatible with fopen() but since this
would have required to parse a string, and to take all the information needed either out of this string, or out of
an additional table that would need to be provided by the application, this approach was not taken.
Note 2:
This basically follows the Unix approach: if a device such as a terminal needs special handling, it is in the
domain of the terminal device driver to provide this functionality. Thus, a simple function suitable as put() for
fdevopen() that talks to a UART interface might look like this:
int
uart_putchar(char c, FILE *stream)
{
if (c == ’\n’)
uart_putchar(’\r’);
loop_until_bit_is_set(UCSRA, UDRE);
UDR = c;
return 0;
}
Note 3:
This implementation has been chosen because the cost of maintaining an alias is considerably smaller
than the cost of maintaining full copies of each stream. Yet, providing an implementation that offers the
complete set of standard streams was deemed to be useful. Not only that writing printf() instead of
fprintf(mystream, ...) saves typing work, but since avr-gcc needs to resort to pass all arguments of
variadic functions on the stack (as opposed to passing them in registers for functions that take a fixed number of
parameters), the ability to pass one parameter less by implying stdin or stdout will also save some execution
time.
EOF declares the value that is returned by various standard IO functions in case of an error. Since the AVR platform
(currently) doesn't contain an abstraction for actual files, its origin as "end of file" is somewhat meaningless here.
This macro frees up any library resources that might be associated with stream. It should be called if stream is
no longer needed, right before the application is going to destroy the stream object itself.
(Currently, this macro evaluates to nothing, but this might change in future versions of the library.)
This macro retrieves a pointer to user defined data from a FILE stream object.
This macro inserts a pointer to user defined data into a FILE stream object.
The user data can be useful for tracking state in the put and get functions supplied to the fdevopen() function.
Note
No assignments to the standard streams will be performed by fdev_setup_stream(). If standard streams are
to be used, these need to be assigned by the user. See also under Running stdio without malloc().
The macro getc used to be a "fast" macro implementation with a functionality identical to fgetc(). For space
constraints, in avr-libc, it is just an alias for fgetc.
The macro getchar reads a character from stdin. Return values and error handling is identical to fgetc().
The macro putc used to be a "fast" macro implementation with a functionality identical to fputc(). For space
constraints, in avr-libc, it is just an alias for fputc.
Stream destined for error output. Unless specifically assigned, identical to stdout.
If stderr should point to another stream, the result of another fdevopen() must be explicitly assigned to it
without closing the previous stderr (since this would also close stdout).
Stream that will be used as an input stream by the simplified functions that don't take a stream argument.
The first stream opened with read intent using fdevopen() will be assigned to stdin.
Stream that will be used as an output stream by the simplified functions that don't take a stream argument.
The first stream opened with write intent using fdevopen() will be assigned to both, stdin, and stderr.
FILE is the opaque structure that is passed around between the various standard IO functions.
This function closes stream, and disallows and further IO to and from it.
When using fdevopen() to setup the stream, a call to fclose() is needed in order to free the internal resources
allocated.
If the stream has been set up using fdev_setup_stream() or FDEV_SETUP_STREAM(), use fdev_close() instead.
It currently always returns 0 (for success).
Note
Test the end-of-file flag of stream. This flag can only be cleared by a call to clearerr().
Test the error flag of stream. This flag can only be cleared by a call to clearerr().
Flush stream.
This is a null operation provided for source-code compatibility only, as the standard IO implementation currently
does not perform any buffering.
The function fgetc reads a character from stream. It returns the character, or EOF in case end-of-file was
encountered or an error occurred. The routines feof() or ferror() must be used to distinguish between both situations.
Read at most size - 1 bytes from stream, until a newline character was encountered, and store the characters
in the buffer pointed to by str. Unless an error was encountered while reading, the string will then be terminated
with a NUL character.
If an error was encountered, the function returns NULL and sets the error flag of stream, which can be tested
using ferror(). Otherwise, a pointer to the string will be returned.
The function fprintf performs formatted output to stream. See vfprintf() for details.
Variant of fprintf() that uses a fmt string that resides in program memory.
The function fputc sends the character c (though given as type int) to stream. It returns the character, or
EOF in case an error occurred.
23.9.4.14 size_t fread ( void ∗ __ptr, size_t __size, size_t __nmemb, FILE ∗ __stream )
Read nmemb objects, size bytes each, from stream, to the buffer pointed to by ptr.
Returns the number of objects successfully read, i. e. nmemb unless an input error occured or end-of-file was
encountered. feof() and ferror() must be used to distinguish between these two conditions.
The function fscanf performs formatted input, reading the input data from stream.
See vfscanf() for details.
23.9.4.17 size_t fwrite ( const void ∗ __ptr, size_t __size, size_t __nmemb, FILE ∗ __stream )
Write nmemb objects, size bytes each, to stream. The first byte of the first object is referenced by ptr.
Returns the number of objects successfully written, i. e. nmemb unless an output error occured.
Similar to fgets() except that it will operate on stream stdin, and the trailing newline (if any) will not be stored in
the string. It is the caller's responsibility to provide enough storage to hold the characters read.
The function printf performs formatted output to stream stdout. See vfprintf() for details.
Variant of printf() that uses a fmt string that resides in program memory.
Write the string pointed to by str, and a trailing newline character, to stdout.
23.9.4.25 int snprintf ( char ∗ __s, size_t __n, const char ∗ __fmt, ... )
Like sprintf(), but instead of assuming s to be of infinite size, no more than n characters (including the trailing
NUL character) will be converted to s.
Returns the number of characters that would have been written to s if there were enough space.
23.9.4.26 int snprintf_P ( char ∗ __s, size_t __n, const char ∗ __fmt, ... )
Variant of snprintf() that uses a fmt string that resides in program memory.
Variant of sprintf() that uses a fmt string that resides in program memory.
23.9.4.29 int sscanf ( const char ∗ __buf, const char ∗ __fmt, ... )
The function sscanf performs formatted input, reading the input data from the buffer pointed to by buf.
23.9.4.30 int sscanf_P ( const char ∗ __buf, const char ∗ __fmt, ... )
The ungetc() function pushes the character c (converted to an unsigned char) back onto the input stream pointed
to by stream. The pushed-back character will be returned by a subsequent read on the stream.
Currently, only a single character can be pushed back onto the stream.
The ungetc() function returns the character pushed back after the conversion, or EOF if the operation fails. If the
value of the argument c character equals EOF, the operation will fail and the stream will remain unchanged.
23.9.4.32 int vfprintf ( FILE ∗ __stream, const char ∗ __fmt, va_list __ap )
vfprintf is the central facility of the printf family of functions. It outputs values to stream under control of
a format string passed in fmt. The actual values to print are passed as a variable argument list ap.
vfprintf returns the number of characters written to stream, or EOF in case of an error. Currently, this will
only happen if stream has not been opened with write intent.
The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged
to the output stream; and conversion specifications, each of which results in fetching zero or more subsequent ar-
guments. Each conversion specification is introduced by the % character. The arguments must properly correspond
(after type promotion) with the conversion specifier. After the %, the following appear in sequence:
– # The value should be converted to an "alternate form". For c, d, i, s, and u conversions, this option has
no effect. For o conversions, the precision of the number is increased to force the first character of the
output string to a zero (except if a zero value is printed with an explicit precision of zero). For x and X
conversions, a non-zero result has the string ‘0x' (or ‘0X' for X conversions) prepended to it.
– 0 (zero) Zero padding. For all conversions, the converted value is padded on the left with zeros rather
than blanks. If a precision is given with a numeric conversion (d, i, o, u, i, x, and X), the 0 flag is ignored.
– - A negative field width flag; the converted value is to be left adjusted on the field boundary. The
converted value is padded on the right with blanks, rather than on the left with blanks or zeros. A -
overrides a 0 if both are given.
– ' ' (space) A blank should be left before a positive number produced by a signed conversion (d, or i).
– + A sign must always be placed before a number produced by a signed conversion. A + overrides a
space if both are used.
• An optional decimal digit string specifying a minimum field width. If the converted value has fewer characters
than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been
given) to fill out the field width.
• An optional precision, in the form of a period . followed by an optional digit string. If the digit string is omitted,
the precision is taken as zero. This gives the minimum number of digits to appear for d, i, o, u, x, and X
conversions, or the maximum number of characters to be printed from a string for s conversions.
• An optional l or h length modifier, that specifies that the argument for the d, i, o, u, x, or X conversion is a
"long int" rather than int. The h is ignored, as "short int" is equivalent to int.
• diouxX The int (or appropriate variant) argument is converted to signed decimal (d and i), unsigned octal
(o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation. The letters "abcdef" are used for
x conversions; the letters "ABCDEF" are used for X conversions. The precision, if any, gives the minimum
number of digits that must appear; if the converted value requires fewer digits, it is padded on the left with
zeros.
• p The void ∗ argument is taken as an unsigned integer, and converted similarly as a %#x command would
do.
• c The int argument is converted to an "unsigned char", and the resulting character is written.
• s The "char ∗" argument is expected to be a pointer to an array of character type (pointer to a string).
Characters from the array are written up to (but not including) a terminating NUL character; if a precision
is specified, no more than the number specified are written. If a precision is given, no null character need
be present; if the precision is not specified, or is greater than the size of the array, the array must contain a
terminating NUL character.
• eE The double argument is rounded and converted in the format "[-]d.ddde±dd" where there is one digit
before the decimal-point character and the number of digits after it is equal to the precision; if the precision is
missing, it is taken as 6; if the precision is zero, no decimal-point character appears. An E conversion uses
the letter 'E' (rather than 'e') to introduce the exponent. The exponent always contains two digits; if the
value is zero, the exponent is 00.
• fF The double argument is rounded and converted to decimal notation in the format "[-]ddd.ddd", where
the number of digits after the decimal-point character is equal to the precision specification. If the precision
is missing, it is taken as 6; if the precision is explicitly zero, no decimal-point character appears. If a decimal
point appears, at least one digit appears before it.
• gG The double argument is converted in style f or e (or F or E for G conversions). The precision specifies
the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is
treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the
precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is
followed by at least one digit.
• S Similar to the s format, except the pointer is expected to point to a program-memory (ROM) string instead
of a RAM string.
In no case does a non-existent or small field width cause truncation of a numeric field; if the result of a conversion
is wider than the field width, the field is expanded to contain the conversion result.
Since the full implementation of all the mentioned features becomes fairly large, three different flavours of vfprintf()
can be selected using linker options. The default vfprintf() implements all the mentioned functionality except floating
point conversions. A minimized version of vfprintf() is available that only implements the very basic integer and
string conversion facilities, but only the # additional option can be specified using conversion flags (these flags are
parsed correctly from the format specification, but then simply ignored). This version can be requested using the
following compiler options:
1 -Wl,-u,vfprintf -lprintf_min
If the full functionality including the floating point conversions is required, the following options should be used:
Limitations:
Notes:
• For floating-point conversions, if you link default or minimized version of vfprintf(), the symbol ? will be
output and double argument will be skiped. So you output below will not be crashed. For default version
the width field and the "pad to left" ( symbol minus ) option will work in this case.
• The hh length modifier is ignored (char argument is promouted to int). More exactly, this realization
does not check the number of h symbols.
• But the ll length modifier will to abort the output, as this realization does not operate long long
arguments.
• The variable width or precision field (an asterisk ∗ symbol) is not realized and will to abort the output.
23.9.4.33 int vfprintf_P ( FILE ∗ __stream, const char ∗ __fmt, va_list __ap )
Variant of vfprintf() that uses a fmt string that resides in program memory.
Formatted input. This function is the heart of the scanf family of functions.
Characters are read from stream and processed in a way described by fmt. Conversion results will be assigned to
the parameters passed via ap.
The format string fmt is scanned for conversion specifications. Anything that doesn't comprise a conversion spec-
ification is taken as text that is matched literally against the input. White space in the format string will match any
white space in the data (including none), all other characters match only itself. Processing is aborted as soon as
the data and format string no longer match, or there is an error or end-of-file condition on stream.
Most conversions skip leading white space before starting the actual conversion.
Conversions are introduced with the character %. Possible options can follow the %:
• a ∗ indicating that the conversion should be performed but the conversion result is to be discarded; no
parameters will be processed from ap,
• the character h indicating that the argument is a pointer to short int (rather than int),
• the 2 characters hh indicating that the argument is a pointer to char (rather than int).
• the character l indicating that the argument is a pointer to long int (rather than int, for integer type
conversions), or a pointer to double (for floating point conversions),
In addition, a maximal field width may be specified as a nonzero positive decimal integer, which will restrict the
conversion to at most this many characters from the input stream. This field width is limited to at most 255 characters
which is also the default value (except for the c conversion that defaults to 1).
The following conversion flags are supported:
• d Matches an optionally signed decimal integer; the next pointer must be a pointer to int.
• i Matches an optionally signed integer; the next pointer must be a pointer to int. The integer is read in
base 16 if it begins with 0x or 0X, in base 8 if it begins with 0, and in base 10 otherwise. Only characters that
correspond to the base are used.
• o Matches an octal integer; the next pointer must be a pointer to unsigned int.
• u Matches an optionally signed decimal integer; the next pointer must be a pointer to unsigned int.
• x Matches an optionally signed hexadecimal integer; the next pointer must be a pointer to unsigned int.
• f Matches an optionally signed floating-point number; the next pointer must be a pointer to float.
• e, g, F, E, G Equivalent to f.
• s Matches a sequence of non-white-space characters; the next pointer must be a pointer to char, and the
array must be large enough to accept all the sequence and the terminating NUL character. The input string
stops at white space or at the maximum field width, whichever occurs first.
• c Matches a sequence of width count characters (default 1); the next pointer must be a pointer to char, and
there must be enough room for all the characters (no terminating NUL is added). The usual skip of leading
white space is suppressed. To skip white space first, use an explicit space in the format.
• [ Matches a nonempty sequence of characters from the specified set of accepted characters; the next pointer
must be a pointer to char, and there must be enough room for all the characters in the string, plus a
terminating NUL character. The usual skip of leading white space is suppressed. The string is to be made
up of characters in (or not in) a particular set; the set is defined by the characters between the open bracket
[ character and a close bracket ] character. The set excludes those characters if the first character after the
open bracket is a circumflex ∧ . To include a close bracket in the set, make it the first character after the open
bracket or the circumflex; any other position will end the set. The hyphen character - is also special; when
placed between two other characters, it adds all intervening characters to the set. To include a hyphen, make
it the last character before the final close bracket. For instance, [∧ ]0-9-] means the set of everything
except close bracket, zero through nine, and hyphen. The string ends with the appearance of a character
not in the (or, with a circumflex, in) set or when the field width runs out. Note that usage of this conversion
enlarges the stack expense.
• p Matches a pointer value (as printed by p in printf()); the next pointer must be a pointer to void.
• n Nothing is expected; instead, the number of characters consumed thus far from the input is stored through
the next pointer, which must be a pointer to int. This is not a conversion, although it can be suppressed with
the ∗ flag.
These functions return the number of input items assigned, which can be fewer than provided for, or even
zero, in the event of a matching failure. Zero indicates that, while there was input available, no conversions
were assigned; typically this is due to an invalid input character, such as an alphabetic character for a d
conversion. The value EOF is returned if an input failure occurs before any conversion such as an end-of-file
occurs. If an error or end-of-file occurs after conversion has begun, the number of conversions which were
successfully completed is returned.
By default, all the conversions described above are available except the floating-point conversions and the
width is limited to 255 characters. The float-point conversion will be available in the extended version provided
by the library libscanf_flt.a. Also in this case the width is not limited (exactly, it is limited to 65535
characters). To link a program against the extended version, use the following compiler flags in the link
stage:
A third version is available for environments that are tight on space. In addition to the restrictions of the standard
one, this version implements no %[ specification. This version is provided in the library libscanf_min.a, and
can be requested using the following options in the link stage:
23.9.4.35 int vfscanf_P ( FILE ∗ __stream, const char ∗ __fmt, va_list __ap )
The function vprintf performs formatted output to stream stdout, taking a variable argument list as in vfprintf().
See vfprintf() for details.
The function vscanf performs formatted input from stream stdin, taking a variable argument list as in vfscanf().
See vfscanf() for details.
23.9.4.38 int vsnprintf ( char ∗ __s, size_t __n, const char ∗ __fmt, va_list ap )
Like vsprintf(), but instead of assuming s to be of infinite size, no more than n characters (including the trailing
NUL character) will be converted to s.
Returns the number of characters that would have been written to s if there were enough space.
23.9.4.39 int vsnprintf_P ( char ∗ __s, size_t __n, const char ∗ __fmt, va_list ap )
Variant of vsnprintf() that uses a fmt string that resides in program memory.
Like sprintf() but takes a variable argument list for the arguments.
Variant of vsprintf() that uses a fmt string that resides in program memory.
Data Structures
• struct div_t
• struct ldiv_t
Macros
Typedefs
Functions
Variables
• size_t __malloc_margin
• char ∗ __malloc_heap_start
• char ∗ __malloc_heap_end
Note that these functions are not located in the default library, libc.a, but in the mathematical library, libm.a.
So when linking the application, the -lm option needs to be specified.
• char ∗ dtostre (double __val, char ∗__s, unsigned char __prec, unsigned char __flags)
• char ∗ dtostrf (double __val, signed char __width, unsigned char __prec, char ∗__s)
• #define DTOSTR_ALWAYS_SIGN 0x01 /∗ put '+' or ' ' for positives ∗/
• #define DTOSTR_PLUS_SIGN 0x02 /∗ put '+' rather than ' ' ∗/
• #define DTOSTR_UPPERCASE 0x04 /∗ put 'E' rather 'e' ∗/
• #define EXIT_SUCCESS 0
• #define EXIT_FAILURE 1
#include <stdlib.h>
This file declares some basic C macros and functions as defined by the ISO standard, plus some AVR-specific
extensions.
23.10.2.1 #define DTOSTR_ALWAYS_SIGN 0x01 /∗ put '+' or ' ' for positives ∗/
23.10.2.2 #define DTOSTR_PLUS_SIGN 0x02 /∗ put '+' rather than ' ' ∗/
The abort() function causes abnormal program termination to occur. This realization disables interrupts and jumps
to _exit() function with argument equal to 1. In the limited AVR environment, execution is effectively halted by
entering an infinite loop.
Note
The atof() function converts the initial portion of the string pointed to by nptr to double representation.
It is equivalent to calling
The atoi() function converts the initial portion of the string pointed to by s to integer representation. In contrast to
this function does not detect overflow (errno is not changed and the result value is not predictable), uses smaller
memory (flash and stack) and works more quickly.
The atol() function converts the initial portion of the string pointed to by s to long integer representation. In contrast
to
this function does not detect overflow (errno is not changed and the result value is not predictable), uses smaller
memory (flash and stack) and works more quickly.
23.10.4.6 void∗ bsearch ( const void ∗ __key, const void ∗ __base, size_t __nmemb, size_t __size, int(∗)(const void ∗, const
void ∗) __compar )
The bsearch() function searches an array of nmemb objects, the initial member of which is pointed to by base, for
a member that matches the object pointed to by key. The size of each member of the array is specified by size.
The contents of the array should be in ascending sorted order according to the comparison function referenced by
compar. The compar routine is expected to have two arguments which point to the key object and to an array
member, in that order, and should return an integer less than, equal to, or greater than zero if the key object is
found, respectively, to be less than, to match, or be greater than the array member.
The bsearch() function returns a pointer to a matching member of the array, or a null pointer if no match is found. If
two members compare as equal, which member is matched is unspecified.
Allocate nele elements of size each. Identical to calling malloc() using nele ∗ size as argument, except
the allocated memory will be cleared to zero.
The div() function computes the value num/denom and returns the quotient and remainder in a structure named
div_t that contains two int members named quot and rem.
23.10.4.9 char∗ dtostre ( double __val, char ∗ __s, unsigned char __prec, unsigned char __flags )
The dtostre() function converts the double value passed in val into an ASCII representation that will be stored
under s. The caller is responsible for providing sufficient storage in s.
Conversion is done in the format "[-]d.ddde±dd" where there is one digit before the decimal-point character
and the number of digits after it is equal to the precision prec; if the precision is zero, no decimal-point character
appears. If flags has the DTOSTRE_UPPERCASE bit set, the letter 'E' (rather than 'e' ) will be used to
introduce the exponent. The exponent always contains two digits; if the value is zero, the exponent is "00".
If flags has the DTOSTRE_ALWAYS_SIGN bit set, a space character will be placed into the leading position for
positive numbers.
If flags has the DTOSTRE_PLUS_SIGN bit set, a plus sign will be used instead of a space character in this case.
The dtostre() function returns the pointer to the converted string s.
23.10.4.10 char∗ dtostrf ( double __val, signed char __width, unsigned char __prec, char ∗ __s )
The dtostrf() function converts the double value passed in val into an ASCII representationthat will be stored under
s. The caller is responsible for providing sufficient storage in s.
Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the possible
'.' and the possible sign for negative values) is given in width, and prec determines the number of digits after
the decimal sign. width is signed value, negative for left adjustment.
The dtostrf() function returns the pointer to the converted string s.
The exit() function terminates the application. Since there is no environment to return to, status is ignored, and
code execution will eventually reach an infinite loop, thereby effectively halting all code processing. Before entering
the infinite loop, interrupts are globally disabled.
In a C++ context, global destructors will be called before halting execution.
The free() function causes the allocated memory referenced by ptr to be made available for future allocations. If
ptr is NULL, no action occurs.
Note
The minimal size of the buffer s depends on the choice of radix. For example, if the radix is 2 (binary), you
need to supply a buffer with a minimal length of 8 ∗ sizeof (int) + 1 characters, i.e. one character for each bit
plus one for the string terminator. Using a larger radix will require a smaller minimal buffer size.
Warning
Conversion is done using the radix as base, which may be a number between 2 (binary conversion) and up to
36. If radix is greater than 10, the next digit after '9' will be the letter 'a'.
The labs() function computes the absolute value of the long integer i.
Note
The ldiv() function computes the value num/denom and returns the quotient and remainder in a structure named
ldiv_t that contains two long integer members named quot and rem.
Note
The minimal size of the buffer s depends on the choice of radix. For example, if the radix is 2 (binary), you
need to supply a buffer with a minimal length of 8 ∗ sizeof (long int) + 1 characters, i.e. one character for each
bit plus one for the string terminator. Using a larger radix will require a smaller minimal buffer size.
Warning
Conversion is done using the radix as base, which may be a number between 2 (binary conversion) and up to
36. If radix is greater than 10, the next digit after '9' will be the letter 'a'.
If radix is 10 and val is negative, a minus sign will be prepended.
The ltoa() function returns the pointer passed as s.
The malloc() function allocates size bytes of memory. If malloc() fails, a NULL pointer is returned.
Note that malloc() does not initialize the returned memory to zero bytes.
See the chapter about malloc() usage for implementation details.
23.10.4.18 void qsort ( void ∗ __base, size_t __nmemb, size_t __size, __compar_fn_t __compar )
The rand() function computes a sequence of pseudo-random integers in the range of 0 to RAND_MAX (as defined
by the header file <stdlib.h>).
The srand() function sets its argument seed as the seed for a new sequence of pseudo-random numbers to be
returned by rand(). These sequences are repeatable by calling srand() with the same seed value.
If no seed value is provided, the functions are automatically seeded with a value of 1.
In compliance with the C standard, these functions operate on int arguments. Since the underlying algorithm
already uses 32-bit calculations, this causes a loss of precision. See random() for an alternate set of functions
that retains full 32-bit precision.
Variant of rand() that stores the context in the user-supplied variable located at ctx instead of a static library
variable so the function becomes re-entrant.
The random() function computes a sequence of pseudo-random integers in the range of 0 to RANDOM_MAX (as
defined by the header file <stdlib.h>).
The srandom() function sets its argument seed as the seed for a new sequence of pseudo-random numbers to be
returned by rand(). These sequences are repeatable by calling srandom() with the same seed value.
If no seed value is provided, the functions are automatically seeded with a value of 1.
Variant of random() that stores the context in the user-supplied variable located at ctx instead of a static library
variable so the function becomes re-entrant.
The realloc() function tries to change the size of the region allocated at ptr to the new size value. It returns a
pointer to the new region. The returned pointer might be the same as the old pointer, or a pointer to a completely
different region.
The contents of the returned region up to either the old or the new size value (whatever is less) will be identical to
the contents of the old region, even in case a new region had to be allocated.
It is acceptable to pass ptr as NULL, in which case realloc() will behave identical to malloc().
If the new memory cannot be allocated, realloc() returns NULL, and the region at ptr will not be changed.
The strtod() function converts the initial portion of the string pointed to by nptr to double representation.
The expected form of the string is an optional plus ( '+' ) or minus sign ( '-' ) followed by a sequence of digits
optionally containing a decimal-point character, optionally followed by an exponent. An exponent consists of an 'E'
or 'e', followed by an optional plus or minus sign, followed by a sequence of digits.
Leading white-space characters in the string are skipped.
The strtod() function returns the converted value, if any.
If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the
location referenced by endptr.
If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.
If the correct value would cause overflow, plus or minus INFINITY is returned (according to the sign of the value),
and ERANGE is stored in errno. If the correct value would cause underflow, zero is returned and ERANGE is
stored in errno.
23.10.4.27 long strtol ( const char ∗ __nptr, char ∗∗ __endptr, int __base )
The strtol() function converts the string in nptr to a long value. The conversion is done according to the given
base, which must be between 2 and 36 inclusive, or be the special value 0.
The string may begin with an arbitrary amount of white space (as determined by isspace()) followed by a single
optional '+' or '-' sign. If base is zero or 16, the string may then include a "0x" prefix, and the number will be
read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it
is taken as 8 (octal).
The remainder of the string is converted to a long value in the obvious manner, stopping at the first character which
is not a valid digit in the given base. (In bases above 10, the letter 'A' in either upper or lower case represents 10,
'B' represents 11, and so forth, with 'Z' representing 35.)
If endptr is not NULL, strtol() stores the address of the first invalid character in ∗endptr. If there were no digits
at all, however, strtol() stores the original value of nptr in endptr. (Thus, if ∗nptr is not '\0' but ∗∗endptr
is '\0' on return, the entire string was valid.)
The strtol() function returns the result of the conversion, unless the value would underflow or overflow. If no con-
version could be performed, 0 is returned. If an overflow or underflow occurs, errno is set to ERANGE and the
function return value is clamped to LONG_MIN or LONG_MAX, respectively.
23.10.4.28 unsigned long strtoul ( const char ∗ __nptr, char ∗∗ __endptr, int __base )
The strtoul() function converts the string in nptr to an unsigned long value. The conversion is done according to
the given base, which must be between 2 and 36 inclusive, or be the special value 0.
The string may begin with an arbitrary amount of white space (as determined by isspace()) followed by a single
optional '+' or '-' sign. If base is zero or 16, the string may then include a "0x" prefix, and the number will be
read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it
is taken as 8 (octal).
The remainder of the string is converted to an unsigned long value in the obvious manner, stopping at the first
character which is not a valid digit in the given base. (In bases above 10, the letter 'A' in either upper or lower
case represents 10, 'B' represents 11, and so forth, with 'Z' representing 35.)
If endptr is not NULL, strtoul() stores the address of the first invalid character in ∗endptr. If there were no digits
at all, however, strtoul() stores the original value of nptr in endptr. (Thus, if ∗nptr is not '\0' but ∗∗endptr
is '\0' on return, the entire string was valid.)
The strtoul() function return either the result of the conversion or, if there was a leading minus sign, the negation
of the result of the conversion, unless the original (non-negated) value would overflow; in the latter case, strtoul()
returns ULONG_MAX, and errno is set to ERANGE. If no conversion could be performed, 0 is returned.
Note
The minimal size of the buffer s depends on the choice of radix. For example, if the radix is 2 (binary), you
need to supply a buffer with a minimal length of 8 ∗ sizeof (unsigned long int) + 1 characters, i.e. one character
for each bit plus one for the string terminator. Using a larger radix will require a smaller minimal buffer size.
Warning
Conversion is done using the radix as base, which may be a number between 2 (binary conversion) and up to
36. If radix is greater than 10, the next digit after '9' will be the letter 'a'.
The ultoa() function returns the pointer passed as s.
Note
The minimal size of the buffer s depends on the choice of radix. For example, if the radix is 2 (binary), you
need to supply a buffer with a minimal length of 8 ∗ sizeof (unsigned int) + 1 characters, i.e. one character for
each bit plus one for the string terminator. Using a larger radix will require a smaller minimal buffer size.
Warning
Conversion is done using the radix as base, which may be a number between 2 (binary conversion) and up to
36. If radix is greater than 10, the next digit after '9' will be the letter 'a'.
The utoa() function returns the pointer passed as s.
malloc() tunable.
malloc() tunable.
malloc() tunable.
Macros
• #define _FFS(x)
Functions
#include <string.h>
Note
If the strings you are working on resident in program space (flash), you will need to use the string functions
described in <avr/pgmspace.h>: Program Space Utilities.
This macro finds the first (least significant) bit set in the input value.
This macro is very similar to the function ffs() except that it evaluates its argument at compile-time, so it should only
be applied to compile-time constant expressions where it will reduce to a constant itself. Application of this macro to
expressions that are not constant at compile-time is not recommended, and might result in a huge amount of code
generated.
Returns
The _FFS() macro returns the position of the first (least significant) bit set in the word val, or 0 if no bits are
set. The least significant bit is position 1. Only 16 bits of argument are evaluted.
This function finds the first (least significant) bit set in the input value.
Returns
The ffs() function returns the position of the first (least significant) bit set in the word val, or 0 if no bits are set.
The least significant bit is position 1.
Note
For expressions that are constant at compile time, consider using the _FFS macro instead.
23.11.3.4 void ∗ memccpy ( void ∗ dest, const void ∗ src, int val, size_t len )
Returns
The memccpy() function returns a pointer to the next character in dest after val, or NULL if val was not
found in the first len characters of src.
23.11.3.5 void ∗ memchr ( const void ∗ src, int val, size_t len )
Returns
The memchr() function returns a pointer to the matching byte or NULL if the character does not occur in the
given memory area.
23.11.3.6 int memcmp ( const void ∗ s1, const void ∗ s2, size_t len )
Returns
The memcmp() function returns an integer less than, equal to, or greater than zero if the first len bytes of s1 is
found, respectively, to be less than, to match, or be greater than the first len bytes of s2.
Note
Be sure to store the result in a 16 bit variable since you may get incorrect results if you use an unsigned char
or char due to truncation.
Warning
This function is not -mint8 compatible, although if you only care about testing for equality, this function should
be safe to use.
23.11.3.7 void ∗ memcpy ( void ∗ dest, const void ∗ src, size_t len )
Returns
23.11.3.8 void ∗ memmem ( const void ∗ s1, size_t len1, const void ∗ s2, size_t len2 )
The memmem() function finds the start of the first occurrence of the substring s2 of length len2 in the memory
area s1 of length len1.
Returns
The memmem() function returns a pointer to the beginning of the substring, or NULL if the substring is not
found. If len2 is zero, the function returns s1.
23.11.3.9 void ∗ memmove ( void ∗ dest, const void ∗ src, size_t len )
Returns
23.11.3.10 void ∗ memrchr ( const void ∗ src, int val, size_t len )
The memrchr() function is like the memchr() function, except that it searches backwards from the end of the len
bytes pointed to by src instead of forwards from the front. (Glibc, GNU extension.)
Returns
The memrchr() function returns a pointer to the matching byte or NULL if the character does not occur in the
given memory area.
Returns
Returns
The strcasecmp() function returns an integer less than, equal to, or greater than zero if s1 is found, respec-
tively, to be less than, to match, or be greater than s2. A consequence of the ordering used by strcasecmp()
is that if s1 is an initial substring of s2, then s1 is considered to be "less than" s2.
The strcasestr() function finds the first occurrence of the substring s2 in the string s1. This is like strstr(), except
that it ignores case of alphabetic symbols in searching for the substring. (Glibc, GNU extension.)
Returns
The strcasestr() function returns a pointer to the beginning of the substring, or NULL if the substring is not
found. If s2 points to a string of zero length, the function returns s1.
Returns
Returns
The strchr() function returns a pointer to the matched character or NULL if the character is not found.
The strchrnul() function is like strchr() except that if c is not found in s, then it returns a pointer to the null byte at
the end of s, rather than NULL. (Glibc, GNU extension.)
Returns
The strchrnul() function returns a pointer to the matched character, or a pointer to the null byte at the end of s
(i.e., s+strlen(s)) if the character is not found.
Returns
The strcmp() function returns an integer less than, equal to, or greater than zero if s1 is found, respectively,
to be less than, to match, or be greater than s2. A consequence of the ordering used by strcmp() is that if s1
is an initial substring of s2, then s1 is considered to be "less than" s2.
Copy a string.
The strcpy() function copies the string pointed to by src (including the terminating '\0' character) to the array pointed
to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy.
Returns
Note
If the destination string of a strcpy() is not large enough (that is, if the programmer was stupid/lazy, and failed
to check the size before copying) then anything might happen. Overflowing fixed length strings is a favourite
cracker technique.
The strcspn() function calculates the length of the initial segment of s which consists entirely of characters not in
reject.
Returns
The strcspn() function returns the number of characters in the initial segment of s which are not in the string
reject. The terminating zero is not considered as a part of string.
Duplicate a string.
The strdup() function allocates memory and copies into it the string addressed by s1, including the terminating null
character.
Warning
The strdup() function calls malloc() to allocate the memory for the duplicated string! The user is responsible
for freeing the memory by calling free().
Returns
The strdup() function returns a pointer to the resulting string dest. If malloc() cannot allocate enough storage
for the string, strdup() will return NULL.
Warning
Be sure to check the return value of the strdup() function to make sure that the function has succeeded in
allocating the memory!
23.11.3.21 size_t strlcat ( char ∗ dst, const char ∗ src, size_t siz )
Returns
The strlcat() function returns strlen(src) + MIN(siz, strlen(initial dst)). If retval >= siz, truncation occurred.
Appends src to string dst of size siz (unlike strncat(), siz is the full size of dst, not space left). At most siz-1 characters
will be copied. Always NULL terminates (unless siz <= strlen(dst)).
Returns
The strlcat() function returns strlen(src) + MIN(siz, strlen(initial dst)). If retval >= siz, truncation occurred.
23.11.3.22 size_t strlcpy ( char ∗ dst, const char ∗ src, size_t siz )
Copy a string.
Copy src to string dst of size siz. At most siz-1 characters will be copied. Always NULL terminates (unless
siz == 0).
Returns
The strlcpy() function returns strlen(src). If retval >= siz, truncation occurred.
Copy src to string dst of size siz. At most siz-1 characters will be copied. Always NULL terminates (unless siz ==
0).
Returns
The strlcpy() function returns strlen(src). If retval >= siz, truncation occurred.
Returns
Returns
23.11.3.25 int strncasecmp ( const char ∗ s1, const char ∗ s2, size_t len )
Returns
The strncasecmp() function returns an integer less than, equal to, or greater than zero if s1 (or the first len
bytes thereof) is found, respectively, to be less than, to match, or be greater than s2. A consequence of the
ordering used by strncasecmp() is that if s1 is an initial substring of s2, then s1 is considered to be "less
than" s2.
23.11.3.26 char ∗ strncat ( char ∗ dest, const char ∗ src, size_t len )
Returns
23.11.3.27 int strncmp ( const char ∗ s1, const char ∗ s2, size_t len )
Returns
The strncmp() function returns an integer less than, equal to, or greater than zero if s1 (or the first n bytes
thereof) is found, respectively, to be less than, to match, or be greater than s2.
23.11.3.28 char ∗ strncpy ( char ∗ dest, const char ∗ src, size_t len )
Copy a string.
The strncpy() function is similar to strcpy(), except that not more than n bytes of src are copied. Thus, if there is no
null byte among the first n bytes of src, the result will not be null-terminated.
In the case where the length of src is less than that of n, the remainder of dest will be padded with nulls.
Returns
Returns
The strnlen function returns strlen(src), if that is less than len, or len if there is no '\0' character among the first
len characters pointed to by src.
The strpbrk() function locates the first occurrence in the string s of any of the characters in the string accept.
Returns
The strpbrk() function returns a pointer to the character in s that matches one of the characters in accept,
or NULL if no such character is found. The terminating zero is not considered as a part of string: if one or
both args are empty, the result will be NULL.
Returns
The strrchr() function returns a pointer to the matched character or NULL if the character is not found.
Reverse a string.
The strrev() function reverses the order of the string.
Returns
The strrev() function returns a pointer to the beginning of the reversed string.
Returns
The strsep() function returns a pointer to the original value of ∗sp. If ∗sp is initially NULL, strsep() returns
NULL.
The strspn() function calculates the length of the initial segment of s which consists entirely of characters in
accept.
Returns
The strspn() function returns the number of characters in the initial segment of s which consist only of char-
acters from accept. The terminating zero is not considered as a part of string.
Locate a substring.
The strstr() function finds the first occurrence of the substring s2 in the string s1. The terminating '\0' characters
are not compared.
Returns
The strstr() function returns a pointer to the beginning of the substring, or NULL if the substring is not found.
If s2 points to a string of zero length, the function returns s1.
Returns
The strtok() function returns a pointer to the next token or NULL when no more tokens are found.
Note
strtok() is NOT reentrant. For a reentrant version of this function see strtok_r().
23.11.3.37 char ∗ strtok_r ( char ∗ string, const char ∗ delim, char ∗∗ last )
Returns
The strtok_r() function returns a pointer to the next token or NULL when no more tokens are found.
Returns
The strupr() function returns a pointer to the converted string. The pointer is the same as that passed in since
the operation is perform in place.
Data Structures
• struct tm
• struct week_date
Macros
Typedefs
Enumerations
• enum _WEEK_DAYS_ {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY }
• enum _MONTHS_ {
JANUARY, FEBRUARY, MARCH, APRIL,
MAY, JUNE, JULY, AUGUST,
SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }
Functions
#include <time.h>
In addition to C standard functions, re-entrant versions of ctime(), asctime(), gmtime() and localtime() are provided
which, in addition to being re-entrant, have the property of claiming less permanent storage in RAM. An additional
time conversion, isotime() and its re-entrant version, uses far less storage than either ctime() or asctime().
Along with the usual smattering of utility functions, such as is_leap_year(), this library includes a set of functions
related the sun and moon, as well as sidereal time functions.
Difference between the Y2K and the NTP epochs, in seconds. To convert a Y2K timestamp to NTP...
Difference between the Y2K and the UNIX epochs, in seconds. To convert a Y2K timestamp to UNIX...
1 long unix;
2 time_t y2k;
3
4 y2k = time(NULL);
5 unix = y2k + UNIX_OFFSET;
time_t represents seconds elapsed from Midnight, Jan 1 2000 UTC (the Y2K 'epoch'). Its range allows this imple-
mentation to represent time up to Tue Feb 7 06:28:15 2136 UTC.
The asctime function converts the broken-down time of timeptr, into an ascii string in the form
Sun Mar 23 01:03:52 2013
Computes the amount of time the sun is above the horizon, at the location of the observer.
NOTE: At observer locations inside a polar circle, this value can be zero during the winter, and can exceed ONE←-
_DAY during the summer.
The returned value is in seconds.
The difftime function returns the difference between two binary time stamps, time1 - time0.
Computes the difference between apparent solar time and mean solar time. The returned value is in seconds.
Convert a Y2K time stamp into a FAT file system time stamp.
Returns Greenwich Mean Sidereal Time, as seconds into the sidereal day. The returned value will range from 0
through 86399 seconds.
The gmtime function converts the time stamp pointed to by timer into broken-down time, expressed as UTC.
Return a week_date structure with the ISO_8601 week based date corresponding to the given year and day of year.
See http://en.wikipedia.org/wiki/ISO_week_date for more information.
1 2013-03-23 01:03:52
Returns Local Mean Sidereal Time, as seconds into the sidereal day. The returned value will range from 0 through
86399 seconds.
The localtime function converts the time stamp pointed to by timer into broken-down time, expressed as Local time.
This function 'compiles' the elements of a broken-down time structure, returning a binary time stamp. The elements
of timeptr are interpreted as representing UTC.
The original values of the tm_wday and tm_yday elements of the structure are ignored, and the original values of
the other elements are not restricted to the ranges stated for struct tm.
Unlike mktime(), this function DOES NOT modify the elements of timeptr.
This function 'compiles' the elements of a broken-down time structure, returning a binary time stamp. The elements
of timeptr are interpreted as representing Local Time.
The original values of the tm_wday and tm_yday elements of the structure are ignored, and the original values of
the other elements are not restricted to the ranges stated for struct tm.
On successful completion, the values of all elements of timeptr are set to the appropriate range.
Return the length of month, given the year and month, where month is in the range 1 to 12.
Returns an approximation to the phase of the moon. The sign of the returned value indicates a waning or waxing
phase. The magnitude of the returned value indicates the percentage illumination.
1 #include <util/eu_dst.h>
1 #include <util/usa_dst.h>
Set the geographic coordinates of the 'observer', for use with several of the following functions. Parameters are
passed as seconds of North Latitude, and seconds of East Longitude.
For New York City...
1 struct tm rtc_time;
2
3 read_rtc(&rtc_time);
4 rtc_time.tm_isdst = 0;
5 set_system_time( mktime(&rtc_time) );
1 set_system_time(ntp_timestamp - NTP_OFFSET);
1 set_system_time(unix_timestamp - UNIX_OFFSET);
Set the 'time zone'. The parameter is given in seconds East of the Prime Meridian. Example for New York City:
1 set_zone(-5 * ONE_HOUR);
If the time zone is not set, the time system will operate in UTC only.
23.12.5.30 size_t strftime ( char ∗ s, size_t maxsize, const char ∗ format, const struct tm ∗ timeptr )
A complete description of strftime() is beyond the pale of this document. Refer to ISO/IEC document 9899 for
details.
All conversions are made using the 'C Locale', ignoring the E or O modifiers. Due to the lack of a time zone 'name',
the 'Z' conversion is also ignored.
Return the time of sunrise, at the location of the observer. See the note about daylight_seconds().
Return the time of sunset, at the location of the observer. See the note about daylight_seconds().
1 ISR(RTC_OVF_vect, ISR_NAKED)
2 {
3 system_tick();
4 reti();
5 }
The time function returns the systems current time stamp. If timer is not a null pointer, the return value is also
assigned to the object it points to.
Return the calendar week of month, where the first week is considered to begin on the day of week specified by
'start'. The returned value may range from zero to 5.
Return the calendar week of year, where week 1 is considered to begin on the day of week specified by 'start'. The
returned value may range from zero to 52.
Macros
#include <avr/io.h>
#include <avr/boot.h>
The macros in this module provide a C language interface to the bootloader support functionality of certain AVR
processors. These macros are designed to work with all sizes of flash memory.
Global interrupts are not automatically disabled for these macros. It is left up to the programmer to do this. See
the code example below. Also see the processor datasheet for caveats on having global interrupts enabled during
writing of the Flash.
Note
Not all AVR processors provide bootloader support. See your processor datasheet to see if it provides boot-
loader support.
Todo 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.
#include <inttypes.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
uint8_t sreg;
// Disable interrupts.
sreg = SREG;
cli();
eeprom_busy_wait ();
boot_page_erase (page);
boot_spm_busy_wait (); // Wait until the memory is erased.
uint16_t w = *buf++;
w += (*buf++) << 8;
boot_rww_enable ();
SREG = sreg;
}
Note
In this context, a 'set bit' will be written to a zero value. Note also that only BLBxx bits can be programmed by
this command.
For example, to disallow the SPM instruction from writing to the Boot Loader memory section of flash, you would
use this macro as such:
Note
Like any lock bits, the Boot Loader Lock Bits, once set, cannot be cleared again except by a chip erase which
will in turn also erase the boot loader itself.
Value:
do { \
boot_spm_busy_wait(); \
eeprom_busy_wait(); \
boot_lock_bits_set (lock_bits); \
} while (0)
Same as boot_lock_bits_set() except waits for eeprom and spm operations to complete before setting the lock bits.
Value:
(__extension__({ \
uint8_t __result; \
__asm__ __volatile__ \
( \
"sts %1, %2\n\t" \
"lpm %0, Z\n\t" \
: "=r" (__result) \
: "i" (_SFR_MEM_ADDR(__SPM_REG)), \
"r" ((uint8_t)(__BOOT_LOCK_BITS_SET)), \
"z" ((uint16_t)(address)) \
); \
__result; \
}))
Note
The lock and fuse bits returned are the physical values, i.e. a bit returned as 0 means the corresponding fuse
or lock bit is programmed.
Note
Value:
do { \
boot_spm_busy_wait(); \
eeprom_busy_wait(); \
boot_page_erase (address); \
} while (0)
Same as boot_page_erase() except it waits for eeprom and spm operations to complete before erasing the page.
Fill the bootloader temporary page buffer for flash address with data word.
Note
The address is a byte address. The data is a word. The AVR writes data to the buffer a word at a time, but
addresses the buffer per byte! So, increment your address by 2 between calls, and send 2 data bytes in a
word format! The LSB of the data is written to the lower address; the MSB of the data is written to the higher
address.
Value:
do { \
boot_spm_busy_wait(); \
eeprom_busy_wait(); \
boot_page_fill(address, data); \
} while (0)
Same as boot_page_fill() except it waits for eeprom and spm operations to complete before filling the page.
Write the bootloader temporary page buffer to flash page that contains address.
Note
Value:
do { \
boot_spm_busy_wait(); \
eeprom_busy_wait(); \
boot_page_write (address); \
} while (0)
Same as boot_page_write() except it waits for eeprom and spm operations to complete before writing the page.
Value:
do { \
boot_spm_busy_wait(); \
eeprom_busy_wait(); \
boot_rww_enable(); \
} while (0)
Same as boot_rww_enable() except waits for eeprom and spm operations to complete before enabling the RWW
mameory.
Value:
(__extension__({ \
uint8_t __result; \
__asm__ __volatile__ \
( \
"sts %1, %2\n\t" \
"lpm %0, Z" "\n\t" \
: "=r" (__result) \
: "i" (_SFR_MEM_ADDR(__SPM_REG)), \
"r" ((uint8_t)(__BOOT_SIGROW_READ)), \
"z" ((uint16_t)(addr)) \
); \
__result; \
}))
Read the Signature Row byte at address. For some MCU types, this function can also retrieve the factory-stored
oscillator calibration bytes.
Parameter address can be 0-0x1f as documented by the datasheet.
Note
Used to declare a function or variable to be placed into a new section called .bootloader. This section and its
contents can then be relocated to any address (such as the bootloader NRWW area) at link-time.
Macros
• #define _NOP()
• #define _MemoryBarrier()
#include <avr/cpufunc.h>
This header file contains macros that access special functions of the AVR CPU which do not fit into any of the other
header files.
Implement a read/write memory barrier. A memory barrier instructs the compiler to not cache any memory data in
registers beyond the barrier. This can sometimes be more effective than blocking certain optimizations by declaring
some object with a volatile qualifier.
See Problems with reordering code for things to be taken into account with respect to compiler optimizations.
Execute a no operation (NOP) CPU instruction. This should not be used to implement delays, better use the
functions from <util/delay_basic.h> or <util/delay.h> for this. For debugging purposes, a NOP can be useful
to have an instruction that is guaranteed to be not optimized away by the compiler, so it can always become a
breakpoint in the debugger.
Macros
Functions
#include <avr/eeprom.h>
This header file declares the interface to some simple library routines suitable for handling the data EEPROM
contained in the AVR microcontrollers. The implementation uses a simple polled mode interface. Applications that
require interrupt-controlled EEPROM access to ensure that no time will be wasted in spinloops will have to deploy
their own implementation.
Notes:
• In addition to the write functions there is a set of update ones. This functions read each byte first and skip
the burning if the old value is the same with new. The scaning direction is from high address to low, to obtain
quick return in common cases.
• All of the read/write functions first make sure the EEPROM is ready to be accessed. Since this may cause
long delays if a write operation is still pending, time-critical applications should first poll the EEPROM e. g.
using eeprom_is_ready() before attempting any actual I/O. But this functions are not wait until SELFPRGEN
in SPMCSR becomes zero. Do this manually, if your softwate contains the Flash burning.
• As these functions modify IO registers, they are known to be non-reentrant. If any of these functions are used
from both, standard and interrupt context, the applications must ensure proper protection (e.g. by disabling
interrupts before accessing them).
• For Xmega the EEPROM start address is 0, like other architectures. The reading functions add the 0x2000
value to use EEPROM mapping into data space.
23.15.2.1 #define __EEGET( var, addr ) (var) = eeprom_read_byte ((const uint8_t ∗)(addr))
23.15.2.3 #define _EEGET( var, addr ) (var) = eeprom_read_byte ((const uint8_t ∗)(addr))
Returns
Nothing.
Returns
23.15.3.1 void eeprom_read_block ( void ∗ __dst, const void ∗ __src, size_t __n )
Read a block of __n bytes from EEPROM address __src to SRAM __dst.
Read one 32-bit double word (little endian) from EEPROM address __p.
Read one float value (little endian) from EEPROM address __p.
Read one 16-bit word (little endian) from EEPROM address __p.
23.15.3.6 void eeprom_update_block ( const void ∗ __src, void ∗ __dst, size_t __n )
Note
23.15.3.11 void eeprom_write_block ( const void ∗ __src, void ∗ __dst, size_t __n )
Note
Introduction
The Fuse API allows a user to specify the fuse settings for the specific AVR device they are compiling for. These
fuse settings will be placed in a special section in the ELF output file, after linking.
Programming tools can take advantage of the fuse information embedded in the ELF file, by extracting this informa-
tion and determining if the fuses need to be programmed before programming the Flash and EEPROM memories.
This also allows a single ELF file to contain all the information needed to program an AVR.
To use the Fuse API, include the <avr/io.h> header file, which in turn automatically includes the individual I/O
header file and the <avr/fuse.h> file. These other two files provides everything necessary to set the AVR fuses.
Fuse API
Each I/O header file must define the FUSE_MEMORY_SIZE macro which is defined to the number of fuse bytes
that exist in the AVR device.
A new type, __fuse_t, is defined as a structure. The number of fields in this structure are determined by the number
of fuse bytes in the FUSE_MEMORY_SIZE macro.
If FUSE_MEMORY_SIZE == 1, there is only a single field: byte, of type unsigned char.
If FUSE_MEMORY_SIZE == 2, there are two fields: low, and high, of type unsigned char.
If FUSE_MEMORY_SIZE == 3, there are three fields: low, high, and extended, of type unsigned char.
If FUSE_MEMORY_SIZE > 3, there is a single field: byte, which is an array of unsigned char with the size of the
array being FUSE_MEMORY_SIZE.
A convenience macro, FUSEMEM, is defined as a GCC attribute for a custom-named section of ".fuse".
A convenience macro, FUSES, is defined that declares a variable, __fuse, of type __fuse_t with the attribute defined
by FUSEMEM. This variable allows the end user to easily set the fuse data.
Note
If a device-specific I/O header file has previously defined FUSEMEM, then FUSEMEM is not redefined. If a
device-specific I/O header file has previously defined FUSES, then FUSES is not redefined.
Each AVR device I/O header file has a set of defined macros which specify the actual fuse bits available on that
device. The AVR fuses have inverted values, logical 1 for an unprogrammed (disabled) bit and logical 0 for a
programmed (enabled) bit. The defined macros for each individual fuse bit represent this in their definition by a
bit-wise inversion of a mask. For example, the FUSE_EESAVE fuse in the ATmega128 is defined as:
Note
The _BV macro creates a bit mask from a bit number. It is then inverted to represent logical values for a fuse
memory byte.
To combine the fuse bits macros together to represent a whole fuse byte, use the bitwise AND operator, like so:
Each device I/O header file also defines macros that provide default values for each fuse byte that is available.
LFUSE_DEFAULT is defined for a Low Fuse byte. HFUSE_DEFAULT is defined for a High Fuse byte. EFUSE_←-
DEFAULT is defined for an Extended Fuse byte.
If FUSE_MEMORY_SIZE > 3, then the I/O header file defines macros that provide default values for each fuse byte
like so: FUSE0_DEFAULT FUSE1_DEFAULT FUSE2_DEFAULT FUSE3_DEFAULT FUSE4_DEFAULT ....
#include <avr/io.h>
FUSES =
{
.low = LFUSE_DEFAULT,
.high = (FUSE_BOOTSZ0 & FUSE_BOOTSZ1 & FUSE_EESAVE & FUSE_SPIEN & FUSE_JTAGEN),
.extended = EFUSE_DEFAULT,
};
int main(void)
{
return 0;
}
#include <avr/io.h>
int main(void)
{
return 0;
}
If you are compiling in C++, you cannot use the designated intializers so you must do:
#include <avr/io.h>
FUSES =
{
LFUSE_DEFAULT, // .low
(FUSE_BOOTSZ0 & FUSE_BOOTSZ1 & FUSE_EESAVE & FUSE_SPIEN & FUSE_JTAGEN), // .high
EFUSE_DEFAULT, // .extended
};
int main(void)
{
return 0;
}
However there are a number of caveats that you need to be aware of to use this API properly.
Be sure to include <avr/io.h> to get all of the definitions for the API. The FUSES macro defines a global variable to
store the fuse data. This variable is assigned to its own linker section. Assign the desired fuse values immediately
in the variable initialization.
The .fuse section in the ELF file will get its values from the initial variable assignment ONLY. This means that you
can NOT assign values to this variable in functions and the new values will not be put into the ELF .fuse section.
The global variable is declared in the FUSES macro has two leading underscores, which means that it is reserved
for the "implementation", meaning the library, so it will not conflict with a user-named variable.
You must initialize ALL fields in the __fuse_t structure. This is because the fuse bits in all bytes default to a logical
1, meaning unprogrammed. Normal uninitialized data defaults to all locgial zeros. So it is vital that all fuse bytes are
initialized, even with default data. If they are not, then the fuse bits may not programmed to the desired settings.
Be sure to have the -mmcu=device flag in your compile command line and your linker command line to have the
correct device selected and to have the correct I/O header file included when you include <avr/io.h>.
You can print out the contents of the .fuse section in the ELF file by using this command line:
The section contents shows the address on the left, then the data going from lower address to a higher address,
left to right.
The global interrupt flag is maintained in the I bit of the status register (SREG).
Handling interrupts frequently requires attention regarding atomic access to objects that could be altered by code
running within an interrupt context, see <util/atomic.h>.
Frequently, interrupts are being disabled for periods of time in order to perform certain operations without being dis-
turbed; see Problems with reordering code for things to be taken into account with respect to compiler optimizations.
• #define sei()
• #define cli()
ISR attributes
• #define ISR_BLOCK
• #define ISR_NOBLOCK
• #define ISR_NAKED
• #define ISR_ALIASOF(target_vector)
Note
This discussion of interrupts was originally taken from Rich Neswold's document. See Acknowledgments.
It's nearly impossible to find compilers that agree on how to handle interrupt code. Since the C language tries to
stay away from machine dependent details, each compiler writer is forced to design their method of support.
In the AVR-GCC environment, the vector table is predefined to point to interrupt routines with predetermined names.
By using the appropriate name, your routine will be called when the corresponding interrupt occurs. The device
library provides a set of default interrupt routines, which will get used if you don't define your own.
Patching into the vector table is only one part of the problem. The compiler uses, by convention, a set of registers
when it's normally executing compiler-generated code. It's important that these registers, as well as the status
register, get saved and restored. The extra code needed to do this is enabled by tagging the interrupt function with
__attribute__((signal)).
These details seem to make interrupt routines a little messy, but all these details are handled by the Interrupt API.
An interrupt routine is defined with ISR(). This macro register and mark the routine as an interrupt handler for the
specified peripheral. The following is an example definition of a handler for the ADC interrupt.
#include <avr/interrupt.h>
ISR(ADC_vect)
{
// user code here
}
Refer to the chapter explaining assembler programming for an explanation about interrupt routines written solely in
assembler language.
If an unexpected interrupt occurs (interrupt is enabled and no handler is installed, which usually indicates a bug),
then the default action is to reset the device by jumping to the reset vector. You can override this by supplying a
function named BADISR_vect which should be defined with ISR() as such. (The name BADISR_vect is actually
an alias for __vector_default. The latter must be used inside assembly code in case <avr/interrupt.h> is not
included.)
#include <avr/interrupt.h>
ISR(BADISR_vect)
{
// user code here
}
Nested interrupts
The AVR hardware clears the global interrupt flag in SREG before entering an interrupt vector. Thus, normally
interrupts will remain disabled inside the handler until the handler exits, where the RETI instruction (that is emitted
by the compiler as part of the normal function epilogue for an interrupt handler) will eventually re-enable further
interrupts. For that reason, interrupt handlers normally do not nest. For most interrupt handlers, this is the desired
behaviour, for some it is even required in order to prevent infinitely recursive interrupts (like UART interrupts, or
level-triggered external interrupts). In rare circumstances though it might be desired to re-enable the global interrupt
flag as early as possible in the interrupt handler, in order to not defer any other interrupt more than absolutely
needed. This could be done using an sei() instruction right at the beginning of the interrupt handler, but this still
leaves few instructions inside the compiler-generated function prologue to run with global interrupts disabled. The
compiler can be instructed to insert an SEI instruction right at the beginning of an interrupt handler by declaring the
handler the following way:
ISR(XXX_vect, ISR_NOBLOCK)
{
...
}
where XXX_vect is the name of a valid interrupt vector for the MCU type in question, as explained below.
In some circumstances, the actions to be taken upon two different interrupts might be completely identical so a
single implementation for the ISR would suffice. For example, pin-change interrupts arriving from two different ports
could logically signal an event that is independent from the actual port (and thus interrupt vector) where it happened.
Sharing interrupt vector code can be accomplished using the ISR_ALIASOF() attribute to the ISR macro:
ISR(PCINT0_vect)
{
...
// Code to handle the event.
}
ISR(PCINT1_vect, ISR_ALIASOF(PCINT0_vect));
Note
Note that the ISR_ALIASOF() feature requires GCC 4.2 or above (or a patched version of GCC 4.1.x). See the
documentation of the ISR_ALIAS() macro for an implementation which is less elegant but could be applied to all
compiler versions.
In rare circumstances, in interrupt vector does not need any code to be implemented at all. The vector must be
declared anyway, so when the interrupt triggers it won't execute the BADISR_vect code (which by default restarts
the application).
This could for example be the case for interrupts that are solely enabled for the purpose of getting the controller out
of sleep_mode().
A handler for such an interrupt vector can be declared using the EMPTY_INTERRUPT() macro:
EMPTY_INTERRUPT(ADC_vect);
Note
In some circumstances, the compiler-generated prologue and epilogue of the ISR might not be optimal for the job,
and a manually defined ISR could be considered particularly to speedup the interrupt handling.
One solution to this could be to implement the entire ISR as manual assembly code in a separate (assembly) file.
See Combining C and assembly source files for an example of how to implement it that way.
Another solution is to still implement the ISR in C language but take over the compiler's job of generating the
prologue and epilogue. This can be done using the ISR_NAKED attribute to the ISR() macro. Note that the
compiler does not generate anything as prologue or epilogue, so the final reti() must be provided by the actual
implementation. SREG must be manually saved if the ISR code modifies it, and the compiler-implied assumption of
__zero_reg__ always being 0 could be wrong (e. g. when interrupting right after of a MUL instruction).
ISR(TIMER1_OVF_vect, ISR_NAKED)
{
PORTB |= _BV(0); // results in SBI which does not affect SREG
reti();
}
Note
The ISR() macro cannot really spell-check the argument passed to them. Thus, by misspelling one of the
names below in a call to ISR(), a function will be created that, while possibly being usable as an interrupt
function, is not actually wired into the interrupt vector table. The compiler will generate a warning if it detects
a suspiciously looking name of a ISR() function (i.e. one that after macro replacement does not start with
"__vector_").
1 #include <avr/interrupt.h>
This is a vector which is aliased to __vector_default, the vector executed when an ISR fires with no accompanying
ISR handler. This may be used along with the ISR() macro to create a catch-all for undefined but used ISRs for
debugging purposes.
Disables all interrupts by clearing the global interrupt mask. This function actually compiles into a single line of
assembly, so there is no function call overhead. However, the macro also implies a memory barrier which can
cause additional loss of optimization.
In order to implement atomic access to multi-byte objects, consider using the macros from <util/atomic.h>, rather
than implementing them manually with cli() and sei().
Defines an empty interrupt handler function. This will not generate any prolog or epilog code and will only return
from the ISR. Do not define a function body as this will define it for you. Example:
1 EMPTY_INTERRUPT(ADC_vect);
Introduces an interrupt handler function (interrupt service routine) that runs with global interrupts initially disabled
by default with no attributes specified.
The attributes are optional and alter the behaviour and resultant generated code of the interrupt routine. Multiple
attributes may be used for a single function, with a space seperating each attribute.
Valid attributes are ISR_BLOCK, ISR_NOBLOCK, ISR_NAKED and ISR_ALIASOF(vect).
vector must be one of the interrupt vector names that are valid for the particular MCU type.
Aliases a given vector to another one in the same manner as the ISR_ALIASOF attribute for the ISR() macro. Unlike
the ISR_ALIASOF attribute macro however, this is compatible for all versions of GCC rather than just GCC version
4.2 onwards.
Note
This macro creates a trampoline function for the aliased macro. This will result in a two cycle penalty for the
aliased vector compared to the ISR the vector is aliased to, due to the JMP/RJMP opcode used.
Example:
1 ISR(INT0_vect)
2 {
3 PORTB = 42;
4 }
5
6 ISR_ALIAS(INT1_vect, INT0_vect);
The ISR is linked to another ISR, specified by the vect parameter. This is compatible with GCC 4.2 and greater only.
Use this attribute in the attributes parameter of the ISR macro.
Identical to an ISR with no attributes specified. Global interrupts are initially disabled by the AVR hardware when
entering the ISR, without the compiler modifying this state.
Use this attribute in the attributes parameter of the ISR macro.
ISR is created with no prologue or epilogue code. The user code is responsible for preservation of the machine
state including the SREG register, as well as placing a reti() at the end of the interrupt routine.
Use this attribute in the attributes parameter of the ISR macro.
ISR runs with global interrupts initially enabled. The interrupt enable flag is activated by the compiler as early as
possible within the ISR to ensure minimal processing delay for nested interrupts.
This may be used to create nested ISRs, however care should be taken to avoid stack overflows, or to avoid infinitely
entering the ISR for those cases where the AVR hardware does not clear the respective interrupt flag before entering
the ISR.
Use this attribute in the attributes parameter of the ISR macro.
Returns from an interrupt routine, enabling global interrupts. This should be the last command executed before
leaving an ISR defined with the ISR_NAKED attribute.
This macro actually compiles into a single line of assembly, so there is no function call overhead.
Enables interrupts by setting the global interrupt mask. This function actually compiles into a single line of assembly,
so there is no function call overhead. However, the macro also implies a memory barrier which can cause additional
loss of optimization.
In order to implement atomic access to multi-byte objects, consider using the macros from <util/atomic.h>, rather
than implementing them manually with cli() and sei().
Introduces an interrupt handler function that runs with global interrupts initially disabled.
This is the same as the ISR macro without optional attributes.
Macros
#include <avr/io.h>
This header file includes the apropriate IO definitions for the device that has been specified by the -mmcu= compiler
command-line switch. This is done by diverting to the appropriate file <avr/ioXXXX.h> which should never be
included directly. Some register names common to all AVR devices are defined directly within <avr/common.←-
h>, which is included in <avr/io.h>, but most of the details come from the respective include file.
Note that this file always includes the following files:
#include <avr/sfr_defs.h>
#include <avr/portpins.h>
#include <avr/common.h>
#include <avr/version.h>
See <avr/sfr_defs.h>: Special function registers for more details about that header file.
Included are definitions of the IO register set and their respective bit values as specified in the Atmel documentation.
Note that inconsistencies in naming conventions, so even identical functions sometimes get different names on
different devices.
Also included are the specific names useable for interrupt function definitions as documented here.
Finally, the following macros are defined:
• RAMEND
The last on-chip RAM address.
• XRAMEND
The last possible RAM location that is addressable. This is equal to RAMEND for devices that do not allow
for external RAM. For devices that allow external RAM, this will be larger than RAMEND.
• E2END
The last EEPROM address.
• FLASHEND
The last byte address in the Flash program space.
• SPM_PAGESIZE
For devices with bootloader support, the flash pagesize (in bytes) to be used for the SPM instruction.
• E2PAGESIZE
The size of the EEPROM page.
Write value value to IO register reg that is protected through the Xmega configuration change protection (CCP)
mechanism. This implements the timed sequence that is required for CCP.
Example to modify the CPU clock:
1 #include <avr/io.h>
2
3 _PROTECTED_WRITE(CLK_PSCTRL, CLK_PSADIV0_bm);
4 _PROTECTED_WRITE(CLK_CTRL, CLK_SCLKSEL0_bm);
Introduction
The Lockbit API allows a user to specify the lockbit settings for the specific AVR device they are compiling for. These
lockbit settings will be placed in a special section in the ELF output file, after linking.
Programming tools can take advantage of the lockbit information embedded in the ELF file, by extracting this infor-
mation and determining if the lockbits need to be programmed after programming the Flash and EEPROM memo-
ries. This also allows a single ELF file to contain all the information needed to program an AVR.
To use the Lockbit API, include the <avr/io.h> header file, which in turn automatically includes the individual I/O
header file and the <avr/lock.h> file. These other two files provides everything necessary to set the AVR lockbits.
Lockbit API
Each I/O header file may define up to 3 macros that controls what kinds of lockbits are available to the user.
If __LOCK_BITS_EXIST is defined, then two lock bits are available to the user and 3 mode settings are defined for
these two bits.
If __BOOT_LOCK_BITS_0_EXIST is defined, then the two BLB0 lock bits are available to the user and 4 mode
settings are defined for these two bits.
If __BOOT_LOCK_BITS_1_EXIST is defined, then the two BLB1 lock bits are available to the user and 4 mode
settings are defined for these two bits.
If __BOOT_LOCK_APPLICATION_TABLE_BITS_EXIST is defined then two lock bits are available to set the locking
mode for the Application Table Section (which is used in the XMEGA family).
If __BOOT_LOCK_APPLICATION_BITS_EXIST is defined then two lock bits are available to set the locking mode
for the Application Section (which is used in the XMEGA family).
If __BOOT_LOCK_BOOT_BITS_EXIST is defined then two lock bits are available to set the locking mode for the
Boot Loader Section (which is used in the XMEGA family).
The AVR lockbit modes have inverted values, logical 1 for an unprogrammed (disabled) bit and logical 0 for a
programmed (enabled) bit. The defined macros for each individual lock bit represent this in their definition by a
bit-wise inversion of a mask. For example, the LB_MODE_3 macro is defined as:
To combine the lockbit mode macros together to represent a whole byte, use the bitwise AND operator, like so:
<avr/lock.h> also defines a macro that provides a default lockbit value: LOCKBITS_DEFAULT which is defined to
be 0xFF.
See the AVR device specific datasheet for more details about these lock bits and the available mode settings.
A convenience macro, LOCKMEM, is defined as a GCC attribute for a custom-named section of ".lock".
A convenience macro, LOCKBITS, is defined that declares a variable, __lock, of type unsigned char with the attribute
defined by LOCKMEM. This variable allows the end user to easily set the lockbit data.
Note
If a device-specific I/O header file has previously defined LOCKMEM, then LOCKMEM is not redefined. If a
device-specific I/O header file has previously defined LOCKBITS, then LOCKBITS is not redefined. LOCK←-
BITS is currently known to be defined in the I/O header files for the XMEGA devices.
#include <avr/io.h>
int main(void)
{
return 0;
}
Or:
#include <avr/io.h>
int main(void)
{
return 0;
}
However there are a number of caveats that you need to be aware of to use this API properly.
Be sure to include <avr/io.h> to get all of the definitions for the API. The LOCKBITS macro defines a global
variable to store the lockbit data. This variable is assigned to its own linker section. Assign the desired lockbit
values immediately in the variable initialization.
The .lock section in the ELF file will get its values from the initial variable assignment ONLY. This means that you
can NOT assign values to this variable in functions and the new values will not be put into the ELF .lock section.
The global variable is declared in the LOCKBITS macro has two leading underscores, which means that it is re-
served for the "implementation", meaning the library, so it will not conflict with a user-named variable.
You must initialize the lockbit variable to some meaningful value, even if it is the default value. This is because the
lockbits default to a logical 1, meaning unprogrammed. Normal uninitialized data defaults to all locgial zeros. So it
is vital that all lockbits are initialized, even with default data. If they are not, then the lockbits may not programmed
to the desired settings and can possibly put your device into an unrecoverable state.
Be sure to have the -mmcu=device flag in your compile command line and your linker command line to have the
correct device selected and to have the correct I/O header file included when you include <avr/io.h>.
You can print out the contents of the .lock section in the ELF file by using this command line:
Macros
Typedefs
Functions
#include <avr/io.h>
#include <avr/pgmspace.h>
The functions in this module provide interfaces for a program to access data stored in program space (flash memory)
of the device. In order to use these functions, the target device must support either the LPM or ELPM instructions.
Note
These functions are an attempt to provide some compatibility with header files that come with IAR C, to make
porting applications between different compilers easier. This is not 100% compatibility though (GCC does not
have full support for multiple address spaces yet).
If you are working with strings which are completely based in ram, use the standard string functions described
in <string.h>: Strings.
If possible, put your constant tables in the lower 64 KB and use pgm_read_byte_near() or pgm_read_word_←-
near() instead of pgm_read_byte_far() or pgm_read_word_far() since it is more efficient that way, and you can
still use the upper 64K for executable code. All functions that are suffixed with a _P require their arguments
to be in the lower 64 KB of the flash ROM, as they do not use ELPM instructions. This is normally not a
big concern as the linker setup arranges any program space constants declared using the macros from this
header file so they are placed right after the interrupt vectors, and in front of any executable code. However, it
can become a problem if there are too many of these constants, or for bootloaders on devices with more than
64 KB of ROM. All these functions will not work in that situation.
For Xmega devices, make sure the NVM controller command register (NVM.CMD or NVM_CMD) is set to 0x00
(NOP) before using any of these functions.
Value:
({ \
uint_farptr_t tmp; \
\
__asm__ __volatile__( \
\
"ldi %A0, lo8(%1)" "\n\t" \
"ldi %B0, hi8(%1)" "\n\t" \
"ldi %C0, hh8(%1)" "\n\t" \
"clr %D0" "\n\t" \
: \
"=d" (tmp) \
: \
"p" (&(var)) \
); \
tmp; \
})
This macro facilitates the obtention of a 32 bit "far" pointer (only 24 bits used) to data even passed the 64KB limit
for the 16 bit ordinary pointer. It is similar to the '&' operator, with some limitations.
Comments:
• The overhead is minimal and it's mainly due to the 32 bit size operation.
• 24 bit sizes guarantees the code compatibility for use in future devices.
• hh8() is an undocumented feature but seems to give the third significant byte of a 32 bit data and accepts
symbols, complementing the functionality of hi8() and lo8(). There is not an equivalent assembler function to
get the high significant byte.
• 'var' has to be resolved at linking time as an existing symbol, i.e, a simple type variable name, an array name
(not an indexed element of the array, if the index is a constant the compiler does not complain but fails to
get the address if optimization is enabled), a struct name or a struct field name, a function identifier, a linker
defined identifier,...
• The returned value is the identifier's VMA (virtual memory address) determined by the linker and falls in
the corresponding memory region. The AVR Harvard architecture requires non overlapping VMA areas
for the multiple address spaces in the processor: Flash ROM, RAM, and EEPROM. Typical offset for this
are 0x00000000, 0x00800xx0, and 0x00810000 respectively, derived from the linker script used and linker
options. The value returned can be seen then as a universal pointer.
Read a byte from the program space with a 16-bit (near) address.
Note
Read a byte from the program space with a 32-bit (far) address.
Note
Read a byte from the program space with a 16-bit (near) address.
Note
Read a double word from the program space with a 16-bit (near) address.
Note
Read a double word from the program space with a 32-bit (far) address.
Note
Read a double word from the program space with a 16-bit (near) address.
Note
Read a float from the program space with a 16-bit (near) address.
Note
Read a float from the program space with a 32-bit (far) address.
Note
Read a float from the program space with a 16-bit (near) address.
Note
Read a pointer from the program space with a 16-bit (near) address.
Note
Read a pointer from the program space with a 32-bit (far) address.
Note
Read a pointer from the program space with a 16-bit (near) address.
Note
Read a word from the program space with a 16-bit (near) address.
Note
Read a word from the program space with a 32-bit (far) address.
Note
Read a word from the program space with a 16-bit (near) address.
Note
23.20.3.1 prog_char
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of a "char" object located in flash ROM.
23.20.3.2 prog_int16_t
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of an "int16_t" object located in flash ROM.
23.20.3.3 prog_int32_t
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of an "int32_t" object located in flash ROM.
23.20.3.4 prog_int64_t
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of an "int64_t" object located in flash ROM.
Note
This type is not available when the compiler option -mint8 is in effect.
23.20.3.5 prog_int8_t
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of an "int8_t" object located in flash ROM.
23.20.3.6 prog_uchar
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of an "unsigned char" object located in flash ROM.
23.20.3.7 prog_uint16_t
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of an "uint16_t" object located in flash ROM.
23.20.3.8 prog_uint32_t
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of an "uint32_t" object located in flash ROM.
23.20.3.9 prog_uint64_t
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of an "uint64_t" object located in flash ROM.
Note
This type is not available when the compiler option -mint8 is in effect.
23.20.3.10 prog_uint8_t
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of an "uint8_t" object located in flash ROM.
23.20.3.11 prog_void
Note
DEPRECATED
This typedef is now deprecated because the usage of the __progmem__ attribute on a type is not supported in
GCC. However, the use of the __progmem__ attribute on a variable declaration is supported, and this is now the
recommended usage.
The typedef is only visible if the macro __PROG_TYPES_COMPAT__ has been defined before including
<avr/pgmspace.h> (either by a #define directive, or by a -D compiler option.)
Type of a "void" object located in flash ROM. Does not make much sense by itself, but can be used to declare a
"void ∗" object in flash ROM.
23.20.4.1 void ∗ memccpy_P ( void ∗ dest, const void ∗ src, int val, size_t len )
This function is similar to memccpy() except that src is pointer to a string in program space.
23.20.4.2 const void ∗ memchr_P ( const void ∗ s, int val, size_t len )
Returns
The memchr_P() function returns a pointer to the matching byte or NULL if the character does not occur in
the given memory area.
23.20.4.3 int memcmp_P ( const void ∗ s1, const void ∗ s2, size_t len )
Returns
The memcmp_P() function returns an integer less than, equal to, or greater than zero if the first len bytes of
s1 is found, respectively, to be less than, to match, or be greater than the first len bytes of s2.
23.20.4.4 int memcmp_PF ( const void ∗ s1, uint_farptr_t s2, size_t len )
Returns
The memcmp_PF() function returns an integer less than, equal to, or greater than zero if the first len bytes
of s1 is found, respectively, to be less than, to match, or be greater than the first len bytes of s2.
The memcpy_P() function is similar to memcpy(), except the src string resides in program space.
Returns
Returns
The memcpy_PF() function returns a pointer to dst. The contents of RAMPZ SFR are undefined when the
function returns.
23.20.4.7 void ∗ memmem_P ( const void ∗ s1, size_t len1, const void ∗ s2, size_t len2 )
The memmem_P() function is similar to memmem() except that s2 is pointer to a string in program space.
23.20.4.8 const void memrchr_P ( const void ∗ src, int val, size_t len )
The memrchr_P() function is like the memchr_P() function, except that it searches backwards from the end of the
len bytes pointed to by src instead of forwards from the front. (Glibc, GNU extension.)
Returns
The memrchr_P() function returns a pointer to the matching byte or NULL if the character does not occur in
the given memory area.
Returns
The strcasecmp_P() function returns an integer less than, equal to, or greater than zero if s1 is found, respec-
tively, to be less than, to match, or be greater than s2. A consequence of the ordering used by strcasecmp_P()
is that if s1 is an initial substring of s2, then s1 is considered to be "less than" s2.
Returns
The strcasecmp_PF() function returns an integer less than, equal to, or greater than zero if s1 is found,
respectively, to be less than, to match, or be greater than s2. The contents of RAMPZ SFR are undefined
when the function returns.
This funtion is similar to strcasestr() except that s2 is pointer to a string in program space.
The strcat_P() function is similar to strcat() except that the src string must be located in program space (flash).
Returns
Returns
The strcat_PF() function returns a pointer to the resulting string dst. The contents of RAMPZ SFR are unde-
fined when the function returns
Returns
The strchr_P() function returns a pointer to the matched character or NULL if the character is not found.
The strchrnul_P() function is like strchr_P() except that if c is not found in s, then it returns a pointer to the null byte
at the end of s, rather than NULL. (Glibc, GNU extension.)
Returns
The strchrnul_P() function returns a pointer to the matched character, or a pointer to the null byte at the end
of s (i.e., s+strlen(s)) if the character is not found.
The strcmp_P() function is similar to strcmp() except that s2 is pointer to a string in program space.
Returns
The strcmp_P() function returns an integer less than, equal to, or greater than zero if s1 is found, respectively,
to be less than, to match, or be greater than s2. A consequence of the ordering used by strcmp_P() is that if
s1 is an initial substring of s2, then s1 is considered to be "less than" s2.
Returns
The strcmp_PF() function returns an integer less than, equal to, or greater than zero if s1 is found, respectively,
to be less than, to match, or be greater than s2. The contents of RAMPZ SFR are undefined when the function
returns.
The strcpy_P() function is similar to strcpy() except that src is a pointer to a string in program space.
Returns
Duplicate a string.
The strcpy_PF() function is similar to strcpy() except that src is a far pointer to a string in program space.
Parameters
dst A pointer to the destination string in SRAM
src A far pointer to the source string in Flash
Returns
The strcpy_PF() function returns a pointer to the destination string dst. The contents of RAMPZ SFR are
undefined when the funcion returns.
The strcspn_P() function calculates the length of the initial segment of s which consists entirely of characters not in
reject. This function is similar to strcspn() except that reject is a pointer to a string in program space.
Returns
The strcspn_P() function returns the number of characters in the initial segment of s which are not in the string
reject. The terminating zero is not considered as a part of string.
23.20.4.21 size_t strlcat_P ( char ∗ dst, const char ∗ src, size_t siz )
Returns
The strlcat_P() function returns strlen(src) + MIN(siz, strlen(initial dst)). If retval >= siz, truncation occurred.
Returns
The strlcat_PF() function returns strlen(src) + MIN(n, strlen(initial dst)). If retval >= n, truncation occurred.
The contents of RAMPZ SFR are undefined when the funcion returns.
23.20.4.23 size_t strlcpy_P ( char ∗ dst, const char ∗ src, size_t siz )
Returns
The strlcpy_P() function returns strlen(src). If retval >= siz, truncation occurred.
Returns
The strlcpy_PF() function returns strlen(src). If retval >= siz, truncation occurred. The contents of RAMPZ
SFR are undefined when the function returns.
The strlen_P() function is similar to strlen(), except that src is a pointer to a string in program space.
Returns
Note
strlen_P() is implemented as an inline function in the avr/pgmspace.h header file, which will check if the length
of the string is a constant and known at compile time. If it is not known at compile time, the macro will issue a
call to __strlen_P() which will then calculate the length of the string as normal.
Returns
The strlen_PF() function returns the number of characters in s. The contents of RAMPZ SFR are undefined
when the function returns.
23.20.4.27 int strncasecmp_P ( const char ∗ s1, const char ∗ s2, size_t n )
Returns
The strncasecmp_P() function returns an integer less than, equal to, or greater than zero if s1 (or the first n
bytes thereof) is found, respectively, to be less than, to match, or be greater than s2. A consequence of the
ordering used by strncasecmp_P() is that if s1 is an initial substring of s2, then s1 is considered to be "less
than" s2.
Returns
The strncasecmp_PF() function returns an integer less than, equal to, or greater than zero if s1 (or the first n
bytes thereof) is found, respectively, to be less than, to match, or be greater than s2. The contents of RAMPZ
SFR are undefined when the function returns.
23.20.4.29 char ∗ strncat_P ( char ∗ dest, const char ∗ src, size_t len )
Returns
Returns
The strncat_PF() function returns a pointer to the resulting string dst. The contents of RAMPZ SFR are
undefined when the function returns.
23.20.4.31 int strncmp_P ( const char ∗ s1, const char ∗ s2, size_t n )
The strncmp_P() function is similar to strcmp_P() except it only compares the first (at most) n characters of s1 and
s2.
Returns
The strncmp_P() function returns an integer less than, equal to, or greater than zero if s1 (or the first n bytes
thereof) is found, respectively, to be less than, to match, or be greater than s2.
Parameters
s1 A pointer to the first string in SRAM
s2 A far pointer to the second string in Flash
n The maximum number of bytes to compare
Returns
The strncmp_PF() function returns an integer less than, equal to, or greater than zero if s1 (or the first n bytes
thereof) is found, respectively, to be less than, to match, or be greater than s2. The contents of RAMPZ SFR
are undefined when the function returns.
The strncpy_P() function is similar to strcpy_P() except that not more than n bytes of src are copied. Thus, if there
is no null byte among the first n bytes of src, the result will not be null-terminated.
In the case where the length of src is less than that of n, the remainder of dest will be padded with nulls.
Returns
Returns
The strncpy_PF() function returns a pointer to the destination string dst. The contents of RAMPZ SFR are
undefined when the function returns.
Returns
The strnlen_P function returns strlen_P(src), if that is less than len, or len if there is no '\0' character among
the first len characters pointed to by src.
Parameters
s A far pointer to the string in Flash
len The maximum number of length to return
Returns
The strnlen_PF function returns strlen_P(s), if that is less than len, or len if there is no '\0' character among
the first len characters pointed to by s. The contents of RAMPZ SFR are undefined when the function returns.
The strpbrk_P() function locates the first occurrence in the string s of any of the characters in the flash string
accept. This function is similar to strpbrk() except that accept is a pointer to a string in program space.
Returns
The strpbrk_P() function returns a pointer to the character in s that matches one of the characters in accept,
or NULL if no such character is found. The terminating zero is not considered as a part of string: if one or
both args are empty, the result will NULL.
Returns
The strrchr_P() function returns a pointer to the matched character or NULL if the character is not found.
Returns
The strsep_P() function returns a pointer to the original value of ∗sp. If ∗sp is initially NULL, strsep_P()
returns NULL.
The strspn_P() function calculates the length of the initial segment of s which consists entirely of characters in
accept. This function is similar to strspn() except that accept is a pointer to a string in program space.
Returns
The strspn_P() function returns the number of characters in the initial segment of s which consist only of
characters from accept. The terminating zero is not considered as a part of string.
Locate a substring.
The strstr_P() function finds the first occurrence of the substring s2 in the string s1. The terminating '\0' characters
are not compared. The strstr_P() function is similar to strstr() except that s2 is pointer to a string in program space.
Returns
The strstr_P() function returns a pointer to the beginning of the substring, or NULL if the substring is not found.
If s2 points to a string of zero length, the function returns s1.
Locate a substring.
The strstr_PF() function finds the first occurrence of the substring s2 in the string s1. The terminating '\0' characters
are not compared. The strstr_PF() function is similar to strstr() except that s2 is a far pointer to a string in program
space.
Returns
The strstr_PF() function returns a pointer to the beginning of the substring, or NULL if the substring is not
found. If s2 points to a string of zero length, the function returns s1. The contents of RAMPZ SFR are
undefined when the function returns.
Returns
The strtok_P() function returns a pointer to the next token or NULL when no more tokens are found.
Note
strtok_P() is NOT reentrant. For a reentrant version of this function see strtok_rP().
23.20.4.44 char ∗ strtok_rP ( char ∗ string, const char ∗ delim, char ∗∗ last )
Returns
The strtok_rP() function returns a pointer to the next token or NULL when no more tokens are found.
Functions
#include <avr/power.h>
Many AVRs contain a Power Reduction Register (PRR) or Registers (PRRx) that allow you to reduce power con-
sumption by disabling or enabling various on-board peripherals as needed. Some devices have the XTAL Divide
Control Register (XDIV) which offer similar functionality as System Clock Prescale Register (CLKPR).
There are many macros in this header file that provide an easy interface to enable or disable on-board peripherals
to reduce power. See the table below.
Note
Not all AVR devices have a Power Reduction Register (for example the ATmega8). On those devices without
a Power Reduction Register, the power reduction macros are not available..
Not all AVR devices contain the same peripherals (for example, the LCD interface), or they will be named
differently (for example, USART and USART0). Please consult your device's datasheet, or the header file, to
find out which macros are applicable to your device.
For device using the XTAL Divide Control Register (XDIV), when prescaler is used, Timer/Counter0 can only
be used in asynchronous mode. Keep in mind that Timer/Counter0 source shall be less than ¼th of peripheral
clock. Therefore, when using a typical 32.768 kHz crystal, one shall not scale the clock below 131.072 kHz.
Some of the newer AVRs contain a System Clock Prescale Register (CLKPR) that allows you to decrease the
system clock frequency and the power consumption when the need for processing power is low. On some earlier A←-
VRs (ATmega103, ATmega64, ATmega128), similar functionality can be achieved through the XTAL Divide Control
Register. Below are two macros and an enumerated type that can be used to interface to the Clock Prescale
Register or XTAL Divide Control Register.
Note
Not all AVR devices have a clock prescaler. On those devices without a Clock Prescale Register or XTAL
Divide Control Register, these macros are not available.
typedef enum
{
clock_div_1 = 0,
clock_div_2 = 1,
clock_div_4 = 2,
clock_div_8 = 3,
clock_div_16 = 4,
clock_div_32 = 5,
clock_div_64 = 6,
clock_div_128 = 7,
clock_div_256 = 8,
clock_div_1_rc = 15, // ATmega128RFA1 only
} clock_div_t;
Clock prescaler setting enumerations for device using System Clock Prescale Register.
typedef enum
{
clock_div_1 = 1,
clock_div_2 = 2,
clock_div_4 = 4,
clock_div_8 = 8,
clock_div_16 = 16,
clock_div_32 = 32,
clock_div_64 = 64,
clock_div_128 = 128
} clock_div_t;
Clock prescaler setting enumerations for device using XTAL Divide Control Register.
Set the clock prescaler register select bits, selecting a system clock division setting. This function is inlined, even if
compiler optimizations are disabled.
The type of x is clock_div_t.
Note
For device with XTAL Divide Control Register (XDIV), x can actually range from 1 to 129. Thus, one does not
need to use clock_div_t type as argument.
The <avr/sfr_defs.h> file is included by all of the <avr/ioXXXX.h> files, which use macros defined
here to make the special function register definitions look like C variables or simple constants, depending on the
_SFR_ASM_COMPAT define. Some examples from <avr/iocanxx.h> to show how to define such macros:
If _SFR_ASM_COMPAT is not defined, C programs can use names like PORTA directly in C expressions (also on
the left side of assignment operators) and GCC will do the right thing (use short I/O instructions if possible). The
__SFR_OFFSET definition is not used in any way in this case.
Define _SFR_ASM_COMPAT as 1 to make these names work as simple constants (addresses of the I/O registers).
This is necessary when included in preprocessed assembler (∗.S) source files, so it is done automatically if _←-
_ASSEMBLER__ is defined. By default, all addresses are defined as if they were memory addresses (used in
lds/sts instructions). To use these addresses in in/out instructions, you must subtract 0x20 from them.
For more backwards compatibility, insert the following at the start of your old assembler source file:
#define __SFR_OFFSET 0
This automatically subtracts 0x20 from I/O space addresses, but it's a hack, so it is recommended to change your
source: wrap such addresses in macros defined here, as shown below. After this is done, the __SFR_OFFSET
definition is no longer necessary and can be removed.
Real example - this code could be used in a boot loader that is portable between devices with SPMCR at different
addresses.
#if _SFR_IO_REG_P(SPMCR)
out _SFR_IO_ADDR(SPMCR), r24
#else
sts _SFR_MEM_ADDR(SPMCR), r24
#endif
You can use the in/out/cbi/sbi/sbic/sbis instructions, without the _SFR_IO_REG_P test, if you know
that the register is in the I/O space (as with SREG, for example). If it isn't, the assembler will complain (I/O address
out of range 0...0x3f), so this should be fairly safe.
If you do not define __SFR_OFFSET (so it will be 0x20 by default), all special register addresses are defined as
memory addresses (so SREG is 0x5f), and (if code size and speed are not important, and you don't like the ugly
#if above) you can always use lds/sts to access them. But, this will not work if __SFR_OFFSET != 0x20, so use a
different macro (defined only if __SFR_OFFSET == 0x20) for safety:
In C programs, all 3 combinations of _SFR_ASM_COMPAT and __SFR_OFFSET are supported - the _SFR_A←-
DDR(SPMCR) macro can be used to get the address of the SPMCR register (0x57 or 0x68 depending on device).
Modules
Bit manipulation
When working with microcontrollers, many tasks usually consist of controlling internal peripherals, or external pe-
ripherals that are connected to the device. The entire IO address space is made available as memory-mapped IO,
i.e. it can be accessed using all the MCU instructions that are applicable to normal data memory. For most AVR
devices, the IO register space is mapped into the data memory address space with an offset of 0x20 since the
bottom of this space is reserved for direct access to the MCU registers. (Actual SRAM is available only behind the
IO register area, starting at some specific address depending on the device.)
For example the user can access memory-mapped IO registers as if they were globally defined variables like this:
PORTA = 0x33;
unsigned char foo = PINA;
The compiler will choose the correct instruction sequence to generate based on the address of the register being
accessed.
The advantage of using the memory-mapped registers in C programs is that it makes the programs more portable
to other C compilers for the AVR platform.
Note that special care must be taken when accessing some of the 16-bit timer IO registers where access from both
the main program and within an interrupt context can happen. See Why do some 16-bit timer registers sometimes
get trashed?.
Access to the AVR single bit set and clear instructions are provided via the standard C bit manipulation commands.
The sbi and cbi macros are no longer directly supported. sbi (sfr,bit) can be replaced by sfr |= _BV(bit) .
i.e.: sbi(PORTB, PB1); is now PORTB |= _BV(PB1);
This actually is more flexible than having sbi directly, as the optimizer will use a hardware sbi if appropriate, or a
read/or/write operation if not appropriate. You do not need to keep track of which registers sbi/cbi will operate on.
Likewise, cbi (sfr,bit) is now sfr &= ∼(_BV(bit));
1 #include <avr/io.h>
Note
The bit shift is performed by the compiler which then inserts the result into the code. Thus, there is no run-time
overhead when using _BV().
1 #include <avr/io.h>
Test whether bit bit in IO register sfr is clear. This will return non-zero if the bit is clear, and a 0 if the bit is set.
1 #include <avr/io.h>
Test whether bit bit in IO register sfr is set. This will return a 0 if the bit is clear, and non-zero if the bit is set.
1 #include <avr/io.h>
1 #include <avr/io.h>
Introduction
The <avr/signature.h> header file allows the user to automatically and easily include the device's signature data in
a special section of the final linked ELF file.
This value can then be used by programming software to compare the on-device signature with the signature
recorded in the ELF file to look for a match before programming the device.
#include <avr/signature.h>
This will declare a constant unsigned char array and it is initialized with the three signature bytes, MSB first, that are
defined in the device I/O header file. This array is then placed in the .signature section in the resulting linked ELF
file.
The three signature bytes that are used to initialize the array are these defined macros in the device I/O header file,
from MSB to LSB: SIGNATURE_2, SIGNATURE_1, SIGNATURE_0.
This header file should only be included once in an application.
Functions
#include <avr/sleep.h>
Use of the SLEEP instruction can allow an application to reduce its power comsumption considerably. AVR devices
can be put into different sleep modes. Refer to the datasheet for the details relating to the device you are using.
There are several macros provided in this header file to actually put the device into sleep mode. The simplest way
is to optionally set the desired sleep mode using set_sleep_mode() (it usually defaults to idle mode where
the CPU is put on sleep but all peripheral clocks are still running), and then call sleep_mode(). This macro
automatically sets the sleep enable bit, goes to sleep, and clears the sleep enable bit.
Example:
#include <avr/sleep.h>
...
set_sleep_mode(<mode>);
sleep_mode();
Note that unless your purpose is to completely lock the CPU (until a hardware reset), interrupts need to be enabled
before going to sleep.
As the sleep_mode() macro might cause race conditions in some situations, the individual steps of manipulating
the sleep enable (SE) bit, and actually issuing the SLEEP instruction, are provided in the macros sleep_←-
enable(), sleep_disable(), and sleep_cpu(). This also allows for test-and-sleep scenarios that take
care of not missing the interrupt that will awake the device from sleep.
Example:
#include <avr/interrupt.h>
#include <avr/sleep.h>
...
set_sleep_mode(<mode>);
cli();
if (some_condition)
{
sleep_enable();
sei();
sleep_cpu();
sleep_disable();
}
sei();
This sequence ensures an atomic test of some_condition with interrupts being disabled. If the condition is met,
sleep mode will be prepared, and the SLEEP instruction will be scheduled immediately after an SEI instruction. As
the intruction right after the SEI is guaranteed to be executed before an interrupt could trigger, it is sure the device
will really be put to sleep.
Some devices have the ability to disable the Brown Out Detector (BOD) before going to sleep. This will also reduce
power while sleeping. If the specific AVR device has this ability then an additional macro is defined: sleep_bod←-
_disable(). This macro generates inlined assembly code that will correctly implement the timed sequence for
disabling the BOD before sleeping. However, there is a limited number of cycles after the BOD has been disabled
that the device can be put into sleep mode, otherwise the BOD will not truly be disabled. Recommended practice
is to disable the BOD (sleep_bod_disable()), set the interrupts (sei()), and then put the device to sleep
(sleep_cpu()), like so:
#include <avr/interrupt.h>
#include <avr/sleep.h>
...
set_sleep_mode(<mode>);
cli();
if (some_condition)
{
sleep_enable();
sleep_bod_disable();
sei();
sleep_cpu();
sleep_disable();
}
sei();
Put the device into sleep mode. The SE bit must be set beforehand, and it is recommended to clear it afterwards.
Put the device in sleep mode. How the device is brought out of sleep mode depends on the specific mode selected
with the set_sleep_mode() function. See the data sheet for your device for more details.
Set the SE (sleep enable) bit.
Put the device into sleep mode, taking care of setting the SE bit before, and clearing it afterwards.
Macros
#include <avr/version.h>
This header file defines macros that contain version numbers and strings describing the current version of avr-libc.
The version number itself basically consists of three pieces that are separated by a dot: the major number, the
minor number, and the revision number. For development versions (which use an odd minor number), the string
representation additionally gets the date code (YYYYMMDD) appended.
This file will also be included by <avr/io.h>. That way, portable tests can be implemented using <avr/io.←-
h> that can be used in code that wants to remain backwards-compatible to library versions prior to the date when
the library version API had been added, as referenced but undefined C preprocessor macros automatically evaluate
to 0.
Macros
Functions
#include <avr/wdt.h>
This header file declares the interface to some inline macros handling the watchdog timer present in many A←-
VR devices. In order to prevent the watchdog timer configuration from being accidentally altered by a crashing
application, a special timed sequence is required in order to change it. The macros within this header file handle
the required sequence automatically before changing any value. Interrupts will be disabled during the manipulation.
Note
Depending on the fuse configuration of the particular device, further restrictions might apply, in particular it
might be disallowed to turn off the watchdog timer.
Note that for newer devices (ATmega88 and newer, effectively any AVR that has the option to also generate inter-
rupts), the watchdog timer remains active even after a system reset (except a power-on condition), using the fastest
prescaler value (approximately 15 ms). It is therefore required to turn off the watchdog early during program startup,
the datasheet recommends a sequence like the following:
#include <stdint.h>
#include <avr/wdt.h>
void get_mcusr(void) \
__attribute__((naked)) \
__attribute__((section(".init3")));
void get_mcusr(void)
{
mcusr_mirror = MCUSR;
MCUSR = 0;
wdt_disable();
}
Saving the value of MCUSR in mcusr_mirror is only needed if the application later wants to examine the reset
source, but in particular, clearing the watchdog reset flag before disabling the watchdog is required, according to
the datasheet.
Reset the watchdog timer. When the watchdog timer is enabled, a call to this instruction is required before the timer
expires, otherwise a watchdog-initiated device reset will occur.
See WDTO_15MS
Symbolic constants for the watchdog timeout. Since the watchdog timer is based on a free-running RC oscillator,
the times are approximate only and apply to a supply voltage of 5 V. At lower supply voltages, the times will increase.
For older devices, the times will be as large as three times when operating at Vcc = 3 V, while the newer devices (e.
g. ATmega128, ATmega8) only experience a negligible change.
Possible timeout values are: 15 ms, 30 ms, 60 ms, 120 ms, 250 ms, 500 ms, 1 s, 2 s. (Some devices also allow for
4 s and 8 s.) Symbolic constants are formed by the prefix WDTO_, followed by the time.
Example that would select a watchdog timer expiry of approximately 500 ms:
1 wdt_enable(WDTO_500MS);
See WDTO_15MS
See WDTO_15MS
See WDTO_15MS
See WDTO_15MS
See WDTO_15MS Note: This is only available on the ATtiny2313, ATtiny24, ATtiny44, ATtiny84, ATtiny84A, A←-
Ttiny25, ATtiny45, ATtiny85, ATtiny261, ATtiny461, ATtiny861, ATmega48, ATmega88, ATmega168, ATmega48P,
ATmega88P, ATmega168P, ATmega328P, ATmega164P, ATmega324P, ATmega644P, ATmega644, ATmega640,
ATmega1280, ATmega1281, ATmega2560, ATmega2561, ATmega8HVA, ATmega16HVA, ATmega32HVB, A←-
Tmega406, ATmega1284P, AT90PWM1, AT90PWM2, AT90PWM2B, AT90PWM3, AT90PWM3B, AT90PWM216,
AT90PWM316, AT90PWM81, AT90PWM161, AT90USB82, AT90USB162, AT90USB646, AT90USB647, AT90←-
USB1286, AT90USB1287, ATtiny48, ATtiny88.
See WDTO_15MS
See WDTO_15MS
See WDTO_15MS Note: This is only available on the ATtiny2313, ATtiny24, ATtiny44, ATtiny84, ATtiny84←-
A, ATtiny25, ATtiny45, ATtiny85, ATtiny261, ATtiny461, ATtiny861, ATmega48, ATmega48A, ATmega48PA, A←-
Tmega88, ATmega168, ATmega48P, ATmega88P, ATmega168P, ATmega328P, ATmega164P, ATmega324P, A←-
Tmega644P, ATmega644, ATmega640, ATmega1280, ATmega1281, ATmega2560, ATmega2561, ATmega8←-
HVA, ATmega16HVA, ATmega32HVB, ATmega406, ATmega1284P, ATmega2564RFR2, ATmega256RFR2, A←-
Tmega1284RFR2, ATmega128RFR2, ATmega644RFR2, ATmega64RFR2 AT90PWM1, AT90PWM2, AT90PW←-
M2B, AT90PWM3, AT90PWM3B, AT90PWM216, AT90PWM316, AT90PWM81, AT90PWM161, AT90USB82, A←-
T90USB162, AT90USB646, AT90USB647, AT90USB1286, AT90USB1287, ATtiny48, ATtiny88, ATxmega16a4u,
ATxmega32a4u, ATxmega16c4, ATxmega32c4, ATxmega128c3, ATxmega192c3, ATxmega256c3.
Enable the watchdog timer, configuring it for expiry after timeout (which is a combination of the WDP0 through
WDP2 bits to write into the WDTCR register; For those devices that have a WDTCSR register, it uses the combination
of the WDP0 through WDP3 bits).
See also the symbolic constants WDTO_15MS et al.
Macros
• #define ATOMIC_BLOCK(type)
• #define NONATOMIC_BLOCK(type)
• #define ATOMIC_RESTORESTATE
• #define ATOMIC_FORCEON
• #define NONATOMIC_RESTORESTATE
• #define NONATOMIC_FORCEOFF
#include <util/atomic.h>
Note
The macros in this header file require the ISO/IEC 9899:1999 ("ISO C99") feature of for loop variables that are
declared inside the for loop itself. For that reason, this header file can only be used if the standard level of the
compiler (option –std=) is set to either c99 or gnu99.
The macros in this header file deal with code blocks that are guaranteed to be excuted Atomically or Non-←-
Atmomically. The term "Atomic" in this context refers to the unability of the respective code to be interrupted.
These macros operate via automatic manipulation of the Global Interrupt Status (I) bit of the SREG register. Exit
paths from both block types are all managed automatically without the need for special considerations, i. e. the
interrupt status will be restored to the same value it has been when entering the respective block.
A typical example that requires atomic access is a 16 (or more) bit variable that is shared between the main execution
path and an ISR. While declaring such a variable as volatile ensures that the compiler will not optimize accesses to
it away, it does not guarantee atomic access to it. Assuming the following example:
#include <inttypes.h>
#include <avr/interrupt.h>
#include <avr/io.h>
ISR(TIMER1_OVF_vect)
{
ctr--;
}
...
int
main(void)
{
...
ctr = 0x200;
start_timer();
while (ctr != 0)
// wait
;
...
}
There is a chance where the main context will exit its wait loop when the variable ctr just reached the value 0xFF.
This happens because the compiler cannot natively access a 16-bit variable atomically in an 8-bit CPU. So the
variable is for example at 0x100, the compiler then tests the low byte for 0, which succeeds. It then proceeds to
test the high byte, but that moment the ISR triggers, and the main context is interrupted. The ISR will decrement
the variable from 0x100 to 0xFF, and the main context proceeds. It now tests the high byte of the variable which is
(now) also 0, so it concludes the variable has reached 0, and terminates the loop.
Using the macros from this header file, the above code can be rewritten like:
#include <inttypes.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <util/atomic.h>
ISR(TIMER1_OVF_vect)
{
ctr--;
}
...
int
main(void)
{
...
ctr = 0x200;
start_timer();
sei();
uint16_t ctr_copy;
do
{
ATOMIC_BLOCK(ATOMIC_FORCEON)
{
ctr_copy = ctr;
}
}
while (ctr_copy != 0);
...
}
This will install the appropriate interrupt protection before accessing variable ctr, so it is guaranteed to be consis-
tently tested. If the global interrupt state were uncertain before entering the ATOMIC_BLOCK, it should be executed
with the parameter ATOMIC_RESTORESTATE rather than ATOMIC_FORCEON.
See Problems with reordering code for things to be taken into account with respect to compiler optimizations.
Creates a block of code that is guaranteed to be executed atomically. Upon entering the block the Global Interrupt
Status flag in SREG is disabled, and re-enabled upon exiting the block from any exit path.
Two possible macro parameters are permitted, ATOMIC_RESTORESTATE and ATOMIC_FORCEON.
This is a possible parameter for ATOMIC_BLOCK. When used, it will cause the ATOMIC_BLOCK to force the state
of the SREG register on exit, enabling the Global Interrupt Status flag bit. This saves on flash space as the previous
value of the SREG register does not need to be saved at the start of the block.
Care should be taken that ATOMIC_FORCEON is only used when it is known that interrupts are enabled before
the block's execution or when the side effects of enabling global interrupts at the block's completion are known and
understood.
This is a possible parameter for ATOMIC_BLOCK. When used, it will cause the ATOMIC_BLOCK to restore the
previous state of the SREG register, saved before the Global Interrupt Status flag bit was disabled. The net effect
of this is to make the ATOMIC_BLOCK's contents guaranteed atomic, without changing the state of the Global
Interrupt Status flag when execution of the block completes.
Creates a block of code that is executed non-atomically. Upon entering the block the Global Interrupt Status flag
in SREG is enabled, and disabled upon exiting the block from any exit path. This is useful when nested inside
ATOMIC_BLOCK sections, allowing for non-atomic execution of small blocks of code while maintaining the atomic
access of the other sections of the parent ATOMIC_BLOCK.
This is a possible parameter for NONATOMIC_BLOCK. When used, it will cause the NONATOMIC_BLOCK to force
the state of the SREG register on exit, disabling the Global Interrupt Status flag bit. This saves on flash space as
the previous value of the SREG register does not need to be saved at the start of the block.
Care should be taken that NONATOMIC_FORCEOFF is only used when it is known that interrupts are disabled
before the block's execution or when the side effects of disabling global interrupts at the block's completion are
known and understood.
This is a possible parameter for NONATOMIC_BLOCK. When used, it will cause the NONATOMIC_BLOCK to
restore the previous state of the SREG register, saved before the Global Interrupt Status flag bit was enabled. The
net effect of this is to make the NONATOMIC_BLOCK's contents guaranteed non-atomic, without changing the
state of the Global Interrupt Status flag when execution of the block completes.
Functions
#include <util/crc16.h>
This header file provides a optimized inline functions for calculating cyclic redundancy checks (CRC) using common
polynomials.
References:
See the Dallas Semiconductor app note 27 for 8051 assembler example and general CRC optimization suggestions.
The table on the last page of the app note is the key to understanding these implementations.
Jack Crenshaw's "Implementing CRCs" article in the January 1992 isue of Embedded Systems Programming. This
may be difficult to find, but it explains CRC's in very clear and concise terms. Well worth the effort to obtain a copy.
A typical application would look like:
int
checkcrc(void)
{
uint8_t crc = 0, i;
23.29.2.1 static __inline__ uint16_t _crc16_update ( uint16_t __crc, uint8_t __data ) [static]
1 uint16_t
2 crc16_update(uint16_t crc, uint8_t a)
3 {
4 int i;
5
6 crc ^= a;
7 for (i = 0; i < 8; ++i)
8 {
9 if (crc & 1)
10 crc = (crc >> 1) ^ 0xA001;
11 else
12 crc = (crc >> 1);
13 }
14
15 return crc;
16 }
23.29.2.2 static __inline__ uint8_t _crc8_ccitt_update ( uint8_t __crc, uint8_t __data ) [static]
1 uint8_t
2 _crc8_ccitt_update (uint8_t inCrc, uint8_t inData)
3 {
4 uint8_t i;
5 uint8_t data;
6
7 data = inCrc ^ inData;
8
9 for ( i = 0; i < 8; i++ )
10 {
11 if (( data & 0x80 ) != 0 )
12 {
13 data <<= 1;
14 data ^= 0x07;
15 }
16 else
17 {
18 data <<= 1;
19 }
20 }
21 return data;
22 }
23.29.2.3 static __inline__ uint16_t _crc_ccitt_update ( uint16_t __crc, uint8_t __data ) [static]
Note
Although the CCITT polynomial is the same as that used by the Xmodem protocol, they are quite different.
The difference is in how the bits are shifted through the alorgithm. Xmodem shifts the MSB of the CRC and
the input first, while CCITT shifts the LSB of the CRC and the input first.
1 uint16_t
2 crc_ccitt_update (uint16_t crc, uint8_t data)
3 {
4 data ^= lo8 (crc);
5 data ^= data << 4;
6
7 return ((((uint16_t)data << 8) | hi8 (crc)) ^ (uint8_t)(data >> 4)
8 ^ ((uint16_t)data << 3));
9 }
23.29.2.4 static __inline__ uint8_t _crc_ibutton_update ( uint8_t __crc, uint8_t __data ) [static]
1 uint8_t
2 _crc_ibutton_update(uint8_t crc, uint8_t data)
3 {
4 uint8_t i;
5
6 crc = crc ^ data;
7 for (i = 0; i < 8; i++)
8 {
9 if (crc & 0x01)
10 crc = (crc >> 1) ^ 0x8C;
11 else
12 crc >>= 1;
13 }
14
15 return crc;
16 }
23.29.2.5 static __inline__ uint16_t _crc_xmodem_update ( uint16_t __crc, uint8_t __data ) [static]
1 uint16_t
2 crc_xmodem_update (uint16_t crc, uint8_t data)
3 {
4 int i;
5
6 crc = crc ^ ((uint16_t)data << 8);
7 for (i=0; i<8; i++)
8 {
9 if (crc & 0x8000)
10 crc = (crc << 1) ^ 0x1021;
11 else
12 crc <<= 1;
13 }
14
15 return crc;
16 }
Macros
Functions
Note
As an alternative method, it is possible to pass the F_CPU macro down to the compiler from the Makefile.
Obviously, in that case, no #define statement should be used.
The functions in this header file are wrappers around the basic busy-wait functions from <util/delay_basic.h>. They
are meant as convenience functions where actual time values can be specified rather than a number of cycles to
wait for. The idea behind is that compile-time constant expressions will be eliminated by compiler optimization so
floating-point expressions can be used to calculate the number of delay cycles needed based on the CPU frequency
passed by the macro F_CPU.
Note
In order for these functions to work as intended, compiler optimizations must be enabled, and the delay time
must be an expression that is a known constant at compile-time. If these requirements are not met, the
resulting delay will be much longer (and basically unpredictable), and applications that otherwise do not use
floating-point calculations will experience severe code bloat by the floating-point library routines linked into the
application.
The functions available allow the specification of microsecond, and millisecond delays directly, using the application-
supplied macro F_CPU as the CPU clock frequency (in Hertz).
The macro F_CPU is supposed to be defined to a constant defining the CPU clock frequency (in Hertz).
The maximal possible delay is 262.14 ms / F_CPU in MHz.
When the user request delay which exceed the maximum possible one, _delay_ms() provides a decreased reso-
lution functionality. In this mode _delay_ms() will work with a resolution of 1/10 ms, providing delays up to 6.5535
seconds (independent from CPU frequency). The user will not be informed about decreased resolution.
If the avr-gcc toolchain has __builtin_avr_delay_cycles() support, maximal possible delay is 4294967.295 ms/ F_←-
CPU in MHz. For values greater than the maximal possible delay, overflows results in no delay i.e., 0ms.
Conversion of __ms into clock cycles may not always result in integer. By default, the clock cycles rounded up to
next integer. This ensures that the user gets at least __ms microseconds of delay.
Alternatively, by defining the macro __DELAY_ROUND_DOWN__, or __DELAY_ROUND_CLOSEST__, before
including this header file, the algorithm can be made to round down, or round to closest integer, respectively.
Note
The implementation of _delay_ms() based on __builtin_avr_delay_cycles() is not backward compatible with older
implementations. In order to get functionality backward compatible with previous versions, the macro "__DELAY←-
_BACKWARD_COMPATIBLE__" must be defined before including this header file. Also, the backward compatible
algorithm will be chosen if the code is compiled in a freestanding environment (GCC option -ffreestanding),
as the math functions required for rounding are not available to the compiler then.
Note
The implementation of _delay_ms() based on __builtin_avr_delay_cycles() is not backward compatible with older
implementations. In order to get functionality backward compatible with previous versions, the macro __DELAY←-
_BACKWARD_COMPATIBLE__ must be defined before including this header file. Also, the backward compatible
algorithm will be chosen if the code is compiled in a freestanding environment (GCC option -ffreestanding),
as the math functions required for rounding are not available to the compiler then.
Functions
#include <util/delay_basic.h>
The functions in this header file implement simple delay loops that perform a busy-waiting. They are typically used
to facilitate short delays in the program execution. They are implemented as count-down loops with a well-known
CPU cycle count per loop iteration. As such, no other processing can occur simultaneously. It should be kept in
mind that the functions described here do not disable interrupts.
In general, for long delays, the use of hardware timers is much preferrable, as they free the CPU, and allow for
concurrent processing of other events while the timer is running. However, in particular for very short delays, the
overhead of setting up a hardware timer is too much compared to the overall delay time.
Two inline functions are provided for the actual delay algorithms.
Delay loop using an 8-bit counter __count, so up to 256 iterations are possible. (The value 256 would have to be
passed as 0.) The loop executes three CPU cycles per iteration, not including the overhead the compiler needs to
setup the counter register.
Thus, at a CPU speed of 1 MHz, delays of up to 768 microseconds can be achieved.
Delay loop using a 16-bit counter __count, so up to 65536 iterations are possible. (The value 65536 would have to
be passed as 0.) The loop executes four CPU cycles per iteration, not including the overhead the compiler requires
to setup the counter register pair.
Thus, at a CPU speed of 1 MHz, delays of up to about 262.1 milliseconds can be achieved.
Macros
• #define parity_even_bit(val)
#include <util/parity.h>
This header file contains optimized assembler code to calculate the parity bit for a byte.
Value:
(__extension__({ \
unsigned char __t; \
__asm__ ( \
"mov __tmp_reg__,%0" "\n\t" \
"swap %0" "\n\t" \
"eor %0,__tmp_reg__" "\n\t" \
"mov __tmp_reg__,%0" "\n\t" \
"lsr %0" "\n\t" \
"lsr %0" "\n\t" \
"eor %0,__tmp_reg__" \
: "=r" (__t) \
: "0" ((unsigned char)(val)) \
: "r0" \
); \
(((__t + 1) >> 1) & 1); \
}))
Returns
Macros
• #define BAUD_TOL 2
• #define UBRR_VALUE
• #define UBRRL_VALUE
• #define UBRRH_VALUE
• #define USE_2X 0
This header file requires that on entry values are already defined for F_CPU and BAUD. In addition, the macro
BAUD_TOL will define the baud rate tolerance (in percent) that is acceptable during the calculations. The value of
BAUD_TOL will default to 2 %.
This header file defines macros suitable to setup the UART baud rate prescaler registers of an AVR. All calculations
are done using the C preprocessor. Including this header file causes no other side effects so it is possible to include
this file more than once (supposedly, with different values for the BAUD parameter), possibly even within the same
function.
Assuming that the requested BAUD is valid for the given F_CPU then the macro UBRR_VALUE is set to the required
prescaler value. Two additional macros are provided for the low and high bytes of the prescaler, respectively: U←-
BRRL_VALUE is set to the lower byte of the UBRR_VALUE and UBRRH_VALUE is set to the upper byte. An
additional macro USE_2X will be defined. Its value is set to 1 if the desired BAUD rate within the given tolerance
could only be achieved by setting the U2X bit in the UART configuration. It will be defined to 0 if U2X is not needed.
Example usage:
#include <avr/io.h>
static void
uart_9600(void)
{
#define BAUD 9600
#include <util/setbaud.h>
UBRRH = UBRRH_VALUE;
UBRRL = UBRRL_VALUE;
#if USE_2X
UCSRA |= (1 << U2X);
#else
UCSRA &= ~(1 << U2X);
#endif
}
static void
uart_38400(void)
{
#undef BAUD // avoid compiler warning
#define BAUD 38400
#include <util/setbaud.h>
UBRRH = UBRRH_VALUE;
UBRRL = UBRRL_VALUE;
#if USE_2X
UCSRA |= (1 << U2X);
#else
UCSRA &= ~(1 << U2X);
#endif
}
In this example, two functions are defined to setup the UART to run at 9600 Bd, and 38400 Bd, respectively. Using
a CPU clock of 4 MHz, 9600 Bd can be achieved with an acceptable tolerance without setting U2X (prescaler 25),
while 38400 Bd require U2X to be set (prescaler 12).
TWSR values
Mnemonics:
TW_MT_xxx - master transmitter
TW_MR_xxx - master receiver
TW_ST_xxx - slave transmitter
TW_SR_xxx - slave receiver
• #define TW_READ 1
• #define TW_WRITE 0
#include <util/twi.h>
This header file contains bit mask definitions for use with the AVR TWI interface.
SLA+R address
Value:
(_BV(TWS7)|_BV(TWS6)|_BV(TWS5)|_BV(TWS4)|\
_BV(TWS3))
The lower 3 bits of TWSR are reserved on the ATmega163. The 2 LSB carry the prescaler bits on the newer
ATmegas.
SLA+W address
In addition to globally enabling interrupts, each device's particular interrupt needs to be enabled separately if inter-
rupts for this device are desired. While some devices maintain their interrupt enable bit inside the device's register
set, external and timer interrupts have system-wide configuration registers.
Example:
// Do some work...
Note
Be careful when you use these functions. If you already have a different interrupt enabled, you could inadver-
tantly disable it by enabling another intterupt.
Obsolete IO macros
Back in a time when AVR-GCC and avr-libc could not handle IO port access in the direct assignment form as
they are handled now, all IO port access had to be done through specific macros that eventually resulted in inline
assembly instructions performing the desired action.
These macros became obsolete, as reading and writing IO ports can be done by simply using the IO port name in
an expression, and all bit manipulation (including those on IO ports) can be done using generic C bit manipulation
operators.
The macros in this group simulate the historical behaviour. While they are supposed to be applied to IO ports, the
emulation actually uses standard C methods, so they could be applied to arbitrary memory locations as well.
This header file contains several items that used to be available in previous versions of this library, but have eventu-
ally been deprecated over time.
#include <compat/deprecated.h>
These items are supplied within that header file for backward compatibility reasons only, so old source code that
has been written for previous library versions could easily be maintained until its end-of-life. Use of any of these
items in new code is strongly discouraged.
23.35.2.1 #define cbi( port, bit ) (port) &= ∼(1 << (bit))
Deprecated
Deprecated
This macro gives access to the GIMSK register (or EIMSK register if using an AVR Mega device or GICR register
for others). Although this macro is essentially the same as assigning to the register, it does adapt slightly to the type
of device being used. This macro is unavailable if none of the registers listed above are defined.
Deprecated
Deprecated
Value:
Deprecated
Introduces an interrupt handler function that runs with global interrupts initially enabled. This allows interrupt han-
dlers to be interrupted.
As this macro has been used by too many unsuspecting people in the past, it has been deprecated, and will be
removed in a future version of the library. Users who want to legitimately re-enable interrupts in their interrupt
handlers as quickly as possible are encouraged to explicitly declare their handlers as described above.
Deprecated
Deprecated
Deprecated
Deprecated
This function modifies the timsk register. The value you pass via ints is device specific.
This is an attempt to provide some compatibility with header files that come with IAR C, to make porting applications
between different compilers easier. No 100% compatibility though.
Note
Modules
Various small demo projects are provided to illustrate several aspects of using the opensource utilities for the AVR
controller series. It should be kept in mind that these demos serve mainly educational purposes, and are normally
not directly suitable for use in any production environment. Usually, they have been kept as simple as sufficient to
demonstrate one particular feature.
The simple project is somewhat like the "Hello world!" application for a microcontroller, about the most simple project
that can be done. It is explained in good detail, to allow the reader to understand the basic concepts behind using
the tools on an AVR microcontroller.
The more sophisticated demo project builds on top of that simple project, and adds some controls to it. It touches a
number of avr-libc's basic concepts on its way.
A comprehensive example on using the standard IO facilities intends to explain that complex topic, using a practical
microcontroller peripheral setup with one RS-232 connection, and an HD44780-compatible industry-standard LCD
display.
The Example using the two-wire interface (TWI) project explains the use of the two-wire hardware interface (also
known as "I2C") that is present on many AVR controllers.
Finally, the Combining C and assembly source files demo shows how C and assembly language source files can
collaborate within one project. While the overall project is managed by a C program part for easy maintenance, time-
critical parts are written directly in manually optimized assembly language for shortest execution times possible.
Naturally, this kind of project is very closely tied to the hardware design, thus it is custom-tailored to a particular
controller type and peripheral setup. As an alternative to the assembly-language solution, this project also offers a
C-only implementation (deploying the exact same peripheral setup) based on a more sophisticated (and thus more
expensive) but pin-compatible controller.
While the simple demo is meant to run on about any AVR setup possible where a LED could be connected to
the OCR1[A] output, the large and stdio demos are mainly targeted to the Atmel STK500 starter kit, and the T←-
WI example requires a controller where some 24Cxx two-wire EEPPROM can be connected to. For the STK500
demos, the default CPU (either an AT90S8515 or an ATmega8515) should be removed from its socket, and the
ATmega16 that ships with the kit should be inserted into socket SCKT3100A3. The ATmega16 offers an on-board
ADC that is used in the large demo, and all AVRs with an ADC feature a different pinout than the industry-standard
compatible devices.
In order to fully utilize the large demo, a female 10-pin header with cable, connecting to a 10 kOhm potentiometer
will be useful.
For the stdio demo, an industry-standard HD44780-compatible LCD display of at least 16x1 characters will be
needed. Among other things, the LCD4Linux project page describes many things around these displays, including
common pinouts.
For time- or space-critical applications, it can often be desirable to combine C code (for easy maintenance) and
assembly code (for maximal speed or minimal code size) together. This demo provides an example of how to do
that.
The objective of the demo is to decode radio-controlled model PWM signals, and control an output PWM based
on the current input signal's value. The incoming PWM pulses follow a standard encoding scheme where a pulse
width of 920 microseconds denotes one end of the scale (represented as 0 % pulse width on output), and 2120
microseconds mark the other end (100 % output PWM). Normally, multiple channels would be encoded that way
in subsequent pulses, followed by a larger gap, so the entire frame will repeat each 14 through 20 ms, but this is
ignored for the purpose of the demo, so only a single input PWM channel is assumed.
The basic challenge is to use the cheapest controller available for the task, an ATtiny13 that has only a single timer
channel. As this timer channel is required to run the outgoing PWM signal generation, the incoming PWM decoding
had to be adjusted to the constraints set by the outgoing PWM.
As PWM generation toggles the counting direction of timer 0 between up and down after each 256 timer cycles,
the current time cannot be deduced by reading TCNT0 only, but the current counting direction of the timer needs
to be considered as well. This requires servicing interrupts whenever the timer hits TOP (255) and BOTTOM (0) to
learn about each change of the counting direction. For PWM generation, it is usually desired to run it at the highest
possible speed so filtering the PWM frequency from the modulated output signal is made easy. Thus, the PWM
timer runs at full CPU speed. This causes the overflow and compare match interrupts to be triggered each 256 CPU
clocks, so they must run with the minimal number of processor cycles possible in order to not impose a too high
CPU load by these interrupt service routines. This is the main reason to implement the entire interrupt handling in
fine-tuned assembly code rather than in C.
In order to verify parts of the algorithm, and the underlying hardware, the demo has been set up in a way so the
pin-compatible but more expensive ATtiny45 (or its siblings ATtiny25 and ATtiny85) could be used as well. In that
case, no separate assembly code is required, as two timer channels are avaible.
The incoming PWM pulse train is fed into PB4. It will generate a pin change interrupt there on eache edge of the
incoming signal.
The outgoing PWM is generated through OC0B of timer channel 0 (PB1). For demonstration purposes, a LED
should be connected to that pin (like, one of the LEDs of an STK500).
The controllers run on their internal calibrated RC oscillators, 1.2 MHz on the ATtiny13, and 1.0 MHz on the A←-
Ttiny45.
23.38.2.1 asmdemo.c
After the usual include files, two variables are defined. The first one, pwm_incoming is used to communicate the
most recent pulse width detected by the incoming PWM decoder up to the main loop.
The second variable actually only constitutes of a single bit, intbits.pwm_received. This bit will be set
whenever the incoming PWM decoder has updated pwm_incoming.
Both variables are marked volatile to ensure their readers will always pick up an updated value, as both variables
will be set by interrupt service routines.
The function ioinit() initializes the microcontroller peripheral devices. In particular, it starts timer 0 to generate
the outgoing PWM signal on OC0B. Setting OCR0A to 255 (which is the TOP value of timer 0) is used to generate
a timer 0 overflow A interrupt on the ATtiny13. This interrupt is used to inform the incoming PWM decoder that the
counting direction of channel 0 is just changing from up to down. Likewise, an overflow interrupt will be generated
whenever the countdown reached BOTTOM (value 0), where the counter will again alter its counting direction to
upwards. This information is needed in order to know whether the current counter value of TCNT0 is to be evaluated
from bottom or top.
Further, ioinit() activates the pin-change interrupt PCINT0 on any edge of PB4. Finally, PB1 (OC0B) will be
activated as an output pin, and global interrupts are being enabled.
In the ATtiny45 setup, the C code contains an ISR for PCINT0. At each pin-change interrupt, it will first be analyzed
whether the interrupt was caused by a rising or a falling edge. In case of the rising edge, timer 1 will be started
with a prescaler of 16 after clearing the current timer value. Then, at the falling edge, the current timer value will be
recorded (and timer 1 stopped), the pin-change interrupt will be suspended, and the upper layer will be notified that
the incoming PWM measurement data is available.
Function main() first initializes the hardware by calling ioinit(), and then waits until some incoming PWM
value is available. If it is, the output PWM will be adjusted by computing the relative value of the incoming PWM.
Finally, the pin-change interrupt is re-enabled, and the CPU is put to sleep.
23.38.2.2 project.h
In order for the interrupt service routines to be as fast as possible, some of the CPU registers are set aside
completely for use by these routines, so the compiler would not use them for C code. This is arranged for in
project.h.
The file is divided into one section that will be used by the assembly source code, and another one to be used
by C code. The assembly part is distinguished by the preprocessing macro __ASSEMBLER__ (which will be
automatically set by the compiler front-end when preprocessing an assembly-language file), and it contains just
macros that give symbolic names to a number of CPU registers. The preprocessor will then replace the symbolic
names by their right-hand side definitions before calling the assembler.
In C code, the compiler needs to see variable declarations for these objects. This is done by using declarations that
bind a variable permanently to a CPU register (see How to permanently bind a variable to a register?). Even in case
the C code never has a need to access these variables, declaring the register binding that way causes the compiler
to not use these registers in C code at all.
The flags variable needs to be in the range of r16 through r31 as it is the target of a load immediate (or SER)
instruction that is not applicable to the entire register file.
23.38.2.3 isrs.S
This file is a preprocessed assembly source file. The C preprocessor will be run by the compiler front-end first,
resolving all #include, #define etc. directives. The resulting program text will then be passed on to the
assembler.
As the C preprocessor strips all C-style comments, preprocessed assembly source files can have both, C-style (/∗
... ∗/, // ...) as well as assembly-style (; ...) comments.
At the top, the IO register definition file avr/io.h and the project declaration file project.h are included. The
remainder of the file is conditionally assembled only if the target MCU type is an ATtiny13, so it will be completely
ignored for the ATtiny45 option.
Next are the two interrupt service routines for timer 0 compare A match (timer 0 hits TOP, as OCR0A is set to 255)
and timer 0 overflow (timer 0 hits BOTTOM). As discussed above, these are kept as short as possible. They only
save SREG (as the flags will be modified by the INC instruction), increment the counter_hi variable which forms
the high part of the current time counter (the low part is formed by querying TCNT0 directly), and clear or set the
variable flags, respectively, in order to note the current counting direction. The RETI instruction terminates these
interrupt service routines. Total cycle count is 8 CPU cycles, so together with the 4 CPU cycles needed for interrupt
setup, and the 2 cycles for the RJMP from the interrupt vector to the handler, these routines will require 14 out of
each 256 CPU cycles, or about 5 % of the overall CPU time.
The pin-change interrupt PCINT0 will be handled in the final part of this file. The basic algorithm is to quickly
evaluate the current system time by fetching the current timer value of TCNT0, and combining it with the overflow
part in counter_hi. If the counter is currently counting down rather than up, the value fetched from TCNT0 must
be negated. Finally, if this pin-change interrupt was triggered by a rising edge, the time computed will be recorded
as the start time only. Then, at the falling edge, this start time will be subracted from the current time to compute the
actual pulse width seen (left in pwm_incoming), and the upper layers are informed of the new value by setting bit
0 in the intbits flags. At the same time, this pin-change interrupt will be disabled so no new measurement can
be performed until the upper layer had a chance to process the current value.
At this point, you should have the GNU tools configured, built, and installed on your system. In this chapter, we
present a simple example of using the GNU tools in an AVR project. After reading this chapter, you should have a
better feel as to how the tools are used and how a Makefile can be configured.
This project will use the pulse-width modulator (PWM) to ramp an LED on and off every two seconds. An AT90S2313
processor will be used as the controller. The circuit for this demonstration is shown in the schematic diagram. If you
have a development kit, you should be able to use it, rather than build the circuit, for this project.
Note
Meanwhile, the AT90S2313 became obsolete. Either use its successor, the (pin-compatible) ATtiny2313
for the project, or perhaps the ATmega8 or one of its successors (ATmega48/88/168) which have become
quite popular since the original demo project had been established. For all these more modern devices, it
is no longer necessary to use an external crystal for clocking as they ship with the internal 1 MHz oscillator
enabled, so C1, C2, and Q1 can be omitted. Normally, for this experiment, the external circuitry on /RESET
(R1, C3) can be omitted as well, leaving only the AVR, the LED, the bypass capacitor C4, and perhaps R2.
For the ATmega8/48/88/168, use PB1 (pin 15 at the DIP-28 package) to connect the LED to. Additionally, this
demo has been ported to many different other AVRs. The location of the respective OC pin varies between
different AVRs, and it is mandated by the AVR hardware.
VCC
IC1
R1 (SCK)PB7 19
1 RESET 18
.01uf
(MISO)PB6
4mhz
20K C2 17
C3
(MOSI)PB5
Q1
4 16 LED5MM
C1 XTAL2 PB4 R2* D1
18pf (OCI)PB3 15
5 XTAL1 14
PB2 See note [8]
18pf 20 VCC (AIN1)PB1 13
12 GND
10 GND (AIN0)PB0
.1uf
11
C4
(ICP)PD6
(T1)PD5 9
GND 8
(T0)PD4
(INT1)PD3 7
GND (INT0)PD2 6
(TXD)PD1 3
(RXD)PD0 2
AT90S2313P
The source code is given in demo.c. For the sake of this example, create a file called demo.c containing this
source code. Some of the more important parts of the code are:
Note [1]:
As the AVR microcontroller series has been developed during the past years, new features have been added
over time. Even though the basic concepts of the timer/counter1 are still the same as they used to be back
in early 2001 when this simple demo was written initially, the names of registers and bits have been changed
slightly to reflect the new features. Also, the port and pin mapping of the output compare match 1A (or 1 for
older devices) pin which is used to control the LED varies between different AVRs. The file iocompat.h tries
to abstract between all this differences using some preprocessor #ifdef statements, so the actual program
itself can operate on a common set of symbolic names. The macros defined by that file are:
• OCR the name of the OCR register used to control the PWM (usually either OCR1 or OCR1A)
• DDROC the name of the DDR (data direction register) for the OC output
• OC1 the pin number of the OC1[A] output within its port
• TIMER1_TOP the TOP value of the timer used for the PWM (1023 for 10-bit PWMs, 255 for devices that can
only handle an 8-bit PWM)
• TIMER1_PWM_INIT the initialization bits to be set into control register 1A in order to setup 10-bit (or 8-bit)
phase and frequency correct PWM mode
• TIMER1_CLOCKSOURCE the clock bits to set in the respective control register to start the PWM timer;
usually the timer runs at full CPU clock for 10-bit PWMs, while it runs on a prescaled clock for 8-bit PWMs
Note [2]:
ISR() is a macro that marks the function as an interrupt routine. In this case, the function will get called when
timer 1 overflows. Setting up interrupts is explained in greater detail in <avr/interrupt.h>: Interrupts.
Note [3]:
The PWM is being used in 10-bit mode, so we need a 16-bit variable to remember the current value.
Note [4]:
Note [5]:
Here's where the newly computed value is loaded into the PWM register. Since we are in an interrupt routine,
it is safe to use a 16-bit assignment to the register. Outside of an interrupt, the assignment should only be
performed with interrupts disabled if there's a chance that an interrupt routine could also access this register
(or another register that uses TEMP), see the appropriate FAQ entry.
Note [6]:
This routine gets called after a reset. It initializes the PWM and enables interrupts.
Note [7]:
The main loop of the program does nothing – all the work is done by the interrupt routine! The sleep_←-
mode() puts the processor on sleep until the next interrupt, to conserve power. Of course, that probably won't
be noticable as we are still driving a LED, it is merely mentioned here to demonstrate the basic principle.
Note [8]:
Early AVR devices saturate their outputs at rather low currents when sourcing current, so the LED can be
connected directly, the resulting current through the LED will be about 15 mA. For modern parts (at least for the
ATmega 128), however Atmel has drastically increased the IO source capability, so when operating at 5 V Vcc,
R2 is needed. Its value should be about 150 Ohms. When operating the circuit at 3 V, it can still be omitted
though.
/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <joerg@FreeBSD.ORG> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Joerg Wunsch
* ----------------------------------------------------------------------------
*
* Simple AVR demonstration. Controls a LED that can be directly
* connected from OC1/OC1A to GND. The brightness of the LED is
* controlled with the PWM. After each period of the PWM, the PWM
* value is either incremented or decremented, that’s all.
*
* $Id: demo.c 1637 2008-03-17 21:49:41Z joerg_wunsch $
*/
#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
case DOWN:
if (--pwm == 0)
direction = UP;
break;
}
void
ioinit (void) /* Note [6] */
{
/* Timer 1 is 10-bit PWM (8-bit PWM on some ATtinys). */
TCCR1A = TIMER1_PWM_INIT;
/*
* Start timer 1.
*
* NB: TCCR1A and TCCR1B could actually be the same register, so
* take care to not clobber it.
*/
TCCR1B |= TIMER1_CLOCKSOURCE;
/*
* Run any device-dependent timer 1 setup hook if present.
*/
#if defined(TIMER1_SETUP_HOOK)
TIMER1_SETUP_HOOK();
#endif
int
main (void)
{
ioinit ();
return (0);
}
This first thing that needs to be done is compile the source. When compiling, the compiler needs to know the
processor type so the -mmcu option is specified. The -Os option will tell the compiler to optimize the code for
efficient space usage (at the possible expense of code execution speed). The -g is used to embed debug info. The
debug info is useful for disassemblies and doesn't end up in the .hex files, so I usually specify it. Finally, the -c tells
the compiler to compile and stop – don't link. This demo is small enough that we could compile and link in one step.
However, real-world projects will have several modules and will typically need to break up the building of the project
into several compiles and one link.
The compilation will create a demo.o file. Next we link it into a binary called demo.elf.
It is important to specify the MCU type when linking. The compiler uses the -mmcu option to choose start-up
files and run-time libraries that get linked together. If this option isn't specified, the compiler defaults to the 8515
processor environment, which is most certainly what you didn't want.
Now we have a binary file. Can we do anything useful with it (besides put it into the processor?) The GNU Binutils
suite is made up of many useful tools for manipulating object files that get generated. One tool is avr-objdump,
which takes information from the object file and displays it in many useful ways. Typing the command by itself will
cause it to list out its options.
For instance, to get a feel of the application's size, the -h option can be used. The output of this option shows
how much space is used in each of the sections (the .stab and .stabstr sections hold the debugging information and
won't make it into the ROM file).
An even more useful option is -S. This option disassembles the binary file and intersperses the source code in the
output! This method is much better, in my opinion, than using the -S with the compiler because this listing includes
routines from the libraries and the vector table contents. Also, all the "fix-ups" have been satisfied. In other words,
the listing generated by this option reflects the actual code that the processor will run.
Sections:
Idx Name Size VMA LMA File off Algn
0 .text 000000d0 00000000 00000000 00000094 2**1
CONTENTS, ALLOC, LOAD, READONLY, CODE
1 .data 00000000 00800060 000000d0 00000164 2**0
CONTENTS, ALLOC, LOAD, DATA
2 .bss 00000003 00800060 00800060 00000164 2**0
ALLOC
3 .stab 0000075c 00000000 00000000 00000164 2**2
CONTENTS, READONLY, DEBUGGING
4 .stabstr 00000d21 00000000 00000000 000008c0 2**0
CONTENTS, READONLY, DEBUGGING
5 .comment 00000011 00000000 00000000 000015e1 2**0
CONTENTS, READONLY
00000000 <__ctors_end>:
0: 20 e0 ldi r18, 0x00 ; 0
2: a0 e6 ldi r26, 0x60 ; 96
4: b0 e0 ldi r27, 0x00 ; 0
6: 01 c0 rjmp .+2 ; 0xa <.do_clear_bss_start>
00000008 <.do_clear_bss_loop>:
8: 1d 92 st X+, r1
0000000a <.do_clear_bss_start>:
a: a3 36 cpi r26, 0x63 ; 99
c: b2 07 cpc r27, r18
e: e1 f7 brne .-8 ; 0x8 <.do_clear_bss_loop>
00000010 <__vector_8>:
case DOWN:
if (--pwm == 0)
2c: 80 91 60 00 lds r24, 0x0060
30: 90 91 61 00 lds r25, 0x0061
34: 01 97 sbiw r24, 0x01 ; 1
36: 90 93 61 00 sts 0x0061, r25
3a: 80 93 60 00 sts 0x0060, r24
3e: 00 97 sbiw r24, 0x00 ; 0
40: 39 f4 brne .+14 ; 0x50 <__SREG__+0x11>
direction = UP;
42: 10 92 62 00 sts 0x0062, r1
46: 04 c0 rjmp .+8 ; 0x50 <__SREG__+0x11>
48: 80 91 60 00 lds r24, 0x0060
4c: 90 91 61 00 lds r25, 0x0061
break;
}
00000086 <ioinit>:
void
ioinit (void) /* Note [6] */
{
/* Timer 1 is 10-bit PWM (8-bit PWM on some ATtinys). */
TCCR1A = TIMER1_PWM_INIT;
86: 83 e8 ldi r24, 0x83 ; 131
88: 8f bd out 0x2f, r24 ; 47
* Start timer 1.
*
* NB: TCCR1A and TCCR1B could actually be the same register, so
* take care to not clobber it.
*/
TCCR1B |= TIMER1_CLOCKSOURCE;
8a: 8e b5 in r24, 0x2e ; 46
8c: 81 60 ori r24, 0x01 ; 1
8e: 8e bd out 0x2e, r24 ; 46
#if defined(TIMER1_SETUP_HOOK)
TIMER1_SETUP_HOOK();
#endif
000000a0 <main>:
void
ioinit (void) /* Note [6] */
{
/* Timer 1 is 10-bit PWM (8-bit PWM on some ATtinys). */
TCCR1A = TIMER1_PWM_INIT;
a0: 83 e8 ldi r24, 0x83 ; 131
a2: 8f bd out 0x2f, r24 ; 47
* Start timer 1.
*
* NB: TCCR1A and TCCR1B could actually be the same register, so
* take care to not clobber it.
*/
TCCR1B |= TIMER1_CLOCKSOURCE;
a4: 8e b5 in r24, 0x2e ; 46
a6: 81 60 ori r24, 0x01 ; 1
a8: 8e bd out 0x2e, r24 ; 46
#if defined(TIMER1_SETUP_HOOK)
TIMER1_SETUP_HOOK();
#endif
000000c8 <exit>:
c8: f8 94 cli
ca: 00 c0 rjmp .+0 ; 0xcc <_exit>
000000cc <_exit>:
cc: f8 94 cli
000000ce <__stop_program>:
ce: ff cf rjmp .-2 ; 0xce <__stop_program>
avr-objdump is very useful, but sometimes it's necessary to see information about the link that can only be
generated by the linker. A map file contains this information. A map file is useful for monitoring the sizes of your
code and data. It also shows where modules are loaded and which modules were loaded from libraries. It is yet
another view of your application. To get a map file, I usually add -Wl,-Map,demo.map to my link command.
Relink the application using the following command to generate demo.map (a portion of which is shown below).
.rela.plt
*(.rela.plt)
The .text segment (where program instructions are stored) starts at location 0x0.
*(.fini2)
*(.fini2)
*(.fini1)
*(.fini1)
*(.fini0)
.fini0 0x00000000000000cc 0x4 /junk/testroot/lib/gcc/avr/5.3.0/avr4/libgcc.a(_exit.o)
*(.fini0)
0x00000000000000d0 _etext = .
The last address in the .text segment is location 0x114 ( denoted by _etext ), so the instructions use up 276
bytes of FLASH.
The .data segment (where initialized static variables are stored) starts at location 0x60, which is the first address
after the register bank on an ATmega8 processor.
The next available address in the .data segment is also location 0x60, so the application has no initialized data.
The .bss segment (where uninitialized data is stored) starts at location 0x60.
The next available address in the .bss segment is location 0x63, so the application uses 3 bytes of uninitialized data.
The .eeprom segment (where EEPROM variables are stored) starts at location 0x0.
The next available address in the .eeprom segment is also location 0x0, so there aren't any EEPROM variables.
We have a binary of the application, but how do we get it into the processor? Most (if not all) programmers will
not accept a GNU executable as an input file, so we need to do a little more processing. The next step is to
extract portions of the binary and save the information into .hex files. The GNU utility that does this is called
avr-objcopy.
The ROM contents can be pulled from our project's binary and put into the file demo.hex using the following
command:
:1000000020E0A0E6B0E001C01D92A336B207E1F700
:100010001F920F920FB60F9211242F938F939F93DD
:10002000809162008823F1F0813071F4809160004A
:100030009091610001979093610080936000009718
:1000400039F41092620004C08091600090916100C8
:100050009BBD8ABD9F918F912F910F900FBE0F90E6
:100060001F90189580916000909161000196909387
:100070006100809360008F3F23E0920749F721E001
:1000800020936200E5CF83E88FBD8EB581608EBD81
:100090001BBC1ABC82E087BB84E089BF78940895BA
:1000A00083E88FBD8EB581608EBD1BBC1ABC82E01B
:1000B00087BB84E089BF789485B7806885BF8895C1
:1000C00085B78F7785BFF8CFF89400C0F894FFCF3D
:00000001FF
The -j option indicates that we want the information from the .text and .data segment extracted. If we specify the
EEPROM segment, we can generate a .hex file that can be used to program the EEPROM:
Rather than type these commands over and over, they can all be placed in a make file. To build the demo project
using make, save the following in a file called Makefile.
Note
This Makefile can only be used as input for the GNU version of make.
1 PRG = demo
2 OBJ = demo.o
3 #MCU_TARGET = at90s2313
4 #MCU_TARGET = at90s2333
5 #MCU_TARGET = at90s4414
6 #MCU_TARGET = at90s4433
7 #MCU_TARGET = at90s4434
8 #MCU_TARGET = at90s8515
9 #MCU_TARGET = at90s8535
10 #MCU_TARGET = atmega128
11 #MCU_TARGET = atmega1280
12 #MCU_TARGET = atmega1281
13 #MCU_TARGET = atmega1284p
14 #MCU_TARGET = atmega16
15 #MCU_TARGET = atmega163
16 #MCU_TARGET = atmega164p
17 #MCU_TARGET = atmega165
18 #MCU_TARGET = atmega165p
19 #MCU_TARGET = atmega168
20 #MCU_TARGET = atmega169
21 #MCU_TARGET = atmega169p
22 #MCU_TARGET = atmega2560
23 #MCU_TARGET = atmega2561
24 #MCU_TARGET = atmega32
25 #MCU_TARGET = atmega324p
26 #MCU_TARGET = atmega325
27 #MCU_TARGET = atmega3250
28 #MCU_TARGET = atmega329
29 #MCU_TARGET = atmega3290
30 #MCU_TARGET = atmega32u4
31 #MCU_TARGET = atmega48
32 #MCU_TARGET = atmega64
33 #MCU_TARGET = atmega640
34 #MCU_TARGET = atmega644
35 #MCU_TARGET = atmega644p
36 #MCU_TARGET = atmega645
37 #MCU_TARGET = atmega6450
38 #MCU_TARGET = atmega649
39 #MCU_TARGET = atmega6490
40 MCU_TARGET = atmega8
41 #MCU_TARGET = atmega8515
42 #MCU_TARGET = atmega8535
43 #MCU_TARGET = atmega88
44 #MCU_TARGET = attiny2313
45 #MCU_TARGET = attiny24
46 #MCU_TARGET = attiny25
47 #MCU_TARGET = attiny26
48 #MCU_TARGET = attiny261
49 #MCU_TARGET = attiny44
50 #MCU_TARGET = attiny45
51 #MCU_TARGET = attiny461
52 #MCU_TARGET = attiny84
53 #MCU_TARGET = attiny85
54 #MCU_TARGET = attiny861
55 OPTIMIZE = -O2
56
57 DEFS =
58 LIBS =
59
60 # You should not have to change anything below here.
61
62 CC = avr-gcc
63
64 # Override is only needed by avr-lib build system.
65
66 override CFLAGS = -g -Wall $(OPTIMIZE) -mmcu=$(MCU_TARGET) $(DEFS)
67 override LDFLAGS = -Wl,-Map,$(PRG).map
68
69 OBJCOPY = avr-objcopy
70 OBJDUMP = avr-objdump
71
72 all: $(PRG).elf lst text eeprom
73
74 $(PRG).elf: $(OBJ)
75 $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LIBS)
76
77 # dependency:
78 demo.o: demo.c iocompat.h
79
80 clean:
81 rm -rf *.o $(PRG).elf *.eps *.png *.pdf *.bak
82 rm -rf *.lst *.map $(EXTRA_CLEAN_FILES)
83
84 lst: $(PRG).lst
85
86 %.lst: %.elf
87 $(OBJDUMP) -h -S $< > $@
88
89 # Rules for building the .text rom images
90
91 text: hex bin srec
92
93 hex: $(PRG).hex
94 bin: $(PRG).bin
95 srec: $(PRG).srec
96
97 %.hex: %.elf
98 $(OBJCOPY) -j .text -j .data -O ihex $< $@
99
100 %.srec: %.elf
101 $(OBJCOPY) -j .text -j .data -O srec $< $@
102
103 %.bin: %.elf
104 $(OBJCOPY) -j .text -j .data -O binary $< $@
105
106 # Rules for building the .eeprom rom images
107
108 eeprom: ehex ebin esrec
109
110 ehex: $(PRG)_eeprom.hex
111 ebin: $(PRG)_eeprom.bin
112 esrec: $(PRG)_eeprom.srec
113
114 %_eeprom.hex: %.elf
115 $(OBJCOPY) -j .eeprom --change-section-lma .eeprom=0 -O ihex $< $@ \
116 || { echo empty $@ not generated; exit 0; }
117
118 %_eeprom.srec: %.elf
119 $(OBJCOPY) -j .eeprom --change-section-lma .eeprom=0 -O srec $< $@ \
120 || { echo empty $@ not generated; exit 0; }
121
This project extends the basic idea of the simple project to control a LED with a PWM output, but adds methods to
adjust the LED brightness. It employs a lot of the basic concepts of avr-libc to achieve that goal.
Understanding this project assumes the simple project has been understood in full, as well as being acquainted with
the basic hardware concepts of an AVR microcontroller.
The demo is set up in a way so it can be run on the ATmega16 that ships with the STK500 development kit. The
only external part needed is a potentiometer attached to the ADC. It is connected to a 10-pin ribbon cable for port A,
both ends of the potentiometer to pins 9 (GND) and 10 (VCC), and the wiper to pin 1 (port A0). A bypass capacitor
from pin 1 to pin 9 (like 47 nF) is recommendable.
The coloured patch cables are used to provide various interconnections. As there are only four of them in the ST←-
K500, there are two options to connect them for this demo. The second option for the yellow-green cable is shown
in parenthesis in the table. Alternatively, the "squid" cable from the JTAG ICE kit can be used if available.
Port Header Color Function Connect to
D0 1 brown RxD RXD of the RS-232
header
D1 2 grey TxD TXD of the RS-232
header
D2 3 black button "down" SW0 (pin 1
switches header)
D3 4 red button "up" SW1 (pin 2
switches header)
The following picture shows the alternate wiring where LED1 is connected but SW2 is not:
As an alternative, this demo can also be run on the popular ATmega8 controller, or its successor ATmega88 as
well as the ATmega48 and ATmega168 variants of the latter. These controllers do not have a port named "A", so
their ADC inputs are located on port C instead, thus the potentiometer needs to be attached to port C. Likewise,
the OC1A output is not on port D pin 5 but on port B pin 1 (PB1). Thus, the above cabling scheme needs to be
changed so that PB1 connects to the LED0 pin. (PD6 remains unconnected.) When using the STK500, use one of
the jumper cables for this connection. All other port D pins should be connected the same way as described for the
ATmega16 above.
When not using an STK500 starter kit, attach the LEDs through some resistor to Vcc (low-active LEDs), and attach
pushbuttons from the respective input pins to GND. The internal pull-up resistors are enabled for the pushbutton
pins, so no external resistors are needed.
Finally, the demo has been ported to the ATtiny2313 as well. As this AVR does not offer an ADC, everything related
to handling the ADC is disabled in the code for that MCU type. Also, port D of this controller type only features 6
pins, so the 1-second flash LED had to be moved from PD6 to PD4. (PD4 is used as the ADC control button on the
other MCU types, but that is not needed here.) OC1A is located at PB3 on this device.
The MCU_TARGET macro in the Makefile needs to be adjusted appropriately for the alternative controller types.
The flash ROM and RAM consumption of this demo are way below the resources of even an ATmega48, and
still well within the capabilities of an ATtiny2313. The major advantage of experimenting with the ATmega16 (in
addition that it ships together with an STK500 anyway) is that it can be debugged online via JTAG. Likewise, the
ATmega48/88/168 and ATtiny2313 devices can be debugged through debugWire, using the Atmel JTAG ICE mkII
or the low-cost AVR Dragon.
Note that in the explanation below, all port/pin names are applicable to the ATmega16 setup.
PD6 will be toggled with each internal clock tick (approx. 10 ms). PD7 will flash once per second.
PD0 and PD1 are configured as UART IO, and can be used to connect the demo kit to a PC (9600 Bd, 8N1 frame
format). The demo application talks to the serial port, and it can be controlled from the serial port.
PD2 through PD4 are configured as inputs, and control the application unless control has been taken over by the
serial port. Shorting PD2 to GND will decrease the current PWM value, shorting PD3 to GND will increase it.
While PD4 is shorted to GND, one ADC conversion for channel 0 (ADC input is on PA0) will be triggered each
internal clock tick, and the resulting value will be used as the PWM value. So the brightness of the LED follows the
analog input value on PC0. VAREF on the STK500 should be set to the same value as VCC.
When running in serial control mode, the function of the watchdog timer can be demonstrated by typing an ‘r'. This
will make the demo application run in a tight loop without retriggering the watchdog so after some seconds, the
watchdog will reset the MCU. This situation can be figured out on startup by reading the MCUCSR register.
The current value of the PWM is backed up in an EEPROM cell after about 3 seconds of idle time after the last
change. If that EEPROM cell contains a reasonable (i. e. non-erased) value at startup, it is taken as the initial
value for the PWM. This virtually preserves the last value across power cycles. By not updating the EEPROM
immmediately but only after a timeout, EEPROM wear is reduced considerably compared to immediately writing the
value at each change.
This section explains the ideas behind individual parts of the code. The source code has been divided into numbered
parts, and the following subsections explain each of these parts.
A number of preprocessor macros are defined to improve readability and/or portability of the application.
The first macros describe the IO pins our LEDs and pushbuttons are connected to. This provides some kind of mini-
HAL (hardware abstraction layer) so should some of the connections be changed, they don't need to be changed
inside the code but only on top. Note that the location of the PWM output itself is mandated by the hardware, so
it cannot be easily changed. As the ATmega48/88/168 controllers belong to a more recent generation of AV←-
Rs, a number of register and bit names have been changed there, so they are mapped back to their ATmega8/16
equivalents to keep the actual program code portable.
The name F_CPU is the conventional name to describe the CPU clock frequency of the controller. This demo
project just uses the internal calibrated 1 MHz RC oscillator that is enabled by default. Note that when using the
<util/delay.h> functions, F_CPU needs to be defined before including that file.
The remaining macros have their own comments in the source code. The macro TMR1_SCALE shows how to use
the preprocessor and the compiler's constant expression computation to calculate the value of timer 1's post-scaler
in a way so it only depends on F_CPU and the desired software clock frequency. While the formula looks a bit
complicated, using a macro offers the advantage that the application will automatically scale to new target softclock
or master CPU frequencies without having to manually re-calculate hardcoded constants.
The intflags structure demonstrates a way to allocate bit variables in memory. Each of the interrupt service
routines just sets one bit within that structure, and the application's main loop then monitors the bits in order to act
appropriately.
Like all variables that are used to communicate values between an interrupt service routine and the main application,
it is declared volatile.
The variable ee_pwm is not a variable in the classical C sense that could be used as an lvalue or within an
expression to obtain its value. Instead, the
__attribute__((section(".eeprom")))
marks it as belonging to the EEPROM section. This section is merely used as a placeholder so the compiler
can arrange for each individual variable's location in EEPROM. The compiler will also keep track of initial values
assigned, and usually the Makefile is arranged to extract these initial values into a separate load file (largedemo←-
_eeprom.∗ in this case) that can be used to initialize the EEPROM.
The actual EEPROM IO must be performed manually.
Similarly, the variable mcucsr is kept in the .noinit section in order to prevent it from being cleared upon application
startup.
The ISR to handle timer 1's overflow interrupt arranges for the software clock. While timer 1 runs the PWM, it calls
its overflow handler rather frequently, so the TMR1_SCALE value is used as a postscaler to reduce the internal
software clock frequency further. If the software clock triggers, it sets the tmr_int bitfield, and defers all further
tasks to the main loop.
The ADC ISR just fetches the value from the ADC conversion, disables the ADC interrupt again, and announces
the presence of the new value in the adc_int bitfield. The interrupt is kept disabled while not needed, because
the ADC will also be triggered by executing the SLEEP instruction in idle mode (which is the default sleep mode).
Another option would be to turn off the ADC completely here, but that increases the ADC's startup time (not that it
would matter much for this application).
The function handle_mcucsr() uses two __attribute__ declarators to achieve specific goals. First, it will
instruct the compiler to place the generated code into the .init3 section of the output. Thus, it will become part of the
application initialization sequence. This is done in order to fetch (and clear) the reason of the last hardware reset
from MCUCSR as early as possible. There is a short period of time where the next reset could already trigger before
the current reason has been evaluated. This also explains why the variable mcucsr that mirrors the register's value
needs to be placed into the .noinit section, because otherwise the default initialization (which happens after .init3)
would blank the value again.
As the initialization code is not called using CALL/RET instructions but rather concatenated together, the compiler
needs to be instructed to omit the entire function prologue and epilogue. This is performed by the naked attribute.
So while syntactically, handle_mcucsr() is a function to the compiler, the compiler will just emit the instructions
for it without setting up any stack frame, and not even a RET instruction at the end.
Function ioinit() centralizes all hardware setup. The very last part of that function demonstrates the use of
the EEPROM variable ee_pwm to obtain an EEPROM address that can in turn be applied as an argument to
eeprom_read_word().
The following functions handle UART character and string output. (UART input is handled by an ISR.) There are two
string output functions, printstr() and printstr_p(). The latter function fetches the string from program
memory. Both functions translate a newline character into a carriage return/newline sequence, so a simple \n can
be used in the source code.
The function set_pwm() propagates the new PWM value to the PWM, performing range checking. When the
value has been changed, the new percentage will be announced on the serial link. The current value is mirrored
in the variable pwm so others can use it in calculations. In order to allow for a simple calculation of a percentage
value without requiring floating-point mathematics, the maximal value of the PWM is restricted to 1000 rather than
1023, so a simple division by 10 can be used. Due to the nature of the human eye, the difference in LED brightness
between 1000 and 1023 is not noticable anyway.
At the start of main(), a variable mode is declared to keep the current mode of operation. An enumeration is
used to improve the readability. By default, the compiler would allocate a variable of type int for an enumeration.
The packed attribute declarator instructs the compiler to use the smallest possible integer type (which would be an
8-bit type here).
After some initialization actions, the application's main loop follows. In an embedded application, this is normally an
infinite loop as there is nothing an application could "exit" into anyway.
At the beginning of the loop, the watchdog timer will be retriggered. If that timer is not triggered for about 2 seconds,
it will issue a hardware reset. Care needs to be taken that no code path blocks longer than this, or it needs to
frequently perform watchdog resets of its own. An example of such a code path would be the string IO functions:
for an overly large string to print (about 2000 characters at 9600 Bd), they might block for too long.
The loop itself then acts on the interrupt indication bitfields as appropriate, and will eventually put the CPU on sleep
at its end to conserve power.
The first interrupt bit that is handled is the (software) timer, at a frequency of approximately 100 Hz. The CLOCKOUT
pin will be toggled here, so e. g. an oscilloscope can be used on that pin to measure the accuracy of our software
clock. Then, the LED flasher for LED2 ("We are alive"-LED) is built. It will flash that LED for about 50 ms, and pause
it for another 950 ms. Various actions depending on the operation mode follow. Finally, the 3-second backup timer
is implemented that will write the PWM value back to EEPROM once it is not changing anymore.
The ADC interrupt will just adjust the PWM value only.
Finally, the UART Rx interrupt will dispatch on the last character received from the UART.
All the string literals that are used as informational messages within main() are placed in program memory so
no SRAM needs to be allocated for them. This is done by using the PSTR macro, and passing the string to
printstr_p().
This project illustrates how to use the standard IO facilities (stdio) provided by this library. It assumes a basic
knowledge of how the stdio subsystem is used in standard C applications, and concentrates on the differences in
this library's implementation that mainly result from the differences of the microcontroller environment, compared to
a hosted environment of a standard computer.
This demo is meant to supplement the documentation, not to replace it.
The demo is set up in a way so it can be run on the ATmega16 that ships with the STK500 development kit. The
UART port needs to be connected to the RS-232 "spare" port by a jumper cable that connects PD0 to RxD and PD1
to TxD. The RS-232 channel is set up as standard input (stdin) and standard output (stdout), respectively.
In order to have a different device available for a standard error channel (stderr), an industry-standard LCD
display with an HD44780-compatible LCD controller has been chosen. This display needs to be connected to port
A of the STK500 in the following way:
Port Header Function
A0 1 LCD D4
A1 2 LCD D5
A2 3 LCD D6
A3 4 LCD D7
A4 5 LCD R/∼W
A5 6 LCD E
A6 7 LCD RS
A7 8 unused
GND 9 GND
VCC 10 Vcc
The LCD controller is used in 4-bit mode, including polling the "busy" flag so the R/∼W line from the LCD controller
needs to be connected. Note that the LCD controller has yet another supply pin that is used to adjust the LCD's
contrast (V5). Typically, that pin connects to a potentiometer between Vcc and GND. Often, it might work to just
connect that pin to GND, while leaving it unconnected usually yields an unreadable display.
Port A has been chosen as 7 pins are needed to connect the LCD, yet all other ports are already partially in use:
port B has the pins for in-system programming (ISP), port C has the ports for JTAG (can be used for debugging),
and port D is used for the UART connection.
23.41.3.1 stdiodemo.c
As usual, include files go first. While conventionally, system header files (those in angular brackets < ... >) go before
application-specific header files (in double quotes), defines.h comes as the first header file here. The main
reason is that this file defines the value of F_CPU which needs to be known before including <utils/delay.←-
h>.
The function ioinit() summarizes all hardware initialization tasks. As this function is declared to be module-
internal only (static), the compiler will notice its simplicity, and with a reasonable optimization level in effect, it will
inline that function. That needs to be kept in mind when debugging, because the inlining might cause the debugger
to "jump around wildly" at a first glance when single-stepping.
The definitions of uart_str and lcd_str set up two stdio streams. The initialization is done using the FD←-
EV_SETUP_STREAM() initializer template macro, so a static object can be constructed that can be used for IO
purposes. This initializer macro takes three arguments, two function macros to connect the corresponding output
and input functions, respectively, the third one describes the intent of the stream (read, write, or both). Those
functions that are not required by the specified intent (like the input function for lcd_str which is specified to only
perform output operations) can be given as NULL.
The stream uart_str corresponds to input and output operations performed over the RS-232 connection to a
terminal (e.g. from/to a PC running a terminal program), while the lcd_str stream provides a method to display
character data on the LCD text display.
The function delay_1s() suspends program execution for approximately one second. This is done using the
_delay_ms() function from <util/delay.h> which in turn needs the F_CPU macro in order to adjust the
cycle counts. As the _delay_ms() function has a limited range of allowable argument values (depending on
F_CPU), a value of 10 ms has been chosen as the base delay which would be safe for CPU frequencies of up to
about 26 MHz. This function is then called 100 times to accomodate for the actual one-second delay.
In a practical application, long delays like this one were better be handled by a hardware timer, so the main CPU
would be free for other tasks while waiting, or could be put on sleep.
At the beginning of main(), after initializing the peripheral devices, the default stdio streams stdin, stdout,
and stderr are set up by using the existing static FILE stream objects. While this is not mandatory, the availability
of stdin and stdout allows to use the shorthand functions (e.g. printf() instead of fprintf()), and
stderr can mnemonically be referred to when sending out diagnostic messages.
Just for demonstration purposes, stdin and stdout are connected to a stream that will perform UART IO, while
stderr is arranged to output its data to the LCD text display.
Finally, a main loop follows that accepts simple "commands" entered via the RS-232 connection, and performs a
few simple actions based on the commands.
First, a prompt is sent out using printf_P() (which takes a program space string). The string is read into an
internal buffer as one line of input, using fgets(). While it would be also possible to use gets() (which implicitly
reads from stdin), gets() has no control that the user's input does not overflow the input buffer provided so it
should never be used at all.
If fgets() fails to read anything, the main loop is left. Of course, normally the main loop of a microcontroller
application is supposed to never finish, but again, for demonstrational purposes, this explains the error handling of
stdio. fgets() will return NULL in case of an input error or end-of-file condition on input. Both these conditions
are in the domain of the function that is used to establish the stream, uart_putchar() in this case. In short, this
function returns EOF in case of a serial line "break" condition (extended start condition) has been recognized on
the serial line. Common PC terminal programs allow to assert this condition as some kind of out-of-band signalling
on an RS-232 connection.
When leaving the main loop, a goodbye message is sent to standard error output (i.e. to the LCD), followed by three
dots in one-second spacing, followed by a sequence that will clear the LCD. Finally, main() will be terminated,
and the library will add an infinite loop, so only a CPU reset will be able to restart the application.
There are three "commands" recognized, each determined by the first letter of the line entered (converted to lower
case):
• The 'q' (quit) command has the same effect of leaving the main loop.
• The 'l' (LCD) command takes its second argument, and sends it to the LCD.
• The 'u' (UART) command takes its second argument, and sends it back to the UART connection.
Command recognition is done using sscanf() where the first format in the format string just skips over the
command itself (as the assignment suppression modifier ∗ is given).
23.41.3.2 defines.h
23.41.3.3 hd44780.h
This file describes the public interface of the low-level LCD driver that interfaces to the HD44780 LCD controller.
Public functions are available to initialize the controller into 4-bit mode, to wait for the controller's busy bit to be clear,
and to read or write one byte from or to the controller.
As there are two different forms of controller IO, one to send a command or receive the controller status (RS signal
clear), and one to send or receive data to/from the controller's SRAM (RS asserted), macros are provided that build
on the mentioned function primitives.
Finally, macros are provided for all the controller commands to allow them to be used symbolically. The HD44780
datasheet explains these basic functions of the controller in more detail.
23.41.3.4 hd44780.c
the input data if the parameter readback is true. When called with a compile-time constant parameter that is
false, the compiler will completely eliminate the unused readback operation, as well as the return value as part of
its optimizations.
As the controller is used in 4-bit interface mode, all byte IO to/from the controller needs to be handled as two
nibble IOs. The functions hd44780_outnibble() and hd44780_innibble() implement this. They do not
belong to the public interface, so they are declared static.
Building upon these, the public functions hd44780_outbyte() and hd44780_inbyte() transfer one byte
to/from the controller.
The function hd44780_wait_ready() waits for the controller to become ready, by continuously polling the
controller's status (which is read by performing a byte read with the RS signal cleard), and examining the BUSY flag
within the status byte. This function needs to be called before performing any controller IO.
Finally, hd44780_init() initializes the LCD controller into 4-bit mode, based on the initialization sequence
mandated by the datasheet. As the BUSY flag cannot be examined yet at this point, this is the only part of this code
where timed delays are used. While the controller can perform a power-on reset when certain constraints on the
power supply rise time are met, always calling the software initialization routine at startup ensures the controller will
be in a known state. This function also puts the interface into 4-bit mode (which would not be done automatically
after a power-on reset).
23.41.3.5 lcd.h
This function declares the public interface of the higher-level (character IO) LCD driver.
23.41.3.6 lcd.c
The implementation of the higher-level LCD driver. This driver builds on top of the HD44780 low-level LCD controller
driver, and offers a character IO interface suitable for direct use by the standard IO facilities. Where the low-
level HD44780 driver deals with setting up controller SRAM addresses, writing data to the controller's SRAM, and
controlling display functions like clearing the display, or moving the cursor, this high-level driver allows to just write
a character to the LCD, in the assumption this will somehow show up on the display.
Control characters can be handled at this level, and used to perform specific actions on the LCD. Currently, there
is only one control character that is being dealt with: a newline character (\n) is taken as an indication to clear
the display and set the cursor into its initial position upon reception of the next character, so a "new line" of text
can be displayed. Therefore, a received newline character is remembered until more characters have been sent by
the application, and will only then cause the display to be cleared before continuing. This provides a convenient
abstraction where full lines of text can be sent to the driver, and will remain visible at the LCD until the next line is to
be displayed.
Further control characters could be implemented, e. g. using a set of escape sequences. That way, it would be
possible to implement self-scrolling display lines etc.
The public function lcd_init() first calls the initialization entry point of the lower-level HD44780 driver, and then
sets up the LCD in a way we'd like to (display cleared, non-blinking cursor enabled, SRAM addresses are increasing
so characters will be written left to right).
The public function lcd_putchar() takes arguments that make it suitable for being passed as a put() function
pointer to the stdio stream initialization functions and macros (fdevopen(), FDEV_SETUP_STREAM() etc.).
Thus, it takes two arguments, the character to display itself, and a reference to the underlying stream object, and it
is expected to return 0 upon success.
This function remembers the last unprocessed newline character seen in the function-local static variable nl_←-
seen. If a newline character is encountered, it will simply set this variable to a true value, and return to the caller.
As soon as the first non-newline character is to be displayed with nl_seen still true, the LCD controller is told to
clear the display, put the cursor home, and restart at SRAM address 0. All other characters are sent to the display.
The single static function-internal variable nl_seen works for this purpose. If multiple LCDs should be controlled
using the same set of driver functions, that would not work anymore, as a way is needed to distinguish between the
various displays. This is where the second parameter can be used, the reference to the stream itself: instead of
keeping the state inside a private variable of the function, it can be kept inside a private object that is attached to
the stream itself. A reference to that private object can be attached to the stream (e.g. inside the function lcd_←-
init() that then also needs to be passed a reference to the stream) using fdev_set_udata(), and can be
accessed inside lcd_putchar() using fdev_get_udata().
23.41.3.7 uart.h
Public interface definition for the RS-232 UART driver, much like in lcd.h except there is now also a character input
function available.
As the RS-232 input is line-buffered in this example, the macro RX_BUFSIZE determines the size of that buffer.
23.41.3.8 uart.c
This implements an stdio-compatible RS-232 driver using an AVR's standard UART (or USART in asynchronous
operation mode). Both, character output as well as character input operations are implemented. Character output
takes care of converting the internal newline \n into its external representation carriage return/line feed (\r\n).
Character input is organized as a line-buffered operation that allows to minimally edit the current line until it is "sent"
to the application when either a carriage return (\r) or newline (\n) character is received from the terminal. The
line editing functions implemented are:
The function uart_init() takes care of all hardware initialization that is required to put the UART into a mode
with 8 data bits, no parity, one stop bit (commonly referred to as 8N1) at the baud rate configured in defines.h. At
low CPU clock frequencies, the U2X bit in the UART is set, reducing the oversampling from 16x to 8x, which allows
for a 9600 Bd rate to be achieved with tolerable error using the default 1 MHz RC oscillator.
The public function uart_putchar() again has suitable arguments for direct use by the stdio stream interface.
It performs the \n into \r\n translation by recursively calling itself when it sees a \n character. Just for demon-
stration purposes, the \a (audible bell, ASCII BEL) character is implemented by sending a string to stderr, so it
will be displayed on the LCD.
The public function uart_getchar() implements the line editor. If there are characters available in the line
buffer (variable rxp is not NULL), the next character will be returned from the buffer without any UART interaction.
If there are no characters inside the line buffer, the input loop will be entered. Characters will be read from the U←-
ART, and processed accordingly. If the UART signalled a framing error (FE bit set), typically caused by the terminal
sending a line break condition (start condition held much longer than one character period), the function will return
an end-of-file condition using _FDEV_EOF. If there was a data overrun condition on input (DOR bit set), an error
condition will be returned as _FDEV_ERR.
Line editing characters are handled inside the loop, potentially modifying the buffer status. If characters are at-
tempted to be entered beyond the size of the line buffer, their reception is refused, and a \a character is sent to the
terminal. If a \r or \n character is seen, the variable rxp (receive pointer) is set to the beginning of the buffer, the
loop is left, and the first character of the buffer will be returned to the application. (If no other characters have been
entered, this will just be the newline character, and the buffer is marked as being exhausted immediately again.)
Some newer devices of the ATmega series contain builtin support for interfacing the microcontroller to a two-wire
bus, called TWI. This is essentially the same called I2C by Philips, but that term is avoided in Atmel's documentation
due to patenting issues.
For further documentation, see:
http://www.nxp.com/documents/user_manual/UM10204.pdf
The two-wire interface consists of two signal lines named SDA (serial data) and SCL (serial clock) (plus a ground
line, of course). All devices participating in the bus are connected together, using open-drain driver circuitry, so the
wires must be terminated using appropriate pullup resistors. The pullups must be small enough to recharge the line
capacity in short enough time compared to the desired maximal clock frequency, yet large enough so all drivers will
not be overloaded. There are formulas in the datasheet that help selecting the pullups.
Devices can either act as a master to the bus (i. e., they initiate a transfer), or as a slave (they only act when being
called by a master). The bus is multi-master capable, and a particular device implementation can act as either
master or slave at different times. Devices are addressed using a 7-bit address (coordinated by Philips) transfered
as the first byte after the so-called start condition. The LSB of that byte is R/∼W, i. e. it determines whether the
request to the slave is to read or write data during the next cycles. (There is also an option to have devices using
10-bit addresses but that is not covered by this example.)
The ATmega TWI hardware supports both, master and slave operation. This example will only demonstrate how to
use an AVR microcontroller as TWI master. The implementation is kept simple in order to concentrate on the steps
that are required to talk to a TWI slave, so all processing is done in polled-mode, waiting for the TWI interface to
indicate that the next processing step is due (by setting the TWINT interrupt bit). If it is desired to have the entire
TWI communication happen in "background", all this can be implemented in an interrupt-controlled way, where only
the start condition needs to be triggered from outside the interrupt routine.
There is a variety of slave devices available that can be connected to a TWI bus. For the purpose of this example,
an EEPROM device out of the industry-standard 24Cxx series has been chosen (where xx can be one of 01, 02, 04,
08, or 16) which are available from various vendors. The choice was almost arbitrary, mainly triggered by the fact
that an EEPROM device is being talked to in both directions, reading and writing the slave device, so the example
will demonstrate the details of both.
Usually, there is probably not much need to add more EEPROM to an ATmega system that way: the smallest
possible AVR device that offers hardware TWI support is the ATmega8 which comes with 512 bytes of EEPROM,
which is equivalent to an 24C04 device. The ATmega128 already comes with twice as much EEPROM as the
24C16 would offer. One exception might be to use an externally connected EEPROM device that is removable; e.
g. SDRAM PC memory comes with an integrated TWI EEPROM that carries the RAM configuration information.
Note [1]
The header file <util/twi.h> contains some macro definitions for symbolic constants used in the TWI status
register. These definitions match the names used in the Atmel datasheet except that all names have been prefixed
with TW_.
Note [2]
The clock is used in timer calculations done by the compiler, for the UART baud rate and the TWI clock rate.
Note [3]
The address assigned for the 24Cxx EEPROM consists of 1010 in the upper four bits. The following three bits are
normally available as slave sub-addresses, allowing to operate more than one device of the same type on a single
bus, where the actual subaddress used for each device is configured by hardware strapping. However, since the
next data packet following the device selection only allows for 8 bits that are used as an EEPROM address, devices
that require more than 8 address bits (24C04 and above) "steal" subaddress bits and use them for the EEPROM
cell address bits 9 to 11 as required. This example simply assumes all subaddress bits are 0 for the smaller devices,
so the E0, E1, and E2 inputs of the 24Cxx must be grounded.
Note [3a]
EEPROMs of type 24C32 and above cannot be addressed anymore even with the subaddress bit trick. Thus, they
require the upper address bits being sent separately on the bus. When activating the WORD_ADDRESS_16BIT
define, the algorithm implements that auxiliary address byte transmission.
Note [4]
For slow clocks, enable the 2 x U[S]ART clock multiplier, to improve the baud rate error. This will allow a 9600 Bd
communication using the standard 1 MHz calibrated RC oscillator. See also the Baud rate tables in the datasheets.
Note [5]
The datasheet explains why a minimum TWBR value of 10 should be maintained when running in master mode.
Thus, for system clocks below 3.6 MHz, we cannot run the bus at the intented clock rate of 100 kHz but have to
slow down accordingly.
Note [6]
This function is used by the standard output facilities that are utilized in this example for debugging and demonstra-
tion purposes.
Note [7]
In order to shorten the data to be sent over the TWI bus, the 24Cxx EEPROMs support multiple data bytes transfered
within a single request, maintaining an internal address counter that is updated after each data byte transfered
successfully. When reading data, one request can read the entire device memory if desired (the counter would
wrap around and start back from 0 when reaching the end of the device).
Note [8]
When reading the EEPROM, a first device selection must be made with write intent (R/∼W bit set to 0 indicating
a write operation) in order to transfer the EEPROM address to start reading from. This is called master transmitter
mode. Each completion of a particular step in TWI communication is indicated by an asserted TWINT bit in T←-
WCR. (An interrupt would be generated if allowed.) After performing any actions that are needed for the next
communication step, the interrupt condition must be manually cleared by setting the TWINT bit. Unlike with many
other interrupt sources, this would even be required when using a true interrupt routine, since as soon as TWINT is
re-asserted, the next bus transaction will start.
Note [9]
Since the TWI bus is multi-master capable, there is potential for a bus contention when one master starts to access
the bus. Normally, the TWI bus interface unit will detect this situation, and will not initiate a start condition while the
bus is busy. However, in case two masters were starting at exactly the same time, the way bus arbitration works,
there is always a chance that one master could lose arbitration of the bus during any transmit operation. A master
that has lost arbitration is required by the protocol to immediately cease talking on the bus; in particular it must not
initiate a stop condition in order to not corrupt the ongoing transfer from the active master. In this example, upon
detecting a lost arbitration condition, the entire transfer is going to be restarted. This will cause a new start condition
to be initiated, which will normally be delayed until the currently active master has released the bus.
Note [10]
Next, the device slave is going to be reselected (using a so-called repeated start condition which is meant to
guarantee that the bus arbitration will remain at the current master) using the same slave address (SLA), but this
time with read intent (R/∼W bit set to 1) in order to request the device slave to start transfering data from the slave
to the master in the next packet.
Note [11]
If the EEPROM device is still busy writing one or more cells after a previous write request, it will simply leave its bus
interface drivers at high impedance, and does not respond to a selection in any way at all. The master selecting
the device will see the high level at SDA after transfering the SLA+R/W packet as a NACK to its selection request.
Thus, the select process is simply started over (effectively causing a repeated start condition), until the device will
eventually respond. This polling procedure is recommended in the 24Cxx datasheet in order to minimize the busy
wait time when writing. Note that in case a device is broken and never responds to a selection (e. g. since it is no
longer present at all), this will cause an infinite loop. Thus the maximal number of iterations made until the device is
declared to be not responding at all, and an error is returned, will be limited to MAX_ITER.
Note [12]
This is called master receiver mode: the bus master still supplies the SCL clock, but the device slave drives the SDA
line with the appropriate data. After 8 data bits, the master responds with an ACK bit (SDA driven low) in order to
request another data transfer from the slave, or it can leave the SDA line high (NACK), indicating to the slave that it
is going to stop the transfer now. Assertion of ACK is handled by setting the TWEA bit in TWCR when starting the
current transfer.
Note [13]
The control word sent out in order to initiate the transfer of the next data packet is initially set up to assert the TWEA
bit. During the last loop iteration, TWEA is de-asserted so the client will get informed that no further transfer is
desired.
Note [14]
Except in the case of lost arbitration, all bus transactions must properly be terminated by the master initiating a stop
condition.
Note [15]
Writing to the EEPROM device is simpler than reading, since only a master transmitter mode transfer is needed.
Note that the first packet after the SLA+W selection is always considered to be the EEPROM address for the
next operation. (This packet is exactly the same as the one above sent before starting to read the device.) In
case a master transmitter mode transfer is going to send more than one data packet, all following packets will be
considered data bytes to write at the indicated address. The internal address pointer will be incremented after each
write operation.
Note [16]
24Cxx devices can become write-protected by strapping their ∼WC pin to logic high. (Leaving it unconnected is
explicitly allowed, and constitutes logic low level, i. e. no write protection.) In case of a write protected device, all
data transfer attempts will be NACKed by the device. Note that some devices might not implement this.
Data Fields
• int quot
• int rem
The Quotient.
The Remainder.
The documentation for this struct was generated from the following file:
• stdlib.h
Data Fields
• long quot
• long rem
The Quotient.
The Remainder.
The documentation for this struct was generated from the following file:
• stdlib.h
Data Fields
• int8_t tm_sec
• int8_t tm_min
• int8_t tm_hour
• int8_t tm_mday
• int8_t tm_wday
• int8_t tm_mon
• int16_t tm_year
• int16_t tm_yday
• int16_t tm_isdst
The tm structure contains a representation of time 'broken down' into components of the Gregorian calendar.
The value of tm_isdst is zero if Daylight Saving Time is not in effect, and is negative if the information is not available.
When Daylight Saving Time is in effect, the value represents the number of seconds the clock is advanced.
See the set_dst() function for more information about Daylight Saving.
• time.h
Data Fields
• int year
• int week
• int day
Structure which represents a date as a year, week number of that year, and day of week. See http://en.←-
wikipedia.org/wiki/ISO_week_date for more information.
• time.h
25 File Documentation
Macros
• #define assert(expression)
Macros
• #define ATOMIC_BLOCK(type)
• #define NONATOMIC_BLOCK(type)
• #define ATOMIC_RESTORESTATE
• #define ATOMIC_FORCEON
• #define NONATOMIC_RESTORESTATE
• #define NONATOMIC_FORCEOFF
Macros
Macros
• #define _NOP()
• #define _MemoryBarrier()
Functions
Functions
Macros
Functions
Functions
Macros
• #define EDOM 33
• #define ERANGE 34
Variables
• int errno
Functions
Macros
• #define sei()
• #define cli()
ISR attributes
• #define ISR_BLOCK
• #define ISR_NOBLOCK
• #define ISR_NAKED
• #define ISR_ALIASOF(target_vector)
@{
Macros
Typedefs
Macros
Functions
Macros
• #define parity_even_bit(val)
Macros
Typedefs
Functions
Macros
Functions
Gets and returns the clock prescaler register setting. The return type is clock_div_t.
Note
For device with XTAL Divide Control Register (XDIV), return can actually range from 1 to 129. Care should
be taken has the return value could differ from the typedef enum clock_div_t. This should only happen if
clock_prescale_set was previously called with a value other than those defined by clock_div_t.
Macros
• #define BAUD_TOL 2
• #define UBRR_VALUE
• #define UBRRL_VALUE
• #define UBRRH_VALUE
• #define USE_2X 0
Functions
Functions
Macros
Typedefs
Macros
Typedefs
Functions
Data Structures
• struct div_t
• struct ldiv_t
Macros
Typedefs
Functions
Variables
• size_t __malloc_margin
• char ∗ __malloc_heap_start
• char ∗ __malloc_heap_end
Note that these functions are not located in the default library, libc.a, but in the mathematical library, libm.a.
So when linking the application, the -lm option needs to be specified.
Macros
• #define _FFS(x)
Functions
Data Structures
• struct tm
• struct week_date
Macros
Typedefs
Enumerations
• enum _WEEK_DAYS_ {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY }
• enum _MONTHS_ {
JANUARY, FEBRUARY, MARCH, APRIL,
MAY, JUNE, JULY, AUGUST,
SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }
Functions
Macros
TWSR values
Mnemonics:
TW_MT_xxx - master transmitter
TW_MR_xxx - master receiver
TW_ST_xxx - slave transmitter
TW_SR_xxx - slave receiver
• #define TW_READ 1
• #define TW_WRITE 0
Macros
Functions
__AVR_LIBC_VERSION_STRING__ acosf
<avr/version.h>: avr-libc version macros, 238 <math.h>: Mathematics, 122
__AVR_LIBC_VERSION__ Additional notes from <avr/sfr_defs.h>, 232
<avr/version.h>: avr-libc version macros, 238 alloca
__EEGET <alloca.h>: Allocate space in the stack, 103
<avr/eeprom.h>: EEPROM handling, 185 asctime
__EEPUT <time.h>: Time, 173
<avr/eeprom.h>: EEPROM handling, 185 asctime_r
__attribute__ <time.h>: Time, 174
<avr/wdt.h>: Watchdog timer handling, 241 asin
power.h, 303 <math.h>: Mathematics, 125
__compar_fn_t asinf
<stdlib.h>: General utilities, 155 <math.h>: Mathematics, 122
__malloc_heap_end assert
<stdlib.h>: General utilities, 161 <assert.h>: Diagnostics, 105
__malloc_heap_start assert.h, 293
<stdlib.h>: General utilities, 161 atan
__malloc_margin <math.h>: Mathematics, 125
<stdlib.h>: General utilities, 161 atan2
_crc16_update <math.h>: Mathematics, 125
<util/crc16.h>: CRC Computations, 245 atan2f
_crc8_ccitt_update <math.h>: Mathematics, 122
<util/crc16.h>: CRC Computations, 246 atanf
_crc_ccitt_update <math.h>: Mathematics, 122
<util/crc16.h>: CRC Computations, 246 atof
_crc_ibutton_update <stdlib.h>: General utilities, 156
<util/crc16.h>: CRC Computations, 247 atoi
_crc_xmodem_update <stdlib.h>: General utilities, 156
<util/crc16.h>: CRC Computations, 247 atol
_delay_loop_1 <stdlib.h>: General utilities, 156
<util/delay_basic.h>: Basic busy-wait delay loops, atomic.h, 293
250 avrdude, usage, 94
_delay_loop_2 avrprog, usage, 94
<util/delay_basic.h>: Basic busy-wait delay loops,
250 BADISR_vect
_delay_ms <avr/interrupt.h>: Interrupts, 204
<util/delay.h>: Convenience functions for busy- BAUD_TOL
wait delay loops, 248 <util/setbaud.h>: Helper macros for baud rate cal-
_delay_us culations, 253
<util/delay.h>: Convenience functions for busy- BOOTLOADER_SECTION
wait delay loops, 249 <avr/boot.h>: Bootloader Support Utilities, 182
bit_is_clear
A more sophisticated project, 277 <avr/sfr_defs.h>: Special function registers, 234
A simple project, 266 bit_is_set
ATOMIC_BLOCK <avr/sfr_defs.h>: Special function registers, 234
<util/atomic.h> Atomically and Non-Atomically Ex- boot.h, 294
ecuted Code Blocks, 243 boot_is_spm_interrupt
ATOMIC_FORCEON <avr/boot.h>: Bootloader Support Utilities, 179
<util/atomic.h> Atomically and Non-Atomically Ex- boot_lock_bits_set
ecuted Code Blocks, 243 <avr/boot.h>: Bootloader Support Utilities, 179
ATOMIC_RESTORESTATE boot_lock_bits_set_safe
<util/atomic.h> Atomically and Non-Atomically Ex- <avr/boot.h>: Bootloader Support Utilities, 179
ecuted Code Blocks, 243 boot_lock_fuse_bits_get
abort <avr/boot.h>: Bootloader Support Utilities, 180
<stdlib.h>: General utilities, 156 boot_page_erase
abs <avr/boot.h>: Bootloader Support Utilities, 180
<stdlib.h>: General utilities, 156 boot_page_erase_safe
acos <avr/boot.h>: Bootloader Support Utilities, 180
<math.h>: Mathematics, 125 boot_page_fill
eeprom_read_float fdev_set_udata
<avr/eeprom.h>: EEPROM handling, 185 <stdio.h>: Standard IO facilities, 145
eeprom_read_word fdev_setup_stream
<avr/eeprom.h>: EEPROM handling, 185 <stdio.h>: Standard IO facilities, 145
eeprom_update_block fdevopen
<avr/eeprom.h>: EEPROM handling, 186 <stdio.h>: Standard IO facilities, 146
eeprom_update_byte fdevopen.c, 296
<avr/eeprom.h>: EEPROM handling, 186 fdim
eeprom_update_dword <math.h>: Mathematics, 126
<avr/eeprom.h>: EEPROM handling, 186 fdimf
eeprom_update_float <math.h>: Mathematics, 122
<avr/eeprom.h>: EEPROM handling, 186 feof
eeprom_update_word <stdio.h>: Standard IO facilities, 146
<avr/eeprom.h>: EEPROM handling, 186 ferror
eeprom_write_block <stdio.h>: Standard IO facilities, 146
<avr/eeprom.h>: EEPROM handling, 186 fflush
eeprom_write_byte <stdio.h>: Standard IO facilities, 147
<avr/eeprom.h>: EEPROM handling, 186 ffs
eeprom_write_dword <string.h>: Strings, 163
<avr/eeprom.h>: EEPROM handling, 186 ffsl
eeprom_write_float <string.h>: Strings, 163
<avr/eeprom.h>: EEPROM handling, 186 ffsll
eeprom_write_word <string.h>: Strings, 163
<avr/eeprom.h>: EEPROM handling, 186 fgetc
enable_external_int <stdio.h>: Standard IO facilities, 147
<compat/deprecated.h>: Deprecated items, 259 fgets
equation_of_time <stdio.h>: Standard IO facilities, 147
<time.h>: Time, 174 floor
errno <math.h>: Mathematics, 126
<errno.h>: System Errors, 108 floorf
errno.h, 295
<math.h>: Mathematics, 122
Example using the two-wire interface (TWI), 287
fma
exit
<math.h>: Mathematics, 126
<stdlib.h>: General utilities, 157
fmaf
exp
<math.h>: Mathematics, 122
<math.h>: Mathematics, 126
fmax
expf
<math.h>: Mathematics, 126
<math.h>: Mathematics, 122
fmaxf
F_CPU <math.h>: Mathematics, 122
<util/delay.h>: Convenience functions for busy- fmin
wait delay loops, 248 <math.h>: Mathematics, 126
FDEV_SETUP_STREAM fminf
<stdio.h>: Standard IO facilities, 145 <math.h>: Mathematics, 122
FILE fmod
<stdio.h>: Standard IO facilities, 146 <math.h>: Mathematics, 126
fabs fmodf
<math.h>: Mathematics, 126 <math.h>: Mathematics, 123
fabsf fprintf
<math.h>: Mathematics, 122 <stdio.h>: Standard IO facilities, 147
FAQ, 45 fprintf_P
fatfs_time <stdio.h>: Standard IO facilities, 147
<time.h>: Time, 174 fputc
fclose <stdio.h>: Standard IO facilities, 147
<stdio.h>: Standard IO facilities, 146 fputs
fdev_close <stdio.h>: Standard IO facilities, 147
<stdio.h>: Standard IO facilities, 144 fputs_P
fdev_get_udata <stdio.h>: Standard IO facilities, 147
<stdio.h>: Standard IO facilities, 144 fread
ISR_BLOCK isascii
<avr/interrupt.h>: Interrupts, 205 <ctype.h>: Character Operations, 106
ISR_NAKED isblank
<avr/interrupt.h>: Interrupts, 205 <ctype.h>: Character Operations, 106
ISR_NOBLOCK iscntrl
<avr/interrupt.h>: Interrupts, 205 <ctype.h>: Character Operations, 106
inb isdigit
<compat/deprecated.h>: Deprecated items, 259 <ctype.h>: Character Operations, 107
inp isfinite
<compat/deprecated.h>: Deprecated items, 259 <math.h>: Mathematics, 127
installation, 65 isfinitef
installation, avarice, 70 <math.h>: Mathematics, 123
installation, avr-libc, 68 isgraph
installation, avrdude, 69 <ctype.h>: Character Operations, 107
installation, avrprog, 69 isinf
installation, binutils, 67 <math.h>: Mathematics, 127
installation, gcc, 68 isinff
Installation, gdb, 69 <math.h>: Mathematics, 123
installation, simulavr, 69 islower
int16_t <ctype.h>: Character Operations, 107
<stdint.h>: Standard Integer Types, 138 isnan
int32_t <math.h>: Mathematics, 127
<stdint.h>: Standard Integer Types, 138 isnanf
int64_t <math.h>: Mathematics, 123
<stdint.h>: Standard Integer Types, 138 iso_week_date
int8_t <time.h>: Time, 174
<stdint.h>: Standard Integer Types, 138 iso_week_date_r
int_farptr_t <time.h>: Time, 174
<inttypes.h>: Integer Type conversions, 118 isotime
int_fast16_t <time.h>: Time, 175
isotime_r
<stdint.h>: Standard Integer Types, 139
int_fast32_t
<time.h>: Time, 175
isprint
<stdint.h>: Standard Integer Types, 139
<ctype.h>: Character Operations, 107
int_fast64_t
ispunct
<stdint.h>: Standard Integer Types, 139
<ctype.h>: Character Operations, 107
int_fast8_t
isspace
<stdint.h>: Standard Integer Types, 139
<ctype.h>: Character Operations, 107
int_least16_t
isupper
<stdint.h>: Standard Integer Types, 139
<ctype.h>: Character Operations, 107
int_least32_t
isxdigit
<stdint.h>: Standard Integer Types, 139
<ctype.h>: Character Operations, 107
int_least64_t
itoa
<stdint.h>: Standard Integer Types, 139
<stdlib.h>: General utilities, 157
int_least8_t
<stdint.h>: Standard Integer Types, 139 labs
interrupt.h, 296 <stdlib.h>: General utilities, 158
intmax_t ldexp
<stdint.h>: Standard Integer Types, 139 <math.h>: Mathematics, 127
intptr_t ldexpf
<stdint.h>: Standard Integer Types, 139 <math.h>: Mathematics, 123
inttypes.h, 296 ldiv
io.h, 298 <stdlib.h>: General utilities, 158
is_leap_year ldiv_t, 291
<time.h>: Time, 174 quot, 291
isalnum rem, 291
<ctype.h>: Character Operations, 106 lm_sidereal
isalpha <time.h>: Time, 175
<ctype.h>: Character Operations, 106 localtime
WDTO_120MS
<avr/wdt.h>: Watchdog timer handling, 240
WDTO_15MS
<avr/wdt.h>: Watchdog timer handling, 240
WDTO_1S
<avr/wdt.h>: Watchdog timer handling, 240
WDTO_250MS
<avr/wdt.h>: Watchdog timer handling, 240
WDTO_2S
<avr/wdt.h>: Watchdog timer handling, 240
WDTO_30MS
<avr/wdt.h>: Watchdog timer handling, 240
WDTO_4S
<avr/wdt.h>: Watchdog timer handling, 240
WDTO_500MS
<avr/wdt.h>: Watchdog timer handling, 240
WDTO_60MS
<avr/wdt.h>: Watchdog timer handling, 240
WDTO_8S
<avr/wdt.h>: Watchdog timer handling, 240
wdt.h, 311
wdt_reset
<avr/wdt.h>: Watchdog timer handling, 240
week
week_date, 293
week_date, 293
day, 293
week, 293
year, 293
week_of_month
<time.h>: Time, 177
week_of_year
<time.h>: Time, 177
year
week_date, 293