
 
#include <avr/interrupt.h>
#define DI() asm volatile   ("cli")
#define EI() asm volatile   ("sei")


void myTmr(void); 
volatile unsigned int tcnt2; // counters for timer system
volatile int fakecnt, fakecnt_preset;

int tmr_indx;


/****** HW Timer ISR **********************************************************
******************************************************************************/
// from snot ISR(TIMER2_OVF_vect, ISR_NAKED) {
ISR(TIMER2_OVF_vect, ISR_BLOCK) {
// no local vars ?!?  ! I think
 
myTmr();
	TCNT2 = tcnt2;// Reload the timer

}

/******************************************************************************
******************************************************************************/
int set_tmr(int tm) {

 
	DI();
	// http://arduinomega.blogspot.dk/2011/05/timer2-and-overflow-interrupt-lets-get.html
	// Inspiration from  http://popdevelop.com/2010/04/mastering-timer-interrupts-on-the-arduino/
	//TIMSK2 &= ~(1 << TOIE2);  // Disable the timer overflow interrupt while we're configuring
	//TCCR2B &= ~(1 << WGM22);

#if defined(__AVR_ATmega32U4__)
	// 32u4 have no intern/extern clock source register
#else
	ASSR &= ~(1 << AS2); // Select clock source: internal I/O clock 32u4 does not have this facility
#endif

	if (0 < tm) {
		TIFR2 = 0x00;
		TCCR2B = 0x00; //silencio from this timer
		TCCR2A &= ~((1 << WGM21) | (1 << WGM20)); //Configure timer2 in normal mode (pure counting, no PWM etc.)
		TCCR2B |= (1 << CS22) | (1 << CS21) | (1 << CS20); // Set prescaler to CPU clock divided by 1024 See p162 i atmega328
		TIMSK2 &= ~(1 << OCIE2A); //Disable Compare Match A interrupt enable (only want overflow)
		TIMSK2 = 0x01; //HACK ?
		TCCR2A = 0x00; // normal

		/* for your and my own memory
		 *  We need to calculate a proper value to load the timer counter.
		 * The following loads the value 131 into the Timer 2 counter register
		 * The math behind this is:
		 * (CPU frequency) / (prescaler value) = 16000000/1024= 15625 Hz ~= 64us.
		 * 100Hz = 10msec
		 * 10000usec / 64us = 156.25
		 * MAX(uint8) + 1 - 156 = 100;
		 * JDN
		 * 100 Hz ~ 100
		 * tm in msec ->
		 * cnt =  tm*1000/64
		 * ex: 10 msec: 10000/64 =156
		 *
		 * some timer reg values:
		 * 1msec: 240 5msec: 178  10msec: 100   15msec: 22
		 */
		tcnt2 = 240; // 1 msec as basic heart beat

		// lets set divider for timer ISR
		if (tm <= 0)
			fakecnt = fakecnt_preset = 10; // 10 msec
		else
			fakecnt = fakecnt_preset = tm;

		TCNT2 = tcnt2;   // Finally load end enable the timer
		TIMSK2 |= (1 << TOIE2);
	}

 	EI();
 }


unsigned char j; 
void myTmr(void)
{
  PORTD=j;
  j++;

}

void setup()
{
 // Serial.begin(9600);
 int i;
 for (i=0; i < 8; i++)
   pinMode(i,OUTPUT);
   set_tmr(1);
}

/*
without volatile approx 60 usec /256 but some glitches
volatile unsigned char j 150 usec for 256 loops
with arduino loop (without goto) ~ 300usec/256
*/

int i=0;
void loop()
{
  
}
