PWM (Pulse-Width Modulation) is a programmable interface that allows you to, for example, control motor speed or change light brightness.
Peripherals that support PWM are controlled by the current strength. To modulate the current, the voltage needs to be modulated. The voltage is proportional to the intensity of the current.
To modulate the voltage, you must set the duty cycle and polarity:
Figure: Duty cycle
For example, if the period is 10,000,000 nanoseconds and the polarity high duty cycle is 7,000,000 nanoseconds, the average voltage is at 70%.
Figure: Average voltage per duty cycle
To open and close a handle:
To open a PWM handle, use the
int chip = 0; int pin = 2; peripheral_pwm_h pwm_h; peripheral_pwm_open(chip, pin, &pwm_h);
For more information on the pin names and locations, see Supported Protocols.
To close a PWM handle that is no longer used, use the
To set the period, use the
The following example sets the period to 20 milliseconds. The unit is nanoseconds.
Uint32_t period = 20000000; peripheral_pwm_set_period(pwm_h, period);
To set the duty cycle, use the
The following example sets the duty cycle to 2 milliseconds. The unit is nanoseconds.
uint32_t duty_cycle = 2000000; peripheral_pwm_set_duty_cycle(pwm_h, duty_cycle);
To set the polarity, use the
peripheral_gpio_set_polarity() function with 1 of the following polarity types:
PERIPHERAL_PWM_POLARITY_ACTIVE_HIGH: Polarity is high.
PERIPHERAL_PWM_POLARITY_ACTIVE_LOW: Polarity is low.
To enable repetition, use the
bool enable = true; peripheral_pwm_set_enabled(pwm_h, enable);