Search code examples
avratmegastatus-register

On an AVR MCU, how does the S flag in the status register work?


How exactly do the V and S flags function on the ATMEGA328?

The ATMEGA328 has separate sign (S), carry (C), 2's complement overflow (V) and negative (N) flags. N is the MSB (corresponding to the sign bit on other processors). How exactly the V flag operates is not well explained in the datasheet. As I understand it, V is generally calculated as N⊕C. But S is defined in the datasheet as V⊕N which implies that it equals N⊕N⊕C or just C. If that's true then it doesn't make much sense to have a separate flag for it so I suspect I've misunderstood something here.


Solution

  • V is not generally the same as N XOR C.

    I found a counterexample by looking at the ADC (Add with Carry) instruction in the manual and considering what would happen if you add 0xFF to 0x02 to get 0x01.

    • C would be 1 because 0xFF + 0x02 = 0x101, which is larger than 0xFF, so there is a carry from the most significant bit of the addition.
    • N would be 0 because it is simply the MSB of the result.
    • V would be 0 because it is defined to be 1 if two's complement overflow happened. From the perspective of two's complement, we simply added -1 and 2 to get 1, so there is no overflow. And you can confirm this by carefully evaluating the formula in the manual to calculate V.