Use Systick on samd21e15b

195 Views Asked by At

I'am working with Systick for the first time with an samd21e15b, so my objective is to be able to count time between delay for example. So here is what I've try to do

SysTick->CTRL = 0;
SysTick->LOAD = 0x7A11FFul;
SysTick->VAL = 0;
SysTick->CTRL = 0x5;
while(SysTick->VAL == 0);
uint32_t start = SysTick->VAL;
delay_ms(1000);
uint32_t stop = SysTick->VAL;
uint32_t volatile temps = start - stop;

So I set SysTick->LOAD = 0x7A11FFul beceause my CPU run at 8Mhz and I want 1s tick, so coming from this math

N = (SysTick delay time / System Clock Period ) - 1

=(SysTick delay time * System Clock Frequency) - 1

= (1s * 8MHz) - 1 = 8M - 1 = 7,999,99

So if my cpu runs at 8MHz I have one cpu cycle every 125ns is it right? But if I inspect temps variable I have a value of 311 after delay of 1s and I don't understand this value

1

There are 1 best solutions below

0
On

Some issues:

  • On SAM parts you first have to configure the general clock settings and the various "GCLK" options, but assuming that's done and you've indeed got a clock running at 8MHz, then one tick is indeed 125ns.

  • The LOAD register wants delay / frequency - 1, so if we for example want 1s then 1 / 125x10-9 = 8x106.

    Thus: SysTick->LOAD = 8000000u - 1. We want self-documenting code in normal base 10 decimal. No mysterious hex magic numbers. And document where you got this number from in comments!

    I'm not sure if it makes sense to set SysTick to use 1s though - I always set it to 1ms. Or otherwise I'm not sure what will happen to code like delay_ms(1000);.

  • while(SysTick->VAL == 0); I don't understand why you do this, you'll introduce a clock inaccuracy right there. The clock supposedly starts running soon as you enable it.

    Which again isn't done with "magic numbers" but named constants. Example using ASF and assuming external clock:

    SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | 
                    SysTick_CTRL_ENABLE_Msk;
    
  • start - stop is wrong, clocks count upwards. You'll want stop - start.