I would like to improve a timer I wrote for a Playground article. It's purpose is to trigger an ISR to alternately shutdown MAX7221 chips.
The requirements for this timer are that it must be settable around a mid-range of about 700Hz, and that the ISR can be disabled and re-enabled efficiently.
The timer I currently have, uses TCNT2 in the ISR to reset the counter to a higher starting value.
After reading this post - http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1215675974/0 - it seems that using "TOP" is a better way to go.
So I wrote the code below. But as I don't require PWM, it seems that there is room for improvement with it too.
I have tried using Mode 2 (CTC) rather than the Fast PWM mode, but when I do, the "TOP" no longer works.
The code I'm trying is as follows:
#define ISR_FREQ 174 // Sets the speed of the ISR - LOWER IS FASTER
// prescaler is /128 - 125,000/ISR_FREQ +1 (i.e 249=500Hz, 175=710Hz)
void setup() {
// stuff
setISRtimer(); // set-up the timer
startISR();
}
void loop() {
//stuff
stopISR();
//stuff
startISR();
}
ISR(TIMER2_OVF_vect) {
//stuff to shutdown chips
}
void setISRtimer(){
TCCR2A = 0x23; // set mode = FAST PWM (can use TOP)
TCCR2B = 0x0D; // set prescaler to /128 (125kHz)
// -- 0x0F=/1024 (15,625Hz), 0xE=/256 (62,500Hz), 0xD=/128 (125kHz), 0x0C=/64 (250kHz) --
OCR2A = ISR_FREQ; // set TOP (divisor) - see #define
}
void startISR(){ // called a lot!
TIMSK2 |= (1<<TOIE2); // set interrupts=enabled
}
void stopISR(){ // called a lot!
TIMSK2 &= (0<<TOIE2); // set interrupts=disabled
}
Help is appreciated. ![]()