int val=0;
ISR(TIMER2_OVF_vect)
{
digitalWrite(13, val);
val=1-val;
}
void setup()
{
pinMode(13,OUTPUT);
// initialize Timer1
cli(); // disable global interrupts
TCCR2A = 0; // set entire TCCR1A register to 0
TCCR2B = 0; // same for TCCR1B
// Set CS10 and CS12 bits for 1024 prescaler:
//so we divide our clock source by 1024. This gives us a timer resolution of 1/(16*10^6 / 1024), or 6.4e-5 seconds.
TCCR2B |= (1 << CS20);
TCCR2B |= (1 << CS22);
// (target time) = (timer resolution) * (# timer counts + 1)
// set compare match register to desired timer count:
OCR2A = 31; // -> 500 times per sec
// turn on CTC mode: Clear Timer on Compare Match. Instead of counting until an overflow occurs, the timer compares its count to a value that was previously stored in a register.
TCCR2A |= (1 << WGM21);
// enable Timer2 overflow interrupt: Setting the TOIE1 bit tells the timer to trigger an interrupt when the timer overflows
//TIMSK2 = (1 << TOIE1);
// enable timer compare interrupt:
TIMSK2 |= (1 << OCIE2A);
// actual 8 bits counter
TCNT2 =0;
// enable global interrupts:
sei();
// enable Timer2 overflow interrupt: Setting the TOIE1 bit tells the timer to trigger an interrupt when the timer overflows
//TIMSK2 = (1 << TOIE1);
// enable timer compare interrupt:
TIMSK2 |= (1 << OCIE2A);
Your enabling the compare interrupt and not the overflow interrupt.
TOIE1 should also be TOIE2 in the commented out section.
I use the below and it works okay.
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
//Timer2 Settings: Timer Prescaler /8
TCCR2A = 0; // Timer2 Settings: WGM mode 0
cbi(TCCR2B,CS20); // Turn off CS20 bit
sbi(TCCR2B,CS21); // Turn on CS21 bit
cbi(TCCR2B,CS22); // Turn off CS22 bit
sbi(TIMSK2,TOIE2); // Timer2 Overflow Interrupt Enable
TCNT2 = CLK_SPEED; // Reset timer
I don't think you actually know whether the interrupt is working. Global variables used in interrupt routines must be declared "volatile". Try volatile int val=0;
There are better ways of making sure the LED flashes, including some that don't involve global variables.
For example:
PINB |= (1<<PB5);
From the ATmegaxx8 data sheet
However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register.