How to improve Arduino Due timer precision?

Hi everyone I am using Due's timer interrupt to call a routine periodically, the code fragment is bellow. I use "ticks" variable to calculate timer's period to call a routine. The code is working very well, the problem is that it isn't very precise. For example if I set period to 200 milliseconds, I get 193.7, it is worse for smallest periods, if I set 10 milliseconds I get only 5.6. I need microseconds precision in my code. I tried all the timers divisors, currently I am using 128, and all the nine timers and the problem persist. Anyone can say why this is so imprecise and how to improve it? Thanks in advance.

  pmc_set_writeprotect(false);      // disable write protection for pmc registers
  pmc_enable_periph_clk(ID_TC7);    // enable peripheral clock TC7

  TC_Configure(TC2,1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4); //Division by 128
  TC_SetRC(TC2, 1, ticks); //ticks = (84MHz/128) * period
  TC_Start(TC2, 1);

  // enable timer interrupts on the timer
  TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS;   // IER = interrupt enable register
  TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS;  // IDR = interrupt disable register

  /* Enable the interrupt in the nested vector interrupt controller */
  NVIC_EnableIRQ(TC7_IRQn);;

Is "ticks" getting correctly calculated? (do it manually, and check if the results in your program.) The most likely cause of this magnitude of error is some sort of truncation/promotion error in the math.

Yes. I had calculated this several times, in both I got the same error. The problem is that the error increase as that period decrease. I plotted the error in function to period and the function is quadratic. It does not make sense.

Post all your code.

  /* Enable the interrupt in the nested vector interrupt controller */
  NVIC_EnableIRQ(TC7_IRQn);;

Double semi-colon.

This statement comes after configuring the TC, however:

37.5.3 Interrupt (page 872) The TC has an interrupt line connected to the Interrupt Controller (IC). Handling the TC interrupt requires programming the IC before configuring the TC.

it may well be 1500 lines long but what you need to do is to remove the code that does not impact on the problem and show us the rest. If your program is like just about every non-trivial bit of code, there will be many lines of code that relate to some other part of the functionality. Remove those lines until either you have a small code snippet that exhibits the problem (we can then try to reproduce the issue ourselves) OR you remove something that makes the problem go away. In that case, the answer will possibly lie in the code you have just removed which, if nothing else, lets you concentrate on a more targeted part of the code base. Susan

You are almost certainly misusing integer division (which truncates). Another (unlikely) possibility is that your board has a duff quartz crystal, but then I doubt it would work (serial, USB, etc need accurate clock).