Skip to main content
Engineering LibreTexts

28.3: Fast PWM Mode

  • Page ID
  • This is the “fast” pulse width modulation mode that can drive an output pin directly. Fast PWM is faster than phase correct PWM because fast PWM performs a single slope (i.e., up only) count. Phase correct PWM uses an up-then-down dual slope counting technique. We will not examine phase correct PWM here.

    To use fast PWM mode to drive an output pin, first remember to set the corresponding DDR bit to output mode (see Table 28.1.1). Following this, the WGM and COM bits need to be set according to Tables 28.1.5 and 28.1.7 as well as the desired prescaler CS bits from Table 28.1.4. Finally a value for the output compare registers (OCR2A and OCR2B) needs to be set. The value of the OCR2x registers will determine the duty cycles of the resulting pulse waveform. Basically, TCNT2 will count up in the normal fashion, overflowing and recycling as usual. When the contents of TCNT2 match those of an associated output compare register, then the corresponding output pin will change to the appropriate state. The duty cycle is defined by the total count range (256) and the compare register value plus one. An example is seen below.

    /* Waveform at external pins OC2A and OC2B (PORTB.3/PORTD.3)
       Fast PWM mode, non-inverting */
    void setup()
        // enable output drivers for OC2A/B!
        DDRB |= 0x08;
        DDRD |= 0x08;
        // the following is done in two steps for clarity
        TCCR2A = (1<<WGM21) | (1<<WGM20);            // specify fast PWM
        TCCR2A|= ((1<<COM2A1) | (1<<COM2B1));        // add in non-inverting output
        TCCR2B = (1<<CS22);                          // prescale by 64x
        OCR2A = 128;    // set duty cycles (0 through 255)
        OCR2B = 100;
    void loop()
        // nothing to do here!

    An interesting new twist here is that there is nothing in the main loop() function! Once the timer/counter is set up it runs without further attention, truly “set and forget” operation. In this case, the output frequency will be the main clock of 16 MHz divided by the 64x prescaler and then divided by the total count of 256. This yields approximately 977 Hz. The duty cycle for output A is (128+1)/256 or about 50.4%. For output B the result is (100+1)/256 or approximately 39.5%.

    The preceding code was downloaded to an Arduino Uno and an oscilloscope was attached to the two output pins. The resulting waveforms are shown in Figure \(\PageIndex{1}\). Note the relative accuracy of the timing computations compared to those measured by the oscilloscope.

    It is worthwhile to note that the values of the output compare registers could be changed programmatically, for example via a potentiometer connected to an analog input pin. This would effectively recreate an alternate form of the analogWrite() function.

    Fast PWM output waveforms.
    Figure \(\PageIndex{1}\): Fast PWM output waveforms.