Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

MCC project creations PIC

kittu20

New Member
Hello Everyone

I'm trying to control the brightness of an LED connected to pin RB1 using PWM PIC18F45K80. I have already read through the datasheet, but I'm facing some difficulties in configuring the PWM module correctly. I followed this link https://circuitdigest.com/microcontroller-projects/pic-microcontroller-pic16f877a-pwm-tutorial for guidance, but I'm still encountering issues.

I am looking for help in configuring the PWM module and writing code to gradually change the LED's brightness. Specifically, I need guidance on setting up the PWM period, duty cycle, and initializing the necessary registers.

Here's what I've done so far:

C:
#define _XTAL_FREQ 8000000
 
 
// PIC18F45K80 Configuration Bit Settings
// 'C' source line config statements
// CONFIG1L
#pragma config RETEN = OFF      // VREG Sleep Enable bit (Ultra low-power regulator is Disabled (Controlled by REGSLP bit))
#pragma config INTOSCSEL = HIGH // LF-INTOSC Low-power Enable bit (LF-INTOSC in High-power mode during Sleep)
#pragma config SOSCSEL = HIGH   // SOSC Power Selection and mode Configuration bits (High Power SOSC circuit selected)
#pragma config XINST = OFF       // Extended Instruction Set (Enabled)
// CONFIG1H
#pragma config FOSC = INTIO2    // Oscillator (Internal RC oscillator)
#pragma config PLLCFG = OFF     // PLL x4 Enable bit (Disabled)
#pragma config FCMEN = OFF      // Fail-Safe Clock Monitor (Disabled)
#pragma config IESO = OFF       // Internal External Oscillator Switch Over Mode (Disabled)
// CONFIG2L
#pragma config PWRTEN = OFF     // Power Up Timer (Disabled)
#pragma config BOREN = SBORDIS  // Brown Out Detect (Enabled in hardware, SBOREN disabled)
#pragma config BORV = 3         // Brown-out Reset Voltage bits (1.8V)
#pragma config BORPWR = ZPBORMV // BORMV Power level (ZPBORMV instead of BORMV is selected)
// CONFIG2H
#pragma config WDTEN = OFF      // Watchdog Timer (WDT disabled in hardware; SWDTEN bit disabled)
#pragma config WDTPS = 1048576  // Watchdog Postscaler (1:1048576)
// CONFIG3H
#pragma config CANMX = PORTB    // ECAN Mux bit (ECAN TX and RX pins are located on RB2 and RB3, respectively)
#pragma config MSSPMSK = MSK7   // MSSP address masking (7 Bit address masking mode)
#pragma config MCLRE = ON       // Master Clear Enable (MCLR Enabled, RE3 Disabled)
// CONFIG4L
#pragma config STVREN = ON      // Stack Overflow Reset (Enabled)
#pragma config BBSIZ = BB2K     // Boot Block Size (2K word Boot Block size)
// CONFIG5L
#pragma config CP0 = OFF        // Code Protect 00800-01FFF (Disabled)
#pragma config CP1 = OFF        // Code Protect 02000-03FFF (Disabled)
#pragma config CP2 = OFF        // Code Protect 04000-05FFF (Disabled)
#pragma config CP3 = OFF        // Code Protect 06000-07FFF (Disabled)
// CONFIG5H
#pragma config CPB = OFF        // Code Protect Boot (Disabled)
#pragma config CPD = OFF        // Data EE Read Protect (Disabled)
// CONFIG6L
#pragma config WRT0 = OFF       // Table Write Protect 00800-01FFF (Disabled)
#pragma config WRT1 = OFF       // Table Write Protect 02000-03FFF (Disabled)
#pragma config WRT2 = OFF       // Table Write Protect 04000-05FFF (Disabled)
#pragma config WRT3 = OFF       // Table Write Protect 06000-07FFF (Disabled)
// CONFIG6H
#pragma config WRTC = OFF       // Config. Write Protect (Disabled)
#pragma config WRTB = OFF       // Table Write Protect Boot (Disabled)
#pragma config WRTD = OFF       // Data EE Write Protect (Disabled)
// CONFIG7L
#pragma config EBTR0 = OFF      // Table Read Protect 00800-01FFF (Disabled)
#pragma config EBTR1 = OFF      // Table Read Protect 02000-03FFF (Disabled)
#pragma config EBTR2 = OFF      // Table Read Protect 04000-05FFF (Disabled)
#pragma config EBTR3 = OFF      // Table Read Protect 06000-07FFF (Disabled)
// CONFIG7H
#pragma config EBTRB = OFF      // Table Read Protect Boot (Disabled)
 
 
#include <xc.h>

