3.1.8 PWM

This block generates a PWM output with an arbitrary duty cycle at frequencies from less than 0.1 Hz to 24 MHz.

Using the Library

The below example demonstrates how to use the PWM peripheral to generate a PWM signal and vary the duty cycle at run time. Based on the user input on the console, the duty cycle is incremented or decremented in steps of 1% while keeping the frequency of PWM output same.
char input = 0;
int16_t onTime = 0;
int16_t offTime = 0;
float dutyCycle = 0;
uint32_t onePercDutyCycleCnt = 0;
uint32_t period;

int main ( void )
{
    /* Initialize all modules */
    SYS_Initialize ( NULL );
    
    printf("\n\r---------------------------------------------------------");
    printf("\n\r                    PWM Demo                     ");
    printf("\n\r  Press '+'/'-' to increment/decrement duty cycle by 1%% ");
    printf("\n\r---------------------------------------------------------\n\r");
    
    period = (PWM0_OnCountGet() + 1 + PWM0_OffCountGet() + 1);
    dutyCycle = ((PWM0_OnCountGet() + 1)/(float)period) * 100.0;
    onePercDutyCycleCnt = (period)/100;
       
    printf("Frequency = %ld Hz\r\n", 48000000/(period));
    printf("Duty Cycle = %2.2f%%\r\n", dutyCycle);
                
    PWM0_Start();

    while ( true )
    {
        scanf("%c", &input);
        
        if ((input == '+') && (dutyCycle <= 99.0))
        {
            dutyCycle += 1;
        }
        else if ((input == '-') && (dutyCycle >= 1.0))
        {
            dutyCycle -= 1;
        }
        
        onTime = onePercDutyCycleCnt * dutyCycle;
        offTime = period - onTime;
        
        if (onTime >= 0 && onTime <= 65535 && offTime >= 0 && offTime <= 65535)
        {
            PWM0_OnCountSet(onTime);
            PWM0_OffCountSet(offTime);
            dutyCycle = (float)(onTime + 1)/(onTime + 1 + offTime + 1);
            dutyCycle *= 100;
            printf("Duty Cycle = %2.2f%%\r\n", dutyCycle);
        }
    }

    /* Execution should not come here during normal operation */

    return ( EXIT_FAILURE );
}

Library Interface

Functions
NameDescription
PWMx_InitializeInitializes given instance of PWM peripheral.
PWMx_OffCountGetReturns the off-time period of the PWM signal
PWMx_OffCountSetSets the off-time period of the PWM signal
PWMx_OnCountSetSets the on-time period of the PWM signal
PWMx_OnCountGetReturns the on-time period of the PWM signal
PWMx_StartEnables and starts PWM peripheral
PWMx_StopDisables PWM peripheral and stops PWM output
PWMx_ClkSelectSelects the clock source for the PWM peripheral
PWMx_ClkDividerSetSelects the divider value for the clock source for the PWM peripheral
Data types and constants
NameTypeDescription
PWM_OUTPUT_ON_STATE_ACTIVE MacroDefines the macros associated with PWM_OUTPUT_ON_STATE_ACTIVE
PWM_CLK_SELMacroDefines the macros associated with PWM_CLK_SEL