Hello.
I'm in the middle of some project, where I must measure time between start of measurement and interrupt. Since Arduino UNO is running on 16MHz and there are a lot of single-cycle instructions, this should give me about 62.5ns resolution or so.
So my thinking was: I will use timer1 with no prescaller, start measurement, set timer to zero and than wait until hardware interrupt (low state on pin 2 or 3). In that ISR I should read the timer1 value and subtract time, that interrupt call needs. Or something similar, isn't really important, since values so far are clearly wrong or I'm really wrong somewhere in my thinking.
I make some experiment with timer1 and there are some strange values coming out of serial print. Here is the code:
const int LED = 13;
const int testPIN = 2;
void setup()
{
Serial.begin(9600);
pinMode(LED, OUTPUT);
pinMode(testPIN, INPUT);
digitalWrite(testPIN, HIGH);
digitalWrite(LED, LOW);
noInterrupts();
TCCR1A = B00000000; //timer control register A - default
TCCR1B = B01000001; //prescaler = 1;
TCCR1C = B00000000; //timer control register C - default
TCNT1 = 0; //inicitialize timer - set it to tero
interrupts();
}
unsigned int timerOne1 = 0;
unsigned int timerOne2 = 0;
unsigned int test = 0;
int timeBasic = 0;
void loop()
{
timeBasic = 0;
cajt = 0;
TCNT1 = 0;
timerOne1 = TCNT1;
/*
int x = 0;
int y = 1;
int z = 2;
x = y + z;
y = z + x;
z = y + x;
x = y + z;
y = z + x;
z = y + x;
*/
timerOne2 = TCNT1;
timeBasic = timerOne2 - timerOne1;
Serial.println(timerOne1);
Serial.println(timerOne2);
Serial.print("Length of read 16bit register: ");
Serial.println(timeBasic);
So, there is the strange thing.
The output (serial monitor) is:
1
9
Length of read 16bit register: 8
So, the first read after TCNT1 = 0 command length is 1, then the next one is 8 cycles later.
Notice the commented variable declarations of x, y and z. They don't have any special functions, but when they are uncommented, the output is the same. I thought TCNT1 would have greater value since uC is doing some instructions between two reads. Well it doesn't. I tried a bunch of other things with no success, so I hope here is someone who could explain me what is going on.
btw.: I read atmega328p datasheet and I know that TCNT1 is 16bit register combined from two 8bit registers TCNT1H and TCNT1L, which could be read separately. I did this too, with no succes.
Thanks.