// Function to initialize PWM
void PWM_Initialize() {
    // Set CCP4 pin (RB0) as an output
    TRISB0 = 0;

    CCP4CONbits.CCP4M = 0b1100;  // Set CCP4 for PWM mode
 
 
    // Set the PWM frequency for approximately 1 kHz with a prescaler of 16
    PR2 = 124;  // For an 8 MHz oscillator, prescaler 16, and 1 kHz PWM frequency


    // Set the initial duty cycle (50%)
    CCPR4L =
  
    DC4B1 = 0;
    DC4B0 = 0;

    // Enable Timer2 and its prescaler (1:4)
    TMR2ON = 1;
    T2CKPS1 = 1;
    T2CKPS0 = 0;
}

void main(void) {
    // Initialize the PWM module
    PWM_Initialize();
    TRISB = 0b00000010; // LED connected to RB1

    while (1) {
    
    }
}

1695188214139.png



1695188238613.png


If anyone could provide step-by-step instructions, it would be greatly appreciated.

Thank you in advance for your help!
 
Use the MCC to set it up - then cut and paste the bits of code you want :D

It takes all the guess work out (and particularly with clock settings).

Here's the code I'm using, on an 18F27K42, originally generated by the MCC.

C:
void PWM5_Initialize(void)
{
    // Set the PWM to the options selected in the PIC10 / PIC12 / PIC16 / PIC18 MCUs.
    // PWM5POL active_hi; PWM5EN enabled;
    PWM5CON = 0x80;   

    // DCH 0; - initialise at zero
    PWM5DCH = 0x00; //0x00;   

    // DCL 0;
    PWM5DCL = 0x00; //0x00;   

    // Select timer
    CCPTMRS1bits.P5TSEL = 2;                                                    // PW5 using TMR4
}
 
void PWM5_LoadDutyValue(unsigned int dutyValue)
{
    // Writing to 8 MSBs of PWM duty cycle in PWMDCH register
    PWM5DCH = (dutyValue & 0x03FC)>>2;
    
    // Writing to 2 LSBs of PWM duty cycle in PWMDCL register
    PWM5DCL = (dutyValue & 0x0003)<<6;
}

// timer for PWM5
void TMR4_Initialize(void)
{
    // Set TMR4 to the options selected in the User Interface

    // T4CS FOSC/4;
    T4CLKCON = 0x01;

    // TPSYNC Not Synchronized; T4MODE Software control; T4CKPOL Rising Edge; T4CKSYNC Not Synchronized;
    T4HLT = 0x00;

    // T4RSEL T4CKIPPS pin;
    T4RST = 0x00;

    // PR2 63;
    T4PR = 0x3F;

    // TMR2 0;
    T4TMR = 0x00;

    // Clearing IF flag.
    PIR7bits.TMR4IF = 0;

    // T4CKPS 1:1; T4OUTPS 1:1; TMR4ON on;
    T4CON = 0x80;
    
    #ifdef Step_TX
        // set for 32MHz clock
        T4CONbits.CKPS=0;       // 122KHz PWM at 8 bits resolution 32MHz clock
    #elif defined Step_RX
        // set for 64MHz clock
        T4CONbits.CKPS=1;       // 122KHz PWM at 8 bits resolution 64MHz clock
    #endif
    //T4CONbits.CKPS=0;       // 122KHz PWM at 8 bits resolution 32MHz clock
    //T4CONbits.CKPS=1;       // 61KHz PWM (or 122KHz with 64MHz clock)
    //T4CONbits.CKPS=2;       // 15.5KHz PWM
} 

void TMR4_Start(void)
{
    // Start the Timer by writing to TMRxON bit
    T4CONbits.TMR4ON = 1;
}

void TMR4_Stop(void)
{
    // Stop the Timer by writing to TMRxON bit
    T4CONbits.TMR4ON = 0;
}
 
Last edited:
Looking to the datasheet, You may be better off using standard PWM. Portb favours the enhanced PWM for half / full motor control. You can use enhanced, but get to grips with standard PWM first.

