My basic timer need is this: wait "x" microseconds then turn on pin A5 for about 50 µsec then turn it off. The timer gets restarted periodically in another ISR which gets triggered on the falling edge of pins A1 and A2. The value of "x" ranges from 2000 to 6000 µsec and changes occasionally depending on other stuff going on. I don't need much precision, ±50 µsec is plenty. With the main clock speed of 48 MHz even a 1024 prescaler would overflow an 8-bit counter in 5300 µsec, so it looks like I need to use a 16-bit counter.
I need some help in selecting which of the many TC/TCC to use for this timer, and which of the many registers need to be configured to trigger an ISR on a matching value condition. And is there a timer feature I can use to turn off that same pin about 50 µsec later? This isn't necessary because I can also use another A1/A2 pin event ISR to turn it off.
Any help would be appreciated.
This is the basic code I wrote for the 32u4 processor:
- Code: Select all | TOGGLE FULL SIZE
ISR( TIMER3_COMPA_vect ) { // interrupt service routine (ISR) is called when timer3 TCNT3 = OCR3A
// if this is a powered cycle then turn on the opto output driver to turn on the triac
if (onCycle) {
digitalWrite( triacPin, HIGH );
triacOn = true;
}
TIMSK3 &= ~(1 << OCIE3A); // clear the compare interrupt bit to disable timer3 compare interrupt.
}
void initTimer3() { // initialize timer3 (16-bit counter) with a prescaler of 8 (1 count equals 1 µsec).
// NOTE: this routine does not enable the timer - this is done in "setISRtrigger()"
cli(); // disable all interrupts
TCCR3A = 0; // Clear timer3 register A
TCCR3B = 0; // Clear timer3 register B
TCCR3B |= (1 << CS31); // 8 prescaler (8 clock ticks = 1 count). So 8 ticks of an 8 MHz clock is 1 µsec in time.
TCNT3 = 0; // Initialize counter register to 0
sei(); // enable interupts
}
void setISRtrigger( int delayCount ) { // Enables timer3 to trigger the ISR when TCNT3 counts up to match the value in OCR3A
TCNT3 = 0; // Reset counter to 0
OCR3A = delayCount; // Count up to value
TIMSK3 |= (1 << OCIE3A); // Enable timer3 compare interrupt bit (interrupt is triggered when TCNT3=OCR3A)
}