1/* Copyright (c) 2002-2007 Joerg Wunsch
2   All rights reserved.
3
4   Redistribution and use in source and binary forms, with or without
5   modification, are permitted provided that the following conditions are met:
6
7   * Redistributions of source code must retain the above copyright
8     notice, this list of conditions and the following disclaimer.
9   * Redistributions in binary form must reproduce the above copyright
10     notice, this list of conditions and the following disclaimer in
11     the documentation and/or other materials provided with the
12     distribution.
13   * Neither the name of the copyright holders nor the names of
14     contributors may be used to endorse or promote products derived
15     from this software without specific prior written permission.
16
17  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  POSSIBILITY OF SUCH DAMAGE. */
28
29/* $Id: faq.dox 2276 2012-01-03 15:36:58Z joerg_wunsch $ */
30
31/** \page FAQ Frequently Asked Questions
32
33\section faq_index FAQ Index
34
35\addindex FAQ
36
37-# \ref faq_volatile
38-# \ref faq_libm
39-# \ref faq_regbind
40-# \ref faq_startup
41-# \ref faq_use_bv
42-# \ref faq_cplusplus
43-# \ref faq_varinit
44-# \ref faq_16bitio
45-# \ref faq_asmconst "How do I use a \#define'd constant in an asm statement?"<!-- The explicit text is necessary since doxygen stumbles on the #define otherwise. -->
46-# \ref faq_gdboptimize
47-# \ref faq_asmstabs
48-# \ref faq_port_pass
49-# \ref faq_reg_usage
50-# \ref faq_rom_array
51-# \ref faq_ext_ram
52-# \ref faq_optflags
53-# \ref faq_reloc_code
54-# \ref faq_fuses
55-# \ref faq_flashstrings
56-# \ref faq_intpromote
57-# \ref faq_ramoverlap
58-# \ref faq_tinyavr_c
59-# \ref faq_clockskew
60-# \ref faq_intbits
61-# \ref faq_fuselow
62-# \ref faq_asmops
63-# \ref faq_spman
64-# \ref faq_linkerscripts
65-# \ref faq_binarydata
66-# \ref faq_softreset
67-# \ref faq_math
68-# \ref faq_reentrant
69-# \ref faq_eeprom_corruption
70-# \ref faq_wrong_baud_rate
71-# \ref faq_funcptr_gt128kib
72-# \ref faq_assign_chain
73
74\section faq_volatile My program doesn't recognize a variable updated within an interrupt routine
75
76When using the optimizer, in a loop like the following one:
77
78\code
79uint8_t flag;
80...
81ISR(SOME_vect) {
82  flag = 1;
83}
84...
85
86	while (flag == 0) {
87		...
88	}
89\endcode
90
91the compiler will typically access \c flag only once, and optimize further accesses completely
92away, since its code path analysis shows that nothing inside the loop
93could change the value of \c flag anyway.  To tell the compiler that
94this variable could be changed outside the scope of its code path
95analysis (e. g. from within an interrupt routine), the variable needs
96to be declared like:
97
98\code
99volatile uint8_t flag;
100\endcode
101
102<small>Back to \ref faq_index.
103</small>
104
105\section faq_libm I get "undefined reference to..." for functions like "sin()"
106
107In order to access the mathematical functions that are declared in
108<tt>\<math.h\></tt>, the linker needs to be told to also link the
109mathematical library, <tt>libm.a</tt>.
110
111Typically, system libraries like <tt>libm.a</tt> are given to the
112final C compiler command line that performs the linking step by adding
113a flag <tt>-lm</tt> at the end.  (That is, the initial \a lib and the
114filename suffix from the library are written immediately after a \a -l
115flag.  So for a <tt>libfoo.a</tt> library, <tt>-lfoo</tt> needs to be
116provided.)  This will make the linker search the library in a path
117known to the system.
118
119An alternative would be to specify the full path to the
120<tt>libm.a</tt> file at the same place on the command line, i. e. \a
121after all the object files (<tt>*.o</tt>).  However, since this
122requires knowledge of where the build system will exactly find those
123library files, this is deprecated for system libraries.
124
125<small>Back to \ref faq_index.
126</small>
127
128\section faq_regbind How to permanently bind a variable to a register?
129
130This can be done with
131
132\code
133register unsigned char counter asm("r3");
134\endcode
135
136Typically, it should be safe to use r2 through r7 that way.
137
138Registers r8 through r15 can be used for argument passing by the
139compiler in case many or long arguments are being passed to callees.
140If this is not the case throughout the entire application, these
141registers could be used for register variables as well.
142
143Extreme care should be taken that the entire application is
144compiled with a consistent set of register-allocated variables,
145including possibly used library functions.
146
147See \ref c_names_in_asm for more details.
148
149<small>Back to \ref faq_index.
150</small>
151
152\section faq_startup How to modify MCUCR or WDTCR early?
153
154The method of early initialization (<tt>MCUCR</tt>, <tt>WDTCR</tt> or
155anything else) is different (and more flexible) in the current
156version.  Basically, write a small assembler file which looks like
157this:
158
159\code
160;; begin xram.S
161
162#include <avr/io.h>
163
164        .section .init1,"ax",@progbits
165
166        ldi r16,_BV(SRE) | _BV(SRW)
167        out _SFR_IO_ADDR(MCUCR),r16
168
169;; end xram.S
170\endcode
171
172Assemble it, link the resulting <tt>xram.o</tt> with other files in
173your program, and this piece of code will be inserted in
174initialization code, which is run right after reset.  See the linker
175script for comments about the new <tt>.init</tt><em>N</em> sections
176(which one to use, etc.).
177
178The advantage of this method is that you can insert any initialization
179code you want (just remember that this is very early startup -- no
180stack and no <tt>__zero_reg__</tt> yet), and no program memory space
181is wasted if this feature is not used.
182
183There should be no need to modify linker scripts anymore, except for
184some very special cases.  It is best to leave <tt>__stack</tt> at its
185default value (end of internal SRAM -- faster, and required on some
186devices like ATmega161 because of errata), and add
187<tt>-Wl,-Tdata,0x801100</tt> to start the data section above the
188stack.
189
190For more information on using sections,
191see \ref mem_sections.
192There is also an example for \ref c_sections.
193Note that in C code, any such function would
194preferably be placed into section \c .init3 as the code in \c .init2
195ensures the internal register <tt>__zero_reg__</tt> is already cleared.
196
197<small>Back to \ref faq_index.
198</small>
199
200\section faq_use_bv What is all this _BV() stuff about?
201
202When performing low-level output work, which is a very central point
203in microcontroller programming, it is quite common that a particular
204bit needs to be set or cleared in some IO register.  While the device
205documentation provides mnemonic names for the various bits in the IO
206registers, and the \ref avr_io "AVR device-specific IO definitions" reflect these names in definitions for
207numerical constants, a way is needed to convert a bit number (usually
208within a byte register) into a byte value that can be assigned
209directly to the register.  However, sometimes the direct bit numbers
210are needed as well (e. g. in an <tt>SBI()</tt> instruction), so the
211definitions cannot usefully be made as byte values in the first place.
212
213So in order to access a particular bit number as a byte value, use the
214<tt>_BV()</tt> macro.  Of course, the implementation of this macro is
215just the usual bit shift (which is done by the compiler anyway, thus
216doesn't impose any run-time penalty), so the following applies:
217
218\code
219_BV(3) => 1 << 3 => 0x08
220\endcode
221
222However, using the macro often makes the program better readable.
223
224"BV" stands for "bit value", in case someone might ask you. :-)
225
226<b>Example:</b> clock timer 2 with full IO clock
227(<tt>CS2</tt><em>x</em> = 0b001), toggle OC2 output on compare match
228(<tt>COM2</tt><em>x</em> = 0b01), and clear timer on compare match
229(<tt>CTC2</tt> = 1).  Make OC2 (<tt>PD7</tt>) an output.
230
231\code
232	TCCR2 = _BV(COM20)|_BV(CTC2)|_BV(CS20);
233	DDRD = _BV(PD7);
234\endcode
235
236<small>Back to \ref faq_index.
237</small>
238
239\section faq_cplusplus Can I use C++ on the AVR?
240
241Basically yes, C++ is supported (assuming your compiler has been
242configured and compiled to support it, of course).  Source files
243ending in \c .cc, \c .cpp or \c .C will automatically cause the
244compiler frontend to invoke the C++ compiler.  Alternatively, the C++
245compiler could be explicitly called by the name \c avr-c++.
246
247However, there's currently no support for \c libstdc++, the standard
248support library needed for a complete C++ implementation.  This
249imposes a number of restrictions on the C++ programs that can be
250compiled.  Among them are:
251
252- Obviously, none of the C++ related standard functions, classes,
253  and template classes are available.
254
255- The operators \c new and \c delete are not implemented, attempting
256  to use them will cause the linker to complain about undefined
257  external references.  (This could perhaps be fixed.)
258
259- Some of the supplied include files are not C++ safe, i. e. they need
260  to be wrapped into \code extern "C" { . . . } \endcode
261  (This could certainly be fixed, too.)
262
263- Exceptions are not supported.  Since exceptions are enabled by
264  default in the C++ frontend, they explicitly need to be turned
265  off using \c -fno-exceptions in the compiler options.  Failing
266  this, the linker will complain about an undefined external
267  reference to \c __gxx_personality_sj0.
268
269Constructors and destructors \e are supported though, including global
270ones.
271
272When programming C++ in space- and runtime-sensitive environments like
273microcontrollers, extra care should be taken to avoid unwanted side
274effects of the C++ calling conventions like implied copy constructors
275that could be called upon function invocation etc.  These things could
276easily add up into a considerable amount of time and program memory
277wasted.  Thus, casual inspection of the generated assembler code
278(using the \c -S compiler option) seems to be warranted.
279
280<small>Back to \ref faq_index.
281</small>
282
283\section faq_varinit Shouldn't I initialize all my variables?
284
285Global and static variables are guaranteed to be initialized to 0 by
286the C standard.  \c avr-gcc does this by placing the appropriate code
287into section \c .init4 (see \ref sec_dot_init).  With respect to the
288standard, this sentence is somewhat simplified (because the standard
289allows for machines where the actual bit pattern used differs
290from all bits being 0), but for the AVR target, in general, all integer-type
291variables are set to 0, all pointers to a NULL pointer, and all
292floating-point variables to 0.0.
293
294As long as these variables are not initialized (i. e. they don't have
295an equal sign and an initialization expression to the right within the
296definition of the variable), they go into the \ref sec_dot_bss ".bss"
297section of the file.  This section simply records the size of the
298variable, but otherwise doesn't consume space, neither within the
299object file nor within flash memory.  (Of course, being a variable, it
300will consume space in the target's SRAM.)
301
302In contrast, global and static variables that have an initializer go
303into the \ref sec_dot_data ".data" section of the file.  This will
304cause them to consume space in the object file (in order to record the
305initializing value), \e and in the flash ROM of the target device.
306The latter is needed since the flash ROM is the only way that the
307compiler can tell the target device the value this variable is going
308to be initialized to.
309
310Now if some programmer "wants to make doubly sure" their variables
311really get a 0 at program startup, and adds an initializer just
312containing 0 on the right-hand side, they waste space.  While this
313waste of space applies to virtually any platform C is implemented on,
314it's usually not noticeable on larger machines like PCs, while the
315waste of flash ROM storage can be very painful on a small
316microcontroller like the AVR.
317
318So in general, variables should only be explicitly initialized if the initial
319value is non-zero.
320
321\note Recent versions of GCC are now smart enough to detect this
322situation, and revert variables that are explicitly initialized to 0
323to the .bss section.  Still, other compilers might not do that
324optimization, and as the C standard guarantees the initialization, it
325is safe to rely on it.
326
327<small>Back to \ref faq_index.
328</small>
329
330\section faq_16bitio Why do some 16-bit timer registers sometimes get trashed?
331
332Some of the timer-related 16-bit IO registers use a temporary register
333(called TEMP in the Atmel datasheet) to guarantee an atomic access to
334the register despite the fact that two separate 8-bit IO transfers are
335required to actually move the data.  Typically, this includes access
336to the current timer/counter value register (<tt>TCNT</tt><em>n</em>),
337the input capture register (<tt>ICR</tt><em>n</em>), and write access
338to the output compare registers (<tt>OCR</tt><em>nM</em>).  Refer to
339the actual datasheet for each device's set of registers that involves
340the TEMP register.
341
342When accessing one of the registers that use TEMP from the main
343application, and possibly any other one from within an interrupt
344routine, care must be taken that no access from within an interrupt
345context could clobber the TEMP register data of an in-progress
346transaction that has just started elsewhere.
347
348To protect interrupt routines against other interrupt routines, it's
349usually best to use the ISR() macro when declaring the interrupt
350function, and to ensure that interrupts are still disabled when
351accessing those 16-bit timer registers.
352
353Within the main program, access to those registers could be
354encapsulated in calls to the cli() and sei() macros.  If the status of
355the global interrupt flag before accessing one of those registers is
356uncertain, something like the following example code can be used.
357
358\code
359uint16_t
360read_timer1(void)
361{
362	uint8_t sreg;
363	uint16_t val;
364
365	sreg = SREG;
366	cli();
367	val = TCNT1;
368	SREG = sreg;
369
370	return val;
371}
372\endcode
373
374<small>Back to \ref faq_index.
375</small>
376
377\section faq_asmconst How do I use a \#define'd constant in an asm statement?
378
379So you tried this:
380
381\code
382asm volatile("sbi 0x18,0x07;");
383\endcode
384
385Which works. When you do the same thing but replace the address of the port
386by its macro name, like this:
387
388\code
389asm volatile("sbi PORTB,0x07;");
390\endcode
391
392you get a compilation error: <tt>"Error: constant value required"</tt>.
393
394\c PORTB is a precompiler definition included in the processor specific file
395included in \c avr/io.h. As you may know, the precompiler will not touch
396strings and <tt>PORTB</tt>, instead of <tt>0x18</tt>, gets passed to the
397assembler. One way to avoid this problem is:
398
399\code
400asm volatile("sbi %0, 0x07" : "I" (_SFR_IO_ADDR(PORTB)):);
401\endcode
402
403\note For C programs, rather use the standard C bit operators instead,
404so the above would be expressed as <tt>PORTB |= (1 << 7)</tt>.  The
405optimizer will take care to transform this into a single SBI
406instruction, assuming the operands allow for this.
407
408<small>Back to \ref faq_index.
409</small>
410
411\section faq_gdboptimize Why does the PC randomly jump around when single-stepping through my program in avr-gdb?
412
413When compiling a program with both optimization (\c -O) and debug
414information (\c -g) which is fortunately possible in \c avr-gcc, the
415code watched in the debugger is optimized code.  While it is not
416guaranteed, very often this code runs with the exact same
417optimizations as it would run without the \c -g switch.
418
419This can have unwanted side effects.  Since the compiler is free to
420reorder code execution as long as the semantics do not change, code
421is often rearranged in order to make it possible to use a single
422branch instruction for conditional operations.  Branch instructions
423can only cover a short range for the target PC (-63 through +64 words
424from the current PC).  If a branch instruction cannot be used
425directly, the compiler needs to work around it by combining a skip
426instruction together with a relative jump (\c rjmp) instruction, which
427will need one additional word of ROM.
428
429Another side effect of optimization is that variable usage is
430restricted to the area of code where it is actually used.  So if a
431variable was placed in a register at the beginning of some function,
432this same register can be re-used later on if the compiler notices
433that the first variable is no longer used inside that function, even
434though the variable is still in lexical scope.  When trying to examine
435the variable in \c avr-gdb, the displayed result will then look
436garbled.
437
438So in order to avoid these side effects, optimization can be turned
439off while debugging.  However, some of these optimizations might also
440have the side effect of uncovering bugs that would otherwise not be
441obvious, so it must be noted that turning off optimization can easily
442change the bug pattern. In most cases, you are better off leaving
443optimizations enabled while debugging.
444
445<small>Back to \ref faq_index.
446</small>
447
448\section faq_asmstabs How do I trace an assembler file in avr-gdb?
449
450When using the \c -g compiler option, <tt>avr-gcc</tt> only generates
451line number and other debug information for C (and C++) files that
452pass the compiler.  Functions that don't have line number information
453will be completely skipped by a single \c step command in \c gdb.
454This includes functions linked from a standard library, but by default
455also functions defined in an assembler source file, since the \c -g
456compiler switch does not apply to the assembler.
457
458So in order to debug an assembler input file (possibly one that has to
459be passed through the C preprocessor), it's the assembler that needs
460to be told to include line-number information into the output file.
461(Other debug information like data types and variable allocation
462cannot be generated, since unlike a compiler, the assembler basically
463doesn't know about this.)  This is done using the (GNU) assembler
464option \c --gstabs.
465
466Example:
467
468\verbatim
469  $ avr-as -mmcu=atmega128 --gstabs -o foo.o foo.s
470\endverbatim
471
472When the assembler is not called directly but through the C compiler
473frontend (either implicitly by passing a source file ending in \c .S,
474or explicitly using <tt>-x assembler-with-cpp</tt>), the compiler
475frontend needs to be told to pass the \c --gstabs option down to the
476assembler.  This is done using <tt>-Wa,--gstabs</tt>.  Please take
477care to \e only pass this option when compiling an assembler input
478file.  Otherwise, the assembler code that results from the C
479compilation stage will also get line number information, which
480confuses the debugger.
481
482\note You can also use <tt>-Wa,-gstabs</tt> since the compiler will add the
483extra \c '-' for you.
484
485Example:
486
487\verbatim
488  $ EXTRA_OPTS="-Wall -mmcu=atmega128 -x assembler-with-cpp"
489  $ avr-gcc -Wa,--gstabs ${EXTRA_OPTS} -c -o foo.o foo.S
490\endverbatim
491
492Also note that the debugger might get confused when entering a piece
493of code that has a non-local label before, since it then takes this
494label as the name of a new function that appears to have been entered.
495Thus, the best practice to avoid this confusion is to only use
496non-local labels when declaring a new function, and restrict anything
497else to local labels.  Local labels consist just of a number only.
498References to these labels consist of the number, followed by the
499letter \b b for a backward reference, or \b f for a forward reference.
500These local labels may be re-used within the source file, references
501will pick the closest label with the same number and given direction.
502
503Example:
504
505\code
506myfunc:	push	r16
507	push	r17
508	push	r18
509	push	YL
510	push	YH
511	...
512	eor	r16, r16	; start loop
513	ldi	YL, lo8(sometable)
514	ldi	YH, hi8(sometable)
515	rjmp	2f		; jump to loop test at end
5161:	ld	r17, Y+		; loop continues here
517	...
518	breq	1f		; return from myfunc prematurely
519	...
520	inc	r16
5212:	cmp	r16, r18
522	brlo	1b		; jump back to top of loop
523
5241:	pop	YH
525	pop	YL
526	pop	r18
527	pop	r17
528	pop	r16
529	ret
530\endcode
531
532<small>Back to \ref faq_index.
533</small>
534
535\section faq_port_pass How do I pass an IO port as a parameter to a function?
536
537Consider this example code:
538
539\code
540#include <inttypes.h>
541#include <avr/io.h>
542
543void
544set_bits_func_wrong (volatile uint8_t port, uint8_t mask)
545{
546    port |= mask;
547}
548
549void
550set_bits_func_correct (volatile uint8_t *port, uint8_t mask)
551{
552    *port |= mask;
553}
554
555#define set_bits_macro(port,mask) ((port) |= (mask))
556
557int main (void)
558{
559    set_bits_func_wrong (PORTB, 0xaa);
560    set_bits_func_correct (&PORTB, 0x55);
561    set_bits_macro (PORTB, 0xf0);
562
563    return (0);
564}
565\endcode
566
567The first function will generate object code which is not even close to what
568is intended. The major problem arises when the function is called. When the
569compiler sees this call, it will actually pass the value of the \c PORTB
570register (using an \c IN instruction), instead of passing the address of \c
571PORTB (e.g. memory mapped io addr of \c 0x38, io port \c 0x18 for the
572mega128). This is seen clearly when looking at the disassembly of the call:
573
574\verbatim
575    set_bits_func_wrong (PORTB, 0xaa);
576 10a:   6a ea           ldi     r22, 0xAA       ; 170
577 10c:   88 b3           in      r24, 0x18       ; 24
578 10e:   0e 94 65 00     call    0xca
579\endverbatim
580
581So, the function, once called, only sees the value of the port register and
582knows nothing about which port it came from. At this point, whatever object
583code is generated for the function by the compiler is irrelevant. The
584interested reader can examine the full disassembly to see that the function's
585body is completely fubar.
586
587The second function shows how to pass (by reference) the memory mapped address
588of the io port to the function so that you can read and write to it in the
589function. Here's the object code generated for the function call:
590
591\verbatim
592    set_bits_func_correct (&PORTB, 0x55);
593 112:   65 e5           ldi     r22, 0x55       ; 85
594 114:   88 e3           ldi     r24, 0x38       ; 56
595 116:   90 e0           ldi     r25, 0x00       ; 0
596 118:   0e 94 7c 00     call    0xf8
597\endverbatim
598
599You can clearly see that \c 0x0038 is correctly passed for the address of the
600io port. Looking at the disassembled object code for the body of the function,
601we can see that the function is indeed performing the operation we intended:
602
603\verbatim
604void
605set_bits_func_correct (volatile uint8_t *port, uint8_t mask)
606{
607  f8:   fc 01           movw    r30, r24
608    *port |= mask;
609  fa:   80 81           ld      r24, Z
610  fc:   86 2b           or      r24, r22
611  fe:   80 83           st      Z, r24
612}
613 100:   08 95           ret
614\endverbatim
615
616Notice that we are accessing the io port via the \c LD and \c ST instructions.
617
618The \c port parameter must be volatile to avoid a compiler warning.
619
620\note Because of the nature of the \c IN and \c OUT assembly instructions,
621they can not be used inside the function when passing the port in this way.
622Readers interested in the details should consult the <em>Instruction Set</em>
623datasheet.
624
625Finally we come to the macro version of the operation. In this contrived
626example, the macro is the most efficient method with respect to both execution
627speed and code size:
628
629\verbatim
630    set_bits_macro (PORTB, 0xf0);
631 11c:   88 b3           in      r24, 0x18       ; 24
632 11e:   80 6f           ori     r24, 0xF0       ; 240
633 120:   88 bb           out     0x18, r24       ; 24
634\endverbatim
635
636Of course, in a real application, you might be doing a lot more in your
637function which uses a passed by reference io port address and thus the use of
638a function over a macro could save you some code space, but still at a cost of
639execution speed.
640
641Care should be taken when such an indirect port access is going to one
642of the 16-bit IO registers where the order of write access is critical
643(like some timer registers).  All versions of avr-gcc up to 3.3 will
644generate instructions that use the wrong access order in this
645situation (since with normal memory operands where the order doesn't
646matter, this sometimes yields shorter code).
647
648See
649http://mail.nongnu.org/archive/html/avr-libc-dev/2003-01/msg00044.html
650for a possible workaround.
651
652avr-gcc versions after 3.3 have been fixed in a way where this
653optimization will be disabled if the respective pointer variable is
654declared to be \c volatile, so the correct behaviour for 16-bit IO
655ports can be forced that way.
656
657<small>Back to \ref faq_index.</small>
658
659\section faq_reg_usage What registers are used by the C compiler?
660
661- <strong>Data types:</strong><br>
662\c char is 8 bits, \c int is 16 bits, \c long is 32 bits, \c long long
663is 64 bits, \c float and \c double are 32 bits (this is the only
664supported floating point format), pointers are 16 bits (function
665pointers are word addresses, to allow addressing up to 128K
666program memory space). There is a \c -mint8 option (see \ref using_avr_gcc) to
667make \c int 8 bits, but that is not supported by avr-libc and violates C
668standards (\c int \e must be at least 16 bits).  It may be removed in
669a future release.
670
671- <strong>Call-used registers (r18-r27, r30-r31):</strong><br>
672May be allocated by gcc for local data.
673You \e may use them freely in assembler subroutines.
674Calling C subroutines can clobber any of them -
675the caller is responsible for saving and restoring.
676
677- <strong>Call-saved registers (r2-r17, r28-r29):</strong><br>
678May be allocated by gcc for local data.
679Calling C subroutines leaves them unchanged.
680Assembler subroutines are responsible for saving
681and restoring these registers, if changed.
682r29:r28 (Y pointer) is used as a frame pointer
683(points to local data on stack) if necessary.
684The requirement for the callee to save/preserve
685the contents of these registers even applies in
686situations where the compiler assigns them for
687argument passing.
688
689- <strong>Fixed registers (r0, r1):</strong><br>
690Never allocated by gcc for local data, but often
691used for fixed purposes:
692<p>
693r0 - temporary register, can be clobbered by any
694C code (except interrupt handlers which save it),
695\e may be used to remember something for a while
696within one piece of assembler code
697</p>
698<p>
699r1 - assumed to be always zero in any C code,
700\e may be used to remember something for a while
701within one piece of assembler code, but \e must
702then be cleared after use (<tt>clr r1</tt>).  This
703includes any use of the <tt>[f]mul[s[u]]</tt> instructions,
704which return their result in r1:r0.
705Interrupt handlers save and clear r1 on entry,
706and restore r1 on exit (in case it was non-zero).
707</p>
708
709- <strong>Function call conventions:</strong><br>
710Arguments - allocated left to right, r25 to r8.
711All arguments are aligned to start in even-numbered
712registers (odd-sized arguments, including \c char, have
713one free register above them).  This allows making better
714use of the \c movw instruction on the enhanced core.
715<p>
716If too many, those that don't fit are passed on
717the stack.
718</p>
719<p>
720Return values: 8-bit in r24 (not r25!), 16-bit in r25:r24,
721up to 32 bits in r22-r25, up to 64 bits in r18-r25.
7228-bit return values are zero/sign-extended to
72316 bits by the called function (<tt>unsigned char</tt> is more
724efficient than <tt>signed char</tt> - just <tt>clr r25</tt>).
725Arguments to functions with variable argument lists
726(printf etc.) are all passed on stack, and \c char
727is extended to \c int.
728</p>
729\warning
730There was no such alignment before 2000-07-01,
731including the old patches for gcc-2.95.2.  Check your old
732assembler subroutines, and adjust them accordingly.
733
734<small>Back to \ref faq_index.</small>
735
736\section faq_rom_array How do I put an array of strings completely in ROM?
737
738There are times when you may need an array of strings which will never be
739modified. In this case, you don't want to waste ram storing the constant
740strings. The most obvious (and incorrect) thing to do is this:
741
742\code
743#include <avr/pgmspace.h>
744
745PGM_P array[2] PROGMEM = {
746    "Foo",
747    "Bar"
748};
749
750int main (void)
751{
752    char buf[32];
753    strcpy_P (buf, array[1]);
754    return 0;
755}
756\endcode
757
758The result is not what you want though. What you end up with is the array
759stored in ROM, while the individual strings end up in RAM (in the \c .data
760section).
761
762To work around this, you need to do something like this:
763
764\code
765#include <avr/pgmspace.h>
766
767const char foo[] PROGMEM = "Foo";
768const char bar[] PROGMEM = "Bar";
769
770PGM_P array[2] PROGMEM = {
771    foo,
772    bar
773};
774
775int main (void)
776{
777    char buf[32];
778    PGM_P p;
779    int i;
780
781    memcpy_P(&p, &array[i], sizeof(PGM_P));
782    strcpy_P(buf, p);
783    return 0;
784}
785\endcode
786
787Looking at the disassembly of the resulting object file we see that array is
788in flash as such:
789
790\code
79100000026 <array>:
792  26:   2e 00           .word   0x002e  ; ????
793  28:   2a 00           .word   0x002a  ; ????
794
7950000002a <bar>:
796  2a:   42 61 72 00                                         Bar.
797
7980000002e <foo>:
799  2e:   46 6f 6f 00                                         Foo.
800\endcode
801
802\c foo is at addr 0x002e.<br>
803\c bar is at addr 0x002a.<br>
804\c array is at addr 0x0026.<br>
805
806Then in main we see this:
807
808\code
809    memcpy_P(&p, &array[i], sizeof(PGM_P));
810  70:   66 0f           add     r22, r22
811  72:   77 1f           adc     r23, r23
812  74:   6a 5d           subi    r22, 0xDA       ; 218
813  76:   7f 4f           sbci    r23, 0xFF       ; 255
814  78:   42 e0           ldi     r20, 0x02       ; 2
815  7a:   50 e0           ldi     r21, 0x00       ; 0
816  7c:   ce 01           movw    r24, r28
817  7e:   81 96           adiw    r24, 0x21       ; 33
818  80:   08 d0           rcall   .+16            ; 0x92
819\endcode
820
821This code reads the pointer to the desired string from the ROM table
822\c array into a register pair.
823
824The value of \c i (in r22:r23) is doubled to accommodate for the word
825offset required to access array[], then the address of array (0x26) is
826added, by subtracting the negated address (0xffda).  The address of
827variable \c p is computed by adding its offset within the stack frame
828(33) to the Y pointer register, and <tt><b>memcpy_P</b></tt> is
829called.
830
831\code
832    strcpy_P(buf, p);
833  82:   69 a1           ldd     r22, Y+33       ; 0x21
834  84:   7a a1           ldd     r23, Y+34       ; 0x22
835  86:   ce 01           movw    r24, r28
836  88:   01 96           adiw    r24, 0x01       ; 1
837  8a:   0c d0           rcall   .+24            ; 0xa4
838\endcode
839
840This will finally copy the ROM string into the local buffer \c buf.
841
842Variable \c p (located at Y+33) is read, and passed together with the
843address of buf (Y+1) to <tt><b>strcpy_P</b></tt>.  This will copy the
844string from ROM to \c buf.
845
846Note that when using a compile-time constant index, omitting the first
847step (reading the pointer from ROM via <tt><b>memcpy_P</b></tt>)
848usually remains unnoticed, since the compiler would then optimize the
849code for accessing \c array at compile-time.
850
851<small>Back to \ref faq_index.</small>
852
853\section faq_ext_ram How to use external RAM?
854
855Well, there is no universal answer to this question; it depends on
856what the external RAM is going to be used for.
857
858Basically, the bit \c SRE (SRAM enable) in the \c MCUCR register needs
859to be set in order to enable the external memory interface.  Depending
860on the device to be used, and the application details, further
861registers affecting the external memory operation like \c XMCRA and
862\c XMCRB, and/or further bits in \c MCUCR might be configured.
863Refer to the datasheet for details.
864
865If the external RAM is going to be used to store the variables from
866the C program (i. e., the \c .data and/or \c .bss segment) in that
867memory area, it is essential to set up the external memory interface
868early during the \ref sec_dot_init "device initialization" so the
869initialization of these variable will take place.  Refer to
870\ref faq_startup for a description how to do this using few lines of
871assembler code, or to the chapter about memory sections for an
872\ref c_sections "example written in C".
873
874The explanation of malloc() contains a \ref malloc_where "discussion"
875about the use of internal RAM vs. external RAM in particular with
876respect to the various possible locations of the \e heap (area
877reserved for malloc()).  It also explains the linker command-line
878options that are required to move the memory regions away from their
879respective standard locations in internal RAM.
880
881Finally, if the application simply wants to use the additional RAM for
882private data storage kept outside the domain of the C compiler
883(e. g. through a <tt>char *</tt> variable initialized directly to a
884particular address), it would be sufficient to defer the
885initialization of the external RAM interface to the beginning of
886<tt><b>main</b><b>()</b></tt>,
887so no tweaking of the \c .init3 section is necessary.  The
888same applies if only the heap is going to be located there, since the
889application start-up code does not affect the heap.
890
891It is not recommended to locate the stack in external RAM.  In
892general, accessing external RAM is slower than internal RAM, and
893errata of some AVR devices even prevent this configuration from
894working properly at all.
895
896<small>Back to \ref faq_index.</small>
897
898\section faq_optflags Which -O flag to use?
899
900There's a common misconception that larger numbers behind the \c -O
901option might automatically cause "better" optimization.  First,
902there's no universal definition for "better", with optimization often
903being a speed vs. code size trade off.  See the
904\ref gcc_optO "detailed discussion" for which option affects which
905part of the code generation.
906
907A test case was run on an ATmega128 to judge the effect of compiling
908the library itself using different optimization levels.  The following
909table lists the results.  The test case consisted of around 2 KB of
910strings to sort.  Test \#1 used qsort() using the standard library
911strcmp(), test \#2 used a function that sorted the strings by their
912size (thus had two calls to strlen() per invocation).
913
914When comparing the resulting code size, it should be noted that a
915floating point version of fvprintf() was linked into the binary (in
916order to print out the time elapsed) which is entirely not affected by
917the different optimization levels, and added about 2.5 KB to the code.
918
919<table>
920 <tr>
921  <td><strong>Optimization flags</strong></td>
922  <td><strong>Size of .text</strong></td>
923  <td><strong>Time for test \#1</strong></td>
924  <td><strong>Time for test \#2</strong></td>
925 </tr>
926 <tr>
927  <td>-O3</td>
928  <td>6898</td>
929  <td>903 �s</td>
930  <td>19.7 ms</td>
931 </tr>
932 <tr>
933  <td>-O2</td>
934  <td>6666</td>
935  <td>972 �s</td>
936  <td>20.1 ms</td>
937 </tr>
938 <tr>
939  <td>-Os</td>
940  <td>6618</td>
941  <td>955 �s</td>
942  <td>20.1 ms</td>
943 </tr>
944 <tr>
945  <td>-Os -mcall-prologues</td>
946  <td>6474</td>
947  <td>972 �s</td>
948  <td>20.1 ms</td>
949 </tr>
950</table>
951
952(The difference between 955 �s and 972 �s was just a single
953timer-tick, so take this with a grain of salt.)
954
955So generally, it seems <tt>-Os -mcall-prologues</tt> is the most
956universal "best" optimization level.  Only applications that need to
957get the last few percent of speed benefit from using \c -O3.
958
959<small>Back to \ref faq_index.</small>
960
961\section faq_reloc_code How do I relocate code to a fixed address?
962
963First, the code should be put into a new
964\ref mem_sections "named section".
965This is done with a section attribute:
966
967\code
968__attribute__ ((section (".bootloader")))
969\endcode
970
971In this example, \c .bootloader is the name of the new section.  This
972attribute needs to be placed after the prototype of any function to
973force the function into the new section.
974
975\code
976void boot(void) __attribute__ ((section (".bootloader")));
977\endcode
978
979To relocate the section to a fixed address the linker flag
980\c --section-start is used.  This option can be passed to the linker
981using the \ref gcc_minusW "-Wl compiler option":
982
983\code
984-Wl,--section-start=.bootloader=0x1E000
985\endcode
986
987The name after section-start is the name of the section to be
988relocated. The number after the section name is the beginning address
989of the named section.
990
991<small>Back to \ref faq_index.</small>
992
993\section faq_fuses My UART is generating nonsense!  My ATmega128 keeps crashing! Port F is completely broken!
994
995Well, certain odd problems arise out of the situation that the AVR
996devices as shipped by Atmel often come with a default fuse bit
997configuration that doesn't match the user's expectations.  Here is a
998list of things to care for:
999
1000- All devices that have an internal RC oscillator ship with the fuse
1001enabled that causes the device to run off this oscillator, instead of
1002an external crystal.  This often remains unnoticed until the first
1003attempt is made to use something critical in timing, like UART
1004communication.
1005- The ATmega128 ships with the fuse enabled that turns this device
1006into ATmega103 compatibility mode.  This means that some ports are not
1007fully usable, and in particular that the internal SRAM is located at
1008lower addresses.  Since by default, the stack is located at the top of
1009internal SRAM, a program compiled for an ATmega128 running on such a
1010device will immediately crash upon the first function call (or rather,
1011upon the first function return).
1012- Devices with a JTAG interface have the \c JTAGEN fuse programmed by
1013default.  This will make the respective port pins that are used for
1014the JTAG interface unavailable for regular IO.
1015
1016<small>Back to \ref faq_index.</small>
1017
1018\section faq_flashstrings Why do all my "foo...bar" strings eat up the SRAM?
1019
1020By default, all strings are handled as all other initialized
1021variables: they occupy RAM (even though the compiler might warn you
1022when it detects write attempts to these RAM locations), and occupy the
1023same amount of flash ROM so they can be initialized to the actual
1024string by startup code.  The compiler can optimize multiple identical
1025strings into a single one, but obviously only for one compilation unit
1026(i. e., a single C source file).
1027
1028That way, any string literal will be a valid argument to any C
1029function that expects a <tt>const char *</tt> argument.
1030
1031Of course, this is going to waste a lot of SRAM.  In
1032\ref avr_pgmspace "Program Space String Utilities", a method is described how such
1033constant data can be moved out to flash ROM.  However, a constant
1034string located in flash ROM is no longer a valid argument to pass to a
1035function that expects a <tt>const char *</tt>-type string, since the
1036AVR processor needs the special instruction \c LPM to access these
1037strings.  Thus, separate functions are needed that take this into
1038account.  Many of the standard C library functions have equivalents
1039available where one of the string arguments can be located in flash
1040ROM.  Private functions in the applications need to handle this, too.
1041For example, the following can be used to implement simple debugging
1042messages that will be sent through a UART:
1043
1044\code
1045#include <inttypes.h>
1046#include <avr/io.h>
1047#include <avr/pgmspace.h>
1048
1049int
1050uart_putchar(char c)
1051{
1052  if (c == '\n')
1053    uart_putchar('\r');
1054  loop_until_bit_is_set(USR, UDRE);
1055  UDR = c;
1056  return 0; /* so it could be used for fdevopen(), too */
1057}
1058
1059void
1060debug_P(const char *addr)
1061{
1062  char c;
1063
1064  while ((c = pgm_read_byte(addr++)))
1065    uart_putchar(c);
1066}
1067
1068int
1069main(void)
1070{
1071  ioinit(); /* initialize UART, ... */
1072  debug_P(PSTR("foo was here\n"));
1073  return 0;
1074}
1075\endcode
1076
1077\note By convention, the suffix \b _P to the function name is used as
1078an indication that this function is going to accept a "program-space
1079string".  Note also the use of the PSTR() macro.
1080
1081<small>Back to \ref faq_index.</small>
1082
1083\section faq_intpromote Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation in assembly?
1084
1085Bitwise operations in Standard C will automatically promote their
1086operands to an int, which is (by default) 16 bits in avr-gcc.
1087
1088To work around this use typecasts on the operands, including
1089literals, to declare that the values are to be 8 bit operands.
1090
1091This may be especially important when clearing a bit:
1092
1093\code
1094var &= ~mask;  /* wrong way! */
1095\endcode
1096
1097The bitwise "not" operator (\c ~) will also promote the value in \c mask
1098to an int. To keep it an 8-bit value, typecast before the "not"
1099operator:
1100
1101\code
1102var &= (unsigned char)~mask;
1103\endcode
1104
1105<small>Back to \ref faq_index.</small>
1106
1107\section faq_ramoverlap How to detect RAM memory and variable overlap problems?
1108
1109You can simply run <tt>avr-nm</tt> on your output (ELF) file.
1110Run it with the <tt>-n</tt> option, and it will sort the symbols
1111numerically (by default, they are sorted alphabetically).
1112
1113Look for the symbol \c _end, that's the first address in
1114RAM that is not allocated by a variable. (avr-gcc
1115internally adds 0x800000 to all data/bss variable
1116addresses, so please ignore this offset.) Then, the
1117run-time initialization code initializes the stack
1118pointer (by default) to point to the last available
1119address in (internal) SRAM. Thus, the region between
1120\c _end and the end of SRAM is what is available for stack.
1121(If your application uses malloc(), which e. g. also
1122can happen inside printf(), the heap for dynamic
1123memory is also located there. See \ref malloc.)
1124
1125The amount of stack required for your application
1126cannot be determined that easily. For example, if
1127you recursively call a function and forget to break
1128that recursion, the amount of stack required is
1129infinite. :-) You can look at the generated assembler
1130code (<tt>avr-gcc ... -S</tt>), there's a comment in each
1131generated assembler file that tells you the frame
1132size for each generated function. That's the amount
1133of stack required for this function, you have to add
1134up that for all functions where you know that the
1135calls could be nested.
1136
1137<small>Back to \ref faq_index.</small>
1138
1139\section faq_tinyavr_c Is it really impossible to program the ATtinyXX in C?
1140
1141While some small AVRs are not directly supported by the C compiler
1142since they do not have a RAM-based stack (and some do not even have
1143RAM at all), it is possible anyway to use the general-purpose
1144registers as a RAM replacement since they are mapped into the data
1145memory region.
1146
1147Bruce D. Lightner wrote an excellent description of how to do this,
1148and offers this together with a toolkit on his web page:
1149
1150http://lightner.net/avr/ATtinyAvrGcc.html
1151
1152<small>Back to \ref faq_index.</small>
1153
1154\section faq_clockskew What is this "clock skew detected" message?
1155
1156It's a known problem of the MS-DOS FAT file system. Since the FAT file
1157system has only a granularity of 2 seconds for maintaining a file's
1158timestamp, and it seems that some MS-DOS derivative (Win9x) perhaps
1159rounds up the current time to the next second when calculating the
1160timestamp of an updated file in case the current time cannot be
1161represented in FAT's terms, this causes a situation where \c make sees
1162a "file coming from the future".
1163
1164Since all make decisions are based on file timestamps, and their
1165dependencies, make warns about this situation.
1166
1167Solution: don't use inferior file systems / operating systems.
1168Neither Unix file systems nor HPFS (aka NTFS) do experience that
1169problem.
1170
1171Workaround: after saving the file, wait a second before starting \c
1172make. Or simply ignore the warning.  If you are paranoid, execute a
1173<tt>make clean all</tt> to make sure everything gets rebuilt.
1174
1175In networked environments where the files are accessed from a file
1176server, this message can also happen if the file server's clock
1177differs too much from the network client's clock.  In this case, the
1178solution is to use a proper time keeping protocol on both systems,
1179like NTP.  As a workaround, synchronize the client's clock frequently
1180with the server's clock.
1181
1182<small>Back to \ref faq_index.</small>
1183
1184\section faq_intbits Why are (many) interrupt flags cleared by writing a logical 1?
1185
1186Usually, each interrupt has its own interrupt flag bit in some control
1187register, indicating the specified interrupt condition has been met by
1188representing a logical 1 in the respective bit position.  When working
1189with interrupt handlers, this interrupt flag bit usually gets cleared
1190automatically in the course of processing the interrupt, sometimes by
1191just calling the handler at all, sometimes (e. g. for the U[S]ART) by
1192reading a particular hardware register that will normally happen
1193anyway when processing the interrupt.
1194
1195From the hardware's point of view, an interrupt is asserted as long as
1196the respective bit is set, while global interrupts are enabled.  Thus,
1197it is essential to have the bit cleared before interrupts get
1198re-enabled again (which usually happens when returning from an
1199interrupt handler).
1200
1201Only few subsystems require an explicit action to clear the interrupt
1202request when using interrupt handlers.  (The notable exception is the
1203TWI interface, where clearing the interrupt indicates to proceed with
1204the TWI bus hardware handshake, so it's never done automatically.)
1205
1206However, if no normal interrupt handlers are to be used, or in order
1207to make extra sure any pending interrupt gets cleared before
1208re-activating global interrupts (e. g. an external edge-triggered
1209one), it can be necessary to explicitly clear the respective hardware
1210interrupt bit by software.  This is usually done by writing a logical
12111 into this bit position.  This seems to be illogical at first, the
1212bit position already carries a logical 1 when reading it, so why does
1213writing a logical 1 to it <i>clear</i> the interrupt bit?
1214
1215The solution is simple: writing a logical 1 to it requires only a
1216single \c OUT instruction, and it is clear that only this single
1217interrupt request bit will be cleared.  There is no need to perform a
1218read-modify-write cycle (like, an \c SBI instruction), since all bits
1219in these control registers are interrupt bits, and writing a logical 0
1220to the remaining bits (as it is done by the simple \c OUT instruction)
1221will not alter them, so there is no risk of any race condition that
1222might accidentally clear another interrupt request bit.  So instead of
1223writing
1224
1225\code
1226TIFR |= _BV(TOV0); /* wrong! */
1227\endcode
1228
1229simply use
1230
1231\code
1232TIFR = _BV(TOV0);
1233\endcode
1234
1235<small>Back to \ref faq_index.</small>
1236
1237\section faq_fuselow Why have "programmed" fuses the bit value 0?
1238
1239Basically, fuses are just a bit in a special EEPROM area.  For
1240technical reasons, erased E[E]PROM cells have all bits set to the
1241value 1, so unprogrammed fuses also have a logical 1.  Conversely,
1242programmed fuse cells read out as bit value 0.
1243
1244<small>Back to \ref faq_index.</small>
1245
1246\section faq_asmops Which AVR-specific assembler operators are available?
1247
1248See \ref ass_pseudoops.
1249
1250<small>Back to \ref faq_index.</small>
1251
1252\section faq_spman Why are interrupts re-enabled in the middle of writing the stack pointer?
1253
1254When setting up space for local variables on the stack, the compiler
1255generates code like this:
1256
1257\code
1258/* prologue: frame size=20 */
1259	push r28
1260	push r29
1261	in r28,__SP_L__
1262	in r29,__SP_H__
1263	sbiw r28,20
1264	in __tmp_reg__,__SREG__
1265	cli
1266	out __SP_H__,r29
1267	out __SREG__,__tmp_reg__
1268	out __SP_L__,r28
1269/* prologue end (size=10) */
1270\endcode
1271
1272It reads the current stack pointer value, decrements it by the
1273required amount of bytes, then disables interrupts, writes back the
1274high part of the stack pointer, writes back the saved \c SREG (which
1275will eventually re-enable interrupts if they have been enabled
1276before), and finally writes the low part of the stack pointer.
1277
1278At the first glance, there's a race between restoring \c SREG, and
1279writing \c SPL.  However, after enabling interrupts (either explicitly
1280by setting the \c I flag, or by restoring it as part of the entire
1281\c SREG), the AVR hardware executes (at least) the next instruction
1282still with interrupts disabled, so the write to \c SPL is guaranteed
1283to be executed with interrupts disabled still.  Thus, the emitted
1284sequence ensures interrupts will be disabled only for the minimum
1285time required to guarantee the integrity of this operation.
1286
1287<small>Back to \ref faq_index.</small>
1288
1289\section faq_linkerscripts Why are there five different linker scripts?
1290
1291From a comment in the source code:
1292
1293Which one of the five linker script files is actually used depends on command
1294line options given to ld.
1295
1296A .x script file is the default script
1297A .xr script is for linking without relocation (-r flag)
1298A .xu script is like .xr but *do* create constructors (-Ur flag)
1299A .xn script is for linking with -n flag (mix text and data on same page).
1300A .xbn script is for linking with -N flag (mix text and data on same page).
1301
1302<small>Back to \ref faq_index.</small>
1303
1304\section faq_binarydata How to add a raw binary image to linker output?
1305
1306The GNU linker <tt>avr-ld</tt> cannot handle binary data
1307directly. However, there's a companion tool called
1308<tt>avr-objcopy</tt>. This is already known from the output side: it's
1309used to extract the contents of the linked ELF file into an Intel Hex
1310load file.
1311
1312<tt>avr-objcopy</tt> can create a relocatable object file from
1313arbitrary binary input, like
1314
1315\code
1316avr-objcopy -I binary -O elf32-avr foo.bin foo.o
1317\endcode
1318
1319This will create a file named <tt>foo.o</tt>, with the contents of
1320<tt>foo.bin</tt>.  The contents will default to section .data, and two
1321symbols will be created named \c _binary_foo_bin_start and \c
1322_binary_foo_bin_end. These symbols can be referred to inside a C
1323source to access these data.
1324
1325If the goal is to have those data go to flash ROM (similar to having
1326used the PROGMEM attribute in C source code), the sections have to be
1327renamed while copying, and it's also useful to set the section flags:
1328
1329\code
1330avr-objcopy --rename-section .data=.progmem.data,contents,alloc,load,readonly,data -I binary -O elf32-avr foo.bin foo.o
1331\endcode
1332
1333Note that all this could be conveniently wired into a Makefile, so
1334whenever <tt>foo.bin</tt> changes, it will trigger the recreation of
1335<tt>foo.o</tt>, and a subsequent relink of the final ELF file.
1336
1337Below are two Makefile fragments that provide rules to convert a .txt file
1338to an object file, and to convert a .bin file to an object file:
1339
1340\code
1341$(OBJDIR)/%.o : %.txt
1342	@echo Converting $<
1343	@cp $(<) $(*).tmp
1344	@echo -n 0 | tr 0 '\000' >> $(*).tmp
1345	@$(OBJCOPY) -I binary -O elf32-avr \
1346	--rename-section .data=.progmem.data,contents,alloc,load,readonly,data \
1347	--redefine-sym _binary_$*_tmp_start=$* \
1348	--redefine-sym _binary_$*_tmp_end=$*_end \
1349	--redefine-sym _binary_$*_tmp_size=$*_size_sym \
1350	$(*).tmp $(@)
1351	@echo "extern const char" $(*)"[] PROGMEM;" > $(*).h
1352	@echo "extern const char" $(*)_end"[] PROGMEM;" >> $(*).h
1353	@echo "extern const char" $(*)_size_sym"[];" >> $(*).h
1354	@echo "#define $(*)_size ((int)$(*)_size_sym)" >> $(*).h
1355	@rm $(*).tmp
1356
1357$(OBJDIR)/%.o : %.bin
1358	@echo Converting $<
1359	@$(OBJCOPY) -I binary -O elf32-avr \
1360	--rename-section .data=.progmem.data,contents,alloc,load,readonly,data \
1361	--redefine-sym _binary_$*_bin_start=$* \
1362	--redefine-sym _binary_$*_bin_end=$*_end \
1363	--redefine-sym _binary_$*_bin_size=$*_size_sym \
1364	$(<) $(@)
1365	@echo "extern const char" $(*)"[] PROGMEM;" > $(*).h
1366	@echo "extern const char" $(*)_end"[] PROGMEM;" >> $(*).h
1367	@echo "extern const char" $(*)_size_sym"[];" >> $(*).h
1368	@echo "#define $(*)_size ((int)$(*)_size_sym)" >> $(*).h
1369\endcode
1370
1371<small>Back to \ref faq_index.</small>
1372
1373\section faq_softreset How do I perform a software reset of the AVR?
1374
1375The canonical way to perform a software reset of non-XMega AVR's is to use the
1376watchdog timer. Enable the watchdog timer to the shortest timeout setting,
1377then go into an infinite, do-nothing loop. The watchdog will then reset the
1378processor.
1379
1380XMega parts have a specific bit <tt>RST_SWRST_bm</tt> in the
1381<tt>RST.CTRL</tt> register, that generates a hardware reset.
1382RST_SWRST_bm is protected by the XMega Configuration Change Protection
1383system.
1384
1385The reason why using the watchdog timer or <tt>RST_SWRST_bm</tt> is
1386preferable over jumping to the reset vector, is that when the watchdog
1387or <tt>RST_SWRST_bm</tt> resets the AVR, the registers will be reset
1388to their known, default settings. Whereas jumping to the reset vector
1389will leave the registers in their previous state, which is generally
1390not a good idea.
1391
1392<b>CAUTION!</b> Older AVRs will have the watchdog timer disabled on a reset. For
1393these older AVRs, doing a soft reset by enabling the watchdog is easy, as the
1394watchdog will then be disabled after the reset. On newer AVRs, once the watchdog
1395is enabled, then it <b>stays enabled, even after a reset</b>! For these
1396newer AVRs a function needs to be added to the .init3 section (i.e. during the
1397startup code, before main()) to disable the watchdog early enough so it does
1398not continually reset the AVR.
1399
1400Here is some example code that creates a macro that can be called to perform
1401a soft reset:
1402
1403\code
1404#include <avr/wdt.h>
1405
1406...
1407
1408#define soft_reset()        \
1409do                          \
1410{                           \
1411    wdt_enable(WDTO_15MS);  \
1412    for(;;)                 \
1413    {                       \
1414    }                       \
1415} while(0)
1416\endcode
1417
1418For newer AVRs (such as the ATmega1281) also add this function to your code
1419to then disable the watchdog after a reset (e.g., after a soft reset):
1420
1421\code
1422#include <avr/wdt.h>
1423
1424...
1425
1426// Function Pototype
1427void wdt_init(void) __attribute__((naked)) __attribute__((section(".init3")));
1428
1429...
1430
1431// Function Implementation
1432void wdt_init(void)
1433{
1434    MCUSR = 0;
1435    wdt_disable();
1436
1437    return;
1438}
1439
1440\endcode
1441
1442<small>Back to \ref faq_index.</small>
1443
1444\section faq_math I am using floating point math. Why is the compiled code so big? Why does my code not work?
1445
1446You are not linking in the math library from AVR-LibC. GCC has a library that
1447is used for floating point operations, but it is not optimized for the AVR, and
1448so it generates big code, or it could be incorrect. This can happen even when
1449you are not using any floating point math functions from the Standard C library,
1450but you are just doing floating point math operations.
1451
1452When you link in the math library from AVR-LibC, those
1453routines get replaced by hand-optimized AVR assembly and it produces much
1454smaller code.
1455
1456See \ref faq_libm for more details on how to link in the math library.
1457
1458<small>Back to \ref faq_index.</small>
1459
1460\section faq_reentrant What pitfalls exist when writing reentrant code?
1461
1462Reentrant code means the ability for a piece of code to be
1463called simultaneously from two or more threads.  Attention
1464to re-enterability is needed when using a multi-tasking
1465operating system, or when using interrupts since an
1466interrupt is really a temporary thread.
1467
1468The code generated natively by gcc is reentrant.  But, only
1469some of the libraries in avr-libc are explicitly reentrant,
1470and some are known not to be reentrant.  In general, any
1471library call that reads and writes global variables
1472(including I/O registers) is not reentrant.
1473This is because more than one thread could read or write the
1474same storage at the same time, unaware that other threads
1475are doing the same, and create inconsistent and/or erroneous
1476results.
1477
1478A library call that is known not to be reentrant will work
1479if it is used only within one thread <em>and</em> no other
1480thread makes use of a library call that shares common
1481storage with it.
1482
1483Below is a table of library calls with known issues.
1484
1485<table>
1486 <tr>
1487  <td><strong>Library call</strong></td>
1488  <td><strong>Reentrant Issue</strong></td>
1489  <td><strong>Workaround/Alternative</strong></td>
1490 </tr>
1491 <tr>
1492  <td>rand(), random()</td>
1493  <td>Uses global variables to keep state information.</td>
1494  <td>Use special reentrant versions: rand_r(), random_r().</td>
1495 </tr>
1496 <tr>
1497  <td>strtod(), strtol(), strtoul()</td>
1498  <td>Uses the global variable \c errno to return success/failure.</td>
1499  <td>Ignore \c errno, or protect calls with cli()/sei() or ATOMIC_BLOCK()
1500      if the application can tolerate it.  Or use sccanf() or sccanf_P()
1501      if possible.
1502  </td>
1503 </tr>
1504 <tr>
1505  <td>malloc(), realloc(), calloc(), free()</td>
1506  <td>Uses the stack pointer and global variables to allocate and
1507      free memory.</td>
1508  <td>Protect calls with cli()/sei() or ATOMIC_BLOCK() if the application
1509      can tolerate it.  If using an OS,
1510      use the OS provided memory allocator since the OS is likely modifying
1511      the stack pointer anyway.
1512  </td>
1513 </tr>
1514 <tr>
1515  <td>fdevopen(), fclose()</td>
1516  <td>Uses calloc() and free().</td>
1517  <td>Protect calls with cli()/sei() or ATOMIC_BLOCK() if the application
1518      can tolerate it.  Or use fdev_setup_stream() or FDEV_SETUP_STREAM().
1519      <br>
1520      Note: fclose() will only call free() if the stream has been opened with fdevopen().
1521  </td>
1522 </tr>
1523 <tr>
1524  <td>eeprom_*(), boot_*()</td>
1525  <td>Accesses I/O registers.</td>
1526  <td>Protect calls with cli()/sei(), ATOMIC_BLOCK(), or use OS locking.</td>
1527 </tr>
1528 <tr>
1529  <td>pgm_*_far()</td>
1530  <td>Accesses I/O register RAMPZ.</td>
1531  <td>Starting with GCC 4.3, RAMPZ is automatically saved for ISRs, so
1532      nothing further is needed if only using interrupts.
1533      <br>Some OSes may automatically preserve RAMPZ during context switching.
1534      Check the OS documentation before assuming it does.
1535      <br>Otherwise, protect calls with cli()/sei(), ATOMIC_BLOCK(), or use
1536          explicit OS locking.
1537  </td>
1538 </tr>
1539 <tr>
1540  <td>printf(), printf_P(), vprintf(), vprintf_P(), puts(), puts_P()</td>
1541  <td>Alters flags and character count in global FILE \c stdout.</td>
1542  <td>Use only in one thread.  Or if returned character count is unimportant,
1543      do not use the *_P versions.
1544      <br>Note: Formatting to a string output, e.g. sprintf(), sprintf_P(),
1545      snprintf(), snprintf_P(), vsprintf(), vsprintf_P(), vsnprintf(), vsnprintf_P(),
1546      is thread safe.  The formatted string could then be followed by an fwrite()
1547      which simply calls the lower layer to send the string.
1548  </td>
1549 </tr>
1550 <tr>
1551  <td>fprintf(), fprintf_P(), vfprintf(), vfprintf_P(), fputs(), fputs_P()</td>
1552  <td>Alters flags and character count in the FILE argument.
1553      Problems can occur if a global FILE is used from multiple threads.
1554  </td>
1555  <td>Assign each thread its own FILE for output.  Or if returned character
1556      count is unimportant, do not use the *_P versions.
1557  </td>
1558 </tr>
1559 <tr>
1560  <td>assert()</td>
1561  <td>Contains an embedded fprintf().  See above for fprintf().</td>
1562  <td>See above for fprintf().</td>
1563 </tr>
1564 <tr>
1565  <td>clearerr()</td>
1566  <td>Alters flags in the FILE argument.
1567  </td>
1568  <td>Assign each thread its own FILE for output.
1569  </td>
1570 </tr>
1571
1572 <tr>
1573  <td>getchar(), gets()</td>
1574  <td>Alters flags, character count, and unget buffer in global FILE \c stdin.</td>
1575  <td>Use only in one thread. ***</td>
1576 </tr>
1577
1578 <tr>
1579  <td>fgetc(), ungetc(), fgets(), scanf(), scanf_P(), fscanf(), fscanf_P(),
1580      vscanf(), vfscanf(), vfscanf_P(), fread()
1581  <td>Alters flags, character count, and unget buffer in the FILE argument.</td>
1582  <td>Assign each thread its own FILE for input. ***
1583      <br>Note: Scanning from a string, e.g. sscanf() and sscanf_P(),
1584      are thread safe.
1585  </td>
1586 </tr>
1587</table>
1588
1589\note It's not clear one would ever want to do character
1590input simultaneously from more than one thread anyway, but
1591these entries are included for completeness.
1592
1593An effort will be made to keep this table up to date if any
1594new issues are discovered or introduced.
1595
1596<small>Back to \ref faq_index.</small>
1597
1598\section faq_eeprom_corruption  Why are some addresses of the EEPROM corrupted (usually address zero)?
1599
1600The two most common reason for EEPROM corruption is either writing to
1601the EEPROM beyond the datasheet endurance specification, or resetting
1602the AVR while an EEPROM write is in progress.
1603
1604EEPROM writes can take up to tens of milliseconds to complete.  So
1605that the CPU is not tied up for that long of time, an internal
1606state-machine handles EEPROM write requests.  The EEPROM state-machine
1607expects to have all of the EEPROM registers setup, then an EEPROM write
1608request to start the process.  Once the EEPROM state-machine has
1609started, changing EEPROM related registers during an EEPROM write is
1610guaranteed to corrupt the EEPROM write process.  The datasheet always
1611shows the proper way to tell when a write is in progress, so that the
1612registers are not changed by the user's program.  The EEPROM
1613state-machine will \b always complete the write in progress unless
1614power is removed from the device.
1615
1616As with all EEPROM technology, if power fails during an EEPROM write
1617the state of the byte being written is undefined.
1618
1619In older generation AVRs the EEPROM Address Register (EEAR) is
1620initialized to zero on reset, be it from Brown Out Detect, Watchdog or
1621the Reset Pin.  If an EEPROM write has just started at the time of the
1622reset, the write will be completed, but now at address zero instead of
1623the requested address.  If the reset occurs later in the write process
1624both the requested address and address zero may be corrupted.
1625
1626To distinguish which AVRs may exhibit the corrupt of address zero
1627while a write is in process during a reset, look at the "initial
1628value" section for the EEPROM Address Register.  If EEAR shows the
1629initial value as 0x00 or 0x0000, then address zero and possibly the
1630one being written will be corrupted.  Newer parts show the initial
1631value as "undefined", these will not corrupt address zero during a
1632reset (unless it was address zero that was being written).
1633
1634EEPROMs have limited write endurance.  The datasheet specifies the
1635number of EEPROM writes that are guaranteed to function across the
1636full temperature specification of the AVR, for a given byte.  A read
1637should always be performed before a write, to see if the value in the
1638EEPROM actually needs to be written, so not to cause unnecessary EEPROM
1639wear.
1640
1641The failure mechanism for an overwritten byte is generally one of
1642"stuck" bits, i. e. a bit will stay at a one or zero state regardless of
1643the byte written.  Also a write followed by a read may return the
1644correct data, but the data will change with the passage of time, due
1645the EEPROM's inability to hold a charge from the excessive write wear.
1646
1647<small>Back to \ref faq_index.</small>
1648
1649\section faq_wrong_baud_rate  Why is my baud rate wrong?
1650
1651Some AVR datasheets give the following formula for calculating baud rates:
1652
1653\code
1654(F_CPU/(UART_BAUD_RATE*16L)-1)
1655\endcode
1656
1657Unfortunately that formula does not work with all combinations of
1658clock speeds and baud rates due to integer truncation during the
1659division operator.
1660
1661When doing integer division it is usually better to round to the nearest
1662integer, rather than to the lowest.  To do this add 0.5 (i. e. half the
1663value of the denominator) to the numerator before the division, resulting
1664in the formula:
1665
1666\code
1667((F_CPU + UART_BAUD_RATE * 8L) / (UART_BAUD_RATE * 16L) - 1)
1668\endcode
1669
1670This is also the way it is implemented in \ref util_setbaud.
1671
1672<small>Back to \ref faq_index.</small>
1673
1674\section faq_funcptr_gt128kib On a device with more than 128 KiB of flash, how to make function pointers work?
1675
1676Function pointers beyond the "magical" 128 KiB barrier(s) on larger
1677devices are supposed to be resolved through so-called
1678<em>trampolines</em> by the linker, so the actual pointers used in
1679the code can remain 16 bits wide.
1680
1681In order for this to work, the option <tt>-mrelax</tt> must be given
1682on the compiler command-line that is used to link the final ELF file.
1683(Older compilers did not implement this option for the AVR, use
1684<tt>-Wl,--relax</tt> instead.)
1685
1686<small>Back to \ref faq_index.</small>
1687
1688\section faq_assign_chain Why is assigning ports in a "chain" a bad idea?
1689
1690Suppose a number of IO port registers should get the value \c 0xff
1691assigned.  Conveniently, it is implemented like this:
1692
1693\code
1694  DDRB = DDRD = 0xff;
1695\endcode
1696
1697According to the rules of the C language, this causes 0xff to be
1698assigned to \c DDRD, then \c DDRD is read back, and the value is
1699assigned to \c DDRB.  The compiler stands no chance to optimize the
1700readback away, as an IO port register is declared "volatile".  Thus,
1701chaining that kind of IO port assignments would better be avoided,
1702using explicit assignments instead:
1703
1704\code
1705  DDRB = 0xff;
1706  DDRD = 0xff;
1707\endcode
1708
1709Even worse ist this, e. g. on an ATmega1281:
1710
1711\code
1712  DDRA = DDRB = DDRC = DDRD = DDRE = DDRF = DDRG = 0xff;
1713\endcode
1714
1715The same happens as outlined above.  However, when reading back
1716register \c DDRG, this register only implements 6 out of the 8 bits,
1717so the two topmost (unimplemented) bits read back as 0!  Consequently,
1718all remaining <tt>DDR</tt><em>x</em> registers get assigned the value
17190x3f, which does not match the intention of the developer in any way.
1720
1721<small>Back to \ref faq_index.</small>
1722
1723*/
1724