blob: 34650031354dc66c6742a7e7ece7b231e498f0ab [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python 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
Damien Georgea12be912014-04-02 15:09:36 +010027#include <stdint.h>
28#include <stdio.h>
29#include <string.h>
30
31#include <stm32f4xx_hal.h>
32#include "usbd_cdc_msc_hid.h"
33#include "usbd_cdc_interface.h"
34
35#include "nlr.h"
36#include "misc.h"
37#include "mpconfig.h"
38#include "qstr.h"
Damien George7fdfa932014-04-21 16:48:16 +010039#include "gc.h"
Damien Georgea12be912014-04-02 15:09:36 +010040#include "obj.h"
41#include "runtime.h"
42#include "timer.h"
43#include "servo.h"
Dave Hylandsbecbc872014-08-20 13:21:11 -070044#include "pin.h"
Damien Georgea12be912014-04-02 15:09:36 +010045
Damien George3eb81632014-05-02 16:58:15 +010046/// \moduleref pyb
47/// \class Timer - periodically call a function
48///
49/// Timers can be used for a great variety of tasks. At the moment, only
50/// the simplest case is implemented: that of calling a function periodically.
51///
52/// Each timer consists of a counter that counts up at a certain rate. The rate
53/// at which it counts is the peripheral clock frequency (in Hz) divided by the
54/// timer prescaler. When the counter reaches the timer period it triggers an
55/// event, and the counter resets back to zero. By using the callback method,
56/// the timer event can call a Python function.
57///
58/// Example usage to toggle an LED at a fixed frequency:
59///
60/// tim = pyb.Timer(4) # create a timer object using timer 4
61/// tim.init(freq=2) # trigger at 2Hz
62/// tim.callback(lambda t:pyb.LED(1).toggle())
63///
64/// Further examples:
65///
66/// tim = pyb.Timer(4, freq=100) # freq in Hz
Dave Hylandsbecbc872014-08-20 13:21:11 -070067/// tim = pyb.Timer(4, prescaler=0, period=99)
Damien George3eb81632014-05-02 16:58:15 +010068/// tim.counter() # get counter (can also set)
69/// tim.prescaler(2) # set prescaler (can also get)
Dave Hylandsbecbc872014-08-20 13:21:11 -070070/// tim.period(199) # set period (can also get)
Damien George3eb81632014-05-02 16:58:15 +010071/// tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance)
72/// tim.callback(None) # clear callback
73///
74/// *Note:* Timer 3 is reserved for internal use. Timer 5 controls
75/// the servo driver, and Timer 6 is used for timed ADC/DAC reading/writing.
76/// It is recommended to use the other timers in your programs.
77
Damien Georgea12be912014-04-02 15:09:36 +010078// The timers can be used by multiple drivers, and need a common point for
79// the interrupts to be dispatched, so they are all collected here.
80//
81// TIM3:
Damien George6d983532014-04-16 23:08:36 +010082// - flash storage controller, to flush the cache
Damien Georgea12be912014-04-02 15:09:36 +010083// - USB CDC interface, interval, to check for new data
84// - LED 4, PWM to set the LED intensity
85//
86// TIM5:
87// - servo controller, PWM
Damien George7fdfa932014-04-21 16:48:16 +010088//
89// TIM6:
90// - ADC, DAC for read_timed and write_timed
Damien George7fdfa932014-04-21 16:48:16 +010091
Dave Hylandsbecbc872014-08-20 13:21:11 -070092typedef enum {
93 CHANNEL_MODE_PWM_NORMAL,
94 CHANNEL_MODE_PWM_INVERTED,
95 CHANNEL_MODE_OC_TIMING,
96 CHANNEL_MODE_OC_ACTIVE,
97 CHANNEL_MODE_OC_INACTIVE,
98 CHANNEL_MODE_OC_TOGGLE,
99 CHANNEL_MODE_OC_FORCED_ACTIVE,
100 CHANNEL_MODE_OC_FORCED_INACTIVE,
101 CHANNEL_MODE_IC,
102} pyb_channel_mode;
103
104STATIC const struct {
105 qstr name;
106 uint32_t oc_mode;
Damien George0e58c582014-09-21 22:54:02 +0100107} channel_mode_info[] = {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700108 { MP_QSTR_PWM, TIM_OCMODE_PWM1 },
109 { MP_QSTR_PWM_INVERTED, TIM_OCMODE_PWM2 },
110 { MP_QSTR_OC_TIMING, TIM_OCMODE_TIMING },
111 { MP_QSTR_OC_ACTIVE, TIM_OCMODE_ACTIVE },
112 { MP_QSTR_OC_INACTIVE, TIM_OCMODE_INACTIVE },
113 { MP_QSTR_OC_TOGGLE, TIM_OCMODE_TOGGLE },
114 { MP_QSTR_OC_FORCED_ACTIVE, TIM_OCMODE_FORCED_ACTIVE },
115 { MP_QSTR_OC_FORCED_INACTIVE, TIM_OCMODE_FORCED_INACTIVE },
116 { MP_QSTR_IC, 0 },
117};
118
119typedef struct _pyb_timer_channel_obj_t {
120 mp_obj_base_t base;
121 struct _pyb_timer_obj_t *timer;
122 uint8_t channel;
123 uint8_t mode;
124 mp_obj_t callback;
125 struct _pyb_timer_channel_obj_t *next;
126} pyb_timer_channel_obj_t;
127
Damien George7fdfa932014-04-21 16:48:16 +0100128typedef struct _pyb_timer_obj_t {
129 mp_obj_base_t base;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700130 uint8_t tim_id;
131 uint8_t is_32bit;
Damien George7fdfa932014-04-21 16:48:16 +0100132 mp_obj_t callback;
133 TIM_HandleTypeDef tim;
134 IRQn_Type irqn;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700135 pyb_timer_channel_obj_t *channel;
Damien George7fdfa932014-04-21 16:48:16 +0100136} pyb_timer_obj_t;
Damien Georgea12be912014-04-02 15:09:36 +0100137
Dave Hylandsbecbc872014-08-20 13:21:11 -0700138// The following yields TIM_IT_UPDATE when channel is zero and
139// TIM_IT_CC1..TIM_IT_CC4 when channel is 1..4
140#define TIMER_IRQ_MASK(channel) (1 << (channel))
Damien Georgee8ea0722014-09-25 15:44:10 +0100141#define TIMER_CNT_MASK(self) ((self)->is_32bit ? 0xffffffff : 0xffff)
Dave Hylandsbecbc872014-08-20 13:21:11 -0700142#define TIMER_CHANNEL(self) ((((self)->channel) - 1) << 2)
143
Damien Georgea12be912014-04-02 15:09:36 +0100144TIM_HandleTypeDef TIM3_Handle;
145TIM_HandleTypeDef TIM5_Handle;
Damien George4d7f4eb2014-04-15 19:52:56 +0100146TIM_HandleTypeDef TIM6_Handle;
Damien Georgea12be912014-04-02 15:09:36 +0100147
Damien George6d983532014-04-16 23:08:36 +0100148// Used to divide down TIM3 and periodically call the flash storage IRQ
Damien George0e58c582014-09-21 22:54:02 +0100149STATIC uint32_t tim3_counter = 0;
Damien George6d983532014-04-16 23:08:36 +0100150
Damien George7fdfa932014-04-21 16:48:16 +0100151// Used to do callbacks to Python code on interrupt
152STATIC pyb_timer_obj_t *pyb_timer_obj_all[14];
Emmanuel Blotf6932d62014-06-19 18:54:34 +0200153#define PYB_TIMER_OBJ_ALL_NUM MP_ARRAY_SIZE(pyb_timer_obj_all)
Damien George7fdfa932014-04-21 16:48:16 +0100154
Damien George97ef94d2014-10-04 14:36:39 +0100155STATIC uint32_t timer_get_source_freq(uint32_t tim_id);
Damien Georgee70b5db2014-07-02 14:09:44 +0100156STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in);
157STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700158STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback);
Damien Georgee70b5db2014-07-02 14:09:44 +0100159
Damien George7fdfa932014-04-21 16:48:16 +0100160void timer_init0(void) {
161 tim3_counter = 0;
162 for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
163 pyb_timer_obj_all[i] = NULL;
164 }
165}
166
Damien Georgee70b5db2014-07-02 14:09:44 +0100167// unregister all interrupt sources
168void timer_deinit(void) {
169 for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
170 pyb_timer_obj_t *tim = pyb_timer_obj_all[i];
171 if (tim != NULL) {
172 pyb_timer_deinit(tim);
173 }
174 }
175}
176
Damien Georgea12be912014-04-02 15:09:36 +0100177// TIM3 is set-up for the USB CDC interface
178void timer_tim3_init(void) {
179 // set up the timer for USBD CDC
180 __TIM3_CLK_ENABLE();
181
182 TIM3_Handle.Instance = TIM3;
Damien George6d983532014-04-16 23:08:36 +0100183 TIM3_Handle.Init.Period = (USBD_CDC_POLLING_INTERVAL*1000) - 1; // TIM3 fires every USBD_CDC_POLLING_INTERVAL ms
Damien George97ef94d2014-10-04 14:36:39 +0100184 TIM3_Handle.Init.Prescaler = timer_get_source_freq(3) / 1000000 - 1; // TIM3 runs at 1MHz
Dave Hylandsbecbc872014-08-20 13:21:11 -0700185 TIM3_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
Damien Georgea12be912014-04-02 15:09:36 +0100186 TIM3_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
187 HAL_TIM_Base_Init(&TIM3_Handle);
188
189 HAL_NVIC_SetPriority(TIM3_IRQn, 6, 0);
190 HAL_NVIC_EnableIRQ(TIM3_IRQn);
191
192 if (HAL_TIM_Base_Start(&TIM3_Handle) != HAL_OK) {
193 /* Starting Error */
194 }
195}
196
197/* unused
198void timer_tim3_deinit(void) {
199 // reset TIM3 timer
200 __TIM3_FORCE_RESET();
201 __TIM3_RELEASE_RESET();
202}
203*/
204
205// TIM5 is set-up for the servo controller
Damien George4d7f4eb2014-04-15 19:52:56 +0100206// This function inits but does not start the timer
Damien Georgea12be912014-04-02 15:09:36 +0100207void timer_tim5_init(void) {
208 // TIM5 clock enable
209 __TIM5_CLK_ENABLE();
210
211 // set up and enable interrupt
212 HAL_NVIC_SetPriority(TIM5_IRQn, 6, 0);
213 HAL_NVIC_EnableIRQ(TIM5_IRQn);
214
215 // PWM clock configuration
216 TIM5_Handle.Instance = TIM5;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700217 TIM5_Handle.Init.Period = 2000 - 1; // timer cycles at 50Hz
Damien George97ef94d2014-10-04 14:36:39 +0100218 TIM5_Handle.Init.Prescaler = (timer_get_source_freq(5) / 100000) - 1; // timer runs at 100kHz
Dave Hylandsbecbc872014-08-20 13:21:11 -0700219 TIM5_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
Damien Georgea12be912014-04-02 15:09:36 +0100220 TIM5_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700221
Damien Georgea12be912014-04-02 15:09:36 +0100222 HAL_TIM_PWM_Init(&TIM5_Handle);
223}
224
Damien George4d7f4eb2014-04-15 19:52:56 +0100225// Init TIM6 with a counter-overflow at the given frequency (given in Hz)
226// TIM6 is used by the DAC and ADC for auto sampling at a given frequency
227// This function inits but does not start the timer
228void timer_tim6_init(uint freq) {
229 // TIM6 clock enable
230 __TIM6_CLK_ENABLE();
231
232 // Timer runs at SystemCoreClock / 2
233 // Compute the prescaler value so TIM6 triggers at freq-Hz
Damien George97ef94d2014-10-04 14:36:39 +0100234 uint32_t period = MAX(1, timer_get_source_freq(6) / freq);
Damien George4d7f4eb2014-04-15 19:52:56 +0100235 uint32_t prescaler = 1;
236 while (period > 0xffff) {
237 period >>= 1;
238 prescaler <<= 1;
239 }
240
241 // Time base clock configuration
242 TIM6_Handle.Instance = TIM6;
243 TIM6_Handle.Init.Period = period - 1;
244 TIM6_Handle.Init.Prescaler = prescaler - 1;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700245 TIM6_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; // unused for TIM6
Damien George4d7f4eb2014-04-15 19:52:56 +0100246 TIM6_Handle.Init.CounterMode = TIM_COUNTERMODE_UP; // unused for TIM6
247 HAL_TIM_Base_Init(&TIM6_Handle);
248}
249
Damien Georgea12be912014-04-02 15:09:36 +0100250// Interrupt dispatch
251void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
252 if (htim == &TIM3_Handle) {
253 USBD_CDC_HAL_TIM_PeriodElapsedCallback();
Damien George6d983532014-04-16 23:08:36 +0100254
255 // Periodically raise a flash IRQ for the flash storage controller
256 if (tim3_counter++ >= 500 / USBD_CDC_POLLING_INTERVAL) {
257 tim3_counter = 0;
258 NVIC->STIR = FLASH_IRQn;
259 }
260
Damien Georgea12be912014-04-02 15:09:36 +0100261 } else if (htim == &TIM5_Handle) {
262 servo_timer_irq_callback();
263 }
264}
265
Damien George97ef94d2014-10-04 14:36:39 +0100266// Get the frequency (in Hz) of the source clock for the given timer.
267// On STM32F405/407/415/417 there are 2 cases for how the clock freq is set.
268// If the APB prescaler is 1, then the timer clock is equal to its respective
269// APB clock. Otherwise (APB prescaler > 1) the timer clock is twice its
270// respective APB clock. See DM00031020 Rev 4, page 115.
271STATIC uint32_t timer_get_source_freq(uint32_t tim_id) {
272 uint32_t source;
273 if (tim_id == 1 || (8 <= tim_id && tim_id <= 11)) {
274 // TIM{1,8,9,10,11} are on APB2
275 source = HAL_RCC_GetPCLK2Freq();
276 if ((uint32_t)((RCC->CFGR & RCC_CFGR_PPRE2) >> 3) != RCC_HCLK_DIV1) {
277 source *= 2;
278 }
279 } else {
280 // TIM{2,3,4,5,6,7,12,13,14} are on APB1
281 source = HAL_RCC_GetPCLK1Freq();
282 if ((uint32_t)(RCC->CFGR & RCC_CFGR_PPRE1) != RCC_HCLK_DIV1) {
283 source *= 2;
284 }
285 }
286 return source;
287}
288
Damien George7fdfa932014-04-21 16:48:16 +0100289/******************************************************************************/
290/* Micro Python bindings */
Damien Georgea12be912014-04-02 15:09:36 +0100291
Damien George0e58c582014-09-21 22:54:02 +0100292STATIC const mp_obj_type_t pyb_timer_channel_type;
293
Dave Hylands39296b42014-09-26 09:04:05 -0700294// This is the largest value that we can multiply by 100 and have the result
295// fit in a uint32_t.
296#define MAX_PERIOD_DIV_100 42949672
297
Damien George97ef94d2014-10-04 14:36:39 +0100298// computes prescaler and period so TIM triggers at freq-Hz
299STATIC uint32_t compute_prescaler_period_from_freq(pyb_timer_obj_t *self, mp_obj_t freq_in, uint32_t *period_out) {
300 uint32_t source_freq = timer_get_source_freq(self->tim_id);
301 uint32_t prescaler = 1;
302 uint32_t period;
303 if (0) {
304 #if MICROPY_PY_BUILTINS_FLOAT
305 } else if (MP_OBJ_IS_TYPE(freq_in, &mp_type_float)) {
306 float freq = mp_obj_get_float(freq_in);
307 if (freq <= 0) {
308 goto bad_freq;
309 }
310 period = MAX(1, source_freq / freq);
311 #endif
312 } else {
313 mp_int_t freq = mp_obj_get_int(freq_in);
314 if (freq <= 0) {
315 goto bad_freq;
316 bad_freq:
317 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "must have positive freq"));
318 }
319 period = MAX(1, source_freq / freq);
320 }
321 while (period > TIMER_CNT_MASK(self)) {
322 prescaler <<= 1;
323 period >>= 1;
324 }
325 *period_out = (period - 1) & TIMER_CNT_MASK(self);
326 return (prescaler - 1) & 0xffff;
327}
328
Dave Hylands39296b42014-09-26 09:04:05 -0700329// Helper function for determining the period used for calculating percent
330STATIC uint32_t compute_period(pyb_timer_obj_t *self) {
331 // In center mode, compare == period corresponds to 100%
332 // In edge mode, compare == (period + 1) corresponds to 100%
333 uint32_t period = (__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
334 if (period != 0xffffffff) {
335 if (self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ||
336 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN) {
337 // Edge mode
338 period++;
339 }
340 }
341 return period;
342}
343
Damien Georgee8ea0722014-09-25 15:44:10 +0100344// Helper function to compute PWM value from timer period and percent value.
Dave Hylands39296b42014-09-26 09:04:05 -0700345// 'percent_in' can be an int or a float between 0 and 100 (out of range
346// values are clamped).
347STATIC uint32_t compute_pwm_value_from_percent(uint32_t period, mp_obj_t percent_in) {
Damien Georgee8ea0722014-09-25 15:44:10 +0100348 uint32_t cmp;
349 if (0) {
350 #if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands39296b42014-09-26 09:04:05 -0700351 } else if (MP_OBJ_IS_TYPE(percent_in, &mp_type_float)) {
352 float percent = mp_obj_get_float(percent_in);
353 if (percent <= 0.0) {
354 cmp = 0;
355 } else if (percent >= 100.0) {
356 cmp = period;
357 } else {
358 cmp = percent / 100.0 * ((float)period);
359 }
Damien Georgee8ea0722014-09-25 15:44:10 +0100360 #endif
361 } else {
362 // For integer arithmetic, if period is large and 100*period will
363 // overflow, then divide period before multiplying by cmp. Otherwise
364 // do it the other way round to retain precision.
Dave Hylands39296b42014-09-26 09:04:05 -0700365 mp_int_t percent = mp_obj_get_int(percent_in);
366 if (percent <= 0) {
367 cmp = 0;
368 } else if (percent >= 100) {
369 cmp = period;
370 } else if (period > MAX_PERIOD_DIV_100) {
371 cmp = (uint32_t)percent * (period / 100);
Damien Georgee8ea0722014-09-25 15:44:10 +0100372 } else {
Dave Hylands39296b42014-09-26 09:04:05 -0700373 cmp = ((uint32_t)percent * period) / 100;
Damien Georgee8ea0722014-09-25 15:44:10 +0100374 }
375 }
Damien Georgee8ea0722014-09-25 15:44:10 +0100376 return cmp;
377}
378
Dave Hylands39296b42014-09-26 09:04:05 -0700379// Helper function to compute percentage from timer perion and PWM value.
380STATIC mp_obj_t compute_percent_from_pwm_value(uint32_t period, uint32_t cmp) {
381 #if MICROPY_PY_BUILTINS_FLOAT
382 float percent;
Damien Georgef042d7a2014-09-29 14:15:01 +0100383 if (cmp >= period) {
Dave Hylands39296b42014-09-26 09:04:05 -0700384 percent = 100.0;
385 } else {
386 percent = (float)cmp * 100.0 / ((float)period);
387 }
388 return mp_obj_new_float(percent);
389 #else
390 mp_int_t percent;
Damien Georgef042d7a2014-09-29 14:15:01 +0100391 if (cmp >= period) {
Dave Hylands39296b42014-09-26 09:04:05 -0700392 percent = 100;
Damien Georgef042d7a2014-09-29 14:15:01 +0100393 } else if (cmp > MAX_PERIOD_DIV_100) {
394 percent = cmp / (period / 100);
Dave Hylands39296b42014-09-26 09:04:05 -0700395 } else {
396 percent = cmp * 100 / period;
397 }
398 return mp_obj_new_int(percent);
399 #endif
400}
401
Damien George7fdfa932014-04-21 16:48:16 +0100402STATIC void pyb_timer_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
403 pyb_timer_obj_t *self = self_in;
Damien Georgea12be912014-04-02 15:09:36 +0100404
Damien George7fdfa932014-04-21 16:48:16 +0100405 if (self->tim.State == HAL_TIM_STATE_RESET) {
406 print(env, "Timer(%u)", self->tim_id);
407 } else {
Damien George97ef94d2014-10-04 14:36:39 +0100408 uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
409 uint32_t period = __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self);
410 // for efficiency, we compute and print freq as an int (not a float)
411 uint32_t freq = timer_get_source_freq(self->tim_id) / ((prescaler + 1) * (period + 1));
412 print(env, "Timer(%u, freq=%u, prescaler=%u, period=%u, mode=%s, div=%u)",
Damien George7fdfa932014-04-21 16:48:16 +0100413 self->tim_id,
Damien George97ef94d2014-10-04 14:36:39 +0100414 freq,
415 prescaler,
416 period,
Dave Hylandsbecbc872014-08-20 13:21:11 -0700417 self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ? "UP" :
418 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN ? "DOWN" : "CENTER",
419 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV4 ? 4 :
420 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV2 ? 2 : 1);
Damien George7fdfa932014-04-21 16:48:16 +0100421 }
422}
Damien Georgea12be912014-04-02 15:09:36 +0100423
Damien George3eb81632014-05-02 16:58:15 +0100424/// \method init(*, freq, prescaler, period)
425/// Initialise the timer. Initialisation must be either by frequency (in Hz)
426/// or by prescaler and period:
427///
428/// tim.init(freq=100) # set the timer to trigger at 100Hz
Dave Hylandsbecbc872014-08-20 13:21:11 -0700429/// tim.init(prescaler=83, period=999) # set the prescaler and period directly
430///
431/// Keyword arguments:
432///
433/// - `freq` - specifies the periodic frequency of the timer. You migh also
434/// view this as the frequency with which the timer goes through
435/// one complete cycle.
436///
437/// - `prescaler` [0-0xffff] - specifies the value to be loaded into the
438/// timer's Prescaler Register (PSC). The timer clock source is divided by
439/// (`prescaler + 1`) to arrive at the timer clock. Timers 2-7 and 12-14
440/// have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
441/// have a clock source of 168 MHz (pyb.freq()[3] * 2).
442///
443/// - `period` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5.
444/// Specifies the value to be loaded into the timer's AutoReload
445/// Register (ARR). This determines the period of the timer (i.e. when the
446/// counter cycles). The timer counter will roll-over after `period + 1`
447/// timer clock cycles.
448///
449/// - `mode` can be one of:
450/// - `Timer.UP` - configures the timer to count from 0 to ARR (default)
451/// - `Timer.DOWN` - configures the timer to count from ARR down to 0.
452/// - `Timer.CENTER` - confgures the timer to count from 0 to ARR and
453/// then back down to 0.
454///
455/// - `div` can be one of 1, 2, or 4. Divides the timer clock to determine
456/// the sampling clock used by the digital filters.
457///
458/// - `callback` - as per Timer.callback()
459///
460/// You must either specify freq or both of period and prescaler.
Damien George97ef94d2014-10-04 14:36:39 +0100461STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
462 static const mp_arg_t allowed_args[] = {
463 { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
464 { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
465 { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
466 { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_COUNTERMODE_UP} },
467 { MP_QSTR_div, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
468 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
469 };
Damien George7fdfa932014-04-21 16:48:16 +0100470
Damien George7fdfa932014-04-21 16:48:16 +0100471 // parse args
Damien George97ef94d2014-10-04 14:36:39 +0100472 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
473 mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
Damien George7fdfa932014-04-21 16:48:16 +0100474
475 // set the TIM configuration values
476 TIM_Base_InitTypeDef *init = &self->tim.Init;
477
Damien George97ef94d2014-10-04 14:36:39 +0100478 if (args[0].u_obj != mp_const_none) {
479 // set prescaler and period from desired frequency
480 init->Prescaler = compute_prescaler_period_from_freq(self, args[0].u_obj, &init->Period);
481 } else if (args[1].u_int != 0xffffffff && args[2].u_int != 0xffffffff) {
Damien George7fdfa932014-04-21 16:48:16 +0100482 // set prescaler and period directly
Damien George97ef94d2014-10-04 14:36:39 +0100483 init->Prescaler = args[1].u_int;
484 init->Period = args[2].u_int;
Damien George7fdfa932014-04-21 16:48:16 +0100485 } else {
486 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "must specify either freq, or prescaler and period"));
487 }
488
Damien George97ef94d2014-10-04 14:36:39 +0100489 init->CounterMode = args[3].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700490 if (!IS_TIM_COUNTER_MODE(init->CounterMode)) {
Damien George97ef94d2014-10-04 14:36:39 +0100491 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid mode (%d)", init->CounterMode));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700492 }
493
Damien George97ef94d2014-10-04 14:36:39 +0100494 init->ClockDivision = args[4].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
495 args[4].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
496 TIM_CLOCKDIVISION_DIV1;
497
498 init->RepetitionCounter = 0;
499
500 // enable TIM clock
Damien George7fdfa932014-04-21 16:48:16 +0100501 switch (self->tim_id) {
502 case 1: __TIM1_CLK_ENABLE(); break;
503 case 2: __TIM2_CLK_ENABLE(); break;
504 case 3: __TIM3_CLK_ENABLE(); break;
505 case 4: __TIM4_CLK_ENABLE(); break;
506 case 5: __TIM5_CLK_ENABLE(); break;
507 case 6: __TIM6_CLK_ENABLE(); break;
508 case 7: __TIM7_CLK_ENABLE(); break;
509 case 8: __TIM8_CLK_ENABLE(); break;
510 case 9: __TIM9_CLK_ENABLE(); break;
511 case 10: __TIM10_CLK_ENABLE(); break;
512 case 11: __TIM11_CLK_ENABLE(); break;
513 case 12: __TIM12_CLK_ENABLE(); break;
514 case 13: __TIM13_CLK_ENABLE(); break;
515 case 14: __TIM14_CLK_ENABLE(); break;
516 }
Damien George97ef94d2014-10-04 14:36:39 +0100517
518 // set IRQ priority (if not a special timer)
Damien George7fdfa932014-04-21 16:48:16 +0100519 if (self->tim_id != 3 && self->tim_id != 5) {
520 HAL_NVIC_SetPriority(self->irqn, 0xe, 0xe); // next-to lowest priority
521 }
522
Damien George97ef94d2014-10-04 14:36:39 +0100523 // init TIM
Dave Hylandsbecbc872014-08-20 13:21:11 -0700524 HAL_TIM_Base_Init(&self->tim);
Damien George97ef94d2014-10-04 14:36:39 +0100525 if (args[5].u_obj == mp_const_none) {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700526 HAL_TIM_Base_Start(&self->tim);
527 } else {
Damien George97ef94d2014-10-04 14:36:39 +0100528 pyb_timer_callback(self, args[5].u_obj);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700529 }
530
Damien George7fdfa932014-04-21 16:48:16 +0100531 return mp_const_none;
532}
533
Damien George3eb81632014-05-02 16:58:15 +0100534/// \classmethod \constructor(id, ...)
535/// Construct a new timer object of the given id. If additional
536/// arguments are given, then the timer is initialised by `init(...)`.
537/// `id` can be 1 to 14, excluding 3.
Damien Georgeecc88e92014-08-30 00:35:11 +0100538STATIC mp_obj_t pyb_timer_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100539 // check arguments
540 mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
541
542 // create new Timer object
543 pyb_timer_obj_t *tim = m_new_obj(pyb_timer_obj_t);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700544 memset(tim, 0, sizeof(*tim));
545
Damien George7fdfa932014-04-21 16:48:16 +0100546 tim->base.type = &pyb_timer_type;
547 tim->callback = mp_const_none;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700548 tim->channel = NULL;
Damien George7fdfa932014-04-21 16:48:16 +0100549
550 // get TIM number
551 tim->tim_id = mp_obj_get_int(args[0]);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700552 tim->is_32bit = false;
Damien George7fdfa932014-04-21 16:48:16 +0100553
554 switch (tim->tim_id) {
555 case 1: tim->tim.Instance = TIM1; tim->irqn = TIM1_UP_TIM10_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700556 case 2: tim->tim.Instance = TIM2; tim->irqn = TIM2_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100557 case 3: nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Timer 3 is for internal use only")); // TIM3 used for low-level stuff; go via regs if necessary
558 case 4: tim->tim.Instance = TIM4; tim->irqn = TIM4_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700559 case 5: tim->tim.Instance = TIM5; tim->irqn = TIM5_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100560 case 6: tim->tim.Instance = TIM6; tim->irqn = TIM6_DAC_IRQn; break;
561 case 7: tim->tim.Instance = TIM7; tim->irqn = TIM7_IRQn; break;
562 case 8: tim->tim.Instance = TIM8; tim->irqn = TIM8_UP_TIM13_IRQn; break;
563 case 9: tim->tim.Instance = TIM9; tim->irqn = TIM1_BRK_TIM9_IRQn; break;
564 case 10: tim->tim.Instance = TIM10; tim->irqn = TIM1_UP_TIM10_IRQn; break;
565 case 11: tim->tim.Instance = TIM11; tim->irqn = TIM1_TRG_COM_TIM11_IRQn; break;
566 case 12: tim->tim.Instance = TIM12; tim->irqn = TIM8_BRK_TIM12_IRQn; break;
567 case 13: tim->tim.Instance = TIM13; tim->irqn = TIM8_UP_TIM13_IRQn; break;
568 case 14: tim->tim.Instance = TIM14; tim->irqn = TIM8_TRG_COM_TIM14_IRQn; break;
569 default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id));
570 }
571
572 if (n_args > 1 || n_kw > 0) {
573 // start the peripheral
574 mp_map_t kw_args;
575 mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
576 pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args);
577 }
578
579 // set the global variable for interrupt callbacks
580 if (tim->tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
581 pyb_timer_obj_all[tim->tim_id - 1] = tim;
582 }
583
584 return (mp_obj_t)tim;
585}
586
Damien Georgeecc88e92014-08-30 00:35:11 +0100587STATIC mp_obj_t pyb_timer_init(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
Damien George7fdfa932014-04-21 16:48:16 +0100588 return pyb_timer_init_helper(args[0], n_args - 1, args + 1, kw_args);
589}
590STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
591
Damien George3eb81632014-05-02 16:58:15 +0100592/// \method deinit()
593/// Deinitialises the timer.
594///
Dave Hylands0d81c132014-06-30 07:55:54 -0700595/// Disables the callback (and the associated irq).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700596/// Disables any channel callbacks (and the associated irq).
Dave Hylands0d81c132014-06-30 07:55:54 -0700597/// Stops the timer, and disables the timer peripheral.
Damien George7fdfa932014-04-21 16:48:16 +0100598STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
Dave Hylands0d81c132014-06-30 07:55:54 -0700599 pyb_timer_obj_t *self = self_in;
600
Dave Hylandsbecbc872014-08-20 13:21:11 -0700601 // Disable the base interrupt
Dave Hylands0d81c132014-06-30 07:55:54 -0700602 pyb_timer_callback(self_in, mp_const_none);
603
Dave Hylandsbecbc872014-08-20 13:21:11 -0700604 pyb_timer_channel_obj_t *chan = self->channel;
605 self->channel = NULL;
606
607 // Disable the channel interrupts
608 while (chan != NULL) {
609 pyb_timer_channel_callback(chan, mp_const_none);
610 pyb_timer_channel_obj_t *prev_chan = chan;
611 chan = chan->next;
612 prev_chan->next = NULL;
613 }
614
Dave Hylands0d81c132014-06-30 07:55:54 -0700615 HAL_TIM_Base_DeInit(&self->tim);
Damien George7fdfa932014-04-21 16:48:16 +0100616 return mp_const_none;
617}
618STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);
619
Dave Hylandsbecbc872014-08-20 13:21:11 -0700620/// \method channel(channel, mode, ...)
621///
Damien George0e58c582014-09-21 22:54:02 +0100622/// If only a channel number is passed, then a previously initialized channel
623/// object is returned (or `None` if there is no previous channel).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700624///
625/// Othwerwise, a TimerChannel object is initialized and returned.
626///
627/// Each channel can be configured to perform pwm, output compare, or
628/// input capture. All channels share the same underlying timer, which means
629/// that they share the same timer clock.
630///
631/// Keyword arguments:
632///
633/// - `mode` can be one of:
634/// - `Timer.PWM` - configure the timer in PWM mode (active high).
635/// - `Timer.PWM_INVERTED` - configure the timer in PWM mode (active low).
636/// - `Timer.OC_TIMING` - indicates that no pin is driven.
637/// - `Timer.OC_ACTIVE` - the pin will be made active when a compare
638/// match occurs (active is determined by polarity)
639/// - `Timer.OC_INACTIVE` - the pin will be made inactive when a compare
640/// match occurs.
641/// - `Timer.OC_TOGGLE` - the pin will be toggled when an compare match occurs.
642/// - `Timer.OC_FORCED_ACTIVE` - the pin is forced active (compare match is ignored).
643/// - `Timer.OC_FORCED_INACTIVE` - the pin is forced inactive (compare match is ignored).
644/// - `Timer.IC` - configure the timer in Input Capture mode.
645///
646/// - `callback` - as per TimerChannel.callback()
647///
648/// - `pin` None (the default) or a Pin object. If specified (and not None)
649/// this will cause the alternate function of the the indicated pin
650/// to be configured for this timer channel. An error will be raised if
651/// the pin doesn't support any alternate functions for this timer channel.
652///
653/// Keyword arguments for Timer.PWM modes:
654///
Damien George0e58c582014-09-21 22:54:02 +0100655/// - `pulse_width` - determines the initial pulse width value to use.
Dave Hylands53d5fa62014-09-21 22:40:42 -0700656/// - `pulse_width_percent` - determines the initial pulse width percentage to use.
Dave Hylandsbecbc872014-08-20 13:21:11 -0700657///
658/// Keyword arguments for Timer.OC modes:
659///
660/// - `compare` - determines the initial value of the compare register.
661///
662/// - `polarity` can be one of:
663/// - `Timer.HIGH` - output is active high
664/// - `Timer.LOW` - output is acive low
665///
666/// Optional keyword arguments for Timer.IC modes:
667///
668/// - `polarity` can be one of:
669/// - `Timer.RISING` - captures on rising edge.
670/// - `Timer.FALLING` - captures on falling edge.
671/// - `Timer.BOTH` - captures on both edges.
672///
673/// PWM Example:
674///
675/// timer = pyb.Timer(2, freq=1000)
676/// ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
677/// ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
678STATIC const mp_arg_t pyb_timer_channel_args[] = {
Dave Hylands53d5fa62014-09-21 22:40:42 -0700679 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
680 { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
Damien Georgee8ea0722014-09-25 15:44:10 +0100681 { MP_QSTR_pulse_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
Dave Hylands53d5fa62014-09-21 22:40:42 -0700682 { MP_QSTR_pulse_width_percent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
683 { MP_QSTR_compare, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
684 { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700685};
686#define PYB_TIMER_CHANNEL_NUM_ARGS MP_ARRAY_SIZE(pyb_timer_channel_args)
687
688STATIC mp_obj_t pyb_timer_channel(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700689 pyb_timer_obj_t *self = args[0];
690 mp_int_t channel = mp_obj_get_int(args[1]);
691
692 if (channel < 1 || channel > 4) {
693 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid channel (%d)", channel));
694 }
695
696 pyb_timer_channel_obj_t *chan = self->channel;
697 pyb_timer_channel_obj_t *prev_chan = NULL;
698
699 while (chan != NULL) {
700 if (chan->channel == channel) {
701 break;
702 }
703 prev_chan = chan;
704 chan = chan->next;
705 }
Damien George0e58c582014-09-21 22:54:02 +0100706
707 // If only the channel number is given return the previously allocated
708 // channel (or None if no previous channel).
709 if (n_args == 2) {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700710 if (chan) {
711 return chan;
712 }
713 return mp_const_none;
714 }
715
716 // If there was already a channel, then remove it from the list. Note that
717 // the order we do things here is important so as to appear atomic to
718 // the IRQ handler.
719 if (chan) {
720 // Turn off any IRQ associated with the channel.
721 pyb_timer_channel_callback(chan, mp_const_none);
722
723 // Unlink the channel from the list.
724 if (prev_chan) {
725 prev_chan->next = chan->next;
726 }
727 self->channel = chan->next;
728 chan->next = NULL;
729 }
730
731 // Allocate and initialize a new channel
732 mp_arg_val_t vals[PYB_TIMER_CHANNEL_NUM_ARGS];
733 mp_arg_parse_all(n_args - 3, args + 3, kw_args, PYB_TIMER_CHANNEL_NUM_ARGS, pyb_timer_channel_args, vals);
734
735 chan = m_new_obj(pyb_timer_channel_obj_t);
736 memset(chan, 0, sizeof(*chan));
737 chan->base.type = &pyb_timer_channel_type;
738 chan->timer = self;
739 chan->channel = channel;
740 chan->mode = mp_obj_get_int(args[2]);
741 chan->callback = vals[0].u_obj;
742
743 mp_obj_t pin_obj = vals[1].u_obj;
744 if (pin_obj != mp_const_none) {
745 if (!MP_OBJ_IS_TYPE(pin_obj, &pin_type)) {
746 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "pin argument needs to be be a Pin type"));
747 }
748 const pin_obj_t *pin = pin_obj;
749 const pin_af_obj_t *af = pin_find_af(pin, AF_FN_TIM, self->tim_id);
750 if (af == NULL) {
751 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "pin %s doesn't have an af for TIM%d", qstr_str(pin->name), self->tim_id));
752 }
753 // pin.init(mode=AF_PP, af=idx)
754 const mp_obj_t args[6] = {
755 (mp_obj_t)&pin_init_obj,
756 pin_obj,
757 MP_OBJ_NEW_QSTR(MP_QSTR_mode), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP),
758 MP_OBJ_NEW_QSTR(MP_QSTR_af), MP_OBJ_NEW_SMALL_INT(af->idx)
759 };
760 mp_call_method_n_kw(0, 2, args);
761 }
762
763 // Link the channel to the timer before we turn the channel on.
764 // Note that this needs to appear atomic to the IRQ handler (the write
765 // to self->channel is atomic, so we're good, but I thought I'd mention
766 // in case this was ever changed in the future).
767 chan->next = self->channel;
768 self->channel = chan;
769
770 switch (chan->mode) {
771
772 case CHANNEL_MODE_PWM_NORMAL:
773 case CHANNEL_MODE_PWM_INVERTED: {
774 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100775 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
Damien Georgee8ea0722014-09-25 15:44:10 +0100776 if (vals[3].u_obj != mp_const_none) {
Dave Hylands53d5fa62014-09-21 22:40:42 -0700777 // pulse width percent given
Dave Hylands39296b42014-09-26 09:04:05 -0700778 uint32_t period = compute_period(self);
Damien Georgee8ea0722014-09-25 15:44:10 +0100779 oc_config.Pulse = compute_pwm_value_from_percent(period, vals[3].u_obj);
Damien George0e58c582014-09-21 22:54:02 +0100780 } else {
Damien Georgee8ea0722014-09-25 15:44:10 +0100781 // use absolute pulse width value (defaults to 0 if nothing given)
782 oc_config.Pulse = vals[2].u_int;
Damien George0e58c582014-09-21 22:54:02 +0100783 }
Dave Hylandsbecbc872014-08-20 13:21:11 -0700784 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
785 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
786 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
787 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
788 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
789
790 HAL_TIM_PWM_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
791 if (chan->callback == mp_const_none) {
792 HAL_TIM_PWM_Start(&self->tim, TIMER_CHANNEL(chan));
793 } else {
794 HAL_TIM_PWM_Start_IT(&self->tim, TIMER_CHANNEL(chan));
795 }
796 break;
797 }
798
799 case CHANNEL_MODE_OC_TIMING:
800 case CHANNEL_MODE_OC_ACTIVE:
801 case CHANNEL_MODE_OC_INACTIVE:
802 case CHANNEL_MODE_OC_TOGGLE:
803 case CHANNEL_MODE_OC_FORCED_ACTIVE:
804 case CHANNEL_MODE_OC_FORCED_INACTIVE: {
805 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100806 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
807 oc_config.Pulse = vals[4].u_int;
808 oc_config.OCPolarity = vals[5].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700809 if (oc_config.OCPolarity == 0xffffffff) {
810 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
811 }
812 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
813 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
814 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
815 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
816
817 if (!IS_TIM_OC_POLARITY(oc_config.OCPolarity)) {
818 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", oc_config.OCPolarity));
819 }
820 HAL_TIM_OC_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
821 if (chan->callback == mp_const_none) {
822 HAL_TIM_OC_Start(&self->tim, TIMER_CHANNEL(chan));
823 } else {
824 HAL_TIM_OC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
825 }
826 break;
827 }
828
829 case CHANNEL_MODE_IC: {
830 TIM_IC_InitTypeDef ic_config;
831
Damien George0e58c582014-09-21 22:54:02 +0100832 ic_config.ICPolarity = vals[5].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700833 if (ic_config.ICPolarity == 0xffffffff) {
834 ic_config.ICPolarity = TIM_ICPOLARITY_RISING;
835 }
836 ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
837 ic_config.ICPrescaler = TIM_ICPSC_DIV1;
838 ic_config.ICFilter = 0;
839
840 if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) {
841 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", ic_config.ICPolarity));
842 }
843 HAL_TIM_IC_ConfigChannel(&self->tim, &ic_config, TIMER_CHANNEL(chan));
844 if (chan->callback == mp_const_none) {
845 HAL_TIM_IC_Start(&self->tim, TIMER_CHANNEL(chan));
846 } else {
847 HAL_TIM_IC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
848 }
849 break;
850 }
851
852 default:
853 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid mode (%d)", chan->mode));
854 }
855
856 return chan;
857}
Damien George0e58c582014-09-21 22:54:02 +0100858STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700859
Damien George3eb81632014-05-02 16:58:15 +0100860/// \method counter([value])
861/// Get or set the timer counter.
Damien George0e58c582014-09-21 22:54:02 +0100862STATIC mp_obj_t pyb_timer_counter(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100863 pyb_timer_obj_t *self = args[0];
864 if (n_args == 1) {
865 // get
866 return mp_obj_new_int(self->tim.Instance->CNT);
867 } else {
868 // set
869 __HAL_TIM_SetCounter(&self->tim, mp_obj_get_int(args[1]));
870 return mp_const_none;
871 }
872}
873STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_counter_obj, 1, 2, pyb_timer_counter);
874
Damien George97ef94d2014-10-04 14:36:39 +0100875/// \method source_freq()
876/// Get the frequency of the source of the timer.
877STATIC mp_obj_t pyb_timer_source_freq(mp_obj_t self_in) {
878 pyb_timer_obj_t *self = self_in;
879 uint32_t source_freq = timer_get_source_freq(self->tim_id);
880 return mp_obj_new_int(source_freq);
881}
882STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_source_freq_obj, pyb_timer_source_freq);
883
884/// \method freq([value])
885/// Get or set the frequency for the timer (changes prescaler and period if set).
886STATIC mp_obj_t pyb_timer_freq(mp_uint_t n_args, const mp_obj_t *args) {
887 pyb_timer_obj_t *self = args[0];
888 if (n_args == 1) {
889 // get
890 uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
891 uint32_t period = __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self);
892 uint32_t source_freq = timer_get_source_freq(self->tim_id);
893 uint32_t divide = ((prescaler + 1) * (period + 1));
894 if (source_freq % divide == 0) {
895 return mp_obj_new_int(source_freq / divide);
896 } else {
897 return mp_obj_new_float((float)source_freq / (float)divide);
898 }
899 } else {
900 // set
901 uint32_t period;
902 uint32_t prescaler = compute_prescaler_period_from_freq(self, args[1], &period);
903 self->tim.Instance->PSC = prescaler;
904 __HAL_TIM_SetAutoreload(&self->tim, period);
905 return mp_const_none;
906 }
907}
908STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_freq_obj, 1, 2, pyb_timer_freq);
909
Damien George3eb81632014-05-02 16:58:15 +0100910/// \method prescaler([value])
911/// Get or set the prescaler for the timer.
Damien George0e58c582014-09-21 22:54:02 +0100912STATIC mp_obj_t pyb_timer_prescaler(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100913 pyb_timer_obj_t *self = args[0];
914 if (n_args == 1) {
915 // get
916 return mp_obj_new_int(self->tim.Instance->PSC & 0xffff);
917 } else {
918 // set
Damien George97ef94d2014-10-04 14:36:39 +0100919 self->tim.Instance->PSC = mp_obj_get_int(args[1]) & 0xffff;
Damien George7fdfa932014-04-21 16:48:16 +0100920 return mp_const_none;
921 }
922}
923STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);
924
Damien George3eb81632014-05-02 16:58:15 +0100925/// \method period([value])
926/// Get or set the period of the timer.
Damien George0e58c582014-09-21 22:54:02 +0100927STATIC mp_obj_t pyb_timer_period(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100928 pyb_timer_obj_t *self = args[0];
929 if (n_args == 1) {
930 // get
Dave Hylandsbecbc872014-08-20 13:21:11 -0700931 return mp_obj_new_int(__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +0100932 } else {
933 // set
Dave Hylandsbecbc872014-08-20 13:21:11 -0700934 __HAL_TIM_SetAutoreload(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +0100935 return mp_const_none;
936 }
937}
938STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
939
Damien George3eb81632014-05-02 16:58:15 +0100940/// \method callback(fun)
941/// Set the function to be called when the timer triggers.
942/// `fun` is passed 1 argument, the timer object.
943/// If `fun` is `None` then the callback will be disabled.
Damien George7fdfa932014-04-21 16:48:16 +0100944STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
945 pyb_timer_obj_t *self = self_in;
946 if (callback == mp_const_none) {
947 // stop interrupt (but not timer)
948 __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
949 self->callback = mp_const_none;
950 } else if (mp_obj_is_callable(callback)) {
951 self->callback = callback;
952 HAL_NVIC_EnableIRQ(self->irqn);
953 // start timer, so that it interrupts on overflow
954 HAL_TIM_Base_Start_IT(&self->tim);
955 } else {
956 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
957 }
Damien Georgea12be912014-04-02 15:09:36 +0100958 return mp_const_none;
959}
Damien George7fdfa932014-04-21 16:48:16 +0100960STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);
Damien Georgea12be912014-04-02 15:09:36 +0100961
Damien George7fdfa932014-04-21 16:48:16 +0100962STATIC const mp_map_elem_t pyb_timer_locals_dict_table[] = {
963 // instance methods
964 { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_timer_init_obj },
965 { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_timer_deinit_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700966 { MP_OBJ_NEW_QSTR(MP_QSTR_channel), (mp_obj_t)&pyb_timer_channel_obj },
Damien George7fdfa932014-04-21 16:48:16 +0100967 { MP_OBJ_NEW_QSTR(MP_QSTR_counter), (mp_obj_t)&pyb_timer_counter_obj },
Damien George97ef94d2014-10-04 14:36:39 +0100968 { MP_OBJ_NEW_QSTR(MP_QSTR_source_freq), (mp_obj_t)&pyb_timer_source_freq_obj },
969 { MP_OBJ_NEW_QSTR(MP_QSTR_freq), (mp_obj_t)&pyb_timer_freq_obj },
Damien George7fdfa932014-04-21 16:48:16 +0100970 { MP_OBJ_NEW_QSTR(MP_QSTR_prescaler), (mp_obj_t)&pyb_timer_prescaler_obj },
971 { MP_OBJ_NEW_QSTR(MP_QSTR_period), (mp_obj_t)&pyb_timer_period_obj },
972 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_callback_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700973 { MP_OBJ_NEW_QSTR(MP_QSTR_UP), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_UP) },
974 { MP_OBJ_NEW_QSTR(MP_QSTR_DOWN), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_DOWN) },
975 { MP_OBJ_NEW_QSTR(MP_QSTR_CENTER), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_CENTERALIGNED1) },
976 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_NORMAL) },
977 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM_INVERTED), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_INVERTED) },
978 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TIMING), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TIMING) },
979 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_ACTIVE) },
980 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_INACTIVE) },
981 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TOGGLE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TOGGLE) },
982 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_ACTIVE) },
983 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_INACTIVE) },
984 { MP_OBJ_NEW_QSTR(MP_QSTR_IC), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_IC) },
985 { MP_OBJ_NEW_QSTR(MP_QSTR_HIGH), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_HIGH) },
986 { MP_OBJ_NEW_QSTR(MP_QSTR_LOW), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_LOW) },
987 { MP_OBJ_NEW_QSTR(MP_QSTR_RISING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_RISING) },
988 { MP_OBJ_NEW_QSTR(MP_QSTR_FALLING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_FALLING) },
989 { MP_OBJ_NEW_QSTR(MP_QSTR_BOTH), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_BOTHEDGE) },
Damien George7fdfa932014-04-21 16:48:16 +0100990};
Damien George7fdfa932014-04-21 16:48:16 +0100991STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table);
Damien Georgea12be912014-04-02 15:09:36 +0100992
Damien George7fdfa932014-04-21 16:48:16 +0100993const mp_obj_type_t pyb_timer_type = {
994 { &mp_type_type },
995 .name = MP_QSTR_Timer,
996 .print = pyb_timer_print,
997 .make_new = pyb_timer_make_new,
998 .locals_dict = (mp_obj_t)&pyb_timer_locals_dict,
999};
Damien Georgea12be912014-04-02 15:09:36 +01001000
Dave Hylandsbecbc872014-08-20 13:21:11 -07001001/// \moduleref pyb
1002/// \class TimerChannel - setup a channel for a timer.
1003///
1004/// Timer channels are used to generate/capture a signal using a timer.
1005///
1006/// TimerChannel objects are created using the Timer.channel() method.
1007STATIC void pyb_timer_channel_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
1008 pyb_timer_channel_obj_t *self = self_in;
1009
1010 print(env, "TimerChannel(timer=%u, channel=%u, mode=%s)",
1011 self->timer->tim_id,
1012 self->channel,
Damien George0e58c582014-09-21 22:54:02 +01001013 qstr_str(channel_mode_info[self->mode].name));
Dave Hylandsbecbc872014-08-20 13:21:11 -07001014}
1015
1016/// \method capture([value])
1017/// Get or set the capture value associated with a channel.
1018/// capture, compare, and pulse_width are all aliases for the same function.
1019/// capture is the logical name to use when the channel is in input capture mode.
1020
1021/// \method compare([value])
1022/// Get or set the compare value associated with a channel.
1023/// capture, compare, and pulse_width are all aliases for the same function.
1024/// compare is the logical name to use when the channel is in output compare mode.
1025
1026/// \method pulse_width([value])
1027/// Get or set the pulse width value associated with a channel.
1028/// capture, compare, and pulse_width are all aliases for the same function.
1029/// pulse_width is the logical name to use when the channel is in PWM mode.
Dave Hylands39296b42014-09-26 09:04:05 -07001030///
1031/// In edge aligned mode, a pulse_width of `period + 1` corresponds to a duty cycle of 100%
1032/// In center aligned mode, a pulse width of `period` corresponds to a duty cycle of 100%
Damien George0e58c582014-09-21 22:54:02 +01001033STATIC mp_obj_t pyb_timer_channel_capture_compare(mp_uint_t n_args, const mp_obj_t *args) {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001034 pyb_timer_channel_obj_t *self = args[0];
Dave Hylandsbecbc872014-08-20 13:21:11 -07001035 if (n_args == 1) {
1036 // get
1037 return mp_obj_new_int(__HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer));
1038 } else {
1039 // set
1040 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self->timer));
1041 return mp_const_none;
1042 }
1043}
1044STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_capture_compare_obj, 1, 2, pyb_timer_channel_capture_compare);
1045
Damien Georgee8ea0722014-09-25 15:44:10 +01001046/// \method pulse_width_percent([value])
1047/// Get or set the pulse width percentage associated with a channel. The value
1048/// is a number between 0 and 100 and sets the percentage of the timer period
1049/// for which the pulse is active. The value can be an integer or
1050/// floating-point number for more accuracy. For example, a value of 25 gives
1051/// a duty cycle of 25%.
Dave Hylands53d5fa62014-09-21 22:40:42 -07001052STATIC mp_obj_t pyb_timer_channel_pulse_width_percent(mp_uint_t n_args, const mp_obj_t *args) {
Damien George0e58c582014-09-21 22:54:02 +01001053 pyb_timer_channel_obj_t *self = args[0];
Dave Hylands39296b42014-09-26 09:04:05 -07001054 uint32_t period = compute_period(self->timer);
Damien George0e58c582014-09-21 22:54:02 +01001055 if (n_args == 1) {
1056 // get
1057 uint32_t cmp = __HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer);
Dave Hylands39296b42014-09-26 09:04:05 -07001058 return compute_percent_from_pwm_value(period, cmp);
Damien George0e58c582014-09-21 22:54:02 +01001059 } else {
1060 // set
Damien Georgee8ea0722014-09-25 15:44:10 +01001061 uint32_t cmp = compute_pwm_value_from_percent(period, args[1]);
Damien George0e58c582014-09-21 22:54:02 +01001062 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), cmp & TIMER_CNT_MASK(self->timer));
1063 return mp_const_none;
1064 }
1065}
Dave Hylands53d5fa62014-09-21 22:40:42 -07001066STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_pulse_width_percent_obj, 1, 2, pyb_timer_channel_pulse_width_percent);
Damien George0e58c582014-09-21 22:54:02 +01001067
Dave Hylandsbecbc872014-08-20 13:21:11 -07001068/// \method callback(fun)
1069/// Set the function to be called when the timer channel triggers.
1070/// `fun` is passed 1 argument, the timer object.
1071/// If `fun` is `None` then the callback will be disabled.
1072STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback) {
1073 pyb_timer_channel_obj_t *self = self_in;
1074 if (callback == mp_const_none) {
1075 // stop interrupt (but not timer)
1076 __HAL_TIM_DISABLE_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
1077 self->callback = mp_const_none;
1078 } else if (mp_obj_is_callable(callback)) {
1079 self->callback = callback;
1080 HAL_NVIC_EnableIRQ(self->timer->irqn);
1081 // start timer, so that it interrupts on overflow
1082 switch (self->mode) {
1083 case CHANNEL_MODE_PWM_NORMAL:
1084 case CHANNEL_MODE_PWM_INVERTED:
1085 HAL_TIM_PWM_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1086 break;
1087 case CHANNEL_MODE_OC_TIMING:
1088 case CHANNEL_MODE_OC_ACTIVE:
1089 case CHANNEL_MODE_OC_INACTIVE:
1090 case CHANNEL_MODE_OC_TOGGLE:
1091 case CHANNEL_MODE_OC_FORCED_ACTIVE:
1092 case CHANNEL_MODE_OC_FORCED_INACTIVE:
1093 HAL_TIM_OC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1094 break;
1095 case CHANNEL_MODE_IC:
1096 HAL_TIM_IC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1097 break;
1098 }
1099 } else {
1100 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
1101 }
1102 return mp_const_none;
1103}
1104STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_channel_callback_obj, pyb_timer_channel_callback);
1105
1106STATIC const mp_map_elem_t pyb_timer_channel_locals_dict_table[] = {
1107 // instance methods
1108 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_channel_callback_obj },
1109 { MP_OBJ_NEW_QSTR(MP_QSTR_pulse_width), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
Dave Hylands53d5fa62014-09-21 22:40:42 -07001110 { MP_OBJ_NEW_QSTR(MP_QSTR_pulse_width_percent), (mp_obj_t)&pyb_timer_channel_pulse_width_percent_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -07001111 { MP_OBJ_NEW_QSTR(MP_QSTR_capture), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1112 { MP_OBJ_NEW_QSTR(MP_QSTR_compare), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1113};
1114STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);
1115
Damien George0e58c582014-09-21 22:54:02 +01001116STATIC const mp_obj_type_t pyb_timer_channel_type = {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001117 { &mp_type_type },
1118 .name = MP_QSTR_TimerChannel,
1119 .print = pyb_timer_channel_print,
1120 .locals_dict = (mp_obj_t)&pyb_timer_channel_locals_dict,
1121};
1122
Damien George0e58c582014-09-21 22:54:02 +01001123STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001124 uint32_t irq_mask = TIMER_IRQ_MASK(channel);
1125
1126 if (__HAL_TIM_GET_FLAG(&tim->tim, irq_mask) != RESET) {
1127 if (__HAL_TIM_GET_ITSTATUS(&tim->tim, irq_mask) != RESET) {
1128 // clear the interrupt
1129 __HAL_TIM_CLEAR_IT(&tim->tim, irq_mask);
1130
1131 // execute callback if it's set
1132 if (callback != mp_const_none) {
1133 // When executing code within a handler we must lock the GC to prevent
1134 // any memory allocations. We must also catch any exceptions.
1135 gc_lock();
1136 nlr_buf_t nlr;
1137 if (nlr_push(&nlr) == 0) {
1138 mp_call_function_1(callback, tim);
1139 nlr_pop();
1140 } else {
1141 // Uncaught exception; disable the callback so it doesn't run again.
1142 tim->callback = mp_const_none;
1143 __HAL_TIM_DISABLE_IT(&tim->tim, irq_mask);
1144 if (channel == 0) {
1145 printf("Uncaught exception in Timer(" UINT_FMT
1146 ") interrupt handler\n", tim->tim_id);
1147 } else {
1148 printf("Uncaught exception in Timer(" UINT_FMT ") channel "
1149 UINT_FMT " interrupt handler\n", tim->tim_id, channel);
1150 }
1151 mp_obj_print_exception((mp_obj_t)nlr.ret_val);
1152 }
1153 gc_unlock();
1154 }
1155 }
1156 }
1157}
1158
Damien George7fdfa932014-04-21 16:48:16 +01001159void timer_irq_handler(uint tim_id) {
1160 if (tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
1161 // get the timer object
1162 pyb_timer_obj_t *tim = pyb_timer_obj_all[tim_id - 1];
Damien Georgea12be912014-04-02 15:09:36 +01001163
Damien George7fdfa932014-04-21 16:48:16 +01001164 if (tim == NULL) {
Damien George0e58c582014-09-21 22:54:02 +01001165 // Timer object has not been set, so we can't do anything.
1166 // This can happen under normal circumstances for timers like
1167 // 1 & 10 which use the same IRQ.
Damien George7fdfa932014-04-21 16:48:16 +01001168 return;
1169 }
Damien Georgea12be912014-04-02 15:09:36 +01001170
Dave Hylandsbecbc872014-08-20 13:21:11 -07001171 // Check for timer (versus timer channel) interrupt.
1172 timer_handle_irq_channel(tim, 0, tim->callback);
1173 uint32_t handled = TIMER_IRQ_MASK(0);
Damien Georgea12be912014-04-02 15:09:36 +01001174
Dave Hylandsbecbc872014-08-20 13:21:11 -07001175 // Check to see if a timer channel interrupt was pending
1176 pyb_timer_channel_obj_t *chan = tim->channel;
1177 while (chan != NULL) {
1178 timer_handle_irq_channel(tim, chan->channel, chan->callback);
1179 handled |= TIMER_IRQ_MASK(chan->channel);
1180 chan = chan->next;
1181 }
1182
1183 // Finally, clear any remaining interrupt sources. Otherwise we'll
1184 // just get called continuously.
1185 uint32_t unhandled = __HAL_TIM_GET_ITSTATUS(&tim->tim, 0xff & ~handled);
1186 if (unhandled != 0) {
1187 __HAL_TIM_CLEAR_IT(&tim->tim, unhandled);
1188 printf("Unhandled interrupt SR=0x%02lx (now disabled)\n", unhandled);
Damien Georgea12be912014-04-02 15:09:36 +01001189 }
1190 }
1191}