Electronic – arduino – 16-bit timer of ATMega: How to calculate timer count


I try to use the 16-bit timer of ATMega on each midi clock tick. A beat has 24 midi clock ticks. So e.g. 60 beats per minute = 1 beat per second = 24 ticks per second.

How can I set the timer for x times a second (depending on the bpm value)?

I'm initializing the timer on my arduino with:

void setup()
cli();          // disable global interrupts
TCCR1A = 0;     // set entire TCCR1A register to 0
TCCR1B = 0;     // same for TCCR1B

// set compare match register to desired timer count:
OCR1A = 6510;

// turn on CTC mode:
TCCR1B |= (1 << WGM12);

// Set CS10 and CS12 bits for 1024 prescaler:
TCCR1B |= (1 << CS10);
TCCR1B |= (1 << CS12);

// enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);

// enable global interrupts:

I don't get the calculation of OCR1A. It should be depending on a bpm value.

Best Answer

The frequency of your timer interrupt will be equal to the following:

$$ \frac{\mbox{microcontroller clock frequency} }{(\mbox{prescaler}) \times (\mbox{compare match register value} + 1)} $$

So, since you mentioned that you're using an Arduino which comes with a 16 MHz crystal, to achieve an interrupt frequency of 24 Hz the value of the compare match register (OCR1A) should be 650, given a prescaler of 1024.

If you want to change the BPM, you'll have to set OCR1A on the fly.