Go Down

Topic: Reading count value from Timer1 (Read 1 time) previous topic - next topic


I need to read the count value from the Timer1. How can I read out the 16bit value from Timer1? I cannot find a starting point...


See the 328p data sheet here: http://www.atmel.com/Images/doc8161.pdf, page 117, for a C code example.



If you can stop the timer, it is very simple.

If you cannot stop the timer, you have to double read it in case the timer advances in between the low/high byte reads. A double read is a fairly typical technique in this kind of solutions.

The fact that those timers don't have a shadow register / read buffer is a shame.


The fact that those timers don't have a shadow register / read buffer is a shame.

The atmega mcus used in Arduinos do have a shadow register - when the low byte is read, the high byte is latched. See the datasheet.
Formal verification of safety-critical software, software development, and electronic design and prototyping. See http://www.eschertech.com. Please do not ask for unpaid help via PM, use the forum.


I read the part of the datasheet. The complete 16-bit set can be accessed by reading " TCNT1 " according to 16.11.4 "The two Timer/Counter I/O locations (TCNT1H and TCNT1L, combined TCNT1) give direct access, both for read and for write operations, to the Timer/Counter unit 16-bit counter."

Correct result shown. Thanks for your hint to the right part of the datasheet

Code: [Select]

#include <avr/io.h>
#include <avr/interrupt.h>
#define LEDPIN 13
int timer;
long counter;

void setup()
  pinMode(LEDPIN, OUTPUT);
  cli();                    // disable global interrupts
  pinMode(2, INPUT);        // Enable Pin2 as input to interrupt
  EIMSK |= (1 << INT0);     // Enable external interrupt INT0  (see table 13-2-2 in Atmel 328 spec)
  EICRA |= (1 << ISC01);    // Trigger INT0 on rising edge (see table 13-1 in Atmel 328 spec)
  EICRA |= (1 << ISC00);    // Trigger INT0 on riding edge (see table 13-1 in Atmel 328 spec)

  // initialize Timer1
  // ZERO Timer1
  TCCR1A = 0;               // set entire TCCR1A register to 0
  TCCR1B = 0;               // same for TCCR1B

  // set compare match register to desired timer count:
  OCR1A = 7000;            // turn on CTC mode:initial value changed in loop
  OCR1B = 14000;            // turn on CTC mode:initial value changed in loop
//TCCR1B |= (1 << WGM12);   // Set CTC mode. Resets the timer after compA has been reached
  TCCR1B |= (1 << CS10);    // prescaler 1024
  TCCR1B |= (1 << CS12);    // prescaler 1024
  TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt:
  TIMSK1 |= (1 << OCIE1B);  // enable timer compare interrupt:
  sei();                    // Enable global interrupts

void loop()
    counter= TCNT1;
  digitalWrite(LEDPIN, HIGH);
  counter= TCNT1;
Serial.print ("counteran:");


  digitalWrite(LEDPIN, LOW);
  Serial.print ("counteraus:");
  counter= TCNT1;

TCNT1 = 0; // Reset Timer1 Count

Go Up