void
set_bits_func_wrong (volatile uint8_t port, uint8_t mask)
{
port |= mask;
}
void
set_bits_func_correct (volatile uint8_t *port, uint8_t mask)
{
*port |= mask;
}
#define set_bits_macro(port,mask) ((port) |= (mask))
int main (void)
{
set_bits_func_wrong (PORTB, 0xaa);
set_bits_func_correct (&PORTB, 0x55);
set_bits_macro (PORTB, 0xf0);
return (0);
}
\endcode
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 \c PORTB
register (using an \c IN instruction), instead of passing the address of \c
PORTB (e.g. memory mapped io addr of \c 0x38, io port \c 0x18 for the
mega128). This is seen clearly when looking at the disassembly of the call:
\verbatim
set_bits_func_wrong (PORTB, 0xaa);
10a: 6a ea ldi r22, 0xAA ; 170
10c: 88 b3 in r24, 0x18 ; 24
10e: 0e 94 65 00 call 0xca
\endverbatim
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:
\verbatim
set_bits_func_correct (&PORTB, 0x55);
112: 65 e5 ldi r22, 0x55 ; 85
114: 88 e3 ldi r24, 0x38 ; 56
116: 90 e0 ldi r25, 0x00 ; 0
118: 0e 94 7c 00 call 0xf8
\endverbatim
You can clearly see that \c 0x0038 is correctly passed for the address of the
io port. Looking at the disassembled object code for the body of the function,
we can see that the function is indeed performing the operation we intended:
\verbatim
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
\endverbatim
Notice that we are accessing the io port via the \c LD and \c ST instructions.
The \c port parameter must be volatile to avoid a compiler warning.
\note Because of the nature of the \c IN and \c 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
data sheet.
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:
\verbatim
set_bits_macro (PORTB, 0xf0);
11c: 88 b3 in r24, 0x18 ; 24
11e: 80 6f ori r24, 0xF0 ; 240
120: 88 bb out 0x18, r24 ; 24
\endverbatim
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 \c volatile, so the correct behaviour for 16-bit IO
ports can be forced that way.
Back to \ref faq_index.
\section faq_reg_usage What registers are used by the C compiler?
- Data types:
\c char is 8 bits, \c int is 16 bits, \c long is 32 bits, \c long long
is 64 bits, \c float and \c double are 32 bits (this is the only
supported floating point format), pointers are 16 bits (function
pointers are word addresses, to allow addressing the whole 128K
program memory space on the ATmega devices with > 64 KB of flash
ROM). There is a \c -mint8 option (see \ref using_avr_gcc) to make
\c int 8 bits, but that is not supported by avr-libc and violates C
standards (\c int \e must be at least 16 bits). It may be removed in
a future release.
- Call-used registers (r18-r27, r30-r31):
May be allocated by gcc for local data.
You \e may use them freely in assembler subroutines.
Calling C subroutines can clobber any of them -
the caller is responsible for saving and restoring.
- Call-saved registers (r2-r17, r28-r29):
May be allocated by gcc for local data.
Calling C subroutines leaves them unchanged.
Assembler subroutines are responsible for saving
and restoring these registers, if changed.
r29:r28 (Y pointer) is used as a frame pointer
(points to local data on stack) if necessary.
The requirement for the callee to save/preserve
the contents of these registers even applies in
situations where the compiler assigns them for
argument passing.
- Fixed registers (r0, r1):
Never allocated by gcc for local data, but often
used for fixed purposes:
r0 - temporary register, can be clobbered by any
C code (except interrupt handlers which save it),
\e 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,
\e may be used to remember something for a while
within one piece of assembler code, but \e must
then be cleared after use (clr r1). This
includes any use of the [f]mul[s[u]] instructions,
which return their result in r1:r0.
Interrupt handlers save and clear r1 on entry,
and restore r1 on exit (in case it was non-zero).
- Function call conventions:
Arguments - allocated left to right, r25 to r8.
All arguments are aligned to start in even-numbered
registers (odd-sized arguments, including \c char, have
one free register above them). This allows making better
use of the \c 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 caller (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 \c char
is extended to \c 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.
Back to \ref faq_index.
\section faq_rom_array How do I put an array of strings completely in ROM?
There are times when you may need an array of strings which will never be
modified. In this case, you don't want to waste ram storing the constant
strings. The most obvious (and incorrect) thing to do is this:
\code
#include
PGM_P array[2] PROGMEM = {
"Foo",
"Bar"
};
int main (void)
{
char buf[32];
strcpy_P (buf, array[1]);
return 0;
}
\endcode
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 \c .data
section).
To work around this, you need to do something like this:
\code
#include
const char foo[] PROGMEM = "Foo";
const char bar[] PROGMEM = "Bar";
PGM_P array[2] PROGMEM = {
foo,
bar
};
int main (void)
{
char buf[32];
PGM_P p;
int i;
memcpy_P(&p, &array[i], sizeof(PGM_P));
strcpy_P(buf, p);
return 0;
}
\endcode
Looking at the disassembly of the resulting object file we see that array is
in flash as such:
\code
00000026 :
26: 2e 00 .word 0x002e ; ????
28: 2a 00 .word 0x002a ; ????
0000002a :
2a: 42 61 72 00 Bar.
0000002e :
2e: 46 6f 6f 00 Foo.
\endcode
\c foo is at addr 0x002e.
\c bar is at addr 0x002a.
\c array is at addr 0x0026.
Then in main we see this:
\code
memcpy_P(&p, &array[i], sizeof(PGM_P));
70: 66 0f add r22, r22
72: 77 1f adc r23, r23
74: 6a 5d subi r22, 0xDA ; 218
76: 7f 4f sbci r23, 0xFF ; 255
78: 42 e0 ldi r20, 0x02 ; 2
7a: 50 e0 ldi r21, 0x00 ; 0
7c: ce 01 movw r24, r28
7e: 81 96 adiw r24, 0x21 ; 33
80: 08 d0 rcall .+16 ; 0x92
\endcode
This code reads the pointer to the desired string from the ROM table
\c array into a register pair.
The value of \c i (in r22:r23) is doubled to accomodate 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 \c p is computed by adding its offset within the stack frame
(33) to the Y pointer register, and memcpy_P is
called.
\code
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
\endcode
This will finally copy the ROM string into the local buffer \c buf.
Variable \c 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 \c 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 \c array at compile-time.
Back to \ref faq_index.
\section faq_ext_ram How to use external RAM?
Well, there is no universal answer to this question; it depends on
what the external RAM is going to be used for.
Basically, the bit \c SRE (SRAM enable) in the \c 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 \c XMCRA and
\c XMCRB, and/or further bits in \c 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 \c .data and/or \c .bss segment) in that
memory area, it is essential to set up the external memory interface
early during the \ref sec_dot_init "device initialization" so the
initialization of these variable will take place. Refer to
\ref faq_startup for a description how to do this using few lines of
assembler code, or to the chapter about memory sections for an
\ref c_sections "example written in C".
The explanation of malloc() contains a \ref malloc_where "discussion"
about the use of internal RAM vs. external RAM in particular with
respect to the various possible locations of the \e 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 \c .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 \ref faq_index.
\section faq_optflags Which -O flag to use?
There's a common misconception that larger numbers behind the \c -O
option might automatically cause "better" optimization. First,
there's no universal definition for "better", with optimization often
being a speed vs. code size tradeoff. See the
\ref gcc_optO "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 applications that need to
get the last few percent of speed benefit from using \c -O3.
Back to \ref faq_index.
\section faq_reloc_code How do I relocate code to a fixed address?
First, the code should be put into a new
\ref mem_sections "named section".
This is done with a section attribute:
\code
__attribute__ ((section (".bootloader")))
\endcode
In this example, \c .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.
\code
void boot(void) __attribute__ ((section (".bootloader")));
\endcode
To relocate the section to a fixed address the linker flag
\c --section-start is used. This option can be passed to the linker
using the \ref gcc_minusW "-Wl compiler option":
\code
-Wl,--section-start=.bootloader=0x1E000
\endcode
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 \ref faq_index.
\section faq_fuses 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 \c JTAGEN fuse programmed by
default. This will make the respective port pins that are used for
the JTAG interface unavailable for regular IO.
Back to \ref faq_index.
\section faq_flashstrings Why do all my "foo...bar" strings eat up the SRAM?
By default, all strings are handled as all other initialized
variables: they occupy RAM (even though the compiler might warn you
when it detects write attempts to these RAM locations), and occupy the
same amount of flash ROM so they can be initialized to the actual
string by startup code. The compiler can optimize multiple identical
strings into a single one, but obviously only for one compilation unit
(i. e., a single C source file).
That way, any string literal will be a valid argument to any C
function that expects a const char * argument.
Of course, this is going to waste a lot of SRAM. In
\ref avr_pgmspace "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 \c 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:
\code
#include
#include
#include
int
uart_putchar(char c)
{
if (c == '\n')
uart_putchar('\r');
loop_until_bit_is_set(USR, UDRE);
UDR = c;
return 0; /* so it could be used for fdevopen(), too */
}
void
debug_P(const char *addr)
{
char c;
while ((c = pgm_read_byte(addr++)))
uart_putchar(c);
}
int
main(void)
{
ioinit(); /* initialize UART, ... */
debug_P(PSTR("foo was here\n"));
return 0;
}
\endcode
\note By convention, the suffix \b _P to the function name is used as
an indication that this function is going to accept a "program-space
string". Note also the use of the PSTR() macro.
Back to \ref faq_index.
\section faq_intpromote 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:
\code
var &= ~mask; /* wrong way! */
\endcode
The bitwise "not" operator (\c ~) will also promote the value in \c mask
to an int. To keep it an 8-bit value, typecast before the "not"
operator:
\code
var &= (unsigned char)~mask;
\endcode
Back to \ref faq_index.
\section faq_ramoverlap How to detect RAM memory and variable overlap problems?
You can simply run avr-nm on your output (ELF) file.
Run it with the -n option, and it will sort the symbols
numerically (by default, they are sorted alphabetically).
Look for the symbol \c _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 avaialable
address in (internal) SRAM. Thus, the region between
\c _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 \ref 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 \ref faq_index.
\section faq_tinyavr_c Is it really impossible to program the ATtinyXX in C?
While some small AVRs are not directly supported by the C compiler
since they do not have a RAM-based stack (and some do not even have
RAM at all), it is possible anyway to use the general-purpose
registers as a RAM replacement since they are mapped into the data
memory region.
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 \ref faq_index.
\section faq_clockskew What is this "clock skew detected" messsage?
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 \c 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 \c
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 \ref faq_index.
\section faq_intbits Why are (many) interrupt flags cleared by writing a logical 1?
Usually, each interrupt has its own interrupt flag bit in some control
register, indicating the specified interrupt condition has been met by
representing a logical 1 in the respective bit position. When working
with interrupt handlers, this interrupt flag bit usually gets cleared
automatically in the course of processing the interrupt, sometimes by
just calling the handler at all, sometimes (e. g. for the U[S]ART) by
reading a particular hardware register that will normally happen
anyway when processing the interrupt.
From the hardware's point of view, an interrupt is asserted as long as
the respective bit is set, while global interrupts are enabled. Thus,
it is essential to have the bit cleared before interrupts get
re-enabled again (which usually happens when returning from an
interrupt handler).
Only few subsystems require an explicit action to clear the interrupt
request when using interrupt handlers. (The notable exception is the
TWI interface, where clearing the interrupt indicates to proceed with
the TWI bus hardware handshake, so it's never done automatically.)
However, if no normal interrupt handlers are to be used, or in order
to make extra sure any pending interrupt gets cleared before
re-activating global interrupts (e. g. an external edge-triggered
one), it can be necessary to explicitly clear the respective hardware
interrupt bit by software. This is usually done by writing a logical
1 into this bit position. This seems to be illogical at first, the
bit position already carries a logical 1 when reading it, so why does
writing a logical 1 to it clear the interrupt bit?
The solution is simple: writing a logical 1 to it requires only a
single \c 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 \c 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 \c 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
\code
TIFR |= _BV(TOV0); /* wrong! */
\endcode
simply use
\code
TIFR = _BV(TOV0);
\endcode
Back to \ref faq_index.
\section faq_fuselow Why have "programmed" fuses the bit value 0?
Basically, fuses are just a bit in a special EEPROM area. For
technical reasons, erased E[E]PROM cells have all bits set to the
value 1, so unprogrammed fuses also have a logical 1. Conversely,
programmed fuse cells read out as bit value 0.
Back to \ref faq_index.
\section faq_asmops Which AVR-specific assembler operators are available?
See \ref ass_pseudoops.
Back to \ref faq_index.
\section faq_spman 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:
\code
/* prologue: frame size=20 */
push r28
push r29
in r28,__SP_L__
in r29,__SP_H__
sbiw r28,20
in __tmp_reg__,__SREG__
cli
out __SP_H__,r29
out __SREG__,__tmp_reg__
out __SP_L__,r28
/* prologue end (size=10) */
\endcode
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 \c 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 \c SREG, and
writing \c SPL. However, after enabling interrupts (either explicitly
by setting the \c I flag, or by restoring it as part of the entire
\c SREG), the AVR hardware executes (at least) the next instruction
still with interrupts disabled, so the write to \c 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 \ref faq_index.
\section faq_linkerscripts Why are there five different linker scripts?
From a comment in the source code:
Which one of the five linker script files is actually used depends on command
line options given to ld.
A .x script file is the default script
A .xr script is for linking without relocation (-r flag)
A .xu script is like .xr but *do* create constructors (-Ur flag)
A .xn script is for linking with -n flag (mix text and data on same page).
A .xbn script is for linking with -N flag (mix text and data on same page).
Back to \ref faq_index.
\section faq_binarydata How to add a raw binary image to linker output?
The GNU linker avr-ld cannot handle binary data
directly. However, there's a companion tool called
avr-objcopy. This is already known from the output side: it's
used to extract the contents of the linked ELF file into an Intel Hex
load file.
avr-objcopy can create a relocatable object file from
arbitrary binary input, like
\code
avr-objcopy -I binary -O elf32-avr foo.bin foo.o
\endcode
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 \c _binary_foo_bin_start_ and \c
_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:
\code
avr-objcopy --rename-section .data=.progmem.data,contents,alloc,load,readonly,data -I binary -O elf32-avr foo.bin foo.o
\endcode
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.
Back to \ref faq_index.
\section faq_softreset How do I perform a software reset of the AVR?
The canonical way to perform a software reset of the AVR 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.
The reason why this is preferrable over jumping to the reset vector, is that
when the watchdog 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:
\code
#include
...
#define soft_reset() \
do \
{ \
wdt_enable(WDTO_15MS); \
for(;;) \
{ \
} \
} while(0)
\endcode
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):
\code
#include
...
// Function Pototype
void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3")));
...
// Function Implementation
void wdt_init(void)
{
MCUSR = 0;
wdt_disable();
return;
}
\endcode
Back to \ref faq_index.
*/