Submitted by Ed_B on Mon, 08/30/2010 - 16:12

Printer-friendly versionPrinter-friendly version

click READ MORE to see the whole post

timerInterrupt_Overflow.pde Copyright (c) 2010 Ed Bennett <ed@kineticsandelectron ics.com>

A simple demo of using the Timer2 overflow to generate interrupts in an Arduino.
Measured output is a sqaure wave of period 8.2mS. Note: A complete, technical explanation of an
AVR timer setup is in the posting on timerInterrupt_Match.pde Refer to that for more detail. Setup
for Timer0 should be nearly identical to implement.

// for an example of a timer match interrupt, see timerInterrupt_match.pde

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

The basis of this code is from the source noted below. Given it's original intention, the author would
probably not be happy with the Arduinoification of his code. But we thank him anyway. 

I significantly modifed this code to run on timer2 of a '168 chip. 

I also Arduino-ified the setup: 
It's no longer at the top of main() where it normally would be in a normal C program.
I also used the Arduino pin direction function, rather than poking the DDR.

Port writes use the Arduino digitalWrite(), rather than using the libc "port.bit" method.


/* A Brief Tutorial on Programming the AVR without Arduino

  $Id: lesson10.c,v 1.2 2009/02/08 15:55:47 ckuethe Exp $ 

 * Copyright (c) 2009 Chris Kuethe <chris.kuethe@gmail.com>
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.

#include <avr/io.h>
#include <avr/interrupt.h>

int LED0 = 13;
int outval = 0;

volatile uint8_t intrs;

void setup(){
    pinMode(LED0, OUTPUT); 
void IRQ_init(void){  
	 * set up cpu clock divider. the TIMER0 overflow ISR toggles the
	 * output port after enough interrupts have happened.
	 * 16MHz (FCPU) / 1024 (CS0 = 5) -> 15625 incr/sec
	 * 15625 / 256 (number of values in TCNT2) -> 61 overflows/sec
	TCCR2B |= _BV(CS22) | _BV(CS20);

	/* Enable Timer Overflow Interrupts */
	TIMSK2 |= _BV(TOIE2);

	/* Enable Interrupts */


  outval ^= 1;          // toggle the pin
  digitalWrite(LED0, outval);
void loop(){ }
/* The loop() is empty. You can still use it, but in this demo, all the work is done in
the Interrupt Service Routine. */