/* Timer0 - An 8 bit timer used by Arduino functions delay(), millis() and micros(). Timer1 - A 16 bit timer used by the Servo() library Timer2 - An 8 bit timer used by the Tone() library Timer_output Arduino_output Chip_pin Pin_name OC0A (Timer0) 6 12 PD6 OC0B (Timer0) 5 11 PD5 OC1A (Timer1) 9 15 PB1 OC1B (Timer1) 10 16 PB2 OC2A (Timer2) 11 17 PB3 OC2B (Timer2) 3 5 PD3 */ void interruptTimer2Setup(int timer2IntervalMsec) { TCCR2A = 0x02; // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE TCCR2B = 0x06; // DON'T FORCE COMPARE, 256 PRESCALER // SET THE TOP OF THE COUNT TO 124 (16MHz/256/500 = 125, because index start from 0, so count=124) FOR 500Hz SAMPLE PulseDurations, 500 Hz/sec => 1000 msec/500 -> 2 MSec //OCR2A = 0X7C; float scaledFrequency = 16000000 / 256.0; float wantedFrequency = 1.0 / (timer2IntervalMsec / 1000.0); //timer2IntervalMSec int tickCount = scaledFrequency / wantedFrequency; OCR2A = tickCount - 1; //#ifdef debug //Serial.print("Scaled Frequency: "); Serial.println(scaledFrequency); //Serial.print("Wanted Frequency: "); Serial.println(wantedFrequency); //Serial.print("TickCount: "); Serial.println(tickCount); //#endif TIMSK2 = 0x02; // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A sei(); // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED } // TIMER 2 INTERRUPT SERVICE ROUTINE ----------------------------------------------------------------------- ISR(TIMER2_COMPA_vect) // triggered when Timer2 counts to 124, 0~124 = 125 { #ifdef debug //Serial.print('Tick: '); Serial.println(millis()); #endif cli(); // disable interrupts OnTimer2Interrupt(); sei(); // enable interrupts when youre done! //#ifdef debug //Serial.print('Finish OnTimer2Interrupt(): '); Serial.println(millis()); //#endif }