You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

815 lines
92 KiB
HTML

<!-- HTML header for doxygen 1.8.7-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.6.3"/>
<!--BEGIN PROJECT_NAME--><title>avr-libc: avr-libc: Frequently Asked Questions</title><!--END PROJECT_NAME-->
<!--BEGIN !PROJECT_NAME--><title>avr-libc: Frequently Asked Questions</title><!--END !PROJECT_NAME-->
<link href="$relpath^tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="$relpath^jquery.js"></script>
<script type="text/javascript" src="$relpath^dynsections.js"></script>
$treeview
$search
$mathjax
<link href="$relpath^$stylesheet" rel="stylesheet" type="text/css" />
$extrastylesheet
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!--BEGIN TITLEAREA-->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<!--BEGIN PROJECT_LOGO-->
<td id="projectlogo"><img alt="Logo" src="$relpath^$projectlogo"/></td>
<!--END PROJECT_LOGO-->
<!--BEGIN PROJECT_NAME-->
<td style="padding-left: 0.5em;">
<div id="projectname">avr-libc
<!--BEGIN PROJECT_NUMBER-->&#160;<span id="projectnumber">2.0.0</span><!--END PROJECT_NUMBER-->
</div>
<!--BEGIN PROJECT_BRIEF--><div id="projectbrief">$projectbrief</div><!--END PROJECT_BRIEF-->
</td>
<!--END PROJECT_NAME-->
<!--BEGIN !PROJECT_NAME-->
<!--BEGIN PROJECT_BRIEF-->
<td style="padding-left: 0.5em;">
<div id="projectbrief">$projectbrief</div>
</td>
<!--END PROJECT_BRIEF-->
<!--END !PROJECT_NAME-->
<!--BEGIN DISABLE_INDEX-->
<!--BEGIN SEARCHENGINE-->
<td>$searchbox</td>
<!--END SEARCHENGINE-->
<!--END DISABLE_INDEX-->
</tr>
</tbody>
</table>
<table>
<tr>
<td align="left"><a href="http://www.nongnu.org/avr-libc/"><h2>AVR Libc Home Page</h2></a></td>
<td align="center" colspan=4><img src="avrs.png" alt="AVRs" align="middle" border="0"></td>
<td align="right"><a href="https://savannah.nongnu.org/projects/avr-libc/"><h2>AVR Libc Development Pages</h2></a></td>
</tr>
<tr>
<td align="center" width="20%"><a href="index.html"><h2>Main Page</h2></a></td>
<td align="center" width="20%"><a href="pages.html"><h2>User Manual</h2></a></td>
<td align="center" width="20%"><a href="modules.html"><h2>Library Reference</h2></a></td>
<td align="center" width="20%"><a href="FAQ.html"><h2>FAQ</h2></a></td>
<td align="center" width="20%"><a href="group__demos.html"><h2>Example Projects</h2></a></td>
</tr>
</table>
</div>
<!--END TITLEAREA-->
<!-- end header part -->
<!-- Generated by Doxygen 1.6.3 -->
<script type="text/javascript"><!--
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div class="contents">
<h1><a class="anchor" id="FAQ">Frequently Asked Questions </a></h1><h2><a class="anchor" id="faq_index">
FAQ Index</a></h2>
<p><a name="FAQ"></a></p>
<ol type="1">
<li><a class="el" href="FAQ.html#faq_volatile">My program doesn't recognize a variable updated within an interrupt routine</a></li>
<li><a class="el" href="FAQ.html#faq_libm">I get "undefined reference to..." for functions like "sin()"</a></li>
<li><a class="el" href="FAQ.html#faq_regbind">How to permanently bind a variable to a register?</a></li>
<li><a class="el" href="FAQ.html#faq_startup">How to modify MCUCR or WDTCR early?</a></li>
<li><a class="el" href="FAQ.html#faq_use_bv">What is all this _BV() stuff about?</a></li>
<li><a class="el" href="FAQ.html#faq_cplusplus">Can I use C++ on the AVR?</a></li>
<li><a class="el" href="FAQ.html#faq_varinit">Shouldn't I initialize all my variables?</a></li>
<li><a class="el" href="FAQ.html#faq_16bitio">Why do some 16-bit timer registers sometimes get trashed?</a></li>
<li><a class="el" href="FAQ.html#faq_asmconst">How do I use a #define'd constant in an asm statement?</a></li>
<li><a class="el" href="FAQ.html#faq_gdboptimize">Why does the PC randomly jump around when single-stepping through my program in avr-gdb?</a></li>
<li><a class="el" href="FAQ.html#faq_asmstabs">How do I trace an assembler file in avr-gdb?</a></li>
<li><a class="el" href="FAQ.html#faq_port_pass">How do I pass an IO port as a parameter to a function?</a></li>
<li><a class="el" href="FAQ.html#faq_reg_usage">What registers are used by the C compiler?</a></li>
<li><a class="el" href="FAQ.html#faq_rom_array">How do I put an array of strings completely in ROM?</a></li>
<li><a class="el" href="FAQ.html#faq_ext_ram">How to use external RAM?</a></li>
<li><a class="el" href="FAQ.html#faq_optflags">Which -O flag to use?</a></li>
<li><a class="el" href="FAQ.html#faq_reloc_code">How do I relocate code to a fixed address?</a></li>
<li><a class="el" href="FAQ.html#faq_fuses">My UART is generating nonsense! My ATmega128 keeps crashing! Port F is completely broken!</a></li>
<li><a class="el" href="FAQ.html#faq_flashstrings">Why do all my "foo...bar" strings eat up the SRAM?</a></li>
<li><a class="el" href="FAQ.html#faq_intpromote">Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation in assembly?</a></li>
<li><a class="el" href="FAQ.html#faq_ramoverlap">How to detect RAM memory and variable overlap problems?</a></li>
<li><a class="el" href="FAQ.html#faq_tinyavr_c">Is it really impossible to program the ATtinyXX in C?</a></li>
<li><a class="el" href="FAQ.html#faq_clockskew">What is this "clock skew detected" message?</a></li>
<li><a class="el" href="FAQ.html#faq_intbits">Why are (many) interrupt flags cleared by writing a logical 1?</a></li>
<li><a class="el" href="FAQ.html#faq_fuselow">Why have "programmed" fuses the bit value 0?</a></li>
<li><a class="el" href="FAQ.html#faq_asmops">Which AVR-specific assembler operators are available?</a></li>
<li><a class="el" href="FAQ.html#faq_spman">Why are interrupts re-enabled in the middle of writing the stack pointer?</a></li>
<li><a class="el" href="FAQ.html#faq_linkerscripts">Why are there five different linker scripts?</a></li>
<li><a class="el" href="FAQ.html#faq_binarydata">How to add a raw binary image to linker output?</a></li>
<li><a class="el" href="FAQ.html#faq_softreset">How do I perform a software reset of the AVR?</a></li>
<li><a class="el" href="FAQ.html#faq_math">I am using floating point math. Why is the compiled code so big? Why does my code not work?</a></li>
<li><a class="el" href="FAQ.html#faq_reentrant">What pitfalls exist when writing reentrant code?</a></li>
<li><a class="el" href="FAQ.html#faq_eeprom_corruption">Why are some addresses of the EEPROM corrupted (usually address zero)?</a></li>
<li><a class="el" href="FAQ.html#faq_wrong_baud_rate">Why is my baud rate wrong?</a></li>
<li><a class="el" href="FAQ.html#faq_funcptr_gt128kib">On a device with more than 128 KiB of flash, how to make function pointers work?</a></li>
<li><a class="el" href="FAQ.html#faq_assign_chain">Why is assigning ports in a "chain" a bad idea?</a></li>
</ol>
<h2><a class="anchor" id="faq_volatile">
My program doesn't recognize a variable updated within an interrupt routine</a></h2>
<p>When using the optimizer, in a loop like the following one:</p>
<div class="fragment"><pre class="fragment"><a class="code" href="group__avr__stdint.html#gaba7bc1797add20fe3efdf37ced1182c5">uint8_t</a> flag;
...
ISR(SOME_vect) {
flag = 1;
}
...
<span class="keywordflow">while</span> (flag == 0) {
...
}
</pre></div><p>the compiler will typically access <code>flag</code> only once, and optimize further accesses completely away, since its code path analysis shows that nothing inside the loop could change the value of <code>flag</code> anyway. To tell the compiler that this variable could be changed outside the scope of its code path analysis (e. g. from within an interrupt routine), the variable needs to be declared like:</p>
<div class="fragment"><pre class="fragment"><span class="keyword">volatile</span> <a class="code" href="group__avr__stdint.html#gaba7bc1797add20fe3efdf37ced1182c5">uint8_t</a> flag;
</pre></div><p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_libm">
I get "undefined reference to..." for functions like "sin()"</a></h2>
<p>In order to access the mathematical functions that are declared in <code>&lt;<a class="el" href="math_8h.html">math.h</a>&gt;</code>, the linker needs to be told to also link the mathematical library, <code>libm.a</code>.</p>
<p>Typically, system libraries like <code>libm.a</code> are given to the final C compiler command line that performs the linking step by adding a flag <code>-lm</code> at the end. (That is, the initial <em>lib</em> and the filename suffix from the library are written immediately after a <em>-l</em> flag. So for a <code>libfoo.a</code> library, <code>-lfoo</code> needs to be provided.) This will make the linker search the library in a path known to the system.</p>
<p>An alternative would be to specify the full path to the <code>libm.a</code> file at the same place on the command line, i. e. <em>after</em> all the object files (<code>*.o</code>). However, since this requires knowledge of where the build system will exactly find those library files, this is deprecated for system libraries.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_regbind">
How to permanently bind a variable to a register?</a></h2>
<p>This can be done with</p>
<div class="fragment"><pre class="fragment"><span class="keyword">register</span> <span class="keywordtype">unsigned</span> <span class="keywordtype">char</span> counter <span class="keyword">asm</span>(<span class="stringliteral">&quot;r3&quot;</span>);
</pre></div><p>Typically, it should be safe to use r2 through r7 that way.</p>
<p>Registers r8 through r15 can be used for argument passing by the compiler in case many or long arguments are being passed to callees. If this is not the case throughout the entire application, these registers could be used for register variables as well.</p>
<p>Extreme care should be taken that the entire application is compiled with a consistent set of register-allocated variables, including possibly used library functions.</p>
<p>See <a class="el" href="inline__asm.html#c_names_in_asm">C Names Used in Assembler Code</a> for more details.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_startup">
How to modify MCUCR or WDTCR early?</a></h2>
<p>The method of early initialization (<code>MCUCR</code>, <code>WDTCR</code> or anything else) is different (and more flexible) in the current version. Basically, write a small assembler file which looks like this:</p>
<div class="fragment"><pre class="fragment">;; begin xram.S
<span class="preprocessor">#include &lt;<a class="code" href="io_8h.html">avr/io.h</a>&gt;</span>
.section .init1,<span class="stringliteral">&quot;ax&quot;</span>,@progbits
ldi r16,<a class="code" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV</a>(SRE) | <a class="code" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV</a>(SRW)
out _SFR_IO_ADDR(MCUCR),r16
;; end xram.S
</pre></div><p>Assemble it, link the resulting <code>xram.o</code> with other files in your program, and this piece of code will be inserted in initialization code, which is run right after reset. See the linker script for comments about the new <code>.init</code><em>N</em> sections (which one to use, etc.).</p>
<p>The advantage of this method is that you can insert any initialization code you want (just remember that this is very early startup -- no stack and no <code>__zero_reg__</code> yet), and no program memory space is wasted if this feature is not used.</p>
<p>There should be no need to modify linker scripts anymore, except for some very special cases. It is best to leave <code>__stack</code> at its default value (end of internal SRAM -- faster, and required on some devices like ATmega161 because of errata), and add <code>-Wl,-Tdata,0x801100</code> to start the data section above the stack.</p>
<p>For more information on using sections, see <a class="el" href="mem__sections.html">Memory Sections</a>. There is also an example for <a class="el" href="mem__sections.html#c_sections">Using Sections in C Code</a>. Note that in C code, any such function would preferably be placed into section <code></code>.init3 as the code in <code></code>.init2 ensures the internal register <code>__zero_reg__</code> is already cleared.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_use_bv">
What is all this _BV() stuff about?</a></h2>
<p>When performing low-level output work, which is a very central point in microcontroller programming, it is quite common that a particular bit needs to be set or cleared in some IO register. While the device documentation provides mnemonic names for the various bits in the IO registers, and the <a class="el" href="group__avr__io.html">AVR device-specific IO definitions</a> reflect these names in definitions for numerical constants, a way is needed to convert a bit number (usually within a byte register) into a byte value that can be assigned directly to the register. However, sometimes the direct bit numbers are needed as well (e. g. in an <code>SBI()</code> instruction), so the definitions cannot usefully be made as byte values in the first place.</p>
<p>So in order to access a particular bit number as a byte value, use the <code><a class="el" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV()</a></code> macro. Of course, the implementation of this macro is just the usual bit shift (which is done by the compiler anyway, thus doesn't impose any run-time penalty), so the following applies:</p>
<div class="fragment"><pre class="fragment"><a class="code" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV</a>(3) =&gt; 1 &lt;&lt; 3 =&gt; 0x08
</pre></div><p>However, using the macro often makes the program better readable.</p>
<p>"BV" stands for "bit value", in case someone might ask you. :-)</p>
<p><b>Example:</b> clock timer 2 with full IO clock (<code>CS2</code><em>x</em> = 0b001), toggle OC2 output on compare match (<code>COM2</code><em>x</em> = 0b01), and clear timer on compare match (<code>CTC2</code> = 1). Make OC2 (<code>PD7</code>) an output.</p>
<div class="fragment"><pre class="fragment"> TCCR2 = <a class="code" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV</a>(COM20)|<a class="code" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV</a>(CTC2)|<a class="code" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV</a>(CS20);
DDRD = <a class="code" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV</a>(PD7);
</pre></div><p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_cplusplus">
Can I use C++ on the AVR?</a></h2>
<p>Basically yes, C++ is supported (assuming your compiler has been configured and compiled to support it, of course). Source files ending in <code></code>.cc, <code></code>.cpp or <code></code>.C will automatically cause the compiler frontend to invoke the C++ compiler. Alternatively, the C++ compiler could be explicitly called by the name <code>avr-c++</code>.</p>
<p>However, there's currently no support for <code>libstdc++</code>, the standard support library needed for a complete C++ implementation. This imposes a number of restrictions on the C++ programs that can be compiled. Among them are:</p>
<ul>
<li>Obviously, none of the C++ related standard functions, classes, and template classes are available.</li>
</ul>
<ul>
<li>The operators <code>new</code> and <code>delete</code> are not implemented, attempting to use them will cause the linker to complain about undefined external references. (This could perhaps be fixed.)</li>
</ul>
<ul>
<li>Some of the supplied include files are not C++ safe, i. e. they need to be wrapped into <div class="fragment"><pre class="fragment"> <span class="keyword">extern</span> <span class="stringliteral">&quot;C&quot;</span> { . . . }
</pre></div> (This could certainly be fixed, too.)</li>
</ul>
<ul>
<li>Exceptions are not supported. Since exceptions are enabled by default in the C++ frontend, they explicitly need to be turned off using <code>-fno-exceptions</code> in the compiler options. Failing this, the linker will complain about an undefined external reference to <code>__gxx_personality_sj0</code>.</li>
</ul>
<p>Constructors and destructors <em>are</em> supported though, including global ones.</p>
<p>When programming C++ in space- and runtime-sensitive environments like microcontrollers, extra care should be taken to avoid unwanted side effects of the C++ calling conventions like implied copy constructors that could be called upon function invocation etc. These things could easily add up into a considerable amount of time and program memory wasted. Thus, casual inspection of the generated assembler code (using the <code>-S</code> compiler option) seems to be warranted.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_varinit">
Shouldn't I initialize all my variables?</a></h2>
<p>Global and static variables are guaranteed to be initialized to 0 by the C standard. <code>avr-gcc</code> does this by placing the appropriate code into section <code></code>.init4 (see <a class="el" href="mem__sections.html#sec_dot_init">The .initN Sections</a>). With respect to the standard, this sentence is somewhat simplified (because the standard allows for machines where the actual bit pattern used differs from all bits being 0), but for the AVR target, in general, all integer-type variables are set to 0, all pointers to a NULL pointer, and all floating-point variables to 0.0.</p>
<p>As long as these variables are not initialized (i. e. they don't have an equal sign and an initialization expression to the right within the definition of the variable), they go into the <a class="el" href="mem__sections.html#sec_dot_bss">.bss</a> section of the file. This section simply records the size of the variable, but otherwise doesn't consume space, neither within the object file nor within flash memory. (Of course, being a variable, it will consume space in the target's SRAM.)</p>
<p>In contrast, global and static variables that have an initializer go into the <a class="el" href="mem__sections.html#sec_dot_data">.data</a> section of the file. This will cause them to consume space in the object file (in order to record the initializing value), <em>and</em> in the flash ROM of the target device. The latter is needed since the flash ROM is the only way that the compiler can tell the target device the value this variable is going to be initialized to.</p>
<p>Now if some programmer "wants to make doubly sure" their variables really get a 0 at program startup, and adds an initializer just containing 0 on the right-hand side, they waste space. While this waste of space applies to virtually any platform C is implemented on, it's usually not noticeable on larger machines like PCs, while the waste of flash ROM storage can be very painful on a small microcontroller like the AVR.</p>
<p>So in general, variables should only be explicitly initialized if the initial value is non-zero.</p>
<dl class="note"><dt><b>Note:</b></dt><dd>Recent versions of GCC are now smart enough to detect this situation, and revert variables that are explicitly initialized to 0 to the .bss section. Still, other compilers might not do that optimization, and as the C standard guarantees the initialization, it is safe to rely on it.</dd></dl>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_16bitio">
Why do some 16-bit timer registers sometimes get trashed?</a></h2>
<p>Some of the timer-related 16-bit IO registers use a temporary register (called TEMP in the Atmel datasheet) to guarantee an atomic access to the register despite the fact that two separate 8-bit IO transfers are required to actually move the data. Typically, this includes access to the current timer/counter value register (<code>TCNT</code><em>n</em>), the input capture register (<code>ICR</code><em>n</em>), and write access to the output compare registers (<code>OCR</code><em>nM</em>). Refer to the actual datasheet for each device's set of registers that involves the TEMP register.</p>
<p>When accessing one of the registers that use TEMP from the main application, and possibly any other one from within an interrupt routine, care must be taken that no access from within an interrupt context could clobber the TEMP register data of an in-progress transaction that has just started elsewhere.</p>
<p>To protect interrupt routines against other interrupt routines, it's usually best to use the <a class="el" href="group__avr__interrupts.html#gad28590624d422cdf30d626e0a506255f">ISR()</a> macro when declaring the interrupt function, and to ensure that interrupts are still disabled when accessing those 16-bit timer registers.</p>
<p>Within the main program, access to those registers could be encapsulated in calls to the <a class="el" href="group__avr__interrupts.html#ga68c330e94fe121eba993e5a5973c3162">cli()</a> and <a class="el" href="group__avr__interrupts.html#gaad5ebd34cb344c26ac87594f79b06b73">sei()</a> macros. If the status of the global interrupt flag before accessing one of those registers is uncertain, something like the following example code can be used.</p>
<div class="fragment"><pre class="fragment"><a class="code" href="group__avr__stdint.html#ga1f1825b69244eb3ad2c7165ddc99c956">uint16_t</a>
read_timer1(<span class="keywordtype">void</span>)
{
<a class="code" href="group__avr__stdint.html#gaba7bc1797add20fe3efdf37ced1182c5">uint8_t</a> sreg;
<a class="code" href="group__avr__stdint.html#ga1f1825b69244eb3ad2c7165ddc99c956">uint16_t</a> val;
sreg = SREG;
<a class="code" href="group__avr__interrupts.html#ga68c330e94fe121eba993e5a5973c3162">cli</a>();
val = TCNT1;
SREG = sreg;
<span class="keywordflow">return</span> val;
}
</pre></div><p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_asmconst">
How do I use a #define'd constant in an asm statement?</a></h2>
<p>So you tried this:</p>
<div class="fragment"><pre class="fragment"><span class="keyword">asm</span> <span class="keyword">volatile</span>(<span class="stringliteral">&quot;sbi 0x18,0x07;&quot;</span>);
</pre></div><p>Which works. When you do the same thing but replace the address of the port by its macro name, like this:</p>
<div class="fragment"><pre class="fragment"><span class="keyword">asm</span> <span class="keyword">volatile</span>(<span class="stringliteral">&quot;sbi PORTB,0x07;&quot;</span>);
</pre></div><p>you get a compilation error: <code>"Error: constant value required"</code>.</p>
<p><code>PORTB</code> is a precompiler definition included in the processor specific file included in <code><a class="el" href="io_8h.html">avr/io.h</a></code>. As you may know, the precompiler will not touch strings and <code>PORTB</code>, instead of <code>0x18</code>, gets passed to the assembler. One way to avoid this problem is:</p>
<div class="fragment"><pre class="fragment"><span class="keyword">asm</span> <span class="keyword">volatile</span>(<span class="stringliteral">&quot;sbi %0, 0x07&quot;</span> : <span class="stringliteral">&quot;I&quot;</span> (_SFR_IO_ADDR(PORTB)):);
</pre></div><dl class="note"><dt><b>Note:</b></dt><dd>For C programs, rather use the standard C bit operators instead, so the above would be expressed as <code>PORTB |= (1 &lt;&lt; 7)</code>. The optimizer will take care to transform this into a single SBI instruction, assuming the operands allow for this.</dd></dl>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_gdboptimize">
Why does the PC randomly jump around when single-stepping through my program in avr-gdb?</a></h2>
<p>When compiling a program with both optimization (<code>-O</code>) and debug information (<code>-g</code>) which is fortunately possible in <code>avr-gcc</code>, the code watched in the debugger is optimized code. While it is not guaranteed, very often this code runs with the exact same optimizations as it would run without the <code>-g</code> switch.</p>
<p>This can have unwanted side effects. Since the compiler is free to reorder code execution as long as the semantics do not change, code is often rearranged in order to make it possible to use a single branch instruction for conditional operations. Branch instructions can only cover a short range for the target PC (-63 through +64 words from the current PC). If a branch instruction cannot be used directly, the compiler needs to work around it by combining a skip instruction together with a relative jump (<code>rjmp</code>) instruction, which will need one additional word of ROM.</p>
<p>Another side effect of optimization is that variable usage is restricted to the area of code where it is actually used. So if a variable was placed in a register at the beginning of some function, this same register can be re-used later on if the compiler notices that the first variable is no longer used inside that function, even though the variable is still in lexical scope. When trying to examine the variable in <code>avr-gdb</code>, the displayed result will then look garbled.</p>
<p>So in order to avoid these side effects, optimization can be turned off while debugging. However, some of these optimizations might also have the side effect of uncovering bugs that would otherwise not be obvious, so it must be noted that turning off optimization can easily change the bug pattern. In most cases, you are better off leaving optimizations enabled while debugging.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_asmstabs">
How do I trace an assembler file in avr-gdb?</a></h2>
<p>When using the <code>-g</code> compiler option, <code>avr-gcc</code> only generates line number and other debug information for C (and C++) files that pass the compiler. Functions that don't have line number information will be completely skipped by a single <code>step</code> command in <code>gdb</code>. This includes functions linked from a standard library, but by default also functions defined in an assembler source file, since the <code>-g</code> compiler switch does not apply to the assembler.</p>
<p>So in order to debug an assembler input file (possibly one that has to be passed through the C preprocessor), it's the assembler that needs to be told to include line-number information into the output file. (Other debug information like data types and variable allocation cannot be generated, since unlike a compiler, the assembler basically doesn't know about this.) This is done using the (GNU) assembler option <code>--gstabs</code>.</p>
<p>Example:</p>
<div class="fragment"><pre class="fragment">
$ avr-as -mmcu=atmega128 --gstabs -o foo.o foo.s
</pre></div><p>When the assembler is not called directly but through the C compiler frontend (either implicitly by passing a source file ending in <code></code>.S, or explicitly using <code>-x assembler-with-cpp</code>), the compiler frontend needs to be told to pass the <code>--gstabs</code> option down to the assembler. This is done using <code>-Wa,--gstabs</code>. Please take care to <em>only</em> pass this option when compiling an assembler input file. Otherwise, the assembler code that results from the C compilation stage will also get line number information, which confuses the debugger.</p>
<dl class="note"><dt><b>Note:</b></dt><dd>You can also use <code>-Wa,-gstabs</code> since the compiler will add the extra <code>'-'</code> for you.</dd></dl>
<p>Example:</p>
<div class="fragment"><pre class="fragment">
$ EXTRA_OPTS="-Wall -mmcu=atmega128 -x assembler-with-cpp"
$ avr-gcc -Wa,--gstabs ${EXTRA_OPTS} -c -o foo.o foo.S
</pre></div><p>Also note that the debugger might get confused when entering a piece of code that has a non-local label before, since it then takes this label as the name of a new function that appears to have been entered. Thus, the best practice to avoid this confusion is to only use non-local labels when declaring a new function, and restrict anything else to local labels. Local labels consist just of a number only. References to these labels consist of the number, followed by the letter <b>b</b> for a backward reference, or <b>f</b> for a forward reference. These local labels may be re-used within the source file, references will pick the closest label with the same number and given direction.</p>
<p>Example:</p>
<div class="fragment"><pre class="fragment">myfunc: push r16
push r17
push r18
push YL
push YH
...
eor r16, r16 ; start loop
ldi YL, lo8(sometable)
ldi YH, hi8(sometable)
rjmp 2f ; jump to loop test at end
1: ld r17, Y+ ; loop continues here
...
breq 1f ; return from myfunc prematurely
...
inc r16
2: cmp r16, r18
brlo 1b ; jump back to top of loop
1: pop YH
pop YL
pop r18
pop r17
pop r16
ret
</pre></div><p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>. </small></p>
<h2><a class="anchor" id="faq_port_pass">
How do I pass an IO port as a parameter to a function?</a></h2>
<p>Consider this example code:</p>
<div class="fragment"><pre class="fragment"><span class="preprocessor">#include &lt;<a class="code" href="inttypes_8h.html">inttypes.h</a>&gt;</span>
<span class="preprocessor">#include &lt;<a class="code" href="io_8h.html">avr/io.h</a>&gt;</span>
<span class="keywordtype">void</span>
set_bits_func_wrong (<span class="keyword">volatile</span> <a class="code" href="group__avr__stdint.html#gaba7bc1797add20fe3efdf37ced1182c5">uint8_t</a> port, <a class="code" href="group__avr__stdint.html#gaba7bc1797add20fe3efdf37ced1182c5">uint8_t</a> mask)
{
port |= mask;
}
<span class="keywordtype">void</span>
set_bits_func_correct (<span class="keyword">volatile</span> <a class="code" href="group__avr__stdint.html#gaba7bc1797add20fe3efdf37ced1182c5">uint8_t</a> *port, <a class="code" href="group__avr__stdint.html#gaba7bc1797add20fe3efdf37ced1182c5">uint8_t</a> mask)
{
*port |= mask;
}
<span class="preprocessor">#define set_bits_macro(port,mask) ((port) |= (mask))</span>
<span class="preprocessor"></span>
<span class="keywordtype">int</span> main (<span class="keywordtype">void</span>)
{
set_bits_func_wrong (PORTB, 0xaa);
set_bits_func_correct (&amp;PORTB, 0x55);
set_bits_macro (PORTB, 0xf0);
<span class="keywordflow">return</span> (0);
}
</pre></div><p>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 <code>PORTB</code> register (using an <code>IN</code> instruction), instead of passing the address of <code>PORTB</code> (e.g. memory mapped io addr of <code>0x38</code>, io port <code>0x18</code> for the mega128). This is seen clearly when looking at the disassembly of the call:</p>
<div class="fragment"><pre class="fragment">
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
</pre></div><p>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.</p>
<p>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:</p>
<div class="fragment"><pre class="fragment">
set_bits_func_correct (&amp;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
</pre></div><p>You can clearly see that <code>0x0038</code> 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:</p>
<div class="fragment"><pre class="fragment">
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
</pre></div><p>Notice that we are accessing the io port via the <code>LD</code> and <code>ST</code> instructions.</p>
<p>The <code>port</code> parameter must be volatile to avoid a compiler warning.</p>
<dl class="note"><dt><b>Note:</b></dt><dd>Because of the nature of the <code>IN</code> and <code>OUT</code> 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 <em>Instruction Set</em> datasheet.</dd></dl>
<p>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:</p>
<div class="fragment"><pre class="fragment">
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
</pre></div><p>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.</p>
<p>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).</p>
<p>See <a href="http://mail.nongnu.org/archive/html/avr-libc-dev/2003-01/msg00044.html">http://mail.nongnu.org/archive/html/avr-libc-dev/2003-01/msg00044.html</a> for a possible workaround.</p>
<p>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 <code>volatile</code>, so the correct behaviour for 16-bit IO ports can be forced that way.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_reg_usage">
What registers are used by the C compiler?</a></h2>
<ul>
<li><b>Data types:</b><br/>
<code>char</code> is 8 bits, <code>int</code> is 16 bits, <code>long</code> is 32 bits, <code>long</code> long is 64 bits, <code>float</code> and <code>double</code> are 32 bits (this is the only supported floating point format), pointers are 16 bits (function pointers are word addresses, to allow addressing up to 128K program memory space). There is a <code>-mint8</code> option (see <a class="el" href="using__tools.html#using_avr_gcc">Options for the C compiler avr-gcc</a>) to make <code>int</code> 8 bits, but that is not supported by avr-libc and violates C standards (<code>int</code> <em>must</em> be at least 16 bits). It may be removed in a future release.</li>
</ul>
<ul>
<li><b>Call-used registers (r18-r27, r30-r31):</b><br/>
May be allocated by gcc for local data. You <em>may</em> use them freely in assembler subroutines. Calling C subroutines can clobber any of them - the caller is responsible for saving and restoring.</li>
</ul>
<ul>
<li><b>Call-saved registers (r2-r17, r28-r29):</b><br/>
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.</li>
</ul>
<ul>
<li><b>Fixed registers (r0, r1):</b><br/>
Never allocated by gcc for local data, but often used for fixed purposes: </li>
</ul>
<p>r0 - temporary register, can be clobbered by any C code (except interrupt handlers which save it), <em>may</em> be used to remember something for a while within one piece of assembler code </p>
<p>r1 - assumed to be always zero in any C code, <em>may</em> be used to remember something for a while within one piece of assembler code, but <em>must</em> then be cleared after use (<code>clr r1</code>). This includes any use of the <code>[f]mul[s[u]]</code> 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). </p>
<ul>
<li><b>Function call conventions:</b><br/>
Arguments - allocated left to right, r25 to r8. All arguments are aligned to start in even-numbered registers (odd-sized arguments, including <code>char</code>, have one free register above them). This allows making better use of the <code>movw</code> instruction on the enhanced core. </li>
</ul>
<p>If too many, those that don't fit are passed on the stack. </p>
<p>Return values: 8-bit in r24 (not r25!), 16-bit in r25:r24, up to 32 bits in r22-r25, up to 64 bits in r18-r25. 8-bit return values are zero/sign-extended to 16 bits by the called function (<code>unsigned char</code> is more efficient than <code>signed char</code> - just <code>clr r25</code>). Arguments to functions with variable argument lists (printf etc.) are all passed on stack, and <code>char</code> is extended to <code>int</code>. </p>
<dl class="warning"><dt><b>Warning:</b></dt><dd>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.</dd></dl>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_rom_array">
How do I put an array of strings completely in ROM?</a></h2>
<p>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:</p>
<div class="fragment"><pre class="fragment"><span class="preprocessor">#include &lt;<a class="code" href="pgmspace_8h.html">avr/pgmspace.h</a>&gt;</span>
<a class="code" href="group__avr__pgmspace.html#ga963f816fc88a5d8479c285ed4c630229">PGM_P</a> array[2] PROGMEM = {
<span class="stringliteral">&quot;Foo&quot;</span>,
<span class="stringliteral">&quot;Bar&quot;</span>
};
<span class="keywordtype">int</span> main (<span class="keywordtype">void</span>)
{
<span class="keywordtype">char</span> buf[32];
<a class="code" href="group__avr__pgmspace.html#ga5749897c91c479d02054fc02128de482">strcpy_P</a> (buf, array[1]);
<span class="keywordflow">return</span> 0;
}
</pre></div><p>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 <code></code>.data section).</p>
<p>To work around this, you need to do something like this:</p>
<div class="fragment"><pre class="fragment"><span class="preprocessor">#include &lt;<a class="code" href="pgmspace_8h.html">avr/pgmspace.h</a>&gt;</span>
<span class="keyword">const</span> <span class="keywordtype">char</span> foo[] PROGMEM = <span class="stringliteral">&quot;Foo&quot;</span>;
<span class="keyword">const</span> <span class="keywordtype">char</span> bar[] PROGMEM = <span class="stringliteral">&quot;Bar&quot;</span>;
<a class="code" href="group__avr__pgmspace.html#ga963f816fc88a5d8479c285ed4c630229">PGM_P</a> array[2] PROGMEM = {
foo,
bar
};
<span class="keywordtype">int</span> main (<span class="keywordtype">void</span>)
{
<span class="keywordtype">char</span> buf[32];
<a class="code" href="group__avr__pgmspace.html#ga963f816fc88a5d8479c285ed4c630229">PGM_P</a> p;
<span class="keywordtype">int</span> i;
<a class="code" href="group__avr__pgmspace.html#gad92fa2ebe26e65fa424051047d21a0eb">memcpy_P</a>(&amp;p, &amp;array[i], <span class="keyword">sizeof</span>(<a class="code" href="group__avr__pgmspace.html#ga963f816fc88a5d8479c285ed4c630229">PGM_P</a>));
<a class="code" href="group__avr__pgmspace.html#ga5749897c91c479d02054fc02128de482">strcpy_P</a>(buf, p);
<span class="keywordflow">return</span> 0;
}
</pre></div><p>Looking at the disassembly of the resulting object file we see that array is in flash as such:</p>
<div class="fragment"><pre class="fragment">00000026 &lt;array&gt;:
26: 2e 00 .word 0x002e ; ????
28: 2a 00 .word 0x002a ; ????
0000002a &lt;bar&gt;:
2a: 42 61 72 00 Bar.
0000002e &lt;foo&gt;:
2e: 46 6f 6f 00 Foo.
</pre></div><p><code>foo</code> is at addr 0x002e.<br/>
<code>bar</code> is at addr 0x002a.<br/>
<code>array</code> is at addr 0x0026.<br/>
</p>
<p>Then in main we see this:</p>
<div class="fragment"><pre class="fragment"> <a class="code" href="group__avr__pgmspace.html#gad92fa2ebe26e65fa424051047d21a0eb">memcpy_P</a>(&amp;p, &amp;array[i], <span class="keyword">sizeof</span>(<a class="code" href="group__avr__pgmspace.html#ga963f816fc88a5d8479c285ed4c630229">PGM_P</a>));
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
</pre></div><p>This code reads the pointer to the desired string from the ROM table <code>array</code> into a register pair.</p>
<p>The value of <code>i</code> (in r22:r23) is doubled to accommodate for the word offset required to access array[], then the address of array (0x26) is added, by subtracting the negated address (0xffda). The address of variable <code>p</code> is computed by adding its offset within the stack frame (33) to the Y pointer register, and <code><b>memcpy_P</b></code> is called.</p>
<div class="fragment"><pre class="fragment"> <a class="code" href="group__avr__pgmspace.html#ga5749897c91c479d02054fc02128de482">strcpy_P</a>(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
</pre></div><p>This will finally copy the ROM string into the local buffer <code>buf</code>.</p>
<p>Variable <code>p</code> (located at Y+33) is read, and passed together with the address of buf (Y+1) to <code><b>strcpy_P</b></code>. This will copy the string from ROM to <code>buf</code>.</p>
<p>Note that when using a compile-time constant index, omitting the first step (reading the pointer from ROM via <code><b>memcpy_P</b></code>) usually remains unnoticed, since the compiler would then optimize the code for accessing <code>array</code> at compile-time.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_ext_ram">
How to use external RAM?</a></h2>
<p>Well, there is no universal answer to this question; it depends on what the external RAM is going to be used for.</p>
<p>Basically, the bit <code>SRE</code> (SRAM enable) in the <code>MCUCR</code> 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 <code>XMCRA</code> and <code>XMCRB</code>, and/or further bits in <code>MCUCR</code> might be configured. Refer to the datasheet for details.</p>
<p>If the external RAM is going to be used to store the variables from the C program (i. e., the <code></code>.data and/or <code></code>.bss segment) in that memory area, it is essential to set up the external memory interface early during the <a class="el" href="mem__sections.html#sec_dot_init">device initialization</a> so the initialization of these variable will take place. Refer to <a class="el" href="FAQ.html#faq_startup">How to modify MCUCR or WDTCR early?</a> for a description how to do this using few lines of assembler code, or to the chapter about memory sections for an <a class="el" href="mem__sections.html#c_sections">example written in C</a>.</p>
<p>The explanation of <a class="el" href="group__avr__stdlib.html#ga4996af830ebe744d9678e5251dfd3ebd">malloc()</a> contains a <a class="el" href="malloc.html#malloc_where">discussion</a> about the use of internal RAM vs. external RAM in particular with respect to the various possible locations of the <em>heap</em> (area reserved for <a class="el" href="group__avr__stdlib.html#ga4996af830ebe744d9678e5251dfd3ebd">malloc()</a>). 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.</p>
<p>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 <code>char *</code> variable initialized directly to a particular address), it would be sufficient to defer the initialization of the external RAM interface to the beginning of <code><b>main</b><b>()</b></code>, so no tweaking of the <code></code>.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.</p>
<p>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.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_optflags">
Which -O flag to use?</a></h2>
<p>There's a common misconception that larger numbers behind the <code>-O</code> option might automatically cause "better" optimization. First, there's no universal definition for "better", with optimization often being a speed vs. code size trade off. See the <a class="el" href="using__tools.html#gcc_optO">detailed discussion</a> for which option affects which part of the code generation.</p>
<p>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 <a class="el" href="group__avr__stdlib.html#gafd4bf2faec43342e7ad3d2ab37bac1fe">qsort()</a> using the standard library <a class="el" href="group__avr__string.html#ga46f3cbd2de457c0fb340a1f379fc33ba" title="Compare two strings.">strcmp()</a>, test #2 used a function that sorted the strings by their size (thus had two calls to <a class="el" href="group__avr__string.html#ga7fd4936b86eb6b87e98587044c562715" title="Calculate the length of a string.">strlen()</a> per invocation).</p>
<p>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.</p>
<table class="doxtable">
<tr>
<td><b>Optimization flags</b> </td><td><b>Size of .text</b> </td><td><b>Time for test #1</b> </td><td><b>Time for test #2</b> </td></tr>
<tr>
<td>-O3 </td><td>6898 </td><td>903 µs </td><td>19.7 ms </td></tr>
<tr>
<td>-O2 </td><td>6666 </td><td>972 µs </td><td>20.1 ms </td></tr>
<tr>
<td>-Os </td><td>6618 </td><td>955 µs </td><td>20.1 ms </td></tr>
<tr>
<td>-Os -mcall-prologues </td><td>6474 </td><td>972 µs </td><td>20.1 ms </td></tr>
</table>
<p>(The difference between 955 µs and 972 µs was just a single timer-tick, so take this with a grain of salt.)</p>
<p>So generally, it seems <code>-Os -mcall-prologues</code> is the most universal "best" optimization level. Only applications that need to get the last few percent of speed benefit from using <code>-O3</code>.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_reloc_code">
How do I relocate code to a fixed address?</a></h2>
<p>First, the code should be put into a new <a class="el" href="mem__sections.html">named section</a>. This is done with a section attribute:</p>
<div class="fragment"><pre class="fragment"><a class="code" href="group__avr__watchdog.html#gadaa6dd28b5d08df35e49b1248d7e5fb0">__attribute__</a> ((section (<span class="stringliteral">&quot;.bootloader&quot;</span>)))
</pre></div><p>In this example, <code></code>.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.</p>
<div class="fragment"><pre class="fragment"><span class="keywordtype">void</span> boot(<span class="keywordtype">void</span>) <a class="code" href="group__avr__watchdog.html#gadaa6dd28b5d08df35e49b1248d7e5fb0">__attribute__</a> ((section (&quot;.bootloader&quot;)));
</pre></div><p>To relocate the section to a fixed address the linker flag <code>--section-start</code> is used. This option can be passed to the linker using the <a class="el" href="using__tools.html#gcc_minusW">-Wl compiler option</a>:</p>
<div class="fragment"><pre class="fragment">-Wl,--section-start=.bootloader=0x1E000
</pre></div><p>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.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_fuses">
My UART is generating nonsense! My ATmega128 keeps crashing! Port F is completely broken!</a></h2>
<p>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:</p>
<ul>
<li>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.</li>
<li>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).</li>
<li>Devices with a JTAG interface have the <code>JTAGEN</code> fuse programmed by default. This will make the respective port pins that are used for the JTAG interface unavailable for regular IO.</li>
</ul>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_flashstrings">
Why do all my "foo...bar" strings eat up the SRAM?</a></h2>
<p>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).</p>
<p>That way, any string literal will be a valid argument to any C function that expects a <code>const char *</code> argument.</p>
<p>Of course, this is going to waste a lot of SRAM. In <a class="el" href="group__avr__pgmspace.html">Program Space String Utilities</a>, 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 <code>const char *</code>-type string, since the AVR processor needs the special instruction <code>LPM</code> 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:</p>
<div class="fragment"><pre class="fragment"><span class="preprocessor">#include &lt;<a class="code" href="inttypes_8h.html">inttypes.h</a>&gt;</span>
<span class="preprocessor">#include &lt;<a class="code" href="io_8h.html">avr/io.h</a>&gt;</span>
<span class="preprocessor">#include &lt;<a class="code" href="pgmspace_8h.html">avr/pgmspace.h</a>&gt;</span>
<span class="keywordtype">int</span>
uart_putchar(<span class="keywordtype">char</span> c)
{
<span class="keywordflow">if</span> (c == <span class="charliteral">&#39;\n&#39;</span>)
uart_putchar(<span class="charliteral">&#39;\r&#39;</span>);
<a class="code" href="group__avr__sfr.html#gaaf6857fa882da35f8685e2001e5c3bbe">loop_until_bit_is_set</a>(USR, UDRE);
UDR = c;
<span class="keywordflow">return</span> 0; <span class="comment">/* so it could be used for fdevopen(), too */</span>
}
<span class="keywordtype">void</span>
debug_P(<span class="keyword">const</span> <span class="keywordtype">char</span> *addr)
{
<span class="keywordtype">char</span> c;
<span class="keywordflow">while</span> ((c = <a class="code" href="group__avr__pgmspace.html#ga73084a8bbde259ffae72980354b3f027">pgm_read_byte</a>(addr++)))
uart_putchar(c);
}
<span class="keywordtype">int</span>
main(<span class="keywordtype">void</span>)
{
ioinit(); <span class="comment">/* initialize UART, ... */</span>
debug_P(<a class="code" href="group__avr__pgmspace.html#ga05ca900ebf7cd121be73c654d9ccb3eb">PSTR</a>(<span class="stringliteral">&quot;foo was here\n&quot;</span>));
<span class="keywordflow">return</span> 0;
}
</pre></div><dl class="note"><dt><b>Note:</b></dt><dd>By convention, the suffix <b>_P</b> 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 <a class="el" href="group__avr__pgmspace.html#ga05ca900ebf7cd121be73c654d9ccb3eb">PSTR()</a> macro.</dd></dl>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_intpromote">
Why does the compiler compile an 8-bit operation that uses bitwise operators into a 16-bit operation in assembly?</a></h2>
<p>Bitwise operations in Standard C will automatically promote their operands to an int, which is (by default) 16 bits in avr-gcc.</p>
<p>To work around this use typecasts on the operands, including literals, to declare that the values are to be 8 bit operands.</p>
<p>This may be especially important when clearing a bit:</p>
<div class="fragment"><pre class="fragment">var &amp;= ~mask; <span class="comment">/* wrong way! */</span>
</pre></div><p>The bitwise "not" operator (<code>~</code>) will also promote the value in <code>mask</code> to an int. To keep it an 8-bit value, typecast before the "not" operator:</p>
<div class="fragment"><pre class="fragment">var &amp;= (<span class="keywordtype">unsigned</span> char)~mask;
</pre></div><p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_ramoverlap">
How to detect RAM memory and variable overlap problems?</a></h2>
<p>You can simply run <code>avr-nm</code> on your output (ELF) file. Run it with the <code>-n</code> option, and it will sort the symbols numerically (by default, they are sorted alphabetically).</p>
<p>Look for the symbol <code>_end</code>, that's the first address in RAM that is not allocated by a variable. (avr-gcc internally adds 0x800000 to all data/bss variable addresses, so please ignore this offset.) Then, the run-time initialization code initializes the stack pointer (by default) to point to the last available address in (internal) SRAM. Thus, the region between <code>_end</code> and the end of SRAM is what is available for stack. (If your application uses <a class="el" href="group__avr__stdlib.html#ga4996af830ebe744d9678e5251dfd3ebd">malloc()</a>, which e. g. also can happen inside <a class="el" href="group__avr__stdio.html#ga4c04da4953607fa5fa4d3908fecde449">printf()</a>, the heap for dynamic memory is also located there. See <a class="el" href="malloc.html">Memory Areas and Using malloc()</a>.)</p>
<p>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 (<code>avr-gcc ... -S</code>), 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.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_tinyavr_c">
Is it really impossible to program the ATtinyXX in C?</a></h2>
<p>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.</p>
<p>Bruce D. Lightner wrote an excellent description of how to do this, and offers this together with a toolkit on his web page:</p>
<p><a href="http://lightner.net/avr/ATtinyAvrGcc.html">http://lightner.net/avr/ATtinyAvrGcc.html</a></p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_clockskew">
What is this "clock skew detected" message?</a></h2>
<p>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 <code>make</code> sees a "file coming from the future".</p>
<p>Since all make decisions are based on file timestamps, and their dependencies, make warns about this situation.</p>
<p>Solution: don't use inferior file systems / operating systems. Neither Unix file systems nor HPFS (aka NTFS) do experience that problem.</p>
<p>Workaround: after saving the file, wait a second before starting <code>make</code>. Or simply ignore the warning. If you are paranoid, execute a <code>make clean all</code> to make sure everything gets rebuilt.</p>
<p>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.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_intbits">
Why are (many) interrupt flags cleared by writing a logical 1?</a></h2>
<p>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.</p>
<p>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).</p>
<p>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.)</p>
<p>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 <em>clear</em> the interrupt bit?</p>
<p>The solution is simple: writing a logical 1 to it requires only a single <code>OUT</code> 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 <code>SBI</code> 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 <code>OUT</code> 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</p>
<div class="fragment"><pre class="fragment">TIFR |= <a class="code" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV</a>(TOV0); <span class="comment">/* wrong! */</span>
</pre></div><p>simply use</p>
<div class="fragment"><pre class="fragment">TIFR = <a class="code" href="group__avr__sfr.html#ga11643f271076024c395a93800b3d9546">_BV</a>(TOV0);
</pre></div><p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_fuselow">
Why have "programmed" fuses the bit value 0?</a></h2>
<p>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.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_asmops">
Which AVR-specific assembler operators are available?</a></h2>
<p>See <a class="el" href="assembler.html#ass_pseudoops">Pseudo-ops and operators</a>.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_spman">
Why are interrupts re-enabled in the middle of writing the stack pointer?</a></h2>
<p>When setting up space for local variables on the stack, the compiler generates code like this:</p>
<div class="fragment"><pre class="fragment"><span class="comment">/* prologue: frame size=20 */</span>
push r28
push r29
in r28,__SP_L__
in r29,__SP_H__
sbiw r28,20
in __tmp_reg__,__SREG__
<a class="code" href="group__avr__interrupts.html#ga68c330e94fe121eba993e5a5973c3162">cli</a>
out __SP_H__,r29
out __SREG__,__tmp_reg__
out __SP_L__,r28
<span class="comment">/* prologue end (size=10) */</span>
</pre></div><p>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 <code>SREG</code> (which will eventually re-enable interrupts if they have been enabled before), and finally writes the low part of the stack pointer.</p>
<p>At the first glance, there's a race between restoring <code>SREG</code>, and writing <code>SPL</code>. However, after enabling interrupts (either explicitly by setting the <code>I</code> flag, or by restoring it as part of the entire <code>SREG</code>), the AVR hardware executes (at least) the next instruction still with interrupts disabled, so the write to <code>SPL</code> 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.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_linkerscripts">
Why are there five different linker scripts?</a></h2>
<p>From a comment in the source code:</p>
<p>Which one of the five linker script files is actually used depends on command line options given to ld.</p>
<p>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).</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_binarydata">
How to add a raw binary image to linker output?</a></h2>
<p>The GNU linker <code>avr-ld</code> cannot handle binary data directly. However, there's a companion tool called <code>avr-objcopy</code>. 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.</p>
<p><code>avr-objcopy</code> can create a relocatable object file from arbitrary binary input, like</p>
<div class="fragment"><pre class="fragment">avr-objcopy -I binary -O elf32-avr foo.bin foo.o
</pre></div><p>This will create a file named <code>foo.o</code>, with the contents of <code>foo.bin</code>. The contents will default to section .data, and two symbols will be created named <code>_binary_foo_bin_start</code> and <code>_binary_foo_bin_end</code>. These symbols can be referred to inside a C source to access these data.</p>
<p>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:</p>
<div class="fragment"><pre class="fragment">avr-objcopy --rename-section .data=.progmem.data,contents,alloc,load,readonly,data -I binary -O elf32-avr foo.bin foo.o
</pre></div><p>Note that all this could be conveniently wired into a Makefile, so whenever <code>foo.bin</code> changes, it will trigger the recreation of <code>foo.o</code>, and a subsequent relink of the final ELF file.</p>
<p>Below are two Makefile fragments that provide rules to convert a .txt file to an object file, and to convert a .bin file to an object file:</p>
<div class="fragment"><pre class="fragment">$(OBJDIR)/%.o : %.txt
@echo Converting $&lt;
@cp $(&lt;) $(*).tmp
@echo -n 0 | tr 0 <span class="charliteral">&#39;\000&#39;</span> &gt;&gt; $(*).tmp
@$(OBJCOPY) -I binary -O elf32-avr \
--rename-section .data=.progmem.data,contents,alloc,load,readonly,data \
--redefine-sym _binary_$*_tmp_start=$* \
--redefine-sym _binary_$*_tmp_end=$*_end \
--redefine-sym _binary_$*_tmp_size=$*_size_sym \
$(*).tmp $(@)
@echo <span class="stringliteral">&quot;extern const char&quot;</span> $(*)<span class="stringliteral">&quot;[] PROGMEM;&quot;</span> &gt; $(*).h
@echo <span class="stringliteral">&quot;extern const char&quot;</span> $(*)_end<span class="stringliteral">&quot;[] PROGMEM;&quot;</span> &gt;&gt; $(*).h
@echo <span class="stringliteral">&quot;extern const char&quot;</span> $(*)_size_sym<span class="stringliteral">&quot;[];&quot;</span> &gt;&gt; $(*).h
@echo <span class="stringliteral">&quot;#define $(*)_size ((int)$(*)_size_sym)&quot;</span> &gt;&gt; $(*).h
@rm $(*).tmp
$(OBJDIR)/%.o : %.bin
@echo Converting $&lt;
@$(OBJCOPY) -I binary -O elf32-avr \
--rename-section .data=.progmem.data,contents,alloc,load,readonly,data \
--redefine-sym _binary_$*_bin_start=$* \
--redefine-sym _binary_$*_bin_end=$*_end \
--redefine-sym _binary_$*_bin_size=$*_size_sym \
$(&lt;) $(@)
@echo <span class="stringliteral">&quot;extern const char&quot;</span> $(*)<span class="stringliteral">&quot;[] PROGMEM;&quot;</span> &gt; $(*).h
@echo <span class="stringliteral">&quot;extern const char&quot;</span> $(*)_end<span class="stringliteral">&quot;[] PROGMEM;&quot;</span> &gt;&gt; $(*).h
@echo <span class="stringliteral">&quot;extern const char&quot;</span> $(*)_size_sym<span class="stringliteral">&quot;[];&quot;</span> &gt;&gt; $(*).h
@echo <span class="stringliteral">&quot;#define $(*)_size ((int)$(*)_size_sym)&quot;</span> &gt;&gt; $(*).h
</pre></div><p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_softreset">
How do I perform a software reset of the AVR?</a></h2>
<p>The canonical way to perform a software reset of non-XMega AVR's is to use the watchdog timer. Enable the watchdog timer to the shortest timeout setting, then go into an infinite, do-nothing loop. The watchdog will then reset the processor.</p>
<p>XMega parts have a specific bit <code>RST_SWRST_bm</code> in the <code>RST.CTRL</code> register, that generates a hardware reset. RST_SWRST_bm is protected by the XMega Configuration Change Protection system.</p>
<p>The reason why using the watchdog timer or <code>RST_SWRST_bm</code> is preferable over jumping to the reset vector, is that when the watchdog or <code>RST_SWRST_bm</code> 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.</p>
<p><b>CAUTION!</b> 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 <b>stays enabled, even after a reset</b>! 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.</p>
<p>Here is some example code that creates a macro that can be called to perform a soft reset:</p>
<div class="fragment"><pre class="fragment"><span class="preprocessor">#include &lt;<a class="code" href="wdt_8h.html">avr/wdt.h</a>&gt;</span>
...
#define soft_reset() \
<span class="keywordflow">do</span> \
{ \
wdt_enable(<a class="code" href="group__avr__watchdog.html#gad45893280f49113ffc2e67e1d741f29d">WDTO_15MS</a>); \
<span class="keywordflow">for</span>(;;) \
{ \
} \
} <span class="keywordflow">while</span>(0)
</pre></div><p>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):</p>
<div class="fragment"><pre class="fragment"><span class="preprocessor">#include &lt;<a class="code" href="wdt_8h.html">avr/wdt.h</a>&gt;</span>
...
<span class="comment">// Function Pototype</span>
void wdt_init(<span class="keywordtype">void</span>) <a class="code" href="group__avr__watchdog.html#gadaa6dd28b5d08df35e49b1248d7e5fb0">__attribute__</a>((naked)) <a class="code" href="group__avr__watchdog.html#gadaa6dd28b5d08df35e49b1248d7e5fb0">__attribute__</a>((section(&quot;.init3&quot;)));
...
<span class="comment">// Function Implementation</span>
<span class="keywordtype">void</span> wdt_init(<span class="keywordtype">void</span>)
{
MCUSR = 0;
wdt_disable();
<span class="keywordflow">return</span>;
}
</pre></div><p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_math">
I am using floating point math. Why is the compiled code so big? Why does my code not work?</a></h2>
<p>You are not linking in the math library from AVR-LibC. GCC has a library that is used for floating point operations, but it is not optimized for the AVR, and so it generates big code, or it could be incorrect. This can happen even when you are not using any floating point math functions from the Standard C library, but you are just doing floating point math operations.</p>
<p>When you link in the math library from AVR-LibC, those routines get replaced by hand-optimized AVR assembly and it produces much smaller code.</p>
<p>See <a class="el" href="FAQ.html#faq_libm">I get "undefined reference to..." for functions like "sin()"</a> for more details on how to link in the math library.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_reentrant">
What pitfalls exist when writing reentrant code?</a></h2>
<p>Reentrant code means the ability for a piece of code to be called simultaneously from two or more threads. Attention to re-enterability is needed when using a multi-tasking operating system, or when using interrupts since an interrupt is really a temporary thread.</p>
<p>The code generated natively by gcc is reentrant. But, only some of the libraries in avr-libc are explicitly reentrant, and some are known not to be reentrant. In general, any library call that reads and writes global variables (including I/O registers) is not reentrant. This is because more than one thread could read or write the same storage at the same time, unaware that other threads are doing the same, and create inconsistent and/or erroneous results.</p>
<p>A library call that is known not to be reentrant will work if it is used only within one thread <em>and</em> no other thread makes use of a library call that shares common storage with it.</p>
<p>Below is a table of library calls with known issues.</p>
<table class="doxtable">
<tr>
<td><b>Library call</b> </td><td><b>Reentrant Issue</b> </td><td><b>Workaround/Alternative</b> </td></tr>
<tr>
<td><a class="el" href="group__avr__stdlib.html#gae23144bcbb8e3742b00eb687c36654d1">rand()</a>, <a class="el" href="group__avr__stdlib.html#ga114aeb1751119382aaf3340355b22cfd">random()</a> </td><td>Uses global variables to keep state information. </td><td>Use special reentrant versions: <a class="el" href="group__avr__stdlib.html#gaf5085001be836a0f2a5d3269a7c9fd04">rand_r()</a>, <a class="el" href="group__avr__stdlib.html#gaa99a0733f06d2b9960a1401c2721af1e">random_r()</a>. </td></tr>
<tr>
<td><a class="el" href="group__avr__stdlib.html#ga5ee4d110a3bb55d2eadda05e3ebedf8a">strtod()</a>, <a class="el" href="group__avr__stdlib.html#gaf8ce3b8dae3d45c34c3b172de503f7b3">strtol()</a>, <a class="el" href="group__avr__stdlib.html#gaea44aa48bda8261f794dcb2d1e7ab2b2">strtoul()</a> </td><td>Uses the global variable <code>errno</code> to return success/failure. </td><td>Ignore <code>errno</code>, or protect calls with <a class="el" href="group__avr__interrupts.html#ga68c330e94fe121eba993e5a5973c3162">cli()</a>/sei() or <a class="el" href="group__util__atomic.html#gaaaea265b31dabcfb3098bec7685c39e4">ATOMIC_BLOCK()</a> if the application can tolerate it. Or use sccanf() or sccanf_P() if possible. </td></tr>
<tr>
<td><a class="el" href="group__avr__stdlib.html#ga4996af830ebe744d9678e5251dfd3ebd">malloc()</a>, <a class="el" href="group__avr__stdlib.html#gafd300bad8b4dd2e88b07d464d76c92aa">realloc()</a>, <a class="el" href="group__avr__stdlib.html#ga51ac965dacbc9daf922f469bdcfe00c2">calloc()</a>, <a class="el" href="group__avr__stdlib.html#gafb8699abb1f51d920a176e695ff3be8a">free()</a> </td><td>Uses the stack pointer and global variables to allocate and free memory. </td><td>Protect calls with <a class="el" href="group__avr__interrupts.html#ga68c330e94fe121eba993e5a5973c3162">cli()</a>/sei() or <a class="el" href="group__util__atomic.html#gaaaea265b31dabcfb3098bec7685c39e4">ATOMIC_BLOCK()</a> if the application can tolerate it. If using an OS, use the OS provided memory allocator since the OS is likely modifying the stack pointer anyway. </td></tr>
<tr>
<td><a class="el" href="group__avr__stdio.html#gab599ddf60819df4cc993c724a83cb1a4">fdevopen()</a>, <a class="el" href="group__avr__stdio.html#gad3d27a6dcc225237171196dd0739bb10">fclose()</a> </td><td>Uses <a class="el" href="group__avr__stdlib.html#ga51ac965dacbc9daf922f469bdcfe00c2">calloc()</a> and <a class="el" href="group__avr__stdlib.html#gafb8699abb1f51d920a176e695ff3be8a">free()</a>. </td><td>Protect calls with <a class="el" href="group__avr__interrupts.html#ga68c330e94fe121eba993e5a5973c3162">cli()</a>/sei() or <a class="el" href="group__util__atomic.html#gaaaea265b31dabcfb3098bec7685c39e4">ATOMIC_BLOCK()</a> if the application can tolerate it. Or use <a class="el" href="group__avr__stdio.html#gaf41f158c022cbb6203ccd87d27301226" title="Setup a user-supplied buffer as an stdio stream.">fdev_setup_stream()</a> or <a class="el" href="group__avr__stdio.html#gaea2b6be92ead4673bc487b271b7227fb" title="Initializer for a user-supplied stdio stream.">FDEV_SETUP_STREAM()</a>. <br/>
Note: <a class="el" href="group__avr__stdio.html#gad3d27a6dcc225237171196dd0739bb10">fclose()</a> will only call <a class="el" href="group__avr__stdlib.html#gafb8699abb1f51d920a176e695ff3be8a">free()</a> if the stream has been opened with <a class="el" href="group__avr__stdio.html#gab599ddf60819df4cc993c724a83cb1a4">fdevopen()</a>. </td></tr>
<tr>
<td>eeprom_*(), boot_*() </td><td>Accesses I/O registers. </td><td>Protect calls with <a class="el" href="group__avr__interrupts.html#ga68c330e94fe121eba993e5a5973c3162">cli()</a>/sei(), <a class="el" href="group__util__atomic.html#gaaaea265b31dabcfb3098bec7685c39e4">ATOMIC_BLOCK()</a>, or use OS locking. </td></tr>
<tr>
<td>pgm_*_far() </td><td>Accesses I/O register RAMPZ. </td><td>Starting with GCC 4.3, RAMPZ is automatically saved for ISRs, so nothing further is needed if only using interrupts. <br/>
Some OSes may automatically preserve RAMPZ during context switching. Check the OS documentation before assuming it does. <br/>
Otherwise, protect calls with <a class="el" href="group__avr__interrupts.html#ga68c330e94fe121eba993e5a5973c3162">cli()</a>/sei(), <a class="el" href="group__util__atomic.html#gaaaea265b31dabcfb3098bec7685c39e4">ATOMIC_BLOCK()</a>, or use explicit OS locking. </td></tr>
<tr>
<td><a class="el" href="group__avr__stdio.html#ga4c04da4953607fa5fa4d3908fecde449">printf()</a>, <a class="el" href="group__avr__stdio.html#ga418e63921ed6259e873cd21b6c5c8e6e">printf_P()</a>, <a class="el" href="group__avr__stdio.html#ga0b15be24dd9db93355e1f62937fdfd9a">vprintf()</a>, vprintf_P(), <a class="el" href="group__avr__stdio.html#ga33f7bd99d40bf6f68a00d5507d65363d">puts()</a>, <a class="el" href="group__avr__stdio.html#gab4de83c560c79bf880fa39b997d61610">puts_P()</a> </td><td>Alters flags and character count in global FILE <code>stdout</code>. </td><td>Use only in one thread. Or if returned character count is unimportant, do not use the *_P versions. <br/>
Note: Formatting to a string output, e.g. <a class="el" href="group__avr__stdio.html#ga6017094d9fd800fa02600d35399f2a2a">sprintf()</a>, <a class="el" href="group__avr__stdio.html#ga2b829d696b17dedbf181cd5dc4d7a31d">sprintf_P()</a>, <a class="el" href="group__avr__stdio.html#ga77070c245d4ca4f7ec7d7144260fb875">snprintf()</a>, <a class="el" href="group__avr__stdio.html#ga53ff61856759709eeceae10aaa10a0a3">snprintf_P()</a>, <a class="el" href="group__avr__stdio.html#gaaeb1bbe21a1b9b50b207ab059a67993f">vsprintf()</a>, <a class="el" href="group__avr__stdio.html#gaf47f5141509d1e434f9da2b27287a707">vsprintf_P()</a>, <a class="el" href="group__avr__stdio.html#gac92e8c42a044c8f50aad5c2c69e638e0">vsnprintf()</a>, <a class="el" href="group__avr__stdio.html#ga2071feb5c92bf50a6bd508a07ead9515">vsnprintf_P()</a>, is thread safe. The formatted string could then be followed by an <a class="el" href="group__avr__stdio.html#gadd5777719a41713629a62b68c239a774">fwrite()</a> which simply calls the lower layer to send the string. </td></tr>
<tr>
<td><a class="el" href="group__avr__stdio.html#ga0e41285401c397eb29692205a95fcd9c">fprintf()</a>, <a class="el" href="group__avr__stdio.html#ga36173b4a8551b61811089198beec69d9">fprintf_P()</a>, <a class="el" href="group__avr__stdio.html#gaa3b98c0d17b35642c0f3e4649092b9f1">vfprintf()</a>, <a class="el" href="group__avr__stdio.html#ga55b25ecbfd3811ea4495d1f235e2e186">vfprintf_P()</a>, <a class="el" href="group__avr__stdio.html#ga19c2bbe9ce4af9f0a7e3448387004fd3">fputs()</a>, <a class="el" href="group__avr__stdio.html#ga3d25813cb225ca410518a3f48eb00caa">fputs_P()</a> </td><td>Alters flags and character count in the FILE argument. Problems can occur if a global FILE is used from multiple threads. </td><td>Assign each thread its own FILE for output. Or if returned character count is unimportant, do not use the *_P versions. </td></tr>
<tr>
<td><a class="el" href="group__avr__assert.html#ga0041af519e0e7d47c9bcc83760c4669e">assert()</a> </td><td>Contains an embedded <a class="el" href="group__avr__stdio.html#ga0e41285401c397eb29692205a95fcd9c">fprintf()</a>. See above for <a class="el" href="group__avr__stdio.html#ga0e41285401c397eb29692205a95fcd9c">fprintf()</a>. </td><td>See above for <a class="el" href="group__avr__stdio.html#ga0e41285401c397eb29692205a95fcd9c">fprintf()</a>. </td></tr>
<tr>
<td><a class="el" href="group__avr__stdio.html#gaaa6d255675688c736c99ebd32f2a7214">clearerr()</a> </td><td>Alters flags in the FILE argument. </td><td><p class="starttd">Assign each thread its own FILE for output. </p>
<p class="endtd"></p>
</td></tr>
<tr>
<td><a class="el" href="group__avr__stdio.html#gac0484b3e3a4d8361d91c3322440f9195">getchar()</a>, <a class="el" href="group__avr__stdio.html#gaf577dcba9afe50a9d068d0b69ac85d2f">gets()</a> </td><td>Alters flags, character count, and unget buffer in global FILE <code>stdin</code>. </td><td><p class="starttd">Use only in one thread. *** </p>
<p class="endtd"></p>
</td></tr>
<tr>
<td><a class="el" href="group__avr__stdio.html#ga818d63019adc9d518a13f9c36ed04f35">fgetc()</a>, <a class="el" href="group__avr__stdio.html#gab4f9b130166e5811519513d6178c1ae3">ungetc()</a>, <a class="el" href="group__avr__stdio.html#ga00d34a8bff0293d2d6f4563d248d8fb2">fgets()</a>, <a class="el" href="group__avr__stdio.html#ga3f0edc16dcabb5344d59d42cf7682102">scanf()</a>, <a class="el" href="group__avr__stdio.html#ga0fb7fd70cd7618f27d8219c97e61bcf3">scanf_P()</a>, <a class="el" href="group__avr__stdio.html#ga0beb4fd9ff6833a364e3ce60370de058">fscanf()</a>, <a class="el" href="group__avr__stdio.html#ga7aec94e711ad64724076666586a26839">fscanf_P()</a>, <a class="el" href="group__avr__stdio.html#ga8bd4b760f67791a54e73111734caa82f">vscanf()</a>, <a class="el" href="group__avr__stdio.html#ga67bae1ad3af79809fd770be392f90e21">vfscanf()</a>, <a class="el" href="group__avr__stdio.html#ga6c6b5b881ce8f4739777ff3a615e988a">vfscanf_P()</a>, <a class="el" href="group__avr__stdio.html#ga54fa47156a34c1659a29ed96e46e3518">fread()</a> </td><td>Alters flags, character count, and unget buffer in the FILE argument. </td><td>Assign each thread its own FILE for input. *** <br/>
Note: Scanning from a string, e.g. <a class="el" href="group__avr__stdio.html#ga5507d0e1bbfd387fbb2ffcfd8f5dca6f">sscanf()</a> and <a class="el" href="group__avr__stdio.html#gaeca11dc4b3757ed4ff2f2a4950eba117">sscanf_P()</a>, are thread safe. </td></tr>
</table>
<dl class="note"><dt><b>Note:</b></dt><dd>It's not clear one would ever want to do character input simultaneously from more than one thread anyway, but these entries are included for completeness.</dd></dl>
<p>An effort will be made to keep this table up to date if any new issues are discovered or introduced.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_eeprom_corruption">
Why are some addresses of the EEPROM corrupted (usually address zero)?</a></h2>
<p>The two most common reason for EEPROM corruption is either writing to the EEPROM beyond the datasheet endurance specification, or resetting the AVR while an EEPROM write is in progress.</p>
<p>EEPROM writes can take up to tens of milliseconds to complete. So that the CPU is not tied up for that long of time, an internal state-machine handles EEPROM write requests. The EEPROM state-machine expects to have all of the EEPROM registers setup, then an EEPROM write request to start the process. Once the EEPROM state-machine has started, changing EEPROM related registers during an EEPROM write is guaranteed to corrupt the EEPROM write process. The datasheet always shows the proper way to tell when a write is in progress, so that the registers are not changed by the user's program. The EEPROM state-machine will <b>always</b> complete the write in progress unless power is removed from the device.</p>
<p>As with all EEPROM technology, if power fails during an EEPROM write the state of the byte being written is undefined.</p>
<p>In older generation AVRs the EEPROM Address Register (EEAR) is initialized to zero on reset, be it from Brown Out Detect, Watchdog or the Reset Pin. If an EEPROM write has just started at the time of the reset, the write will be completed, but now at address zero instead of the requested address. If the reset occurs later in the write process both the requested address and address zero may be corrupted.</p>
<p>To distinguish which AVRs may exhibit the corrupt of address zero while a write is in process during a reset, look at the "initial
value" section for the EEPROM Address Register. If EEAR shows the initial value as 0x00 or 0x0000, then address zero and possibly the one being written will be corrupted. Newer parts show the initial value as "undefined", these will not corrupt address zero during a reset (unless it was address zero that was being written).</p>
<p>EEPROMs have limited write endurance. The datasheet specifies the number of EEPROM writes that are guaranteed to function across the full temperature specification of the AVR, for a given byte. A read should always be performed before a write, to see if the value in the EEPROM actually needs to be written, so not to cause unnecessary EEPROM wear.</p>
<p>The failure mechanism for an overwritten byte is generally one of "stuck" bits, i. e. a bit will stay at a one or zero state regardless of the byte written. Also a write followed by a read may return the correct data, but the data will change with the passage of time, due the EEPROM's inability to hold a charge from the excessive write wear.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_wrong_baud_rate">
Why is my baud rate wrong?</a></h2>
<p>Some AVR datasheets give the following formula for calculating baud rates:</p>
<div class="fragment"><pre class="fragment">(<a class="code" href="group__util__delay.html#ga43bafb28b29491ec7f871319b5a3b2f8" title="CPU frequency in Hz.">F_CPU</a>/(UART_BAUD_RATE*16L)-1)
</pre></div><p>Unfortunately that formula does not work with all combinations of clock speeds and baud rates due to integer truncation during the division operator.</p>
<p>When doing integer division it is usually better to round to the nearest integer, rather than to the lowest. To do this add 0.5 (i. e. half the value of the denominator) to the numerator before the division, resulting in the formula:</p>
<div class="fragment"><pre class="fragment">((<a class="code" href="group__util__delay.html#ga43bafb28b29491ec7f871319b5a3b2f8" title="CPU frequency in Hz.">F_CPU</a> + UART_BAUD_RATE * 8L) / (UART_BAUD_RATE * 16L) - 1)
</pre></div><p>This is also the way it is implemented in <a class="el" href="group__util__setbaud.html">&lt;util/setbaud.h&gt;: Helper macros for baud rate calculations</a>.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_funcptr_gt128kib">
On a device with more than 128 KiB of flash, how to make function pointers work?</a></h2>
<p>Function pointers beyond the "magical" 128 KiB barrier(s) on larger devices are supposed to be resolved through so-called <em>trampolines</em> by the linker, so the actual pointers used in the code can remain 16 bits wide.</p>
<p>In order for this to work, the option <code>-mrelax</code> must be given on the compiler command-line that is used to link the final ELF file. (Older compilers did not implement this option for the AVR, use <code>-Wl,--relax</code> instead.)</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small></p>
<h2><a class="anchor" id="faq_assign_chain">
Why is assigning ports in a "chain" a bad idea?</a></h2>
<p>Suppose a number of IO port registers should get the value <code>0xff</code> assigned. Conveniently, it is implemented like this:</p>
<div class="fragment"><pre class="fragment"> DDRB = DDRD = 0xff;
</pre></div><p>According to the rules of the C language, this causes 0xff to be assigned to <code>DDRD</code>, then <code>DDRD</code> is read back, and the value is assigned to <code>DDRB</code>. The compiler stands no chance to optimize the readback away, as an IO port register is declared "volatile". Thus, chaining that kind of IO port assignments would better be avoided, using explicit assignments instead:</p>
<div class="fragment"><pre class="fragment"> DDRB = 0xff;
DDRD = 0xff;
</pre></div><p>Even worse ist this, e. g. on an ATmega1281:</p>
<div class="fragment"><pre class="fragment"> DDRA = DDRB = DDRC = DDRD = DDRE = DDRF = DDRG = 0xff;
</pre></div><p>The same happens as outlined above. However, when reading back register <code>DDRG</code>, this register only implements 6 out of the 8 bits, so the two topmost (unimplemented) bits read back as 0! Consequently, all remaining <code>DDR</code><em>x</em> registers get assigned the value 0x3f, which does not match the intention of the developer in any way.</p>
<p><small>Back to <a class="el" href="FAQ.html#faq_index">FAQ Index</a>.</small> </p>
</div>
<!--- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&nbsp;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&nbsp;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&nbsp;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&nbsp;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&nbsp;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&nbsp;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&nbsp;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&nbsp;</span>Defines</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<!-- HTML footer for doxygen 1.8.7-->
<!-- start footer part -->
<!--BEGIN GENERATE_TREEVIEW-->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
$navpath
<li class="footer">$generatedby
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="$relpath^doxygen.png" alt="doxygen"/></a> 1.6.3 </li>
</ul>
</div>
<!--END GENERATE_TREEVIEW-->
<!--BEGIN !GENERATE_TREEVIEW-->
<hr class="footer"/><address class="footer"><small>
$generatedby &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="$relpath^doxygen.png" alt="doxygen"/>
</a> 1.6.3
</small></address>
<!--END !GENERATE_TREEVIEW-->
</body>
</html>