Skip to content

Commit ce5ee17

Browse files
author
Laurent MEUNIER
committed
[STM32F1] Handle higher range pwm periods
As first reported on STM32F3 family in #1682, we need to cope with periods in the seconds range as well. This is fixed here in the same way as was done for STM32F3 by using the pre-scaler.
1 parent 00e51f4 commit ce5ee17

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

hal/targets/hal/TARGET_STM/TARGET_STM32F1/common_objects.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ extern "C" {
4242
struct pwmout_s {
4343
PWMName pwm;
4444
PinName pin;
45+
uint32_t prescaler;
4546
uint32_t period;
4647
uint32_t pulse;
4748
};

hal/targets/hal/TARGET_STM/TARGET_STM32F1/pwmout_api.c

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ void pwmout_init(pwmout_t* obj, PinName pin)
5858
obj->pin = pin;
5959
obj->period = 0;
6060
obj->pulse = 0;
61+
obj->prescaler = 1;
6162

6263
pwmout_period_us(obj, 20000); // 20 ms per default
6364
}
@@ -86,7 +87,7 @@ void pwmout_write(pwmout_t* obj, float value)
8687

8788
// Configure channels
8889
sConfig.OCMode = TIM_OCMODE_PWM1;
89-
sConfig.Pulse = obj->pulse;
90+
sConfig.Pulse = obj->pulse / obj->prescaler;
9091
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
9192
sConfig.OCNPolarity = TIM_OCNPOLARITY_HIGH;
9293
sConfig.OCFastMode = TIM_OCFAST_DISABLE;
@@ -193,18 +194,37 @@ void pwmout_period_us(pwmout_t* obj, int us)
193194
// Update the SystemCoreClock variable
194195
SystemCoreClockUpdate();
195196

196-
TimHandle.Init.Period = us - 1;
197-
TimHandle.Init.Prescaler = (uint16_t)(SystemCoreClock / 1000000) - 1; // 1 us tick
197+
/* To make it simple, we use to possible prescaler values which lead to:
198+
* pwm unit = 1us, period/pulse can be from 1us to 65535us
199+
* or
200+
* pwm unit = 500us, period/pulse can be from 500us to ~32.76sec
201+
* Be careful that all the channels of a PWM shares the same prescaler
202+
*/
203+
if (us > 0xFFFF) {
204+
obj->prescaler = 500;
205+
} else {
206+
obj->prescaler = 1;
207+
}
208+
209+
TimHandle.Init.Prescaler = ((SystemCoreClock / 1000000) * obj->prescaler) - 1;
210+
211+
if (TimHandle.Init.Prescaler > 0xFFFF)
212+
error("PWM: out of range prescaler");
213+
214+
TimHandle.Init.Period = (us - 1) / obj->prescaler;
215+
if (TimHandle.Init.Period > 0xFFFF)
216+
error("PWM: out of range period");
217+
198218
TimHandle.Init.ClockDivision = 0;
199219
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
200220
HAL_TIM_PWM_Init(&TimHandle);
201221

202-
// Set duty cycle again
203-
pwmout_write(obj, dc);
204-
205222
// Save for future use
206223
obj->period = us;
207224

225+
// Set duty cycle again
226+
pwmout_write(obj, dc);
227+
208228
__HAL_TIM_ENABLE(&TimHandle);
209229
}
210230

0 commit comments

Comments
 (0)