In the datasheet there are two sections, there is an example the puts a PWM on RC2. Section 19.4
The enhanced is at 20.4 You will see the difference in complexity straight away.
 
This puts a pwm out on RB5 CCCP5
The CCP5RL = 64 as the PR2 reg = 124 ergo 50%

C:
#define _XTAL_FREQ 8000000
 
 
// PIC18F45K80 Configuration Bit Settings
// 'C' source line config statements
// CONFIG1L
#pragma config RETEN = OFF      // VREG Sleep Enable bit (Ultra low-power regulator is Disabled (Controlled by REGSLP bit))
#pragma config INTOSCSEL = HIGH // LF-INTOSC Low-power Enable bit (LF-INTOSC in High-power mode during Sleep)
#pragma config SOSCSEL = HIGH   // SOSC Power Selection and mode Configuration bits (High Power SOSC circuit selected)
#pragma config XINST = OFF       // Extended Instruction Set (Enabled)
// CONFIG1H
#pragma config FOSC = INTIO2    // Oscillator (Internal RC oscillator)
#pragma config PLLCFG = OFF     // PLL x4 Enable bit (Disabled)
#pragma config FCMEN = OFF      // Fail-Safe Clock Monitor (Disabled)
#pragma config IESO = OFF       // Internal External Oscillator Switch Over Mode (Disabled)
// CONFIG2L
#pragma config PWRTEN = OFF     // Power Up Timer (Disabled)
#pragma config BOREN = SBORDIS  // Brown Out Detect (Enabled in hardware, SBOREN disabled)
#pragma config BORV = 3         // Brown-out Reset Voltage bits (1.8V)
#pragma config BORPWR = ZPBORMV // BORMV Power level (ZPBORMV instead of BORMV is selected)
// CONFIG2H
#pragma config WDTEN = OFF      // Watchdog Timer (WDT disabled in hardware; SWDTEN bit disabled)
#pragma config WDTPS = 1048576  // Watchdog Postscaler (1:1048576)
// CONFIG3H
#pragma config CANMX = PORTB    // ECAN Mux bit (ECAN TX and RX pins are located on RB2 and RB3, respectively)
#pragma config MSSPMSK = MSK7   // MSSP address masking (7 Bit address masking mode)
#pragma config MCLRE = ON       // Master Clear Enable (MCLR Enabled, RE3 Disabled)
// CONFIG4L
#pragma config STVREN = ON      // Stack Overflow Reset (Enabled)
#pragma config BBSIZ = BB2K     // Boot Block Size (2K word Boot Block size)
// CONFIG5L
#pragma config CP0 = OFF        // Code Protect 00800-01FFF (Disabled)
#pragma config CP1 = OFF        // Code Protect 02000-03FFF (Disabled)
#pragma config CP2 = OFF        // Code Protect 04000-05FFF (Disabled)
#pragma config CP3 = OFF        // Code Protect 06000-07FFF (Disabled)
// CONFIG5H
#pragma config CPB = OFF        // Code Protect Boot (Disabled)
#pragma config CPD = OFF        // Data EE Read Protect (Disabled)
// CONFIG6L
#pragma config WRT0 = OFF       // Table Write Protect 00800-01FFF (Disabled)
#pragma config WRT1 = OFF       // Table Write Protect 02000-03FFF (Disabled)
#pragma config WRT2 = OFF       // Table Write Protect 04000-05FFF (Disabled)
#pragma config WRT3 = OFF       // Table Write Protect 06000-07FFF (Disabled)
// CONFIG6H
#pragma config WRTC = OFF       // Config. Write Protect (Disabled)
#pragma config WRTB = OFF       // Table Write Protect Boot (Disabled)
#pragma config WRTD = OFF       // Data EE Write Protect (Disabled)
// CONFIG7L
#pragma config EBTR0 = OFF      // Table Read Protect 00800-01FFF (Disabled)
#pragma config EBTR1 = OFF      // Table Read Protect 02000-03FFF (Disabled)
#pragma config EBTR2 = OFF      // Table Read Protect 04000-05FFF (Disabled)
#pragma config EBTR3 = OFF      // Table Read Protect 06000-07FFF (Disabled)
// CONFIG7H
#pragma config EBTRB = OFF      // Table Read Protect Boot (Disabled)
 
 
#include <xc.h>

