@@ -58,6 +58,7 @@ void pwmout_init(pwmout_t* obj, PinName pin)
58
58
obj -> pin = pin ;
59
59
obj -> period = 0 ;
60
60
obj -> pulse = 0 ;
61
+ obj -> prescaler = 1 ;
61
62
62
63
pwmout_period_us (obj , 20000 ); // 20 ms per default
63
64
}
@@ -86,7 +87,7 @@ void pwmout_write(pwmout_t* obj, float value)
86
87
87
88
// Configure channels
88
89
sConfig .OCMode = TIM_OCMODE_PWM1 ;
89
- sConfig .Pulse = obj -> pulse ;
90
+ sConfig .Pulse = obj -> pulse / obj -> prescaler ;
90
91
sConfig .OCPolarity = TIM_OCPOLARITY_HIGH ;
91
92
sConfig .OCNPolarity = TIM_OCNPOLARITY_HIGH ;
92
93
sConfig .OCFastMode = TIM_OCFAST_DISABLE ;
@@ -193,18 +194,37 @@ void pwmout_period_us(pwmout_t* obj, int us)
193
194
// Update the SystemCoreClock variable
194
195
SystemCoreClockUpdate ();
195
196
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
+
198
218
TimHandle .Init .ClockDivision = 0 ;
199
219
TimHandle .Init .CounterMode = TIM_COUNTERMODE_UP ;
200
220
HAL_TIM_PWM_Init (& TimHandle );
201
221
202
- // Set duty cycle again
203
- pwmout_write (obj , dc );
204
-
205
222
// Save for future use
206
223
obj -> period = us ;
207
224
225
+ // Set duty cycle again
226
+ pwmout_write (obj , dc );
227
+
208
228
__HAL_TIM_ENABLE (& TimHandle );
209
229
}
210
230
0 commit comments