avr-c timers

avr-c timers
  1. Arduino UNO
#include <avr/io.h> #include <avr/interrupt.h> int extraTimeTCCR0A = 0; int extraTimeTCCR2A = 0; int main(void) { /** * TIMER 0 SETUP */ DDRD |= (1<<PCINT18); // PD2 = 2 = PORTD2 => OUTPUT ARDUINO PIN 2 TCCR0A = (1<<WGM01); // CTC OCRA Immediate MAX TCCR0A |= (1<<COM0A1); // Clear OC0A on Compare Match OCR0A = (0.01 * F_CPU)/1024; // Output Compare 0 A => calculate for 10 millisecond TIMSK0 = (1<<OCIE0A); // Bit 1 – OCIEA: Timer/Counter0, Output Compare A Match Interrupt Enable TCCR0B = (1<<CS00)|(1<<CS02); // clkI/O/1024 (From prescaler) /** * TIMER 1 SETUP */ DDRD |= (1<<PCINT19); // PD3 = 3 = PORTD3 = OUTPUT ARDUINO PIN 3 TCCR1B = (1<<WGM12); // CTC OCR1A Immediate MAX OCR1A = (0.5 * F_CPU)/1024; // set 500 ms max value TIMSK1 = (1<<OCIE1A); // Bit 1 – OCIEA: Output Compare A Match Interrupt Enable TCCR1B |= (1<<CS10)|(1<<CS12); // clkI/O/1024 (From prescaler) /** * TIMER 2 SETUP */ DDRD |= (1<<PCINT20); // PD4 = 4 = PORTD4 = OUTPUT ARDUINO PIN 4 TCCR2A = (1<<WGM21); // CTC OCRA Immediate MAX TCCR2A |= (1<<COM2A1); // Clear OC2A on Compare Match. OCR2A = (0.01*F_CPU)/1024; // Output Compare 0 A => calculate for 10 millisecond TIMSK2 = (1<<OCIE2A); // Bit 1 – OCIEA: Timer/Counter2, Output Compare A Match Interrupt Enable TCCR2B = (1<<CS20)|(1<<CS21)|(1<<CS22); sei(); // Set Global Interrupt Flag while (1) { } } /** * TIMER 0 Interrupt Function */ ISR(TIMER0_COMPA_vect) { extraTimeTCCR0A++; if (extraTimeTCCR0A > 50) { // every 500 millisecond turn on/off PD2 port. PORTD ^= (1<<PCINT18); extraTimeTCCR0A = 0; } } /** * TIMER 1 Interrupt Function */ ISR(TIMER1_COMPA_vect) { PORTD ^= (1<<PCINT19); // turn on/off PD3 port. } /** * TIMER 2 Interrupt Function */ ISR(TIMER2_COMPA_vect) { extraTimeTCCR2A++; if (extraTimeTCCR2A > 50) { // every 500 millisecond turn on/off PD4 port. PORTD ^= (1<<PCINT20); extraTimeTCCR2A = 0; } }