8-Bit Pulse Width Modulation

Pulse Width Modulation (PWM) can be useful in many ways, one being able to control the brightness of a Light Emitting Diode (LED). Varying the time between pulses at a very high rate can make the LED look dimmer or brighter without the human eye detecting the flashing. The same technique can be used for speed control of motors. PWM can be a useful technique on many designs and a PWM peripheral is built into most 8-bit MCU devices.

proj1.png

Step by Step Instructions

Using the MPLAB® Code Configurator (MCC), this project generates the code to control the brightness of an LED using a hardware PWM peripheral to generate the variable on/off time at a very high rate. This on/off frequency averages out to appear as a variable brightness on the LED.

proj5bd.jpg

The project uses:

  • PIC16F18875
  • HPC Curiosity Board
  • MPLAB X IDE
  • MPLAB Code Configurator (MCC) plug-in
  • MPLAB XC8 Compiler

To follow along with these steps, MPLAB X should be open and the HPC Curiosity Board connected to the computer through a USB cable.

1

Create a new 'standalone' project in MPLAB X for a PIC16F18875.

If this is your first time creating an MPLAB X project, please visit the "Create a Standalone Project" page to follow a step-by-step instruction on how to do this.

2

Open the MPLAB Code Configurator under the Tools > Embedded menu of MPLAB X IDE.

mcclaunch.png

3

Select the peripherals for your project. In this first project, the following peripherals need to be selected:

  • System Module
  • Interrupt Module
  • Pin Module
  • TMR2
  • PWM6

These modules will automatically be included when you launch the MCC, with the exception of TMR2 and PWM6. TMR2 and PWM6 need to be added from Device Resources. Just click on Timer and then double-click on Timer 2 to add it to the project. Click on the PWM and then double click PWM6. The result should look like the picture below:

proj5per.png

4

Timer2 needs to be set up. Click on Timer2 under Project Resources to make the Timer2 setup appear.

timer2.png

Timer2 will be driven by the instruction clock, which will be set up in a future step. These selections need to be made for the TMR2 operation.

  1. Check the Enable Timer box.
  2. Set the Prescaler box to '1:1'.
  3. Set the Postscaler box to '1:16'.
  4. Set the Timer Period to '16.384 ms'.

After set up, the window will appear as below:

timer2setup2.png

5

The next step is to setup the PWM6 module. Click on PWM6 under Project Resources.

pwm6.png

The PWM6 setup will appear in the center of the MPLAB X screen. This requires a few setup selections.

  1. Check the Enable PWM box
  2. Select Timer2 from the Select a Timer drop-down menu.
  3. Set the Duty Cycle to '50%'.

The result should look like this:

pwm6setup.png

6

Open the Pin Manager: Grid View tab and then click on the PWM6 Output pin row in the RA4 column to select the blue lock. It should turn green. This will output the PWM signal to the RA4 pin connected to the D2 LED. It should look like the picture when completed:

proj5pwm.png

7

Close the Pin Manager: Grid View. Click on the Pin Module under Project Resources.

pinmod.png

The center screen will show RA4 listed on the I/O chart. Click on the Output box to make the pin an output (if not checked) and make sure Analog and WPU are not checked (click on them to uncheck them).

proj5pin.png

8

The System needs to be setup next. Click on System Module under Project Resources.

system.png

In this section, the oscillator settings and the configuration settings are selected.

Oscillator

  1. Select the HFINTOSC from the Oscillator Select drop-down menu.
  2. Select the 4_MHz selection from the HF Internal Clock drop-down menu.
  3. Select Clock Divider value of '4'.

The window should look like the one below after the proper setup:

oscillator.png

Also, make sure the Low-voltage Programming Enable mode is selected at the bottom of the System Module screen.

lvp.png

9

Click on the Generate code button to have MCC create the software libraries for this project.

generate.png

10

The project will now have both generated header and source files. It should also have a generated main.c file.

Note: MCC may offer to generate a main.c file. Click on Yes to allow it to complete this task.

proj5files.png

Double click on the main.c file to open it up in the Editor window.

11

The PWM Duty cycle is adjusted by a value of 0 to 1023 in the PWM control routine. This is a 10-bit resolution. This example will only use half of the range of 1 to 512 to change the brightness of the LED connected to the PWM output. The main loop of code adjusts the PWM value in increments of ten and uses a for-loop delay routine to allow the PWM value to be displayed on the D2 (RA4) LED. To perform this routine, the following code needs to be entered in the main.c file under the while (1) area where the MCC generated template says // Add your application code.

while (1)
    {
        // Add your application code
        PWM6_Initialize();
        for (int duty = 1; duty < 512; duty = duty + 10)
        {
            PWM6_LoadDutyValue(duty);
            for (int delay = 1; delay < 500; delay++)
            {;}
        }
    }

The PWM6_LoadDutyValue(duty) function was generated by the MCC and its definition is located in the pwm6.h file.
The PWM6_Initialize() function is also generated to initialize the PWM peripheral. It's also located in the pwm6.h file.

This is a simple example of how the MCC generates a library of useful functions to make creating a PWM project code much easier and quicker.

12

Click on the Build Project (hammer icon) to compile the code and you should see a "BUILD SUCCESSFUL" message in the Output window of MPLAB X.

Main_Build_Project.png
BUILD SUCCESSFUL

13

Make sure your project has the Curiosity Board selected and the USB cable is connected to the board.

Click on Make and Program Device Main Project. This will build the project again and launch the programmer. In the Output window, you should see a series of messages and, if successful, it will end with a "Programming/Verify complete" message and the D2 LED connected to RA4 will slowly get brighter on the HPC Curiosity Board.

Main_Program_Target_Project.png
Connecting to Starter Kit on Board...

Currently loaded firmware on Starter Kit on Board
Firmware Suite Version.....01.54.00
Firmware type..............Enhanced Midrange

Target voltage detected
Target device PIC16F18875 found.
Device Revision ID = 2002

Device Erased...

Programming...

The following memory area(s) will be programmed:
program memory: start address = 0x0, end address = 0x7ff
configuration memory
**Programming/Verify complete**
proj5.png

If it's the first time the programmer is connected to the board, the programming tool may need to download the proper operating firmware for the exact device. You may see a series of processes if this occurs. This should only happen once:

Downloading Firmware…
Downloading bootloader
Bootloader download complete
Programming download…
Downloading RS…
RS download complete
Programming download…
Downloading AP…
AP download complete
Programming download…
Firmware Suite Version…..01.34.11
Firmware type…………..Enhanced Midrange

Download

If you have any problems with your project, the completed MPLAB X project file can be downloaded from the link below:

File Download
Installation
Instructions
Windows Linux Mac OSX
Project 5 Files
© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.