Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is my function static variable never different despite being incremented?
    text
    copied!<p>I am writing a callback function in C. It is intended to initialise an I2C sensor, and it called at the conclusion of each (split-phase) configuration step; after the 9th call, the device is almost ready to use.</p> <p>The basic idea of the function is this:</p> <pre><code>void callback(void) { static uint8_t calls = 0; if (++calls == 9) { // Finalise device setup (literally a single line of code) } } </code></pre> <p>My problem is that the above if statement is never being entered, despite the function being called 9 times.</p> <p>The (dis)assembly code for my function seems sane (with the exception of the <code>subi . 0xFF</code> trick for an increment, despite the inclusion of an <code>inc</code> instruction):</p> <pre><code>00000a4c &lt;callback&gt;: a4c: 80 91 9e 02 lds r24, 0x029E a50: 8f 5f subi r24, 0xFF ; 255 a52: 80 93 9e 02 sts 0x029E, r24 a56: 89 30 cpi r24, 0x09 ; 9 a58: 09 f0 breq .+2 ; 0xa5c &lt;callback+0x10&gt; a5a: 08 95 ret a5c: 2e e1 ldi r18, 0x1E ; 30 a5e: 35 e0 ldi r19, 0x05 ; 5 a60: 41 e0 ldi r20, 0x01 ; 1 a62: 60 e0 ldi r22, 0x00 ; 0 a64: 84 e7 ldi r24, 0x74 ; 116 a66: 0c 94 c7 02 jmp 0x58e ; 0x58e &lt;twi_set_register&gt; </code></pre> <p>I am writing the code for an Atmel AVR chip, and thus compiling with avr-gcc. I have no meaningful code debugging capabilities (I don't have access to a JTAG programmer, and the function is asynchronous/split-phase in any case; USART printing is too slow).</p> <p>However, I have access to a logic analyser, and have been able to determine a number of things by placing <code>while (1) ;</code> statements inside the code:</p> <ul> <li><strong>the function is called</strong> - if I place an infinite loop at the start of the function, the microcontroller hangs</li> <li><strong>the function should be called 9 times</strong> - the trigger for the function is an I2C communication, and in the previous step it hangs immediately after the first communication; I can observe 9 complete and valid I2C communications</li> <li><strong>calls is incremented within the function</strong> - if I add <code>if (calls == 0) { while (1) ; }</code> <em>after</em> the increment, it does not hang</li> <li><strong>calls is never non-zero at the start of the function</strong> - if I add <code>if (calls) { while(1) ; }</code> <em>before</em> the increment, it does not hang</li> </ul> <p>I'm completely at a loss for ideas.</p> <p>Does anyone have any suggestions as to what could cause this, or even for new debugging steps I could take?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload