9 years, 6 months ago.

Accuracy of Timer() function with or without 8MHz crystal

Hi dude,

I'm trying to test RTC ds1307 with F401 board and found out timer function is not accurate. It drifts about one sec at every minute. My simple code is as follow

int main() 
{
  Timer t;
  char c='a', Sec, cntSec=0;
  int tmpSec=0;
  led=0;
  t.start();
  while (1) 
  { 
		if(t.read()>=5.0f) {
			t.reset();
			led=!led;
			cntSec++;
			Sec = getSecond(); //read sec from rtc
			if(tmpSec != Sec)  {
				tmpSec = Sec;
				if(cntSec>=12) {
					cntSec=0;
					displayRTC(); //display rtc value
					//t.start();
				}
			}
		}
      }
}

If I install 8MHz crystal at X3 and other capacitors at C33, C34 and jumpers, timer function is quite accurate as one second at every hour. Anyone know how's relation between timer function and clock frequency?

Regards,

Aung

Question relating to:

Affordable and flexible platform to ease prototyping using a STM32F401RET6 microcontroller.

1 Answer

9 years, 6 months ago.

The internal clock source (IRC) in any MCU is not accurate and will drift with temperature changes. All the MCU internal clocking is derived from which ever clock source you use. If you want accurate timer functions then the only way to go is using the external crystal clock set up as you indicated. If the MCU has a separate RTC clock crystal (usually 32KHz) then this part will be accurate however the rest of the MCU timers will still have the inaccuracy of the IRC if you use IRC as the clock source.

The accuracy using external crystal set up will depend on the quality of the crystal you use and values of the capacitors.

Thank for your answer, and I agree to use external crystal for accurate timer generally but my question is that what clock is controlling timer module. I have read the manual, it could be APB1 prescaler.

posted by Aung KL 15 Aug 2014

Hi Aung KL

doesn't stm32cube help you to manage clock sources?

posted by homayoun mh 25 Aug 2014

The link below may help with the RTC set up code.

http://mbed.org/users/mbed_official/code/mbed-src/file/ec1b66a3d094/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/rtc_api.c

This is for a different ST target, however this is the only board I can get the 32KHz crystal auto detected and working. There is one problem though, the RTC time registers are cleared on a reset, trying to sort this out now.

And for clock set up for the 401 is here:

http://mbed.org/users/mbed_official/code/mbed-src/file/ec1b66a3d094/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/stm32f4xx_hal_rcc.c

posted by Paul Staron 26 Aug 2014