Skip to main content
1 of 3
Nick Gammon
  • 38.9k
  • 13
  • 70
  • 126

I had to create an interrupt timer ...

Be warned that there are things you should not do in interrupts, like delays, serial printing, etc. In the interests of answering the question though, this works:

// ATMEL ATTINY 25/45/85 / ARDUINO
// Pin 1 is /RESET
//
//                  +-\/-+
// Ain0 (D 5) PB5  1|    |8  Vcc
// Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1 
// Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
//            GND  4|    |5  PB0 (D 0) pwm0
//                  +----+

ISR (TIMER1_COMPA_vect)
  {
  digitalWrite (4, ! digitalRead (4));  //toggle D4 (pin 3 on chip)
  }
  
void setup() 
 {
  pinMode (4, OUTPUT);  // chip pin 3 

  // Timer 1
  TCCR1 = bit (CTC1);   // Clear Timer/Counter on Compare Match
  TCCR1 |= bit (CS10) | bit (CS13);  // prescaler of 256
  OCR1C = 123;          // what to count to (zero-relative)
  TIMSK = bit (OCIE1A); // interrupt on compare
 
  }  // end of setup

void loop() 
  { 
  // other code here
  }

You can tweak the time delay by changing both the prescaler and the counter in OCR1C. The prescaler gives you coarse tuning, which gets you into the ballpark of the delay time. The timer then counts up to give you the final delay.


From the datasheet:

ATtiny85 timer 1 prescalers

In my case I chose a prescaler of 256 which is or'ing together CS10 and CS13.

The delay is then:

125 ns * 256 * 124 = 3.968 ms

Where 256 is the prescaler and 124 is what we are counting to. This is assuming an 8 MHz clock which gives a clock period of 125 ns.

Nick Gammon
  • 38.9k
  • 13
  • 70
  • 126