// Function to initialize PWM
void PWM_Initialize() {
    // Set CCP4 pin (RB0) as an output
    TRISB5 = 0;

    CCP5CONbits.CCP5M = 0b1100;  // Set CCP4 for PWM mode
 
 
    // Set the PWM frequency for approximately 1 kHz with a prescaler of 16
    PR2 = 124;  // For an 8 MHz oscillator, prescaler 16, and 1 kHz PWM frequency


    // Set the initial duty cycle (50%)
    CCPR5L =  64;
 
    DC5B1 = 0;
    DC5B0 = 0;

    // Enable Timer2 and its prescaler (1:4)
    TMR2ON = 1;
    T2CKPS1 = 1;
    T2CKPS0 = 0;
}

void main(void) {
    // Initialize the PWM module
    PWM_Initialize();
    // you not me TRISB = 0b00000010; // LED connected to RB5

    while (1) {
  
    }
}
 
Last edited:
Use the MCC to set it up - then cut and paste the bits of code you want
It appears that you have a good understanding of the MCC (MPLAB Code Configurator) tool, I've been trying to use the MCC (MPLAB Code Configurator) tool to create a project. However, I can't seem to find the MCC Configurator tool when I click on "Tools" and then "Embedded." I installed MPLAB IDE V.40 with the XC8 compiler, and I've also searched in the available plugin list, but it doesn't appear there either. I initially thought it might not be downloaded, so I downloaded it from a link https://gallery.microchip.com/packages/MCC-Standalone-(Windows)/5.1.6 , but when I installed the exe file and opened it, it didn't seem to be what I was looking for.

1695199087295.png
 
This puts a pwm out on RB5 CCCP5
The CCP5RL = 64 as the PR2 reg = 124 ergo 50%
I ran your code example for controlling an LED connected to RB1, the LED is turned on at the start, but it automatically stops. I have a question regarding a discrepancy I noticed between the code and comments. I observed that you are setting two pins in two different functions: RB1 in the main function and RB5 in the PWM function.

I would greatly appreciate it if you could clarify this for me. Specifically, I'm curious about the intention behind setting RB5 in the PWM function and how it relates to the overall LED control. Did you intend to control the LED using both RB1 and RB5, or is there a specific reason for this configuration?

Understanding the rationale behind this setup will help me better comprehend your code and its intended functionality.
 
It appears that you have a good understanding of the MCC (MPLAB Code Configurator) tool, I've been trying to use the MCC (MPLAB Code Configurator) tool to create a project. However, I can't seem to find the MCC Configurator tool when I click on "Tools" and then "Embedded."
That's why :D

You need to go to Tools/Plugins/Available Plugins.
 
I ran your code example for controlling an LED connected to RB1, the LED is turned on at the start, but it automatically stops. I have a question regarding a discrepancy I noticed between the code and comments. I observed that you are setting two pins in two different functions: RB1 in the main function and RB5 in the PWM function.

I would greatly appreciate it if you could clarify this for me. Specifically, I'm curious about the intention behind setting RB5 in the PWM function and how it relates to the overall LED control. Did you intend to control the LED using both RB1 and RB5, or is there a specific reason for this configuration?

Understanding the rationale behind this setup will help me better comprehend your code and its intended functionality.
RB5... If you look at the pins for standard PWM they are labeled CCP1 ~ CCP5
The RB1 was in your code.. I set RB5 in the init routine. Connect the led to RB5. ( PWM output )
 
RB5... If you look at the pins for standard PWM they are labeled CCP1 ~ CCP5
The RB1 was in your code.. I set RB5 in the init routine. Connect the led to RB5. ( PWM output )
I followed the instructions and connected LED to RB5 pin , but the LED seems to stay on continuously at a high. I'm not observing any changes in brightness as expected.
 
As I mentioned before, I don't see option of mcc. I've attached a screenshot below that doesn't shows the MCC options

Try under 'Installed', see if it's there - it's called 'MPLAB® Code Configurator' in the list, not actually MCC. Asuming it is there?, make sure it's 'Activated', if not click in the tick box and select 'Activate'.
 
Try under 'Installed', see if it's there - it's called 'MPLAB® Code Configurator' in the list, not actually MCC. Asuming it is there?, make sure it's 'Activated', if not click in the tick box and select 'Activate'.
I don't find 'MPLAB® Code Configurator' (MCC) under the 'Installed' section. It's not present in the list
 
