Converting timer 1 interrupt program into timer 2 interrupt?

I've found this piece of code on-line that generates a timer interrupt and it works pretty well.

Link here http://www.hobbytronics.co.uk/arduino-timer-interrupts

#define ledPin 13
int timer1_counter;
void setup()
{
  pinMode(ledPin, OUTPUT);

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

  // Set timer1_counter to the correct value for our interrupt interval
  //timer1_counter = 64886;   // preload timer 65536-16MHz/256/100Hz
  //timer1_counter = 64286;   // preload timer 65536-16MHz/256/50Hz
  timer1_counter = 34286;   // preload timer 65536-16MHz/256/2Hz
  
  TCNT1 = timer1_counter;   // preload timer
  TCCR1B |= (1 << CS12);    // 256 prescaler 
  TIMSK1 |= (1 << TOIE1);   // enable timer overflow interrupt
  interrupts();             // enable all interrupts
}

ISR(TIMER1_OVF_vect)        // interrupt service routine 
{
  TCNT1 = timer1_counter;   // preload timer
  digitalWrite(ledPin, digitalRead(ledPin) ^ 1);
}

void loop()
{
  // your program here...
}

The issue I have is that what I want to use it for involves using servos which use the same timer as this code (timer 1).
So I want to make this code work off of timer 2 instead, however I'm not sure what I have to change to do that; I've tried changing all the 1's in the AVR declarations into 2's in various ways but haven't had any luck.

Can anyone tell me what I'm doing wrong or suggest the right datasheet to help fix this?

Timer2 is 8 bits, whereas Timer1 is 16 bits, so that code won't work. You may be able to do what you want with Timer2, but you will need to study the Timer2 section of the ATmega328 data sheet carefully.

Using a 16 bit timer to blink an LED at 2 Hz is a waste. Just use blink-without-delay.

Its only a waste if you need it for other more urgent purposes :slight_smile: The timer's sat there clocking
away whether or not you use analogWrite () too...

Its only a waste if you need it for other more urgent purposes

Like running a servo, as OP stated he/she needs to do? I agree with Coding Badly that working with the timer is a much better approach than expecting the timer to do all the work.

I did defeat it in the end, I could only use timer2 as im using an uno and timer1 was busy handling the servos; timer 2 is pretty hopeless on its own, the maximum size prescaler is a 256 bit one and the timer itself can only be preloaded with a maximum count of 256 meaning it cant do very long times between interrupts and not enough for what I wanted anyway.

So to cheat around this whenever the interrupt routine is called the routine has its own separate prescaler inside the routine to make up the difference; a bit crude but it seems to work.