Skip to main content
Engineering LibreTexts

29.5: Internal Interrupts — CTC Mode

  • Page ID
    35919
  • This example also involves toggling an arbitrary output pin although the OCnx pin could be piggybacked if desired. Instead of PWM, this example varies the frequency of a square wave using Clear Timer on Compare (CTC) mode. This mode simply counts up to the value stored in the output compare match register (OCR2A) and then resets back to zero.

    /* Timer/Counter Interrupt Example
       Uses CTC mode (Clear Timer on Compare)
    */
    
    #define ARBPINMASK 0x01
    #define COMPARE_MATCH 128
    
    void setup()
    {
        DDRB |= ARBPINMASK;
    
        // enable output driver for OC2A for piggyback!
        DDRB |= 0x08;
    
        TCCR2A = (1<<COM2A0); // non PWM, OC2A pin toggle on compare match
        TCCR2A |= (1<<WGM21); // add CTC mode, Top=OCR2A
    
        TCCR2B = 0x07;        // 1024x prescale
    
        OCR2A = COMPARE_MATCH;
    
        TIMSK2 = (1<<OCIE2A); // enable compare match interrupt
    }
    
    ISR(TIMER2_COMPA_vect)
    {
        PORTB ^= ARBPINMASK;
    }
    
    void loop()
    {
    }
    

    Note that a new bit must be set in the timer/counter interrupt mask register, namely OCIE2A (Output Compare Interrupt Enable for unit 2A). The Output Compare Register (OCR2A) is set with a fixed value but again, this could be set by a variable. A COMPARE_MATCH value of 128 yields a square wave frequency of slightly more than 60 Hz. Halving the value to 64 will roughly double the frequency to about 120 Hz.