Skip to main content
Engineering LibreTexts

29.5: Internal Interrupts — CTC Mode

  • Page ID
    35919
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    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.


    This page titled 29.5: Internal Interrupts — CTC Mode is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by James M. Fiore via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.