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

volatile unsigned long _millis; // for millis tick !! Overflow every ~49.7 days

// Timer0
// 1ms IRQ
// Used for millis() timing
void timer0_init()
{
    TCCR0A = (1<<WGM01); //TIMER0 SET-UP: CTC MODE
    TCCR0B = (1<<CS01)|(1<<CS00); // PS 1:64
    OCR0A = 249; // 1ms reach for clear (16mz:64=>250kHz:250-=>1kHz)
    TIMSK0 |= 1<<OCIE0A;	 //IRQ on TIMER0 output compareA
}

ISR (TIMER0_COMPA_vect)
{
	_millis++; // INC millis tick
}

unsigned long millis(void)
{
	unsigned long i;
	cli();
	// Atomic tick reading
	i = _millis;
	sei();
	return i;
}
