I have a little question about the TOVn flag located in the TIFRn register.

The datasheet says, if the TCNTn counter overflows, then the TOVn flag located in the register TIFRn will be set to 1. (at the same clock cycle the overflow occoured).

The code to handle such event is the following:

/* Check if TOV1 flag is set */
if (TIFR1 & _BV(TOV1)) {
    /* Since TOV1 is set, we know we missed an overflow interrupt */

    /* Handle the event... */
    // ... timer_ovf_cnt++;

    /* Prevent ISR to be called, because we already handled the overflow */
    TIFR1 = _BV(TOV1); // .. but TOV1 is already set in TIFR1?

But what confuses me is: why should I set the TOV1 bit when its already set by hardware? Does setting the TOV1 flag in TIFR1 to 1 by user hand disable the timer interrupt? (Even, if the TOV1 flag is already set by hardware?)

EDIT: Found the answer: Clearing flag bits by writing 1?

  • 6
    \$\begingroup\$ +1 for flagging your own question as duplicate. That's what I call discipline. Well done! \$\endgroup\$ – Ricardo Feb 3 '15 at 12:53

The point of writing 1 to clear is to clear the flag atomically without changing any of the other bits. Sure, it is possible to do a read-modify-write and clear one bit that way, but then you may overwrite a flag that got set in hardware between the read and the write. Since there is no reason to set the bit from software, the flip flop is configured so that the hardware can set the bit and the software can clear it by writing 1. This is not necessary for flags that are set in an interrupt handler as you can simply disable interrupts during the read-modify-write operation.

The other post does not mention anything anything about atomicity, which is the reasoning behind this design.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.