// Mega 644 version //Run all three timers in different modes // timer 0 -- compare-match timebase // timer 1 -- input capture from analog comparator // timer 2 -- stand alone square wave gen // main will schedule task1, and poll the ACSR ACO bit // task 1 will print the periods // timer0 compare ISR will increment a timer // timer1 capture ISR will compute a period from the capture // MUST connect port B.3 (AIN1) to port D.7 (OC2) // Capture yields cycle-accurate period measurement // Polling the ACO bit yields 20 cycle variability #include #include #include #include //set up the debugging utility ASSERT //#define __ASSERT_USE_STDERR //#include #include "uart.h" // UART file descriptor // putchar and getchar are in uart.c FILE uart_str = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW); //time for task #define t1 250 #define begin { #define end } //the task subroutine void task1(void); //execute at 2 Hz void initialize(void); //all the usual mcu stuff //timeout counter for task1 volatile unsigned char time1; // timer 1 capture variables for computing sq wave period volatile unsigned int T1capture, lastT1capture, period ; // polling variables for computing sq wave period (low accuracy) unsigned int periodPoll, T1poll, lastT1poll ; //comparator output bit char ACObit, lastACObit ; //********************************************************** //timer 0 overflow ISR ISR (TIMER0_COMPA_vect) begin //Decrement the time if not already zero if (time1>0) --time1; end //********************************************************** // timer 1 capture ISR ISR (TIMER1_CAPT_vect) begin // read timer1 input capture register T1capture = ICR1 ; // compute time between captures period = T1capture - lastT1capture; lastT1capture = T1capture ; end //********************************************************** //Entry point and task scheduler loop int main(void) begin initialize(); // main task scheduler loop while(1) begin // task1 prints the period if (time1==0){time1=t1; task1();} // poll for ACO 0->1 transition (ACSR.5) // as fast as possible and record Timer1 ACObit = ACSR & (1<