PIC16F877A-HITECH C- PWM

Photo of author

By Jackson Taylor

Home » Programming » PIC16F877A-HITECH C- PWM

As an Amazon Associate we earn from qualifying purchases.

Pulse width modulation (PWM) lets a microcontroller control power to a load, such as an LED, a DC motor or a buzzer, using only a digital pin. The PIC16F877A has a hardware PWM generator built into its CCP1 module, so once it is set up, the pulses are produced without using CPU time. This article shows a working HI-TECH C example and explains each register and formula, so you can change the frequency and duty cycle for your own project.

If you want a refresher on how PWM works in general, read that first. The rest of this page is specific to the PIC16F877A. It also follows on from the earlier parts of this series.

How PWM works on the PIC16F877A

The PIC16F877A has two CCP (Capture/Compare/PWM) modules. In this example we use CCP1, whose output appears on pin RC2/CCP1. Two parts of the chip work together to make the signal:

Hardware Hack

Stop Buying New Batteries for Your Tech

Electronics are expensive, but their power sources don't have to be. Discover the simple engineering trick to recondition dead batteries and bring your gadgets back to 100% capacity.

Watch the Free Video
  • Timer2 sets the PWM period. Its period register, PR2, decides when the cycle restarts.
  • The CCP1 module sets the duty cycle. The duty value is a 10-bit number: the upper 8 bits are in CCPR1L and the lower 2 bits are in CCP1X and CCP1Y (bits 5 and 4 of CCP1CON).

At the start of each period the RC2 pin goes high. When Timer2 reaches the duty value the pin goes low, and it stays low until PR2 is matched and the cycle repeats.

The example program

The code below uses a 16 MHz crystal. Timer2 runs from FOSC/4, which is 4 MHz, and both the prescaler and postscaler are set to 1 in the T2CON register. That means Timer2 counts once every 0.25 microseconds.

//External clock frequency, FOSC = 16MHz
//Clock frequency for TIMER2 = FOSC/4 = 4MHz
//(in the datasheet, the timer clock is one quarter of the oscillator frequency)
//Here the pre-scale & post-scale values = 1 (set in T2CON register)
//so one timer count = 1/4MHz = 0.25 microseconds
//PWM period = (PR2 + 1) * 0.25 microseconds (with prescale = 1)
#include<pic.h>
void main()
{
TOUTPS3=0;//Timer2 Output Postscale Select bits
TOUTPS2=0;
TOUTPS1=0;
TOUTPS0=0;
T2CKPS1=0;//Timer2 Clock Prescale Select bits
T2CKPS0=0;
TMR2ON=1; //enables timer 2
CCP1M3=1;//SETS CCP1 MODULE IN PWM MODE
CCP1M2=1;//SETS CCP1 MODULE IN PWM MODE
TRISC2=0; //setting RC2 in output mode
PR2=245; //PWM PERIOD (FREQUENCY) VALUE
CCPR1L=0X7F;//8 msb of pwm duty value (roughly 50% duty here)
CCP1X=1;//2 lsb of pwm duty value
CCP1Y=1;
while(1);
}

Remember to set the configuration bits (oscillator type, watchdog timer, and so on) to match your hardware, either in your IDE or with the __CONFIG directive. Otherwise the chip may not run at the frequency you expect.

See also
PIC16F877A-HITECH C-Digital Output & Input

What each part of the code does

Timer2 setup

  • TOUTPS3:TOUTPS0 = 0000 sets the output postscaler to 1:1. It does not affect the PWM period, but it is cleared here for a clean start.
  • T2CKPS1:T2CKPS0 = 00 sets the Timer2 prescaler to 1:1, so Timer2 counts at the full 4 MHz.
  • TMR2ON = 1 starts Timer2. PWM will not run unless the timer is on.

CCP1 setup

  • CCP1M3 = 1 and CCP1M2 = 1 put the CCP1 module into PWM mode. The lower two mode bits (CCP1M1 and CCP1M0) can stay at 0 for plain PWM.
  • TRISC2 = 0 makes RC2 an output. If you skip this, the pin stays an input and you will see no signal.

Period and duty

  • PR2 = 245 sets the period.
  • CCPR1L = 0x7F with CCP1X = 1 and CCP1Y = 1 sets the duty value.

The final while(1); loop keeps the program running. The hardware keeps producing PWM on its own while the CPU idles.

Calculating the PWM frequency

The datasheet formula for the PWM period is:

PWM period = (PR2 + 1) × 4 × TOSC × (Timer2 prescale value)

