cancel
Showing results for 
Search instead for 
Did you mean: 

Dynamic Change Duty Cycle PWM using tim.h

Sean Mutlu
Associate II
Posted on July 04, 2017 at 22:53

Working off the provided example for PWM on STM32F100RB I am able to output varying levels of PWM, however, my attempts to change the duty cycle of a specific channel according to user input have failed. I do not see any way to change the duty cycle using tim.h except on timer initialization.

#duty-cycle #pwm #dynamic-change
4 REPLIES 4
bbee
Associate III
Posted on July 05, 2017 at 10:45

It would have been nice to have more information about what you are using e.g. STM32Cube, the standard perihperal libray or whatever.

However to change the duty cycle you just have to modify the autoreload and compare register on the fly. If PWM is running, then stop it. Afterwards modify the registers and start it again. If you use STM32Cube there should be __HAL_TIM_SET_AUTORELOAD and __HAL_TIM_SET_COMPARE to do the job.

Posted on July 05, 2017 at 14:54

tim.h? where'd you get that?

TIMx->CCRx = Width;

Where Period = N-1,  Width = N/2 is 50% duty

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Sean Mutlu
Associate II
Posted on July 06, 2017 at 01:37

I have been using Coocox and it lets me enable the timer library:

#include <stm32f10x_tim.h>

I am not familiar with how to do this by writing to the registers or using HAL, if you think these methods are easier I could use some help getting my foot in the door. I figured these libraries and documentation would be my best bet to learn fast but I could've been mislead. 

Posted on July 09, 2017 at 00:15

Ok, so the SPL (Standard Peripheral Library), I'm good with that.

The register in this case is simple enough, the library works well for initialization, but when you're just wrapping a register write sometimes it makes sense to just do that.

/**

* @brief Sets the TIMx Capture Compare1 Register value

* @param TIMx: where x can be 1 to 14 except 6 and 7, to select the TIM peripheral.

* @param Compare1: specifies the Capture Compare1 register new value.

* @retval None

*/

void TIM_SetCompare1(TIM_TypeDef* TIMx, uint32_t Compare1)

{

/* Check the parameters */

assert_param(IS_TIM_LIST1_PERIPH(TIMx));

/* Set the Capture Compare1 Register value */

TIMx->CCR1 = Compare1;

}
Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..