1 /*
2 * This file is part of the MicroPython project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
27 #include <stdint.h>
28 #include <string.h>
29
30 #include "py/runtime.h"
31 #include "py/gc.h"
32 #include "timer.h"
33 #include "servo.h"
34 #include "pin.h"
35 #include "irq.h"
36
37 /// \moduleref pyb
38 /// \class Timer - periodically call a function
39 ///
40 /// Timers can be used for a great variety of tasks. At the moment, only
41 /// the simplest case is implemented: that of calling a function periodically.
42 ///
43 /// Each timer consists of a counter that counts up at a certain rate. The rate
44 /// at which it counts is the peripheral clock frequency (in Hz) divided by the
45 /// timer prescaler. When the counter reaches the timer period it triggers an
46 /// event, and the counter resets back to zero. By using the callback method,
47 /// the timer event can call a Python function.
48 ///
49 /// Example usage to toggle an LED at a fixed frequency:
50 ///
51 /// tim = pyb.Timer(4) # create a timer object using timer 4
52 /// tim.init(freq=2) # trigger at 2Hz
53 /// tim.callback(lambda t:pyb.LED(1).toggle())
54 ///
55 /// Further examples:
56 ///
57 /// tim = pyb.Timer(4, freq=100) # freq in Hz
58 /// tim = pyb.Timer(4, prescaler=0, period=99)
59 /// tim.counter() # get counter (can also set)
60 /// tim.prescaler(2) # set prescaler (can also get)
61 /// tim.period(199) # set period (can also get)
62 /// tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance)
63 /// tim.callback(None) # clear callback
64 ///
65 /// *Note:* Timer 3 is used for fading the blue LED. Timer 5 controls
66 /// the servo driver, and Timer 6 is used for timed ADC/DAC reading/writing.
67 /// It is recommended to use the other timers in your programs.
68
69 // The timers can be used by multiple drivers, and need a common point for
70 // the interrupts to be dispatched, so they are all collected here.
71 //
72 // TIM3:
73 // - LED 4, PWM to set the LED intensity
74 //
75 // TIM5:
76 // - servo controller, PWM
77 //
78 // TIM6:
79 // - ADC, DAC for read_timed and write_timed
80
81 typedef enum {
82 CHANNEL_MODE_PWM_NORMAL,
83 CHANNEL_MODE_PWM_INVERTED,
84 CHANNEL_MODE_OC_TIMING,
85 CHANNEL_MODE_OC_ACTIVE,
86 CHANNEL_MODE_OC_INACTIVE,
87 CHANNEL_MODE_OC_TOGGLE,
88 CHANNEL_MODE_OC_FORCED_ACTIVE,
89 CHANNEL_MODE_OC_FORCED_INACTIVE,
90 CHANNEL_MODE_IC,
91 CHANNEL_MODE_ENC_A,
92 CHANNEL_MODE_ENC_B,
93 CHANNEL_MODE_ENC_AB,
94 } pyb_channel_mode;
95
96 STATIC const struct {
97 qstr name;
98 uint32_t oc_mode;
99 } channel_mode_info[] = {
100 { MP_QSTR_PWM, TIM_OCMODE_PWM1 },
101 { MP_QSTR_PWM_INVERTED, TIM_OCMODE_PWM2 },
102 { MP_QSTR_OC_TIMING, TIM_OCMODE_TIMING },
103 { MP_QSTR_OC_ACTIVE, TIM_OCMODE_ACTIVE },
104 { MP_QSTR_OC_INACTIVE, TIM_OCMODE_INACTIVE },
105 { MP_QSTR_OC_TOGGLE, TIM_OCMODE_TOGGLE },
106 { MP_QSTR_OC_FORCED_ACTIVE, TIM_OCMODE_FORCED_ACTIVE },
107 { MP_QSTR_OC_FORCED_INACTIVE, TIM_OCMODE_FORCED_INACTIVE },
108 { MP_QSTR_IC, 0 },
109 { MP_QSTR_ENC_A, TIM_ENCODERMODE_TI1 },
110 { MP_QSTR_ENC_B, TIM_ENCODERMODE_TI2 },
111 { MP_QSTR_ENC_AB, TIM_ENCODERMODE_TI12 },
112 };
113
114 enum {
115 BRK_OFF,
116 BRK_LOW,
117 BRK_HIGH,
118 };
119
120 typedef struct _pyb_timer_channel_obj_t {
121 mp_obj_base_t base;
122 struct _pyb_timer_obj_t *timer;
123 uint8_t channel;
124 uint8_t mode;
125 mp_obj_t callback;
126 struct _pyb_timer_channel_obj_t *next;
127 } pyb_timer_channel_obj_t;
128
129 typedef struct _pyb_timer_obj_t {
130 mp_obj_base_t base;
131 uint8_t tim_id;
132 uint8_t is_32bit;
133 mp_obj_t callback;
134 TIM_HandleTypeDef tim;
135 IRQn_Type irqn;
136 pyb_timer_channel_obj_t *channel;
137 } pyb_timer_obj_t;
138
139 // The following yields TIM_IT_UPDATE when channel is zero and
140 // TIM_IT_CC1..TIM_IT_CC4 when channel is 1..4
141 #define TIMER_IRQ_MASK(channel) (1 << (channel))
142 #define TIMER_CNT_MASK(self) ((self)->is_32bit ? 0xffffffff : 0xffff)
143 #define TIMER_CHANNEL(self) ((((self)->channel) - 1) << 2)
144
145 TIM_HandleTypeDef TIM5_Handle;
146 TIM_HandleTypeDef TIM6_Handle;
147
148 #define PYB_TIMER_OBJ_ALL_NUM MP_ARRAY_SIZE(MP_STATE_PORT(pyb_timer_obj_all))
149
150 STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in);
151 STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback);
152 STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback);
153
timer_init0(void)154 void timer_init0(void) {
155 for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
156 MP_STATE_PORT(pyb_timer_obj_all)[i] = NULL;
157 }
158 }
159
160 // unregister all interrupt sources
timer_deinit(void)161 void timer_deinit(void) {
162 for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
163 pyb_timer_obj_t *tim = MP_STATE_PORT(pyb_timer_obj_all)[i];
164 if (tim != NULL) {
165 pyb_timer_deinit(MP_OBJ_FROM_PTR(tim));
166 }
167 }
168 }
169
170 #if defined(TIM5)
171 // TIM5 is set-up for the servo controller
172 // This function inits but does not start the timer
timer_tim5_init(void)173 void timer_tim5_init(void) {
174 // TIM5 clock enable
175 __HAL_RCC_TIM5_CLK_ENABLE();
176
177 // set up and enable interrupt
178 NVIC_SetPriority(TIM5_IRQn, IRQ_PRI_TIM5);
179 HAL_NVIC_EnableIRQ(TIM5_IRQn);
180
181 // PWM clock configuration
182 TIM5_Handle.Instance = TIM5;
183 TIM5_Handle.Init.Period = 2000 - 1; // timer cycles at 50Hz
184 TIM5_Handle.Init.Prescaler = (timer_get_source_freq(5) / 100000) - 1; // timer runs at 100kHz
185 TIM5_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
186 TIM5_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
187
188 HAL_TIM_PWM_Init(&TIM5_Handle);
189 }
190 #endif
191
192 #if defined(TIM6)
193 // Init TIM6 with a counter-overflow at the given frequency (given in Hz)
194 // TIM6 is used by the DAC and ADC for auto sampling at a given frequency
195 // This function inits but does not start the timer
timer_tim6_init(uint freq)196 TIM_HandleTypeDef *timer_tim6_init(uint freq) {
197 // TIM6 clock enable
198 __HAL_RCC_TIM6_CLK_ENABLE();
199
200 // Timer runs at SystemCoreClock / 2
201 // Compute the prescaler value so TIM6 triggers at freq-Hz
202 uint32_t period = MAX(1, timer_get_source_freq(6) / freq);
203 uint32_t prescaler = 1;
204 while (period > 0xffff) {
205 period >>= 1;
206 prescaler <<= 1;
207 }
208
209 // Time base clock configuration
210 TIM6_Handle.Instance = TIM6;
211 TIM6_Handle.Init.Period = period - 1;
212 TIM6_Handle.Init.Prescaler = prescaler - 1;
213 TIM6_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; // unused for TIM6
214 TIM6_Handle.Init.CounterMode = TIM_COUNTERMODE_UP; // unused for TIM6
215 HAL_TIM_Base_Init(&TIM6_Handle);
216
217 return &TIM6_Handle;
218 }
219 #endif
220
221 // Interrupt dispatch
HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef * htim)222 void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
223 #if MICROPY_HW_ENABLE_SERVO
224 if (htim == &TIM5_Handle) {
225 servo_timer_irq_callback();
226 }
227 #endif
228 }
229
230 // Get the frequency (in Hz) of the source clock for the given timer.
231 // On STM32F405/407/415/417 there are 2 cases for how the clock freq is set.
232 // If the APB prescaler is 1, then the timer clock is equal to its respective
233 // APB clock. Otherwise (APB prescaler > 1) the timer clock is twice its
234 // respective APB clock. See DM00031020 Rev 4, page 115.
timer_get_source_freq(uint32_t tim_id)235 uint32_t timer_get_source_freq(uint32_t tim_id) {
236 uint32_t source, clk_div;
237 if (tim_id == 1 || (8 <= tim_id && tim_id <= 11)) {
238 // TIM{1,8,9,10,11} are on APB2
239 #if defined(STM32F0)
240 source = HAL_RCC_GetPCLK1Freq();
241 clk_div = RCC->CFGR & RCC_CFGR_PPRE;
242 #elif defined(STM32H7)
243 source = HAL_RCC_GetPCLK2Freq();
244 clk_div = RCC->D2CFGR & RCC_D2CFGR_D2PPRE2;
245 #else
246 source = HAL_RCC_GetPCLK2Freq();
247 clk_div = RCC->CFGR & RCC_CFGR_PPRE2;
248 #endif
249 } else {
250 // TIM{2,3,4,5,6,7,12,13,14} are on APB1
251 source = HAL_RCC_GetPCLK1Freq();
252 #if defined(STM32F0)
253 clk_div = RCC->CFGR & RCC_CFGR_PPRE;
254 #elif defined(STM32H7)
255 clk_div = RCC->D2CFGR & RCC_D2CFGR_D2PPRE1;
256 #else
257 clk_div = RCC->CFGR & RCC_CFGR_PPRE1;
258 #endif
259 }
260 if (clk_div != 0) {
261 // APB prescaler for this timer is > 1
262 source *= 2;
263 }
264 return source;
265 }
266
267 /******************************************************************************/
268 /* MicroPython bindings */
269
270 STATIC const mp_obj_type_t pyb_timer_channel_type;
271
272 // This is the largest value that we can multiply by 100 and have the result
273 // fit in a uint32_t.
274 #define MAX_PERIOD_DIV_100 42949672
275
276 // computes prescaler and period so TIM triggers at freq-Hz
compute_prescaler_period_from_freq(pyb_timer_obj_t * self,mp_obj_t freq_in,uint32_t * period_out)277 STATIC uint32_t compute_prescaler_period_from_freq(pyb_timer_obj_t *self, mp_obj_t freq_in, uint32_t *period_out) {
278 uint32_t source_freq = timer_get_source_freq(self->tim_id);
279 uint32_t prescaler = 1;
280 uint32_t period;
281 if (0) {
282 #if MICROPY_PY_BUILTINS_FLOAT
283 } else if (mp_obj_is_type(freq_in, &mp_type_float)) {
284 float freq = mp_obj_get_float_to_f(freq_in);
285 if (freq <= 0) {
286 goto bad_freq;
287 }
288 while (freq < 1 && prescaler < 6553) {
289 prescaler *= 10;
290 freq *= 10.0f;
291 }
292 period = (uint32_t)((float)source_freq / freq);
293 #endif
294 } else {
295 mp_int_t freq = mp_obj_get_int(freq_in);
296 if (freq <= 0) {
297 goto bad_freq;
298 bad_freq:
299 mp_raise_ValueError(MP_ERROR_TEXT("must have positive freq"));
300 }
301 period = source_freq / freq;
302 }
303 period = MAX(1, period);
304 while (period > TIMER_CNT_MASK(self)) {
305 // if we can divide exactly, do that first
306 if (period % 5 == 0) {
307 prescaler *= 5;
308 period /= 5;
309 } else if (period % 3 == 0) {
310 prescaler *= 3;
311 period /= 3;
312 } else {
313 // may not divide exactly, but loses minimal precision
314 prescaler <<= 1;
315 period >>= 1;
316 }
317 }
318 *period_out = (period - 1) & TIMER_CNT_MASK(self);
319 return (prescaler - 1) & 0xffff;
320 }
321
322 // computes prescaler and period so TIM triggers with a period of t_num/t_den seconds
compute_prescaler_period_from_t(pyb_timer_obj_t * self,int32_t t_num,int32_t t_den,uint32_t * period_out)323 STATIC uint32_t compute_prescaler_period_from_t(pyb_timer_obj_t *self, int32_t t_num, int32_t t_den, uint32_t *period_out) {
324 uint32_t source_freq = timer_get_source_freq(self->tim_id);
325 if (t_num <= 0 || t_den <= 0) {
326 mp_raise_ValueError(MP_ERROR_TEXT("must have positive freq"));
327 }
328 uint64_t period = (uint64_t)source_freq * (uint64_t)t_num / (uint64_t)t_den;
329 uint32_t prescaler = 1;
330 while (period > TIMER_CNT_MASK(self)) {
331 // if we can divide exactly, and without prescaler overflow, do that first
332 if (prescaler <= 13107 && period % 5 == 0) {
333 prescaler *= 5;
334 period /= 5;
335 } else if (prescaler <= 21845 && period % 3 == 0) {
336 prescaler *= 3;
337 period /= 3;
338 } else {
339 // may not divide exactly, but loses minimal precision
340 uint32_t period_lsb = period & 1;
341 prescaler <<= 1;
342 period >>= 1;
343 if (period < prescaler) {
344 // round division up
345 prescaler |= period_lsb;
346 }
347 if (prescaler > 0x10000) {
348 mp_raise_ValueError(MP_ERROR_TEXT("period too large"));
349 }
350 }
351 }
352 *period_out = (period - 1) & TIMER_CNT_MASK(self);
353 return (prescaler - 1) & 0xffff;
354 }
355
356 // Helper function for determining the period used for calculating percent
compute_period(pyb_timer_obj_t * self)357 STATIC uint32_t compute_period(pyb_timer_obj_t *self) {
358 // In center mode, compare == period corresponds to 100%
359 // In edge mode, compare == (period + 1) corresponds to 100%
360 uint32_t period = (__HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self));
361 if (period != 0xffffffff) {
362 if (self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ||
363 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN) {
364 // Edge mode
365 period++;
366 }
367 }
368 return period;
369 }
370
371 // Helper function to compute PWM value from timer period and percent value.
372 // 'percent_in' can be an int or a float between 0 and 100 (out of range
373 // values are clamped).
compute_pwm_value_from_percent(uint32_t period,mp_obj_t percent_in)374 STATIC uint32_t compute_pwm_value_from_percent(uint32_t period, mp_obj_t percent_in) {
375 uint32_t cmp;
376 if (0) {
377 #if MICROPY_PY_BUILTINS_FLOAT
378 } else if (mp_obj_is_type(percent_in, &mp_type_float)) {
379 mp_float_t percent = mp_obj_get_float(percent_in);
380 if (percent <= 0.0) {
381 cmp = 0;
382 } else if (percent >= 100.0) {
383 cmp = period;
384 } else {
385 cmp = (uint32_t)(percent / MICROPY_FLOAT_CONST(100.0) * ((mp_float_t)period));
386 }
387 #endif
388 } else {
389 // For integer arithmetic, if period is large and 100*period will
390 // overflow, then divide period before multiplying by cmp. Otherwise
391 // do it the other way round to retain precision.
392 mp_int_t percent = mp_obj_get_int(percent_in);
393 if (percent <= 0) {
394 cmp = 0;
395 } else if (percent >= 100) {
396 cmp = period;
397 } else if (period > MAX_PERIOD_DIV_100) {
398 cmp = (uint32_t)percent * (period / 100);
399 } else {
400 cmp = ((uint32_t)percent * period) / 100;
401 }
402 }
403 return cmp;
404 }
405
406 // Helper function to compute percentage from timer perion and PWM value.
compute_percent_from_pwm_value(uint32_t period,uint32_t cmp)407 STATIC mp_obj_t compute_percent_from_pwm_value(uint32_t period, uint32_t cmp) {
408 #if MICROPY_PY_BUILTINS_FLOAT
409 mp_float_t percent;
410 if (cmp >= period) {
411 percent = 100.0;
412 } else {
413 percent = (mp_float_t)cmp * 100.0 / ((mp_float_t)period);
414 }
415 return mp_obj_new_float(percent);
416 #else
417 mp_int_t percent;
418 if (cmp >= period) {
419 percent = 100;
420 } else if (cmp > MAX_PERIOD_DIV_100) {
421 percent = cmp / (period / 100);
422 } else {
423 percent = cmp * 100 / period;
424 }
425 return mp_obj_new_int(percent);
426 #endif
427 }
428
429 #if !defined(STM32L0)
430
431 // Computes the 8-bit value for the DTG field in the BDTR register.
432 //
433 // 1 tick = 1 count of the timer's clock (source_freq) divided by div.
434 // 0-128 ticks in inrements of 1
435 // 128-256 ticks in increments of 2
436 // 256-512 ticks in increments of 8
437 // 512-1008 ticks in increments of 16
compute_dtg_from_ticks(mp_int_t ticks)438 STATIC uint32_t compute_dtg_from_ticks(mp_int_t ticks) {
439 if (ticks <= 0) {
440 return 0;
441 }
442 if (ticks < 128) {
443 return ticks;
444 }
445 if (ticks < 256) {
446 return 0x80 | ((ticks - 128) / 2);
447 }
448 if (ticks < 512) {
449 return 0xC0 | ((ticks - 256) / 8);
450 }
451 if (ticks < 1008) {
452 return 0xE0 | ((ticks - 512) / 16);
453 }
454 return 0xFF;
455 }
456
457 // Given the 8-bit value stored in the DTG field of the BDTR register, compute
458 // the number of ticks.
compute_ticks_from_dtg(uint32_t dtg)459 STATIC mp_int_t compute_ticks_from_dtg(uint32_t dtg) {
460 if ((dtg & 0x80) == 0) {
461 return dtg & 0x7F;
462 }
463 if ((dtg & 0xC0) == 0x80) {
464 return 128 + ((dtg & 0x3F) * 2);
465 }
466 if ((dtg & 0xE0) == 0xC0) {
467 return 256 + ((dtg & 0x1F) * 8);
468 }
469 return 512 + ((dtg & 0x1F) * 16);
470 }
471
config_deadtime(pyb_timer_obj_t * self,mp_int_t ticks,mp_int_t brk)472 STATIC void config_deadtime(pyb_timer_obj_t *self, mp_int_t ticks, mp_int_t brk) {
473 TIM_BreakDeadTimeConfigTypeDef deadTimeConfig;
474 deadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
475 deadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
476 deadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
477 deadTimeConfig.DeadTime = compute_dtg_from_ticks(ticks);
478 deadTimeConfig.BreakState = brk == BRK_OFF ? TIM_BREAK_DISABLE : TIM_BREAK_ENABLE;
479 deadTimeConfig.BreakPolarity = brk == BRK_LOW ? TIM_BREAKPOLARITY_LOW : TIM_BREAKPOLARITY_HIGH;
480 #if defined(STM32F7) || defined(STM32H7) || defined(STM32L4) || defined(STM32WB)
481 deadTimeConfig.BreakFilter = 0;
482 deadTimeConfig.Break2State = TIM_BREAK_DISABLE;
483 deadTimeConfig.Break2Polarity = TIM_BREAKPOLARITY_LOW;
484 deadTimeConfig.Break2Filter = 0;
485 #endif
486 deadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
487 HAL_TIMEx_ConfigBreakDeadTime(&self->tim, &deadTimeConfig);
488 }
489
490 #endif
491
pyb_timer_get_handle(mp_obj_t timer)492 TIM_HandleTypeDef *pyb_timer_get_handle(mp_obj_t timer) {
493 if (mp_obj_get_type(timer) != &pyb_timer_type) {
494 mp_raise_ValueError(MP_ERROR_TEXT("need a Timer object"));
495 }
496 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(timer);
497 return &self->tim;
498 }
499
pyb_timer_print(const mp_print_t * print,mp_obj_t self_in,mp_print_kind_t kind)500 STATIC void pyb_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
501 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
502
503 if (self->tim.State == HAL_TIM_STATE_RESET) {
504 mp_printf(print, "Timer(%u)", self->tim_id);
505 } else {
506 uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
507 uint32_t period = __HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self);
508 // for efficiency, we compute and print freq as an int (not a float)
509 uint32_t freq = timer_get_source_freq(self->tim_id) / ((prescaler + 1) * (period + 1));
510 mp_printf(print, "Timer(%u, freq=%u, prescaler=%u, period=%u, mode=%s, div=%u",
511 self->tim_id,
512 freq,
513 prescaler,
514 period,
515 self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ? "UP" :
516 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN ? "DOWN" : "CENTER",
517 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV4 ? 4 :
518 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV2 ? 2 : 1);
519
520 #if !defined(STM32L0)
521 #if defined(IS_TIM_ADVANCED_INSTANCE)
522 if (IS_TIM_ADVANCED_INSTANCE(self->tim.Instance))
523 #elif defined(IS_TIM_BREAK_INSTANCE)
524 if (IS_TIM_BREAK_INSTANCE(self->tim.Instance))
525 #else
526 if (0)
527 #endif
528 {
529 mp_printf(print, ", deadtime=%u",
530 compute_ticks_from_dtg(self->tim.Instance->BDTR & TIM_BDTR_DTG));
531 if ((self->tim.Instance->BDTR & TIM_BDTR_BKE) == TIM_BDTR_BKE) {
532 mp_printf(print, ", brk=%s",
533 ((self->tim.Instance->BDTR & TIM_BDTR_BKP) == TIM_BDTR_BKP) ? "BRK_HIGH" : "BRK_LOW");
534 } else {
535 mp_printf(print, ", brk=BRK_OFF");
536 }
537 }
538 #endif
539 mp_print_str(print, ")");
540 }
541 }
542
543 /// \method init(*, freq, prescaler, period)
544 /// Initialise the timer. Initialisation must be either by frequency (in Hz)
545 /// or by prescaler and period:
546 ///
547 /// tim.init(freq=100) # set the timer to trigger at 100Hz
548 /// tim.init(prescaler=83, period=999) # set the prescaler and period directly
549 ///
550 /// Keyword arguments:
551 ///
552 /// - `freq` - specifies the periodic frequency of the timer. You migh also
553 /// view this as the frequency with which the timer goes through
554 /// one complete cycle.
555 ///
556 /// - `prescaler` [0-0xffff] - specifies the value to be loaded into the
557 /// timer's Prescaler Register (PSC). The timer clock source is divided by
558 /// (`prescaler + 1`) to arrive at the timer clock. Timers 2-7 and 12-14
559 /// have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
560 /// have a clock source of 168 MHz (pyb.freq()[3] * 2).
561 ///
562 /// - `period` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5.
563 /// Specifies the value to be loaded into the timer's AutoReload
564 /// Register (ARR). This determines the period of the timer (i.e. when the
565 /// counter cycles). The timer counter will roll-over after `period + 1`
566 /// timer clock cycles.
567 ///
568 /// - `mode` can be one of:
569 /// - `Timer.UP` - configures the timer to count from 0 to ARR (default)
570 /// - `Timer.DOWN` - configures the timer to count from ARR down to 0.
571 /// - `Timer.CENTER` - confgures the timer to count from 0 to ARR and
572 /// then back down to 0.
573 ///
574 /// - `div` can be one of 1, 2, or 4. Divides the timer clock to determine
575 /// the sampling clock used by the digital filters.
576 ///
577 /// - `callback` - as per Timer.callback()
578 ///
579 /// - `deadtime` - specifies the amount of "dead" or inactive time between
580 /// transitions on complimentary channels (both channels will be inactive)
581 /// for this time). `deadtime` may be an integer between 0 and 1008, with
582 /// the following restrictions: 0-128 in steps of 1. 128-256 in steps of
583 /// 2, 256-512 in steps of 8, and 512-1008 in steps of 16. `deadime`
584 /// measures ticks of `source_freq` divided by `div` clock ticks.
585 /// `deadtime` is only available on timers 1 and 8.
586 ///
587 /// - `brk` - specifies if the break mode is used to kill the output of
588 /// the PWM when the BRK_IN input is asserted. The polarity set how the
589 /// BRK_IN input is triggered. It can be set to `BRK_OFF`, `BRK_LOW`
590 /// and `BRK_HIGH`.
591 ///
592 ///
593 /// You must either specify freq or both of period and prescaler.
pyb_timer_init_helper(pyb_timer_obj_t * self,size_t n_args,const mp_obj_t * pos_args,mp_map_t * kw_args)594 STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
595 enum { ARG_freq, ARG_prescaler, ARG_period, ARG_tick_hz, ARG_mode, ARG_div, ARG_callback, ARG_deadtime, ARG_brk };
596 static const mp_arg_t allowed_args[] = {
597 { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
598 { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
599 { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
600 { MP_QSTR_tick_hz, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
601 { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_COUNTERMODE_UP} },
602 { MP_QSTR_div, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
603 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
604 { MP_QSTR_deadtime, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
605 { MP_QSTR_brk, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = BRK_OFF} },
606 };
607
608 // parse args
609 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
610 mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
611
612 // set the TIM configuration values
613 TIM_Base_InitTypeDef *init = &self->tim.Init;
614
615 if (args[ARG_freq].u_obj != mp_const_none) {
616 // set prescaler and period from desired frequency
617 init->Prescaler = compute_prescaler_period_from_freq(self, args[ARG_freq].u_obj, &init->Period);
618 } else if (args[ARG_prescaler].u_int != 0xffffffff && args[ARG_period].u_int != 0xffffffff) {
619 // set prescaler and period directly
620 init->Prescaler = args[ARG_prescaler].u_int;
621 init->Period = args[ARG_period].u_int;
622 } else if (args[ARG_period].u_int != 0xffffffff) {
623 // set prescaler and period from desired period and tick_hz scale
624 init->Prescaler = compute_prescaler_period_from_t(self, args[ARG_period].u_int, args[ARG_tick_hz].u_int, &init->Period);
625 } else {
626 mp_raise_TypeError(MP_ERROR_TEXT("must specify either freq, period, or prescaler and period"));
627 }
628
629 init->CounterMode = args[ARG_mode].u_int;
630 if (!IS_TIM_COUNTER_MODE(init->CounterMode)) {
631 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("invalid mode (%d)"), init->CounterMode);
632 }
633
634 init->ClockDivision = args[ARG_div].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
635 args[ARG_div].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
636 TIM_CLOCKDIVISION_DIV1;
637
638 #if !defined(STM32L0)
639 init->RepetitionCounter = 0;
640 #endif
641
642 // enable TIM clock
643 switch (self->tim_id) {
644 #if defined(TIM1)
645 case 1:
646 __HAL_RCC_TIM1_CLK_ENABLE();
647 break;
648 #endif
649 case 2:
650 __HAL_RCC_TIM2_CLK_ENABLE();
651 break;
652 #if defined(TIM3)
653 case 3:
654 __HAL_RCC_TIM3_CLK_ENABLE();
655 break;
656 #endif
657 #if defined(TIM4)
658 case 4:
659 __HAL_RCC_TIM4_CLK_ENABLE();
660 break;
661 #endif
662 #if defined(TIM5)
663 case 5:
664 __HAL_RCC_TIM5_CLK_ENABLE();
665 break;
666 #endif
667 #if defined(TIM6)
668 case 6:
669 __HAL_RCC_TIM6_CLK_ENABLE();
670 break;
671 #endif
672 #if defined(TIM7)
673 case 7:
674 __HAL_RCC_TIM7_CLK_ENABLE();
675 break;
676 #endif
677 #if defined(TIM8)
678 case 8:
679 __HAL_RCC_TIM8_CLK_ENABLE();
680 break;
681 #endif
682 #if defined(TIM9)
683 case 9:
684 __HAL_RCC_TIM9_CLK_ENABLE();
685 break;
686 #endif
687 #if defined(TIM10)
688 case 10:
689 __HAL_RCC_TIM10_CLK_ENABLE();
690 break;
691 #endif
692 #if defined(TIM11)
693 case 11:
694 __HAL_RCC_TIM11_CLK_ENABLE();
695 break;
696 #endif
697 #if defined(TIM12)
698 case 12:
699 __HAL_RCC_TIM12_CLK_ENABLE();
700 break;
701 #endif
702 #if defined(TIM13)
703 case 13:
704 __HAL_RCC_TIM13_CLK_ENABLE();
705 break;
706 #endif
707 #if defined(TIM14)
708 case 14:
709 __HAL_RCC_TIM14_CLK_ENABLE();
710 break;
711 #endif
712 #if defined(TIM15)
713 case 15:
714 __HAL_RCC_TIM15_CLK_ENABLE();
715 break;
716 #endif
717 #if defined(TIM16)
718 case 16:
719 __HAL_RCC_TIM16_CLK_ENABLE();
720 break;
721 #endif
722 #if defined(TIM17)
723 case 17:
724 __HAL_RCC_TIM17_CLK_ENABLE();
725 break;
726 #endif
727 #if defined(TIM18)
728 case 18:
729 __HAL_RCC_TIM18_CLK_ENABLE();
730 break;
731 #endif
732 #if defined(TIM19)
733 case 19:
734 __HAL_RCC_TIM19_CLK_ENABLE();
735 break;
736 #endif
737 #if defined(TIM20)
738 case 20:
739 __HAL_RCC_TIM20_CLK_ENABLE();
740 break;
741 #endif
742 #if defined(TIM21)
743 case 21:
744 __HAL_RCC_TIM21_CLK_ENABLE();
745 break;
746 #endif
747 #if defined(TIM22)
748 case 22:
749 __HAL_RCC_TIM22_CLK_ENABLE();
750 break;
751 #endif
752 }
753
754 // set IRQ priority (if not a special timer)
755 if (self->tim_id != 5) {
756 NVIC_SetPriority(IRQn_NONNEG(self->irqn), IRQ_PRI_TIMX);
757 if (self->tim_id == 1) {
758 #if defined(TIM1)
759 NVIC_SetPriority(TIM1_CC_IRQn, IRQ_PRI_TIMX);
760 #endif
761 } else if (self->tim_id == 8) {
762 #if defined(TIM8)
763 NVIC_SetPriority(TIM8_CC_IRQn, IRQ_PRI_TIMX);
764 #endif
765 }
766 }
767
768 // init TIM
769 HAL_TIM_Base_Init(&self->tim);
770 #if !defined(STM32L0)
771 #if defined(IS_TIM_ADVANCED_INSTANCE)
772 if (IS_TIM_ADVANCED_INSTANCE(self->tim.Instance))
773 #elif defined(IS_TIM_BREAK_INSTANCE)
774 if (IS_TIM_BREAK_INSTANCE(self->tim.Instance))
775 #else
776 if (0)
777 #endif
778 {
779 config_deadtime(self, args[ARG_deadtime].u_int, args[ARG_brk].u_int);
780 }
781 #endif
782
783 // Enable ARPE so that the auto-reload register is buffered.
784 // This allows to smoothly change the frequency of the timer.
785 self->tim.Instance->CR1 |= TIM_CR1_ARPE;
786
787 // Start the timer running
788 if (args[ARG_callback].u_obj == mp_const_none) {
789 HAL_TIM_Base_Start(&self->tim);
790 } else {
791 pyb_timer_callback(MP_OBJ_FROM_PTR(self), args[ARG_callback].u_obj);
792 }
793
794 return mp_const_none;
795 }
796
797 // This table encodes the timer instance and irq number (for the update irq).
798 // It assumes that timer instance pointer has the lower 8 bits cleared.
799 #define TIM_ENTRY(id, irq) [id - 1] = (uint32_t)TIM##id | irq
800 STATIC const uint32_t tim_instance_table[MICROPY_HW_MAX_TIMER] = {
801 #if defined(TIM1)
802 #if defined(STM32F0)
803 TIM_ENTRY(1, TIM1_BRK_UP_TRG_COM_IRQn),
804 #elif defined(STM32F4) || defined(STM32F7)
805 TIM_ENTRY(1, TIM1_UP_TIM10_IRQn),
806 #elif defined(STM32H7)
807 TIM_ENTRY(1, TIM1_UP_IRQn),
808 #elif defined(STM32L4) || defined(STM32WB)
809 TIM_ENTRY(1, TIM1_UP_TIM16_IRQn),
810 #endif
811 #endif
812 TIM_ENTRY(2, TIM2_IRQn),
813 #if defined(TIM3)
814 TIM_ENTRY(3, TIM3_IRQn),
815 #endif
816 #if defined(TIM4)
817 TIM_ENTRY(4, TIM4_IRQn),
818 #endif
819 #if defined(TIM5)
820 TIM_ENTRY(5, TIM5_IRQn),
821 #endif
822 #if defined(TIM6)
823 #if defined(STM32F412Zx)
824 TIM_ENTRY(6, TIM6_IRQn),
825 #else
826 TIM_ENTRY(6, TIM6_DAC_IRQn),
827 #endif
828 #endif
829 #if defined(TIM7)
830 TIM_ENTRY(7, TIM7_IRQn),
831 #endif
832 #if defined(TIM8)
833 #if defined(STM32F4) || defined(STM32F7) || defined(STM32H7)
834 TIM_ENTRY(8, TIM8_UP_TIM13_IRQn),
835 #elif defined(STM32L4)
836 TIM_ENTRY(8, TIM8_UP_IRQn),
837 #endif
838 #endif
839 #if defined(TIM9)
840 TIM_ENTRY(9, TIM1_BRK_TIM9_IRQn),
841 #endif
842 #if defined(TIM10)
843 TIM_ENTRY(10, TIM1_UP_TIM10_IRQn),
844 #endif
845 #if defined(TIM11)
846 TIM_ENTRY(11, TIM1_TRG_COM_TIM11_IRQn),
847 #endif
848 #if defined(TIM12)
849 TIM_ENTRY(12, TIM8_BRK_TIM12_IRQn),
850 #endif
851 #if defined(TIM13)
852 TIM_ENTRY(13, TIM8_UP_TIM13_IRQn),
853 #endif
854 #if defined(STM32F0)
855 TIM_ENTRY(14, TIM14_IRQn),
856 #elif defined(TIM14)
857 TIM_ENTRY(14, TIM8_TRG_COM_TIM14_IRQn),
858 #endif
859 #if defined(TIM15)
860 #if defined(STM32F0) || defined(STM32H7)
861 TIM_ENTRY(15, TIM15_IRQn),
862 #else
863 TIM_ENTRY(15, TIM1_BRK_TIM15_IRQn),
864 #endif
865 #endif
866 #if defined(TIM16)
867 #if defined(STM32F0) || defined(STM32H7)
868 TIM_ENTRY(16, TIM16_IRQn),
869 #else
870 TIM_ENTRY(16, TIM1_UP_TIM16_IRQn),
871 #endif
872 #endif
873 #if defined(TIM17)
874 #if defined(STM32F0) || defined(STM32H7)
875 TIM_ENTRY(17, TIM17_IRQn),
876 #else
877 TIM_ENTRY(17, TIM1_TRG_COM_TIM17_IRQn),
878 #endif
879 #endif
880 };
881 #undef TIM_ENTRY
882
883 /// \classmethod \constructor(id, ...)
884 /// Construct a new timer object of the given id. If additional
885 /// arguments are given, then the timer is initialised by `init(...)`.
886 /// `id` can be 1 to 14, excluding 3.
pyb_timer_make_new(const mp_obj_type_t * type,size_t n_args,size_t n_kw,const mp_obj_t * args)887 STATIC mp_obj_t pyb_timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
888 // check arguments
889 mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
890
891 // get the timer id
892 mp_int_t tim_id = mp_obj_get_int(args[0]);
893
894 // check if the timer exists
895 if (tim_id <= 0 || tim_id > MICROPY_HW_MAX_TIMER || tim_instance_table[tim_id - 1] == 0) {
896 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("Timer(%d) doesn't exist"), tim_id);
897 }
898
899 // check if the timer is reserved for system use or not
900 if (MICROPY_HW_TIM_IS_RESERVED(tim_id)) {
901 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("Timer(%d) is reserved"), tim_id);
902 }
903
904 pyb_timer_obj_t *tim;
905 if (MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1] == NULL) {
906 // create new Timer object
907 tim = m_new_obj(pyb_timer_obj_t);
908 memset(tim, 0, sizeof(*tim));
909 tim->base.type = &pyb_timer_type;
910 tim->tim_id = tim_id;
911 tim->is_32bit = tim_id == 2 || tim_id == 5;
912 tim->callback = mp_const_none;
913 uint32_t ti = tim_instance_table[tim_id - 1];
914 tim->tim.Instance = (TIM_TypeDef *)(ti & 0xffffff00);
915 tim->irqn = ti & 0xff;
916 MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1] = tim;
917 } else {
918 // reference existing Timer object
919 tim = MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1];
920 }
921
922 if (n_args > 1 || n_kw > 0) {
923 // start the peripheral
924 mp_map_t kw_args;
925 mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
926 pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args);
927 }
928
929 return MP_OBJ_FROM_PTR(tim);
930 }
931
pyb_timer_init(size_t n_args,const mp_obj_t * args,mp_map_t * kw_args)932 STATIC mp_obj_t pyb_timer_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
933 return pyb_timer_init_helper(MP_OBJ_TO_PTR(args[0]), n_args - 1, args + 1, kw_args);
934 }
935 STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
936
937 // timer.deinit()
pyb_timer_deinit(mp_obj_t self_in)938 STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
939 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
940
941 // Disable the base interrupt
942 pyb_timer_callback(self_in, mp_const_none);
943
944 pyb_timer_channel_obj_t *chan = self->channel;
945 self->channel = NULL;
946
947 // Disable the channel interrupts
948 while (chan != NULL) {
949 pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), mp_const_none);
950 pyb_timer_channel_obj_t *prev_chan = chan;
951 chan = chan->next;
952 prev_chan->next = NULL;
953 }
954
955 self->tim.State = HAL_TIM_STATE_RESET;
956 self->tim.Instance->CCER = 0x0000; // disable all capture/compare outputs
957 self->tim.Instance->CR1 = 0x0000; // disable the timer and reset its state
958
959 return mp_const_none;
960 }
961 STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);
962
963 /// \method channel(channel, mode, ...)
964 ///
965 /// If only a channel number is passed, then a previously initialized channel
966 /// object is returned (or `None` if there is no previous channel).
967 ///
968 /// Othwerwise, a TimerChannel object is initialized and returned.
969 ///
970 /// Each channel can be configured to perform pwm, output compare, or
971 /// input capture. All channels share the same underlying timer, which means
972 /// that they share the same timer clock.
973 ///
974 /// Keyword arguments:
975 ///
976 /// - `mode` can be one of:
977 /// - `Timer.PWM` - configure the timer in PWM mode (active high).
978 /// - `Timer.PWM_INVERTED` - configure the timer in PWM mode (active low).
979 /// - `Timer.OC_TIMING` - indicates that no pin is driven.
980 /// - `Timer.OC_ACTIVE` - the pin will be made active when a compare
981 /// match occurs (active is determined by polarity)
982 /// - `Timer.OC_INACTIVE` - the pin will be made inactive when a compare
983 /// match occurs.
984 /// - `Timer.OC_TOGGLE` - the pin will be toggled when an compare match occurs.
985 /// - `Timer.OC_FORCED_ACTIVE` - the pin is forced active (compare match is ignored).
986 /// - `Timer.OC_FORCED_INACTIVE` - the pin is forced inactive (compare match is ignored).
987 /// - `Timer.IC` - configure the timer in Input Capture mode.
988 /// - `Timer.ENC_A` --- configure the timer in Encoder mode. The counter only changes when CH1 changes.
989 /// - `Timer.ENC_B` --- configure the timer in Encoder mode. The counter only changes when CH2 changes.
990 /// - `Timer.ENC_AB` --- configure the timer in Encoder mode. The counter changes when CH1 or CH2 changes.
991 ///
992 /// - `callback` - as per TimerChannel.callback()
993 ///
994 /// - `pin` None (the default) or a Pin object. If specified (and not None)
995 /// this will cause the alternate function of the the indicated pin
996 /// to be configured for this timer channel. An error will be raised if
997 /// the pin doesn't support any alternate functions for this timer channel.
998 ///
999 /// Keyword arguments for Timer.PWM modes:
1000 ///
1001 /// - `pulse_width` - determines the initial pulse width value to use.
1002 /// - `pulse_width_percent` - determines the initial pulse width percentage to use.
1003 ///
1004 /// Keyword arguments for Timer.OC modes:
1005 ///
1006 /// - `compare` - determines the initial value of the compare register.
1007 ///
1008 /// - `polarity` can be one of:
1009 /// - `Timer.HIGH` - output is active high
1010 /// - `Timer.LOW` - output is acive low
1011 ///
1012 /// Optional keyword arguments for Timer.IC modes:
1013 ///
1014 /// - `polarity` can be one of:
1015 /// - `Timer.RISING` - captures on rising edge.
1016 /// - `Timer.FALLING` - captures on falling edge.
1017 /// - `Timer.BOTH` - captures on both edges.
1018 ///
1019 /// Note that capture only works on the primary channel, and not on the
1020 /// complimentary channels.
1021 ///
1022 /// Notes for Timer.ENC modes:
1023 ///
1024 /// - Requires 2 pins, so one or both pins will need to be configured to use
1025 /// the appropriate timer AF using the Pin API.
1026 /// - Read the encoder value using the timer.counter() method.
1027 /// - Only works on CH1 and CH2 (and not on CH1N or CH2N)
1028 /// - The channel number is ignored when setting the encoder mode.
1029 ///
1030 /// PWM Example:
1031 ///
1032 /// timer = pyb.Timer(2, freq=1000)
1033 /// ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
1034 /// ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
pyb_timer_channel(size_t n_args,const mp_obj_t * pos_args,mp_map_t * kw_args)1035 STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
1036 static const mp_arg_t allowed_args[] = {
1037 { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
1038 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
1039 { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
1040 { MP_QSTR_pulse_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
1041 { MP_QSTR_pulse_width_percent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
1042 { MP_QSTR_compare, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
1043 { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
1044 };
1045
1046 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
1047 mp_int_t channel = mp_obj_get_int(pos_args[1]);
1048
1049 if (channel < 1 || channel > 4) {
1050 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("invalid channel (%d)"), channel);
1051 }
1052
1053 pyb_timer_channel_obj_t *chan = self->channel;
1054 pyb_timer_channel_obj_t *prev_chan = NULL;
1055
1056 while (chan != NULL) {
1057 if (chan->channel == channel) {
1058 break;
1059 }
1060 prev_chan = chan;
1061 chan = chan->next;
1062 }
1063
1064 // If only the channel number is given return the previously allocated
1065 // channel (or None if no previous channel).
1066 if (n_args == 2 && kw_args->used == 0) {
1067 if (chan) {
1068 return MP_OBJ_FROM_PTR(chan);
1069 }
1070 return mp_const_none;
1071 }
1072
1073 // If there was already a channel, then remove it from the list. Note that
1074 // the order we do things here is important so as to appear atomic to
1075 // the IRQ handler.
1076 if (chan) {
1077 // Turn off any IRQ associated with the channel.
1078 pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), mp_const_none);
1079
1080 // Unlink the channel from the list.
1081 if (prev_chan) {
1082 prev_chan->next = chan->next;
1083 }
1084 self->channel = chan->next;
1085 chan->next = NULL;
1086 }
1087
1088 // Allocate and initialize a new channel
1089 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
1090 mp_arg_parse_all(n_args - 2, pos_args + 2, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
1091
1092 chan = m_new_obj(pyb_timer_channel_obj_t);
1093 memset(chan, 0, sizeof(*chan));
1094 chan->base.type = &pyb_timer_channel_type;
1095 chan->timer = self;
1096 chan->channel = channel;
1097 chan->mode = args[0].u_int;
1098 chan->callback = args[1].u_obj;
1099
1100 mp_obj_t pin_obj = args[2].u_obj;
1101 if (pin_obj != mp_const_none) {
1102 if (!mp_obj_is_type(pin_obj, &pin_type)) {
1103 mp_raise_ValueError(MP_ERROR_TEXT("pin argument needs to be be a Pin type"));
1104 }
1105 const pin_obj_t *pin = MP_OBJ_TO_PTR(pin_obj);
1106 const pin_af_obj_t *af = pin_find_af(pin, AF_FN_TIM, self->tim_id);
1107 if (af == NULL) {
1108 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("Pin(%q) doesn't have an af for Timer(%d)"), pin->name, self->tim_id);
1109 }
1110 // pin.init(mode=AF_PP, af=idx)
1111 const mp_obj_t args2[6] = {
1112 MP_OBJ_FROM_PTR(&pin_init_obj),
1113 pin_obj,
1114 MP_OBJ_NEW_QSTR(MP_QSTR_mode), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP),
1115 MP_OBJ_NEW_QSTR(MP_QSTR_af), MP_OBJ_NEW_SMALL_INT(af->idx)
1116 };
1117 mp_call_method_n_kw(0, 2, args2);
1118 }
1119
1120 // Link the channel to the timer before we turn the channel on.
1121 // Note that this needs to appear atomic to the IRQ handler (the write
1122 // to self->channel is atomic, so we're good, but I thought I'd mention
1123 // in case this was ever changed in the future).
1124 chan->next = self->channel;
1125 self->channel = chan;
1126
1127 switch (chan->mode) {
1128
1129 case CHANNEL_MODE_PWM_NORMAL:
1130 case CHANNEL_MODE_PWM_INVERTED: {
1131 TIM_OC_InitTypeDef oc_config;
1132 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
1133 if (args[4].u_obj != mp_const_none) {
1134 // pulse width percent given
1135 uint32_t period = compute_period(self);
1136 oc_config.Pulse = compute_pwm_value_from_percent(period, args[4].u_obj);
1137 } else {
1138 // use absolute pulse width value (defaults to 0 if nothing given)
1139 oc_config.Pulse = args[3].u_int;
1140 }
1141 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
1142 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
1143 #if !defined(STM32L0)
1144 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
1145 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
1146 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
1147 #endif
1148
1149 HAL_TIM_PWM_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
1150 if (chan->callback == mp_const_none) {
1151 HAL_TIM_PWM_Start(&self->tim, TIMER_CHANNEL(chan));
1152 } else {
1153 pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), chan->callback);
1154 }
1155 #if !defined(STM32L0)
1156 // Start the complimentary channel too (if its supported)
1157 if (IS_TIM_CCXN_INSTANCE(self->tim.Instance, TIMER_CHANNEL(chan))) {
1158 HAL_TIMEx_PWMN_Start(&self->tim, TIMER_CHANNEL(chan));
1159 }
1160 #endif
1161 break;
1162 }
1163
1164 case CHANNEL_MODE_OC_TIMING:
1165 case CHANNEL_MODE_OC_ACTIVE:
1166 case CHANNEL_MODE_OC_INACTIVE:
1167 case CHANNEL_MODE_OC_TOGGLE:
1168 case CHANNEL_MODE_OC_FORCED_ACTIVE:
1169 case CHANNEL_MODE_OC_FORCED_INACTIVE: {
1170 TIM_OC_InitTypeDef oc_config;
1171 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
1172 oc_config.Pulse = args[5].u_int;
1173 oc_config.OCPolarity = args[6].u_int;
1174 if (oc_config.OCPolarity == 0xffffffff) {
1175 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
1176 }
1177 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
1178 #if !defined(STM32L0)
1179 if (oc_config.OCPolarity == TIM_OCPOLARITY_HIGH) {
1180 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
1181 } else {
1182 oc_config.OCNPolarity = TIM_OCNPOLARITY_LOW;
1183 }
1184 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
1185 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
1186 #endif
1187
1188 if (!IS_TIM_OC_POLARITY(oc_config.OCPolarity)) {
1189 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("invalid polarity (%d)"), oc_config.OCPolarity);
1190 }
1191 HAL_TIM_OC_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
1192 if (chan->callback == mp_const_none) {
1193 HAL_TIM_OC_Start(&self->tim, TIMER_CHANNEL(chan));
1194 } else {
1195 pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), chan->callback);
1196 }
1197 #if !defined(STM32L0)
1198 // Start the complimentary channel too (if its supported)
1199 if (IS_TIM_CCXN_INSTANCE(self->tim.Instance, TIMER_CHANNEL(chan))) {
1200 HAL_TIMEx_OCN_Start(&self->tim, TIMER_CHANNEL(chan));
1201 }
1202 #endif
1203 break;
1204 }
1205
1206 case CHANNEL_MODE_IC: {
1207 TIM_IC_InitTypeDef ic_config;
1208
1209 ic_config.ICPolarity = args[6].u_int;
1210 if (ic_config.ICPolarity == 0xffffffff) {
1211 ic_config.ICPolarity = TIM_ICPOLARITY_RISING;
1212 }
1213 ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
1214 ic_config.ICPrescaler = TIM_ICPSC_DIV1;
1215 ic_config.ICFilter = 0;
1216
1217 if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) {
1218 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("invalid polarity (%d)"), ic_config.ICPolarity);
1219 }
1220 HAL_TIM_IC_ConfigChannel(&self->tim, &ic_config, TIMER_CHANNEL(chan));
1221 if (chan->callback == mp_const_none) {
1222 HAL_TIM_IC_Start(&self->tim, TIMER_CHANNEL(chan));
1223 } else {
1224 pyb_timer_channel_callback(MP_OBJ_FROM_PTR(chan), chan->callback);
1225 }
1226 break;
1227 }
1228
1229 case CHANNEL_MODE_ENC_A:
1230 case CHANNEL_MODE_ENC_B:
1231 case CHANNEL_MODE_ENC_AB: {
1232 TIM_Encoder_InitTypeDef enc_config;
1233
1234 enc_config.EncoderMode = channel_mode_info[chan->mode].oc_mode;
1235 enc_config.IC1Polarity = args[6].u_int;
1236 if (enc_config.IC1Polarity == 0xffffffff) {
1237 enc_config.IC1Polarity = TIM_ICPOLARITY_RISING;
1238 }
1239 enc_config.IC2Polarity = enc_config.IC1Polarity;
1240 enc_config.IC1Selection = TIM_ICSELECTION_DIRECTTI;
1241 enc_config.IC2Selection = TIM_ICSELECTION_DIRECTTI;
1242 enc_config.IC1Prescaler = TIM_ICPSC_DIV1;
1243 enc_config.IC2Prescaler = TIM_ICPSC_DIV1;
1244 enc_config.IC1Filter = 0;
1245 enc_config.IC2Filter = 0;
1246
1247 if (!IS_TIM_IC_POLARITY(enc_config.IC1Polarity)) {
1248 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("invalid polarity (%d)"), enc_config.IC1Polarity);
1249 }
1250 // Only Timers 1, 2, 3, 4, 5, and 8 support encoder mode
1251 if (
1252 #if defined(TIM1)
1253 self->tim.Instance != TIM1
1254 &&
1255 #endif
1256 self->tim.Instance != TIM2
1257 #if defined(TIM3)
1258 && self->tim.Instance != TIM3
1259 #endif
1260 #if defined(TIM4)
1261 && self->tim.Instance != TIM4
1262 #endif
1263 #if defined(TIM5)
1264 && self->tim.Instance != TIM5
1265 #endif
1266 #if defined(TIM8)
1267 && self->tim.Instance != TIM8
1268 #endif
1269 ) {
1270 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("encoder not supported on timer %d"), self->tim_id);
1271 }
1272
1273 // Disable & clear the timer interrupt so that we don't trigger
1274 // an interrupt by initializing the timer.
1275 __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
1276 HAL_TIM_Encoder_Init(&self->tim, &enc_config);
1277 __HAL_TIM_SET_COUNTER(&self->tim, 0);
1278 if (self->callback != mp_const_none) {
1279 __HAL_TIM_CLEAR_FLAG(&self->tim, TIM_IT_UPDATE);
1280 __HAL_TIM_ENABLE_IT(&self->tim, TIM_IT_UPDATE);
1281 }
1282 HAL_TIM_Encoder_Start(&self->tim, TIM_CHANNEL_ALL);
1283 break;
1284 }
1285
1286 default:
1287 mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("invalid mode (%d)"), chan->mode);
1288 }
1289
1290 return MP_OBJ_FROM_PTR(chan);
1291 }
1292 STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
1293
1294 /// \method counter([value])
1295 /// Get or set the timer counter.
pyb_timer_counter(size_t n_args,const mp_obj_t * args)1296 STATIC mp_obj_t pyb_timer_counter(size_t n_args, const mp_obj_t *args) {
1297 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);
1298 if (n_args == 1) {
1299 // get
1300 return mp_obj_new_int(self->tim.Instance->CNT);
1301 } else {
1302 // set
1303 __HAL_TIM_SET_COUNTER(&self->tim, mp_obj_get_int(args[1]));
1304 return mp_const_none;
1305 }
1306 }
1307 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_counter_obj, 1, 2, pyb_timer_counter);
1308
1309 /// \method source_freq()
1310 /// Get the frequency of the source of the timer.
pyb_timer_source_freq(mp_obj_t self_in)1311 STATIC mp_obj_t pyb_timer_source_freq(mp_obj_t self_in) {
1312 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
1313 uint32_t source_freq = timer_get_source_freq(self->tim_id);
1314 return mp_obj_new_int(source_freq);
1315 }
1316 STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_source_freq_obj, pyb_timer_source_freq);
1317
1318 /// \method freq([value])
1319 /// Get or set the frequency for the timer (changes prescaler and period if set).
pyb_timer_freq(size_t n_args,const mp_obj_t * args)1320 STATIC mp_obj_t pyb_timer_freq(size_t n_args, const mp_obj_t *args) {
1321 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);
1322 if (n_args == 1) {
1323 // get
1324 uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
1325 uint32_t period = __HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self);
1326 uint32_t source_freq = timer_get_source_freq(self->tim_id);
1327 uint32_t divide_a = prescaler + 1;
1328 uint32_t divide_b = period + 1;
1329 #if MICROPY_PY_BUILTINS_FLOAT
1330 if (source_freq % divide_a != 0) {
1331 return mp_obj_new_float((mp_float_t)source_freq / (mp_float_t)divide_a / (mp_float_t)divide_b);
1332 }
1333 source_freq /= divide_a;
1334 if (source_freq % divide_b != 0) {
1335 return mp_obj_new_float((mp_float_t)source_freq / (mp_float_t)divide_b);
1336 } else {
1337 return mp_obj_new_int(source_freq / divide_b);
1338 }
1339 #else
1340 return mp_obj_new_int(source_freq / divide_a / divide_b);
1341 #endif
1342 } else {
1343 // set
1344 uint32_t period;
1345 uint32_t prescaler = compute_prescaler_period_from_freq(self, args[1], &period);
1346 self->tim.Instance->PSC = prescaler;
1347 __HAL_TIM_SET_AUTORELOAD(&self->tim, period);
1348 return mp_const_none;
1349 }
1350 }
1351 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_freq_obj, 1, 2, pyb_timer_freq);
1352
1353 /// \method prescaler([value])
1354 /// Get or set the prescaler for the timer.
pyb_timer_prescaler(size_t n_args,const mp_obj_t * args)1355 STATIC mp_obj_t pyb_timer_prescaler(size_t n_args, const mp_obj_t *args) {
1356 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);
1357 if (n_args == 1) {
1358 // get
1359 return mp_obj_new_int(self->tim.Instance->PSC & 0xffff);
1360 } else {
1361 // set
1362 self->tim.Instance->PSC = mp_obj_get_int(args[1]) & 0xffff;
1363 return mp_const_none;
1364 }
1365 }
1366 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);
1367
1368 /// \method period([value])
1369 /// Get or set the period of the timer.
pyb_timer_period(size_t n_args,const mp_obj_t * args)1370 STATIC mp_obj_t pyb_timer_period(size_t n_args, const mp_obj_t *args) {
1371 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(args[0]);
1372 if (n_args == 1) {
1373 // get
1374 return mp_obj_new_int(__HAL_TIM_GET_AUTORELOAD(&self->tim) & TIMER_CNT_MASK(self));
1375 } else {
1376 // set
1377 __HAL_TIM_SET_AUTORELOAD(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
1378 return mp_const_none;
1379 }
1380 }
1381 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
1382
1383 /// \method callback(fun)
1384 /// Set the function to be called when the timer triggers.
1385 /// `fun` is passed 1 argument, the timer object.
1386 /// If `fun` is `None` then the callback will be disabled.
pyb_timer_callback(mp_obj_t self_in,mp_obj_t callback)1387 STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
1388 pyb_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
1389 if (callback == mp_const_none) {
1390 // stop interrupt (but not timer)
1391 __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
1392 self->callback = mp_const_none;
1393 } else if (mp_obj_is_callable(callback)) {
1394 __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
1395 self->callback = callback;
1396 // start timer, so that it interrupts on overflow, but clear any
1397 // pending interrupts which may have been set by initializing it.
1398 __HAL_TIM_CLEAR_FLAG(&self->tim, TIM_IT_UPDATE);
1399 HAL_TIM_Base_Start_IT(&self->tim); // This will re-enable the IRQ
1400 HAL_NVIC_EnableIRQ(self->irqn);
1401 } else {
1402 mp_raise_ValueError(MP_ERROR_TEXT("callback must be None or a callable object"));
1403 }
1404 return mp_const_none;
1405 }
1406 STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);
1407
1408 STATIC const mp_rom_map_elem_t pyb_timer_locals_dict_table[] = {
1409 // instance methods
1410 { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_timer_init_obj) },
1411 { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_timer_deinit_obj) },
1412 { MP_ROM_QSTR(MP_QSTR_channel), MP_ROM_PTR(&pyb_timer_channel_obj) },
1413 { MP_ROM_QSTR(MP_QSTR_counter), MP_ROM_PTR(&pyb_timer_counter_obj) },
1414 { MP_ROM_QSTR(MP_QSTR_source_freq), MP_ROM_PTR(&pyb_timer_source_freq_obj) },
1415 { MP_ROM_QSTR(MP_QSTR_freq), MP_ROM_PTR(&pyb_timer_freq_obj) },
1416 { MP_ROM_QSTR(MP_QSTR_prescaler), MP_ROM_PTR(&pyb_timer_prescaler_obj) },
1417 { MP_ROM_QSTR(MP_QSTR_period), MP_ROM_PTR(&pyb_timer_period_obj) },
1418 { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_timer_callback_obj) },
1419 { MP_ROM_QSTR(MP_QSTR_UP), MP_ROM_INT(TIM_COUNTERMODE_UP) },
1420 { MP_ROM_QSTR(MP_QSTR_DOWN), MP_ROM_INT(TIM_COUNTERMODE_DOWN) },
1421 { MP_ROM_QSTR(MP_QSTR_CENTER), MP_ROM_INT(TIM_COUNTERMODE_CENTERALIGNED1) },
1422 { MP_ROM_QSTR(MP_QSTR_PWM), MP_ROM_INT(CHANNEL_MODE_PWM_NORMAL) },
1423 { MP_ROM_QSTR(MP_QSTR_PWM_INVERTED), MP_ROM_INT(CHANNEL_MODE_PWM_INVERTED) },
1424 { MP_ROM_QSTR(MP_QSTR_OC_TIMING), MP_ROM_INT(CHANNEL_MODE_OC_TIMING) },
1425 { MP_ROM_QSTR(MP_QSTR_OC_ACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_ACTIVE) },
1426 { MP_ROM_QSTR(MP_QSTR_OC_INACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_INACTIVE) },
1427 { MP_ROM_QSTR(MP_QSTR_OC_TOGGLE), MP_ROM_INT(CHANNEL_MODE_OC_TOGGLE) },
1428 { MP_ROM_QSTR(MP_QSTR_OC_FORCED_ACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_FORCED_ACTIVE) },
1429 { MP_ROM_QSTR(MP_QSTR_OC_FORCED_INACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_FORCED_INACTIVE) },
1430 { MP_ROM_QSTR(MP_QSTR_IC), MP_ROM_INT(CHANNEL_MODE_IC) },
1431 { MP_ROM_QSTR(MP_QSTR_ENC_A), MP_ROM_INT(CHANNEL_MODE_ENC_A) },
1432 { MP_ROM_QSTR(MP_QSTR_ENC_B), MP_ROM_INT(CHANNEL_MODE_ENC_B) },
1433 { MP_ROM_QSTR(MP_QSTR_ENC_AB), MP_ROM_INT(CHANNEL_MODE_ENC_AB) },
1434 { MP_ROM_QSTR(MP_QSTR_HIGH), MP_ROM_INT(TIM_OCPOLARITY_HIGH) },
1435 { MP_ROM_QSTR(MP_QSTR_LOW), MP_ROM_INT(TIM_OCPOLARITY_LOW) },
1436 { MP_ROM_QSTR(MP_QSTR_RISING), MP_ROM_INT(TIM_ICPOLARITY_RISING) },
1437 { MP_ROM_QSTR(MP_QSTR_FALLING), MP_ROM_INT(TIM_ICPOLARITY_FALLING) },
1438 { MP_ROM_QSTR(MP_QSTR_BOTH), MP_ROM_INT(TIM_ICPOLARITY_BOTHEDGE) },
1439 { MP_ROM_QSTR(MP_QSTR_BRK_OFF), MP_ROM_INT(BRK_OFF) },
1440 { MP_ROM_QSTR(MP_QSTR_BRK_LOW), MP_ROM_INT(BRK_LOW) },
1441 { MP_ROM_QSTR(MP_QSTR_BRK_HIGH), MP_ROM_INT(BRK_HIGH) },
1442 };
1443 STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table);
1444
1445 const mp_obj_type_t pyb_timer_type = {
1446 { &mp_type_type },
1447 .name = MP_QSTR_Timer,
1448 .print = pyb_timer_print,
1449 .make_new = pyb_timer_make_new,
1450 .locals_dict = (mp_obj_dict_t *)&pyb_timer_locals_dict,
1451 };
1452
1453 /// \moduleref pyb
1454 /// \class TimerChannel - setup a channel for a timer.
1455 ///
1456 /// Timer channels are used to generate/capture a signal using a timer.
1457 ///
1458 /// TimerChannel objects are created using the Timer.channel() method.
pyb_timer_channel_print(const mp_print_t * print,mp_obj_t self_in,mp_print_kind_t kind)1459 STATIC void pyb_timer_channel_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
1460 pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(self_in);
1461
1462 mp_printf(print, "TimerChannel(timer=%u, channel=%u, mode=%s)",
1463 self->timer->tim_id,
1464 self->channel,
1465 qstr_str(channel_mode_info[self->mode].name));
1466 }
1467
1468 /// \method capture([value])
1469 /// Get or set the capture value associated with a channel.
1470 /// capture, compare, and pulse_width are all aliases for the same function.
1471 /// capture is the logical name to use when the channel is in input capture mode.
1472
1473 /// \method compare([value])
1474 /// Get or set the compare value associated with a channel.
1475 /// capture, compare, and pulse_width are all aliases for the same function.
1476 /// compare is the logical name to use when the channel is in output compare mode.
1477
1478 /// \method pulse_width([value])
1479 /// Get or set the pulse width value associated with a channel.
1480 /// capture, compare, and pulse_width are all aliases for the same function.
1481 /// pulse_width is the logical name to use when the channel is in PWM mode.
1482 ///
1483 /// In edge aligned mode, a pulse_width of `period + 1` corresponds to a duty cycle of 100%
1484 /// In center aligned mode, a pulse width of `period` corresponds to a duty cycle of 100%
pyb_timer_channel_capture_compare(size_t n_args,const mp_obj_t * args)1485 STATIC mp_obj_t pyb_timer_channel_capture_compare(size_t n_args, const mp_obj_t *args) {
1486 pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(args[0]);
1487 if (n_args == 1) {
1488 // get
1489 return mp_obj_new_int(__HAL_TIM_GET_COMPARE(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer));
1490 } else {
1491 // set
1492 __HAL_TIM_SET_COMPARE(&self->timer->tim, TIMER_CHANNEL(self), mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self->timer));
1493 return mp_const_none;
1494 }
1495 }
1496 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_capture_compare_obj, 1, 2, pyb_timer_channel_capture_compare);
1497
1498 /// \method pulse_width_percent([value])
1499 /// Get or set the pulse width percentage associated with a channel. The value
1500 /// is a number between 0 and 100 and sets the percentage of the timer period
1501 /// for which the pulse is active. The value can be an integer or
1502 /// floating-point number for more accuracy. For example, a value of 25 gives
1503 /// a duty cycle of 25%.
pyb_timer_channel_pulse_width_percent(size_t n_args,const mp_obj_t * args)1504 STATIC mp_obj_t pyb_timer_channel_pulse_width_percent(size_t n_args, const mp_obj_t *args) {
1505 pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(args[0]);
1506 uint32_t period = compute_period(self->timer);
1507 if (n_args == 1) {
1508 // get
1509 uint32_t cmp = __HAL_TIM_GET_COMPARE(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer);
1510 return compute_percent_from_pwm_value(period, cmp);
1511 } else {
1512 // set
1513 uint32_t cmp = compute_pwm_value_from_percent(period, args[1]);
1514 __HAL_TIM_SET_COMPARE(&self->timer->tim, TIMER_CHANNEL(self), cmp & TIMER_CNT_MASK(self->timer));
1515 return mp_const_none;
1516 }
1517 }
1518 STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_pulse_width_percent_obj, 1, 2, pyb_timer_channel_pulse_width_percent);
1519
1520 /// \method callback(fun)
1521 /// Set the function to be called when the timer channel triggers.
1522 /// `fun` is passed 1 argument, the timer object.
1523 /// If `fun` is `None` then the callback will be disabled.
pyb_timer_channel_callback(mp_obj_t self_in,mp_obj_t callback)1524 STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback) {
1525 pyb_timer_channel_obj_t *self = MP_OBJ_TO_PTR(self_in);
1526 if (callback == mp_const_none) {
1527 // stop interrupt (but not timer)
1528 __HAL_TIM_DISABLE_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
1529 self->callback = mp_const_none;
1530 } else if (mp_obj_is_callable(callback)) {
1531 self->callback = callback;
1532 __HAL_TIM_CLEAR_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
1533 #if defined(TIM1)
1534 if (self->timer->tim_id == 1) {
1535 HAL_NVIC_EnableIRQ(TIM1_CC_IRQn);
1536 } else
1537 #endif
1538 #if defined(TIM8) // STM32F401 doesn't have a TIM8
1539 if (self->timer->tim_id == 8) {
1540 HAL_NVIC_EnableIRQ(TIM8_CC_IRQn);
1541 } else
1542 #endif
1543 {
1544 HAL_NVIC_EnableIRQ(self->timer->irqn);
1545 }
1546 // start timer, so that it interrupts on overflow
1547 switch (self->mode) {
1548 case CHANNEL_MODE_PWM_NORMAL:
1549 case CHANNEL_MODE_PWM_INVERTED:
1550 HAL_TIM_PWM_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1551 break;
1552 case CHANNEL_MODE_OC_TIMING:
1553 case CHANNEL_MODE_OC_ACTIVE:
1554 case CHANNEL_MODE_OC_INACTIVE:
1555 case CHANNEL_MODE_OC_TOGGLE:
1556 case CHANNEL_MODE_OC_FORCED_ACTIVE:
1557 case CHANNEL_MODE_OC_FORCED_INACTIVE:
1558 HAL_TIM_OC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1559 break;
1560 case CHANNEL_MODE_IC:
1561 HAL_TIM_IC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1562 break;
1563 }
1564 } else {
1565 mp_raise_ValueError(MP_ERROR_TEXT("callback must be None or a callable object"));
1566 }
1567 return mp_const_none;
1568 }
1569 STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_channel_callback_obj, pyb_timer_channel_callback);
1570
1571 STATIC const mp_rom_map_elem_t pyb_timer_channel_locals_dict_table[] = {
1572 // instance methods
1573 { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_timer_channel_callback_obj) },
1574 { MP_ROM_QSTR(MP_QSTR_pulse_width), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
1575 { MP_ROM_QSTR(MP_QSTR_pulse_width_percent), MP_ROM_PTR(&pyb_timer_channel_pulse_width_percent_obj) },
1576 { MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
1577 { MP_ROM_QSTR(MP_QSTR_compare), MP_ROM_PTR(&pyb_timer_channel_capture_compare_obj) },
1578 };
1579 STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);
1580
1581 STATIC const mp_obj_type_t pyb_timer_channel_type = {
1582 { &mp_type_type },
1583 .name = MP_QSTR_TimerChannel,
1584 .print = pyb_timer_channel_print,
1585 .locals_dict = (mp_obj_dict_t *)&pyb_timer_channel_locals_dict,
1586 };
1587
timer_handle_irq_channel(pyb_timer_obj_t * tim,uint8_t channel,mp_obj_t callback)1588 STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) {
1589 uint32_t irq_mask = TIMER_IRQ_MASK(channel);
1590
1591 if (__HAL_TIM_GET_FLAG(&tim->tim, irq_mask) != RESET) {
1592 if (__HAL_TIM_GET_IT_SOURCE(&tim->tim, irq_mask) != RESET) {
1593 // clear the interrupt
1594 __HAL_TIM_CLEAR_IT(&tim->tim, irq_mask);
1595
1596 // execute callback if it's set
1597 if (callback != mp_const_none) {
1598 mp_sched_lock();
1599 // When executing code within a handler we must lock the GC to prevent
1600 // any memory allocations. We must also catch any exceptions.
1601 gc_lock();
1602 nlr_buf_t nlr;
1603 if (nlr_push(&nlr) == 0) {
1604 mp_call_function_1(callback, MP_OBJ_FROM_PTR(tim));
1605 nlr_pop();
1606 } else {
1607 // Uncaught exception; disable the callback so it doesn't run again.
1608 tim->callback = mp_const_none;
1609 __HAL_TIM_DISABLE_IT(&tim->tim, irq_mask);
1610 if (channel == 0) {
1611 mp_printf(MICROPY_ERROR_PRINTER, "uncaught exception in Timer(%u) interrupt handler\n", tim->tim_id);
1612 } else {
1613 mp_printf(MICROPY_ERROR_PRINTER, "uncaught exception in Timer(%u) channel %u interrupt handler\n", tim->tim_id, channel);
1614 }
1615 mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val));
1616 }
1617 gc_unlock();
1618 mp_sched_unlock();
1619 }
1620 }
1621 }
1622 }
1623
timer_irq_handler(uint tim_id)1624 void timer_irq_handler(uint tim_id) {
1625 if (tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
1626 // get the timer object
1627 pyb_timer_obj_t *tim = MP_STATE_PORT(pyb_timer_obj_all)[tim_id - 1];
1628
1629 if (tim == NULL) {
1630 // Timer object has not been set, so we can't do anything.
1631 // This can happen under normal circumstances for timers like
1632 // 1 & 10 which use the same IRQ.
1633 return;
1634 }
1635
1636 // Check for timer (versus timer channel) interrupt.
1637 timer_handle_irq_channel(tim, 0, tim->callback);
1638 uint32_t handled = TIMER_IRQ_MASK(0);
1639
1640 // Check to see if a timer channel interrupt was pending
1641 pyb_timer_channel_obj_t *chan = tim->channel;
1642 while (chan != NULL) {
1643 timer_handle_irq_channel(tim, chan->channel, chan->callback);
1644 handled |= TIMER_IRQ_MASK(chan->channel);
1645 chan = chan->next;
1646 }
1647
1648 // Finally, clear any remaining interrupt sources. Otherwise we'll
1649 // just get called continuously.
1650 uint32_t unhandled = tim->tim.Instance->DIER & 0xff & ~handled;
1651 if (unhandled != 0) {
1652 __HAL_TIM_DISABLE_IT(&tim->tim, unhandled);
1653 __HAL_TIM_CLEAR_IT(&tim->tim, unhandled);
1654 mp_printf(MICROPY_ERROR_PRINTER, "unhandled interrupt SR=0x%02x (now disabled)\n", (unsigned int)unhandled);
1655 }
1656 }
1657 }
1658