Electronic – SysTick accuracy in STM32

cstm32timer

I have coded a simple timing check for my STM32F4 Discovery board.

#define IT_PER_SEC 100

int main(void)
{
   if (SysTick_Config(SystemCoreClock / IT_PER_SEC)) 
   {          
      while (1){}; // error
   }

   initGPIO();

   for(;;)
   {
   }

   return 0;
}

void SysTick_Handler(void)
{
   static uint32_t csec  = 0;
   static uint32_t ctime = 0;

   ++csec;
   if(csec == IT_PER_SEC) // every second
   {
      // every second
      GPIO_ToggleBits(GPIOD, GPIO_Pin_12);
      csec = 0;

      // clock
      ++ctime;

      if((ctime % 10) == 0) // every 10 seconds
      {
         GPIO_ToggleBits(GPIOD, GPIO_Pin_13);
      }

      if((ctime % 60) == 0)     // every minute
      {
         GPIO_ToggleBits(GPIOD, GPIO_Pin_14);
      }

      if(ctime == 3600)         // every hour
      {
         GPIO_ToggleBits(GPIOD, GPIO_Pin_15);
         ctime = 0;
      }
   }
}

This seems to be working fine. I checked it with the stopwatch app on my android phone. But after an hour and something I noticed that the LED timing was about a second in advance and after two and a half hours I'm almost at two seconds.

I guess my app is not at fault here, or is it? The SysTick should be fine as well, I suppose. So it must be my code…

The schematics are the standard schematics of the STM32F4 Discovery board. They can be found in the user manual on page 32. There, one can find an 8 MHz crystal together with the two common 20 pF capacitors.

Best Answer

Crystals are usually much better than 50ppm accuracy ... BUT ... crystals have two resonance modes - series resonance and parallel resonance (with an impedance plot, you will see the impedance rise towards infinity at parallel resonance and fall towards zero at series resonance).

Now the importance of this is that the two resonant modes are usually a few hundred PPM apart, and only one of them will be at the marked frequency!

If you just buy an "8 MHz" crystal without paying due attention to the fine print, you may get one cut to 8 MHz in the wrong mode; and your oscillator will be several hundred PPM off tune.

(The parallel resonance is also tunable over 50ppm or more, so it is usually specified at a given load capacitance).

You'd think most professional designers would pay more attention and select the correct crystal - and you'd usually be right - but I have even seen some high-priced digital audio equipment where this mistake was made!

Or perhaps component purchasing found a "good deal" or it was simply decided that for a budget evaluation board, price was more important than timing accuracy...

But anyway my guess is that the crystal is operating in the wrong mode to produce a 300ppm frequency error.