Tuesday, September 2, 2014

Arduino Timer/Counter

A timer/counter is a piece of hardware built in the Arduino ATmega microcontroller. It is like a clock, and can be used to measure time events.
The timer can be programmed by some special registers. You can configure the pre-scaler for the timer, or the mode of operation and many other things.
The Arduino board is based on the Atmel AVR ATmega168 or the ATmega328 microcontroller. These chips are pin compatible and only differ in the size of internal memory. Both have 3 timers, called Timer0, Timer1 and Timer2. Timer0 and Timer2 are 8bit timer, where Timer1 is a 16bit timer.

 Timer0 is a 8bit timer.
 In the Arduino world Timer0 is been used for the timer functions, like delay(), millis() and micros().
 If you change Timer0 registers, this may influence the Arduino timer function. So you should know what 
 you are doing.
 Timer1 is a 16bit timer.
 In the Arduino world the Servo library uses Timer1 on Arduino Uno (Timer5 on Arduino Mega).
 Timer2 is a 8bit timer like Timer0.
 In the Arduino work the tone() function uses Timer2.
Arduino uno timer/counter1 registers and time frequency:
  • TCCRx - Timer/Counter Control Register. The pre-scaler can be configured here. 
  • TCNTx - Timer/Counter Register. The actual timer value is stored here. 
  • Timer/Counter Interrupt Mask Register. To enable/disable timer interrupts.