How to: PWM

Pulse Width Modulation (PWM) is a method to create analog-like signal from the microcontroller digital output. It will achieve that by fast toggling of the pin with different ration of logic HIGH and LOW. This ratio is called duty cycle.

Please check the Core Module pinout to see which pins allows PWM.

SDK PWM functions

Here are the main functions. You need to call all three of them for every PWM output.

1void twr_pwm_init(twr_pwm_channel_t channel);
2void twr_pwm_enable(twr_pwm_channel_t channel);
3void twr_pwm_set(twr_pwm_channel_t channel, uint16_t pwm_value);

The channel parameter can be one of the output pins.

1TWR_PWM_P0
2TWR_PWM_P1
3TWR_PWM_P2
4TWR_PWM_P3
5TWR_PWM_P6
6TWR_PWM_P7
7TWR_PWM_P8
8TWR_PWM_P12
9TWR_PWM_P14

The value is a number between 0 and 255. I choose this to be the same like in Arduino analogWrite() function. But by calling twr_pwm_tim_configure() function you can simply change period of the PWM.

Example code

Enable PWM signal on P6, P7 and P8 outputs. Every output has different duty cycle: 180, 210 and 255 (which is permanent HIGH).

 1void application_init()
 2{
 3    twr_pwm_init(TWR_PWM_P6);
 4    twr_pwm_set(TWR_PWM_P6, 180);
 5    twr_pwm_enable(TWR_PWM_P6);
 6
 7    twr_pwm_init(TWR_PWM_P7);
 8    twr_pwm_set(TWR_PWM_P7, 210);
 9    twr_pwm_enable(TWR_PWM_P7);
10
11    twr_pwm_init(TWR_PWM_P8);
12    twr_pwm_set(TWR_PWM_P8, 255);
13    twr_pwm_enable(TWR_PWM_P8);
14}