Arduino Compare and Match Timer Interrupt

I am designing a Arduino signal generator with a DAC. On looking around I could not find a working example so I am putting my firmware here. The atmega has a 16 bit timer (timer1) with an extra register to set a count value at which the counter will reset to zero. So by adjusting the compare register an the prescaller a wide range of frequencies can be generated.

Here is the code it flashes the test led

****************************************

/*
* timer and interrupts
* Timer1 compare match interrupt example
*
*/

#define ledPin 13
// PRESCALLER SETUP for TCCR1B including reset on OCR1A match.
#define PS1 B00001001
#define PS8 B00001010
#define PS64 B00001011
#define PS256 B00001100
#define PS1024 B00001101

void setup()
{
pinMode(ledPin, OUTPUT);

// initialize Timer1
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;

TCCR1A = B00000000; // CTC MODE
TCCR1B = PS256; // prescaller see defines
TCCR1C = B00000000; //OUTPUT COMPARE and RESET COUNTER on match ;
TIMSK1 = B00100010; //
OCR1A = 3000; // DIVIDES COUNTER 1 – 6400 interupt freq = 16mhz / (OCRIA * prescaller)

interrupts(); // enable all interrupts
}

ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine
{
digitalWrite(ledPin, digitalRead(ledPin) ^ 1); // toggle LED pin
}

void loop()
{

//digitalWrite(ledPin, digitalRead(ledPin) ^ 1);
delay( 500);

}

 

*******************************

here is the download. Copy an Paste may result in funny artifacts from the html code.

timer1_test2

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *