Tag Archives: interrupt

Real Time Counter and Integer Overflow

After writing the article about event-based firmware, I realised there are some misunderstandings how real-time counter are working and should be used. Especially there is a misconception about an imagined problem if such counter overflows. In this article, I try to explain this topic in more detail, using example code for the Arduino IDE.

What is a Real-Time Counter?

A real-time counter is a variable or register which increases at a given time interval. The term real-time may be confusing. It just states the fact this counter ideally does count independently of any other parts of the firmware. Therefore, even if the main code stops at one point and waiting for a specific condition, the real-time counter will get increased in the “background” at the given interval.

How is the Real-Time Counter Implemented?

These counters are usually implemented using a hardware timer and an interrupt. For the Arduino platform, a hardware timer is set to create an interrupt each millisecond. If you can find most of this code in the file wired.c (AVR) or delay.c (SAMD). The following code is a summary of the relevant parts of the simpler implementation for the SAMD platform:

static volatile uint32_t _ulTickCount=0;

unsigned long millis(void)
{
  return _ulTickCount;
}

void SysTick_DefaultHandler(void)
{
  _ulTickCount++;
}

You see the variable _ulTickCount which is an unsigned 32bit integer. It is marked as volatile to tell the compiler, this variable can be modified from an interrupt and reads can not be optimised away.

You can access the current value using the millis() function. Interrupts do not need to be blocked while reading this value, because reading a single 32bit value is an atomic operation for the SAMD platform. It means, it is not possible to process an interrupt in the middle of reading the integer. The interrupt will occur before or after reading the value, but never e.g. after reading the first byte of the integer value. For some platforms, this can be a problem.

The last function is SysTick_DefaultHandler which just increases the variable by one every millisecond.

What is Integer Overflow?

An integer overflow happens, if you add to an integer value and the result exceeds the maximum number it can store. You can easily verify this using the following code:

Continue reading Real Time Counter and Integer Overflow