1.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
Name | Description |
---|---|
PWMx_Initialize | Initializes given instance of PWM peripheral. |
PWMx_OffCountGet | Returns the off-time period of the PWM signal |
PWMx_OffCountSet | Sets the off-time period of the PWM signal |
PWMx_OnCountSet | Sets the on-time period of the PWM signal |
PWMx_OnCountGet | Returns the on-time period of the PWM signal |
PWMx_Start | Enables and starts PWM peripheral |
PWMx_Stop | Disables PWM peripheral and stops PWM output |
PWMx_ClkSelect | Selects the clock source for the PWM peripheral |
PWMx_ClkDividerSet | Selects the divider value for the clock source for the PWM peripheral |
Data types and constants
Name | Type | Description |
---|---|---|
PWM_OUTPUT_ON_STATE_ACTIVE | Macro | Defines the macros associated with PWM_OUTPUT_ON_STATE_ACTIVE |
PWM_CLK_SEL | Macro | Defines the macros associated with PWM_CLK_SEL |