lpcware

change PWM frequency

Discussion created by lpcware Employee on Jun 15, 2016
Content originally posted in LPCWare by juergen.zach@pentair.com on Fri Jul 26 17:56:58 MST 2013
The code below sets up a simple 2-edged PWM signal. In my application, I need to change the frequency occasionally, which is what I THINK I am doing in the main loop, but the only change is the duty cycle. That is, the frequency always remains to what it was set at the beginning (1kHz), and only the "on" duty cycle is commensurate with the 2kHz I'm switching it to.

Any ideas, anything I'm obviously forgetting here?

--J.



#include "LPC17xx.h"

float duty;
int PWMclock;
int PWMrate;
float frequency;


int main()
{
    int PWMwidth, PWMhalf, PWMrising, PWMfalling;  

    duty = 50.0;
    frequency = 1000.0;
   
    PWMclock = SystemCoreClock / 4;
    PWMrate = PWMclock / frequency;
    LPC_PINCON->PINSEL4 |= 0x00000040;                     // Set P2.3 for PWM1.4
   
    LPC_PWM1->MCR |= 0x00000002; // Reset PWM0 on match

    // Set up match registers
    LPC_PWM1->MR0 = PWMrate; // Set MR0 (PWM rate)

    LPC_PWM1->PCR |= 0x00000010; // Select double edge PWM for PWM4

    LPC_PWM1->PCR |= 0x00001000; // Enable PWM4

    LPC_PWM1->TCR |= 0x08; // Enable PWM mode
    LPC_PWM1->TCR |= 0x01; // Enable counter

    //pwmChg.attach_us(&pwmupdate, 100000);

    while (1)
    {

        frequency = 1000.0;
        PWMrate = PWMclock / frequency;
        LPC_PWM1->MR0 = PWMrate; // Set MR0 (PWM rate)

        PWMwidth = (duty * PWMrate) / 100;
        PWMhalf = PWMwidth / 2;
        //PWMrising = PWMrate - PWMhalf;
        //PWMfalling = PWMhalf;
        PWMfalling = PWMrate - PWMhalf;
        PWMrising = PWMhalf;       
   
        LPC_PWM1->MR3 = PWMrising; // Set rising edge
        LPC_PWM1->MR4 = PWMfalling; // Set falling edge
   
        LPC_PWM1->LER |= 0x18; // Enable PWM Match 3 & 4 latch
   
        for (int i; i<10000000;i++){}
       
        frequency = 2000.0;
        PWMrate = PWMclock / frequency;
        LPC_PWM1->MR0 = PWMrate; // Set MR0 (PWM rate)

        PWMwidth = (duty * PWMrate) / 100;
        PWMhalf = PWMwidth / 2;
        //PWMrising = PWMrate - PWMhalf;
        //PWMfalling = PWMhalf;
        PWMfalling = PWMrate - PWMhalf;
        PWMrising = PWMhalf;  
   
        LPC_PWM1->MR3 = PWMrising; // Set rising edge
        LPC_PWM1->MR4 = PWMfalling; // Set falling edge
   
        LPC_PWM1->LER |= 0x18; // Enable PWM Match 3 & 4 latch
       
        for (int i; i<10000000;i++){}      
       
    }
}

Attachments

Outcomes