title: Can ICR1 time be wrongly synchronized to overflow counter?
body: <p>I have an Atmega328p that I want to program to precisley caputre the time of an input event.</p>
  <p>However now a question came up to me if my code would work in all situations. This question, I think, is more related to the general handling of interrupts on the Atmega platform.</p>
  <p>So my code looks like this (in summary):</p>
  <pre><code>volatile uint16_t overflow = 0;
  
  ISR(TIMER1_CAPT_vect) {
      uint16_t captureCount = ICR1;
      uint32_t t = ((uint32_t) overflow &lt;&lt; 16) | captureCount;
  }
  
  ISR(TIMER1_OVF_vect) {
      overflow++;
  }
  </code></pre>
  <p>This should capture when an input event occures within the interrupt ISR(TIMER1_CAPT_vect), furthermore the overflow of timer1 is counted with the other interrupt. As far as I understand it correctly ICR1 stores the time of timer1 exactly when the input event occures and then some short time later fires the interrupt to notify the code that this event occures where I then calculated the real time by using the current overflow counter.</p>
  <p>I know from <a href="https://stackoverflow.com/questions/24128926/what-happens-when-an-isr-is-running-and-another-interrupt-happens">this</a> answer that the code inside the interrupt is not interrupted by another interrupt (e.g. the overflow interrupt), so the addition of overflow and captureCount to form t is &quot;atomic&quot;/&quot;thread safe&quot;.
  But what I am wondering now is what would happen if the ICR1 is set by the current timer1 value and right after that an overflow occured, before my code is notified by the ISR(TIMER1_CAPT_vect). With this it could be that, maybe, the overflow interrupt is run before the event-capture interrupt. This would then result in the possibility that the overflow counter is increased by 1 but the ICR1 stills holds the time corresponding to the old overflow range, giving a wrong t.</p>
  <p>So in general this problem would only occure if the overflow interrupt is fired before the event-capture interrupt is fired, although the true capture event (when ICR1 is set to current timer1) happend before the overflow.</p>
  <p>This leads me to the overall general question: Are interrupts handled in the same order as the actual true event occure on Atmega?</p>
  <p>And especially regarding my two interrupts of timer1?</p>