I would like to set up a timer in order to call a function 100800 times per second. I'm using the Arduino Mega and Timer3 with a prescaler of 2561024. To choose the prescaler factor I've considered the following steps:
- CPU freq: 16MHz
- Timer resolution: 65536 (16 bits)
- Divide CPU freq by the chosen prescaler:
16x10^6/2561024=62500=15625
- Divide the rest through the desired freq
62500/100=800=62519.
- Put the result + 1 in OCR3 register.
volatile int cont = 0;
unsigned long aCont = 0;
void setup()
{
[...]
// initialize Timer3
cli(); // disable global interrupts
TCCR3A = 0; // set entire TCCR3A register to 0
TCCR3B = 0; // same for TCCR3B
// set compare match register to desired timer count: 800 Hz
OCR3A = 625; // for 100Hz20;
// turn on CTC mode:
TCCR3B |= (1 << WGM12);
// Set CS30CS10 and CS32CS12 bits for 2561024 prescaler:
TCCR3B |= (1 << CS30) | (1 << CS32);
// enable timer compare interrupt:
TIMSK3 |= (1 << OCIE3A);
// enable global interrupts:
sei();
}
void loop()
{
// Print every second the number of ISR invoked -> should be 100
if ( millis() % 1000 == 0)
{
Serial.println();
Serial.print(" tick: ");
Serial.println(contatore);
contatore = 0;
}
}
[...]
// This is the 457-th line
ISR(TIMER3_COMPA_vect)
{
accRoutine();
contatore++;
}
void accRoutine()
{
// reads analog values
}
EDITSOLUTION
The counter it's supposed to increment its value 800 times per second but this is what I get:
Setup completed
tick: 0
tick: 0
tick: 0
tick: 1
tick: 0
tick: 0
tick: 0
tick: 0
It is aSince the main problem has been solved, I've created another question here related to variable cont?the problem of the counter incrementation.