Skip to content

Commit 6eab29c

Browse files
author
Laurent MEUNIER
committed
[STM32L1] 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 332660e commit 6eab29c

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

hal/targets/hal/TARGET_STM/TARGET_STM32L1/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_STM32L1/pwmout_api.c

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ void pwmout_init(pwmout_t* obj, PinName pin)
6262
obj->pin = pin;
6363
obj->period = 0;
6464
obj->pulse = 0;
65+
obj->prescaler = 1;
6566

6667
pwmout_period_us(obj, 20000); // 20 ms per default
6768
}
@@ -89,7 +90,7 @@ void pwmout_write(pwmout_t* obj, float value)
8990

9091
// Configure channels
9192
sConfig.OCMode = TIM_OCMODE_PWM1;
92-
sConfig.Pulse = obj->pulse;
93+
sConfig.Pulse = obj->pulse / obj->prescaler;
9394
sConfig.OCPolarity = TIM_OCPOLARITY_HIGH;
9495
sConfig.OCFastMode = TIM_OCFAST_ENABLE;
9596

@@ -167,18 +168,39 @@ void pwmout_period_us(pwmout_t* obj, int us)
167168

168169
SystemCoreClockUpdate();
169170

170-
TimHandle.Init.Period = us - 1;
171-
TimHandle.Init.Prescaler = (uint16_t)(SystemCoreClock / 1000000) - 1; // 1 us tick
171+
/* To make it simple, we use to possible prescaler values which lead to:
172+
* pwm unit = 1us, period/pulse can be from 1us to 65535us
173+
* or
174+
* pwm unit = 500us, period/pulse can be from 500us to ~32.76sec
175+
* Be careful that all the channels of a PWM shares the same prescaler
176+
*/
177+
if (us > 0xFFFF) {
178+
obj->prescaler = 500;
179+
} else {
180+
obj->prescaler = 1;
181+
}
182+
TimHandle.Init.Prescaler = ((SystemCoreClock / 1000000) * obj->prescaler) - 1;
183+
184+
if (TimHandle.Init.Prescaler > 0xFFFF)
185+
error("PWM: out of range prescaler");
186+
187+
TimHandle.Init.Period = (us - 1) / obj->prescaler;
188+
if (TimHandle.Init.Period > 0xFFFF)
189+
error("PWM: out of range period");
190+
172191
TimHandle.Init.ClockDivision = 0;
173192
TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP;
174-
HAL_TIM_PWM_Init(&TimHandle);
175193

176-
// Set duty cycle again
177-
pwmout_write(obj, dc);
194+
if (HAL_TIM_PWM_Init(&TimHandle) != HAL_OK) {
195+
error("Cannot initialize PWM");
196+
}
178197

179198
// Save for future use
180199
obj->period = us;
181200

201+
// Set duty cycle again
202+
pwmout_write(obj, dc);
203+
182204
__HAL_TIM_ENABLE(&TimHandle);
183205
}
184206

0 commit comments

Comments
 (0)