0

I have set up Timer2 to count every tick at 16MHz, or 62.5ns per tick. Then I run the following code:

int t = 0;
    for (int i=0;i<64;i++){
  data[4*i] = TCNT2;
  data[4*i+1] = TCNT2;
  byte now = data[4*i+1];
  byte last = data[4*i];
  t += now > last? (long)(now-last) : 256 -(long)(last-now);
  data[4*i+2] = TCNT2;
  data[4*i+3] = TCNT2;    
  }
}
for (int i=0;i<255;i++){
  Serial.println(data[i]-data[i+1]);
}

and I get the output: "4 4 4 11" (repeated) which makes sense, 4 clock cycles to read TCNT2 and write it to the correct place in data and 11 cycles when also evaluating the loop condition. However, I can't understand when the variable t is updated. I have tried running with and without t and both give the same timings. From my (obviously lacking) understanding updating a variable is at minimum one instruction, so how can it do it under one clock cycle? Am I misunderstanding what one instruction is or does the TCNT2 counter for the timer not update accurately here?

1

Ops, I just realized it's the compiler working it's magic. I never used t, thus the compiler said "Wtf is this guy doing, this t is useless and I'll remove it!". When I used t I got sensible results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.