The goal is generate exact value of pulses in high frequency using fast PWM mode in the Timer/Counter unit. I notice that there are interrupts like T/C overflow flag(TOVn) and compare flag (OCFnx) that will be set each time the timer counter reach TOP. I believe that this is similar to PWM_ISR1 in Arduino DUE. Ideally if I can know when the interrupt is set I can include a counter with it to count the number of pulses.
So my questions are:
Q1) Are there any ways to read the value of TOVn or OCFnx?
Q2) Are there any functions similar to PWM_Handler(DUE) in Arduino Uno which I can add counter in it?
I am welcome if there are any other suggestions for me to achieve my goal.
Thank you.
Here's a sample initialization of timer0 to generate a 10ms ticker using output compare interrupt
volatile uint16_t timer0_flag = 0;
// 10 ms ticker
ISR(TIMER0_COMPA_vect)
{
timer0_flag++;
}
void setup()
{
timer0_init();
}
void loop()
{
if(timer0_flag > 99)
{
timer0_flag = 0;
// do something every second
}
}
// system clock runs at 16 MHz
void timer0_init(void)
{
// CTC mode
TCCR0A = 1<<WGM01 | 0<<WGM00;
TCCR0B = 0<<WGM02;
// enable output compare interrupt
TIMSK0 = 1<<OCIE0A;
// compare match every 10 ms
OCR0A = 156;
// start timer 0 (1024 DIV), timer 0 runs at 15625 Hz (16MHz/1024)
TCCR0B = 0<<WGM02 | 1<<CS02 | 0<<CS01 | 1<<CS00;
return;
}
You can change the frequency of the interrupt by modifying the 0CR0A register (the TOP value), and the clock pre-scaler (these bits x<<CS02 | x<<CS01 | x<<CS00)
Do note that modifying timer0 will render millis() and delay() useless
I just finished go through the timers tutorial from Nick Gammon (http://www.gammon.com.au/timers), and tested out with his examples, after modify my code it is more or less the same with yours hzrnbgy, just I am using different mode and different pre-scaller.
The functions ISR(TIMERx_COMA_vect) and ISR(TIMERx_OVF_vect) are what I am looking for, going to test with different modes and interrupt later.