@@ -62,6 +62,7 @@ void pwmout_init(pwmout_t* obj, PinName pin)
62
62
obj -> pin = pin ;
63
63
obj -> period = 0 ;
64
64
obj -> pulse = 0 ;
65
+ obj -> prescaler = 1 ;
65
66
66
67
pwmout_period_us (obj , 20000 ); // 20 ms per default
67
68
}
@@ -89,7 +90,7 @@ void pwmout_write(pwmout_t* obj, float value)
89
90
90
91
// Configure channels
91
92
sConfig .OCMode = TIM_OCMODE_PWM1 ;
92
- sConfig .Pulse = obj -> pulse ;
93
+ sConfig .Pulse = obj -> pulse / obj -> prescaler ;
93
94
sConfig .OCPolarity = TIM_OCPOLARITY_HIGH ;
94
95
sConfig .OCFastMode = TIM_OCFAST_ENABLE ;
95
96
@@ -167,18 +168,39 @@ void pwmout_period_us(pwmout_t* obj, int us)
167
168
168
169
SystemCoreClockUpdate ();
169
170
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
+
172
191
TimHandle .Init .ClockDivision = 0 ;
173
192
TimHandle .Init .CounterMode = TIM_COUNTERMODE_UP ;
174
- HAL_TIM_PWM_Init (& TimHandle );
175
193
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
+ }
178
197
179
198
// Save for future use
180
199
obj -> period = us ;
181
200
201
+ // Set duty cycle again
202
+ pwmout_write (obj , dc );
203
+
182
204
__HAL_TIM_ENABLE (& TimHandle );
183
205
}
184
206
0 commit comments