This is the quickstart guide for the PWM module, with step-by-step instructions on how to configure and use the drivers in a selection of use cases.
The use cases contain several code fragments. The code fragments in the steps for setup can be copied into a custom initialization function, while the steps for usage can be copied into, e.g., the main application function.
Basic use case
In this basic use case, the PWM module is configured to:
- Output a square wave on PWM channel 0
- The frequency of the square wave is 1KHz, 50% duty cycle
- Clock A as the source clock
- The output wave can be checked on the selected output pin
Setup steps
Prerequisites
Example code
Add this PWM initialization code at the beginning of the main function:
pmc_enable_periph_clk(
ID_PWM);
.ul_clka = 1000 * 100,
.ul_clkb = 0,
.ul_mck = 48000000
};
#define PWM_CMR_CPRE_CLKA
(PWM_CMR) Clock A
uint32_t pwm_init(Pwm *p_pwm, pwm_clock_t *clock_config)
Initialize the PWM source clock (clock A and clock B).
void pwm_channel_disable(Pwm *p_pwm, uint32_t ul_channel)
Disable the PWM channel.
uint32_t pwm_channel_init(Pwm *p_pwm, pwm_channel_t *p_channel)
Initialize one PWM channel.
#define PWM
(PWM ) Base Address
#define ID_PWM
Pulse Width Modulation (PWM).
Input parameters when configuring a PWM channel mode.
uint32_t ul_period
Period Cycle Value.
uint32_t ul_prescaler
Channel prescaler.
uint32_t channel
Channel number.
uint32_t ul_duty
Duty Cycle Value.
Input parameters when initializing PWM.
Workflow
- Define the PWM channel instance in order to configure channel 0:
- Enable the module clock for the PWM peripheral:
pmc_enable_periph_clk(
ID_PWM);
- Disable PWM channel 0:
- Setup clock for PWM module:
.ul_clka = 1000 * 100,
.ul_clkb = 0,
.ul_mck = 48000000
};
- Note
- 1. Only Clock A is configured (clock B is not used).
- The expected frequency is 1KHz, system main clock is assumed to be 48MHz.
- Initialize channel instance and configure PWM channel 0, selecting clock A as its source clock and setting the duty cycle at 50%:
- Note
- 1. Period is left-aligned and output waveform starts at a low level.
- The pwm_channel_instance can be re-used to configure other PWM channels after setting the required parameters.
Usage steps
Example code
Add to, e.g., main loop in application C-file:
void pwm_channel_enable(Pwm *p_pwm, uint32_t ul_channel)
Enable the PWM channel.
Workflow
- Enable PWM channel 0 and output square wave on this channel:
Advanced use cases
For more advanced use of the pwm driver, see the following use cases:
- Use case #1 : PWM channel 0 outputs square wave and duty cycle is updated in the PWM ISR.