@@ -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