Go Down

Topic: measure time <1ms (Read 2 times) previous topic - next topic


Ok, I think I found the documentation and a description of TCNT0 and TCNT1. But I have to admit that I didn't understand much of it especially how that information relates to the Arduino.

I did some testing with this code:
Code: [Select]

int ledPin = 13;
int t1,t2,diff;

void setup() {
 pinMode(ledPin, OUTPUT);  
 digitalWrite(ledPin, HIGH);  

void loop() {

 t1 = TCNT0;
 t2 = TCNT0;
 Serial.print("TCNT 1: ");  
 Serial.println(t1,DEC);           // print the value to the serial port
 Serial.print("TCNT 2: ");  
 Serial.println(t2,DEC);           // print the value to the serial port
 diff = t2 - t1;
 Serial.print("Diff: ");  
 Serial.println(diff,DEC);           // print the value to the serial port
 delay(900);                          // stop the program for some time

I get values from 12-20 for t1 and 37-47 for t2 but diff is always 25. Looks good, but I don't understand why I always get similar values back and not in the range from 0-255?

Next try: I read that TCNT1 is a 16bit counter so it should be able to measure up to 262ms (2^16 * 4microseconds). Now I get values in the range of 0-255 (diff is 25).

Could someone please explain this behaviour?


Jun 10, 2007, 01:46 am Last Edit: Jun 10, 2007, 01:51 am by jims Reason: 1
It is the delay(900) at the bottom. This waits for a counter that is incremented by TCNT0 rolling over so your code is always called not too long after the rollover.

About TCNT1, 16 bits is better, but... The way it is configured in the arduino I think it counts from 0 up to a limit based on your PWM output and then back down to 0. That would be difficult or impossible to interpret. You could change the counter mode, but you would lose the analog output.


Aha. Do you mean I would loose the PWM analog output or all analog outputs? I could live without PWM.

I read through the manual and as I understand it, I have to set the waveform generation mode bits (WGM13:0) to 0 to get into 'normal mode'. These can be found in the Timer/Counter Control registers A and B (TCCR1A and TCCR1B).

How do I write to those registers?


All of the outputs on the Arduino are PWM, that is just the way it works. You would only use the ones driven by the counter you mess with, and you could probably choose a mode where they would work, just not in "phase correct pwm" which  is the mode that causes downward counting.

Writing to a register, like TCCR1A is just like assigning a variable.


TCCR1A = 0;

will yield a 16 Bit counter TCNT1 which increases every 4 microseconds -> max. measurable time is ~260ms.

Analog out still works but is probably not phase correct anymore (can't measure that).

There also bit 0 (TOV1) in TIFR1 register which signals an overflow. Unfortunatley it looks like that is never reset. Can/must I do that myself?

Go Up