This is an arduino mega2560
TCCR3A is set to 0 to run the timer in normal mode (page 158 of the datasheet)
TCCR3B is set to 4 to use a prescaler of 256 (page 162 of the datasheet)
initializing TNCT3 to 65504 will cause the timer to overflow exactly every 1 milliseconds.
Calculated using the formula:
INIT_VAL = TOP - (F_CPU * T ) / 2*PRESCALER
with T being the desired period in seconds
I did try without the print, even used an oscilloscope to check the period. For my purposes I want the ISR to update a PID controller, in order to achieve a constant time period and for the PID equations to make sense I have to use interrupts.
Otherwise, I dont see how Serial print will cause issue especially with an empty main loop
No, you don't. Millis() works great for timing PID loops. Most people choose the PID loop time to be about 1/10 of the system response time. Rarely is anything gained by faster loop timing.
I dont see how Serial print will cause issue especially with an empty main loop
The Serial.println() IN THE ISR is a serious mistake and will crash anything other than an AVR Arduino. Take it out and try again.
62500 timer ticks per second = 62.5 ticks per millisecond.
The code still doesnt work, I ran a test on an arduino uno (which is all I have in hand at the moment) and it's showing wrong results. Here's the test code:
uint8_t FLAG = 0;
ISR(TIMER2_OVF_vect)
{
FLAG = !FLAG;
TCNT2 = 34286;
TIFR2 |= bit(TOV2);
}
void setup() {
// put your setup code here, to run once:
TCCR2A = 0;
TCCR2B = 4;
//1 second period
TCNT2 = 34286;
TIMSK2 = bit(TOIE2);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(FLAG);
}
okay I modified TCNT2 to initialize at 225 which should result in a 1 ms period but it didn't seem to result in the intended period. Here's the serial output