I think the problem might be that in CTC mode, interrupt is generated when OCF1A
flag is set (in TIFR
). Since your timer is always running, just not generating interrupts, it sets OCF1A
flag, which never gets cleared. On page 142 in the datasheet it says:
OCF1B is automatically cleared when the Output Compare Match B Interrupt Vector is executed. Alternatively, OCF1B can be cleared by writing a logic one to its bit location.
This means that when you set up timer 1, you also need to clear OCF1A
:
TIFR1 &= ~(1<<OCF1A)
However, I think you can do better. You could just stop the timer when not needed, and start it when you do, instead of twiddling the TIMSK
and having timer 1 run always. If you set TCCR1B
to zero, that clears CS12
, CS11
, and CS10
, which, according to the datasheet means "Timer stopped." Then, when your counter reaches 4 you can turn on timer1 as you have it above:
TCCR1B = ((1<<CS12) | (1<<CS10) | (1<<WGM12));
If you do this, you shouldn't need to turn timer 1 interrupts on and off: just leave them on, and only turn the counting on when you need it.
Also I am wondering if it is actually necessary to fire off two interrupts to toggle pins on PORTC
? Are you not using PWM for that because it doesn't give you the pulse lengths precisely enough?