Timers of Arduino and Xmega don't match

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi everyone, 

I am using xmega as the I2C master of an Arduino Uno. However, when I use millis() to calculate the time that consumed by one loop cycle in the arduino code 

void loop(){
    unsigned long currentMillis = millis();
    dt = currentMillis - previousMillis;
      previousMillis = currentMillis;        
      send_data_to_xmega();
}

dt is 22 milliseconds give or take.

By using the similar way to calculate the loop cycle in Xmega code, I implemented

int main(void)
{
	timerINI();
	
    while (1) 
    {
	int16_t currentCycles= TCC0_CNT;
	dt=currentCycles-previousCycles;
	previousCycles=currentCycles;
    receive_data();
    data_calibration();
    }
}
void timerINI() {
	TCC0.CTRLA = TC_CLKSEL_DIV1024_gc;
	TCC0.CTRLB = TC_BYTEM_NORMAL_gc;
}

In this case, I'm using 32 MHz clock and dt is around 520 cycles, which could be converted as 520*(1024/32000000)*1000=17 milliseconds. 

Is this even possible?  The second device is running faster that the primary one even the data input of the second device is based on the output of the first one? Are there any reasonable explanation for this case? Or what I have done wrong when calculating the running time of each loop? Any response is welcomed. Many thanks.!!! 

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 1

Use a uint16_t instead of a int16_t. Why? What happens if the timer count wraps around? Your calculation won't give the correct answer.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Arduino code has so much overhead that it actually might be so that the transmission takes extra time. Do it in pure C (without arduino librarys) on Arduino board aswell, this way the results are actually comparable.