With a 16 MHz oscillator, TOSC is 62.5 ns, so 4 × TOSC is 0.25 µs. The original comment in this program said the output frequency was 0.25 µs × PR2, which leaves out the +1 and does not give a frequency. The correct calculation for PR2 = 245 and a prescale of 1 is:

  • Period = 246 × 0.25 µs = 61.5 µs
  • Frequency = 1 / 61.5 µs ≈ 16.3 kHz

To change the frequency, change PR2 or the Timer2 prescaler (1, 4 or 16). A larger PR2 or a larger prescaler gives a lower frequency.

Calculating the duty cycle

The duty cycle uses the full 10-bit value made from CCPR1L and the two extra bits:

PWM high time = (CCPR1L:CCP1X:CCP1Y) × TOSC × (Timer2 prescale value)

Sustainable Tech

Keep Toxic E-Waste Out of Landfills

Don't throw away your failing laptop, phone, or car batteries. Learn how to recondition them at home in just a few hours. It's better for the planet—and your wallet.

Learn How It Works

In this program, CCPR1L is 0x7F (127) and the two low bits are both 1, so the 10-bit value is 127 × 4 + 3 = 511. The high time is 511 × 62.5 ns ≈ 31.9 µs. Against a 61.5 µs period, that is about 52%, so the original "50%" comment is close but not exact.

See also
PIC16F877A - MIKRO C - DIGITAL OUT

For a duty cycle near any target, use this shortcut:

  1. Work out the total counts in one period: 4 × (PR2 + 1). For PR2 = 245 that is 984.
  2. Multiply by the duty you want. For 50%, that is 492.
  3. Split the result into two parts. Divide by 4 for CCPR1L (492 / 4 = 123, or 0x7B) and use the remainder for CCP1X and CCP1Y (0 here, so both are 0).

Getting the best resolution

The duty value has 10 bits, so it can range from 0 to 1023. That full range is only usable when the period has 1024 counts, which happens when PR2 = 255 with a prescaler of 1. With PR2 = 245 the duty value tops out at 984, so you get slightly less than 10 bits of resolution. This is fine for most LED and motor jobs. If you need very fine steps, pick the PR2 and prescaler combination that matches your target frequency as closely as possible.

Changing the duty cycle while running

To dim an LED or control motor speed, write new values to CCPR1L (and to CCP1X and CCP1Y if you need the extra precision) inside your main loop. The new value is latched at the end of the current period, so the output does not glitch. A common approach is to read a potentiometer with the analog-to-digital converter and copy the result into the duty registers. Details on the timer side are covered in the post about the other timers on the PIC16F877A.

Testing the output

  1. Connect the oscillator and power the chip as usual, with the supply and ground pins all connected.
  2. Probe pin RC2/CCP1 with an oscilloscope. You should see a square wave of about 16 kHz.
  3. If you have no scope, connect an LED with a resistor to RC2. At this frequency the LED will look steadily lit, and changing the duty value will change its brightness.
See also
KEYPAD INTERFACING WITH PIC16F877A SIMULATION IN PROTEUS AND MIKRO C

If you are new to the pin registers used here, the post on digital output and input explains TRIS and PORT settings in more detail.

Common mistakes

  • Forgetting to set TRISC2 to 0, so the pin never drives the output.
  • Leaving TMR2ON at 0, so the PWM never starts.
  • Using the wrong oscillator value in your calculation. Check your crystal and configuration bits.
  • Expecting the duty to be exact from CCPR1L alone. The two low bits matter when you want precise values.

FAQ

Which pin gives PWM output on the PIC16F877A?

CCP1 outputs on RC2 and CCP2 outputs on RC1. This example uses CCP1, so the signal appears on RC2.

How do I change the PWM frequency?

Change the PR2 value or the Timer2 prescaler. Use the formula (PR2 + 1) × 4 × TOSC × prescale to find the new period. Both CCP modules share Timer2, so they share the same frequency.

How do I change the duty cycle?

Write a new 10-bit value across CCPR1L (the upper 8 bits) and CCP1X and CCP1Y (the lower 2 bits). A larger value gives a longer high time.

Can I use both CCP modules for PWM at once?

Yes. They share the same period because they both use Timer2, but each module has its own duty cycle registers, so each output can have a different duty cycle.

Revive Your Dead Electronics

Got a drawer full of dead gadgets or a failing car battery? Instead of paying a premium for replacements, use this simple trick to easily recondition them right from home.

See How It Works