I followed the instructions and connected LED to RB5 pin , but the LED seems to stay on continuously at a high. I'm not observing any changes in brightness as expected.
No because it is stuck at 50% from the init routine.

If the while() forever loop use a delay and swing CCPR5L from 20 -> 122 and back again.

for( x = 22; x<122: x++)
{
CCPR5L = x;
delay 200ms to see..
}

for( x = 122; x> 22: x--)
{
CCPR5L = x;
delay 200ms to see..
}
 
Nigel Goodwin

After upgrading to MPLAB V6.00 and discovering the MCC features, I'm excited to create my first MCC project. However, I'm a bit puzzled about configuring the oscillator settings to ensure my PIC runs at the correct speed.

Here are the details of my setup:

  • MPLAB Version: V6.00
  • Target Device: [pic18f45k80]
  • Crystal Frequency: 20 MHz
  • Capacitors: Two ceramic capacitors with a value of 30pF each
I want to create a simple MCC project where an LED toggles every 1 second. However, I'm not sure which oscillator option to select in my case an external oscillator

1696000261648.png
 
I suggest you probably want the one off the bottom of the list :D

XT Oscillator is for an external crystal, BUT for a 20MHz crystal you should select HS Oscillator (for High Speed).

Initially creating a program to flash an LED every second is an excellent way to ensure you're actually running at the correct speed, using the __delay_ms(500); function (half second ON, half second OFF).

And don't forget:

#define _XTAL_FREQ 20000000 // set crystal frequency for delay routines
 
I suggest you probably want the one off the bottom of the list :D

XT Oscillator is for an external crystal, BUT for a 20MHz crystal you should select HS Oscillator (for High Speed).

Initially creating a program to flash an LED every second is an excellent way to ensure you're actually running at the correct speed, using the __delay_ms(500); function (half second ON, half second OFF).

And don't forget:

#define _XTAL_FREQ 20000000 // set crystal frequency for delay routines
I'm facing an issue with my MCC-generated code. I've written the logic to blink an LED at regular intervals, but LED is not blinking

To provide more context and seek your assistance, I've attached a zip file containing the project files. If you prefer not to open the zip file, please let me know, and I'll be happy to post the relevant code files here.

C:
/**
  Generated Main Source File

  Company:
    Microchip Technology Inc.

  File Name:
    main.c

  Summary:
    This is the main file generated using PIC10 / PIC12 / PIC16 / PIC18 MCUs

  Description:
    This header file provides implementations for driver APIs for all modules selected in the GUI.
    Generation Information :
        Product Revision  :  PIC10 / PIC12 / PIC16 / PIC18 MCUs - 1.81.8
        Device            :  PIC18F45K80
        Driver Version    :  2.00
*/

/*
    (c) 2018 Microchip Technology Inc. and its subsidiaries.
 
    Subject to your compliance with these terms, you may use Microchip software and any
    derivatives exclusively with Microchip products. It is your responsibility to comply with third party
    license terms applicable to your use of third party software (including open source software) that
    may accompany Microchip software.
 
    THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
    EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY
    IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS
    FOR A PARTICULAR PURPOSE.
 
    IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
    INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
    WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP
    HAS BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO
    THE FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL
    CLAIMS IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT
    OF FEES, IF ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS
    SOFTWARE.
*/

#include "mcc_generated_files/mcc.h"

/*
                         Main application
 */
void main(void)
{
    // Initialize the device
    SYSTEM_Initialize();

    // If using interrupts in PIC18 High/Low Priority Mode you need to enable the Global High and Low Interrupts
    // If using interrupts in PIC Mid-Range Compatibility Mode you need to enable the Global and Peripheral Interrupts
    // Use the following macros to:

    // Enable the Global Interrupts
    //INTERRUPT_GlobalInterruptEnable();

    // Disable the Global Interrupts
    //INTERRUPT_GlobalInterruptDisable();

    // Enable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptEnable();

    // Disable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptDisable();

    while (1)
    {
        // Add your application code
        IO_RB0_SetHigh();
        __delay_ms(1000);
        IO_RB0_SetLow();
        __delay_ms(1000);
    }
}
/**

Nigel Goodwin
 

Attachments

  • Temp1.X.zip
    228.5 KB · Views: 82
Last edited:

Latest threads

New Articles From Microcontroller Tips

Back
Top