# Should I use Counter1 to record time series data?

My Atmega328 will record data from an external sensor at around 100Hz over several minutes. Communication is done through I2C requests to the sensor. I need to store the time of measurement (relative to the first measurement) together with the sensor data. Precision of at least 1ms is required.

My plan is:

• Start Counter1 (16 bit) at an appropriate scaling
• Whenever Counter1 wraps, increment some register
• When sensor data is requested, also store the values of Counter1 and the wrap-count register

Is this a good plan? Are there better solutions?

Sounds fine. The way this is generally done is to have the timer rollover throw and interrupt, which sets a flag. In your main loop, handle everything that needs handling, and then wait for the flag to be set. Once set, reset the flag to zero, call your read routine, increment your index, then repeat.

This assumes you have time to do everything you need to do between timer rollovers. If you don't, it's a more complicated issue.

Pseudocode below. Each compiler will have different ways to define interrupt routines.

int1 flag=0;

null timer_isr(){
flag=1;
preload_your_timer_to_correct_value; // there are more exact ways to do this
}

main {
int8 x=0;

while (1) {
while (flag==0) {} //program will hold here
flag =0 ;
x +=;

}

}

• Overflow already sets TOV1 in TIFR1; there is no need to maintain your own flag. May 5 '14 at 19:57

Timestamp is a great solution, and there do exist ADC chips with hardware timestamp feature. Unfortunately not this one.

So you're going to want to use a Timer Counter if it exists.