AVR timer library

Simple AVR millisecond timer library for ATmega88/168/328.

timer-example.cpp

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

#include "timer.h"
#include "serial.h"

volatile int counter;

void timerFunc() {
	printf("timerFunc\r\n");
	if (++counter == 5) {
		// Stop timer after 5 runs.
		stopTimer();
		printf("stopping timer\r\n");
	}
}

int main() {
	serialInit();

	counter = 0;

	// Set timer to use function timerFunc
	setTimerCallback(timerFunc);
	// Start timer with an interval of 1.5 seconds
	setTimer(1000);

	// enable interrupts
	sei();

	for (;;); // loop forever
}

timer.h

#ifndef TIMER_H
#define TIMER_H

void setTimer(uint16_t milliseconds);
void startTimer();
void stopTimer();
void setTimerCallback(void (*func)());

#endif

timer.cpp

#include <avr/interrupt.h>

#include "timer.h"

void (*timerCallback)();

volatile uint16_t millis;
uint16_t targetMillis;

void setTimer(uint16_t milliseconds) {
	targetMillis = milliseconds;
	startTimer();
}

void startTimer() {
	// start timer with interrupt every millisecond.

	// Enable timer, CLKio/8, Clear Timer on Compare
	TCCR1A = 0;
	TCCR1B = (1 << WGM12) | (1 << CS11);
	uint16_t ticks = (F_CPU/8)/1000;


	// Set timer to 0 as starting value
	TCNT1 = 0;

	// Disable force output compare
	TCCR1C = 0;

	// Set timer compare to calculated value
	OCR1A = ticks;

	// Enable timer compare interrupt
	TIMSK1 = (1 << OCIE1A);
}

void stopTimer() {
	// disable timer interrupts
	TIMSK1 = 0;
}

void setTimerCallback(void (*func)()) {
	timerCallback = func;
}

ISR(TIMER1_COMPA_vect) {
	millis++;
	if (millis == targetMillis) {
		millis = 0;
		timerCallback();
	}
}