blob: f33fe5afb3411b28b523710092f899f5a91c47a3 [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 }
Damien George55f68b32014-10-04 14:59:35 +0100310 while (freq < 1 && prescaler < 6553) {
311 prescaler *= 10;
312 freq *= 10;
313 }
314 period = (float)source_freq / freq;
Damien George97ef94d2014-10-04 14:36:39 +0100315 #endif
316 } else {
317 mp_int_t freq = mp_obj_get_int(freq_in);
318 if (freq <= 0) {
319 goto bad_freq;
320 bad_freq:
321 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "must have positive freq"));
322 }
Damien George55f68b32014-10-04 14:59:35 +0100323 period = source_freq / freq;
Damien George97ef94d2014-10-04 14:36:39 +0100324 }
Damien George55f68b32014-10-04 14:59:35 +0100325 period = MAX(1, period);
Damien George97ef94d2014-10-04 14:36:39 +0100326 while (period > TIMER_CNT_MASK(self)) {
Damien George55f68b32014-10-04 14:59:35 +0100327 // if we can divide exactly, do that first
328 if (period % 5 == 0) {
329 prescaler *= 5;
330 period /= 5;
331 } else if (period % 3 == 0) {
332 prescaler *= 3;
333 period /= 3;
334 } else {
335 // may not divide exactly, but loses minimal precision
336 prescaler <<= 1;
337 period >>= 1;
338 }
Damien George97ef94d2014-10-04 14:36:39 +0100339 }
340 *period_out = (period - 1) & TIMER_CNT_MASK(self);
341 return (prescaler - 1) & 0xffff;
342}
343
Dave Hylands39296b42014-09-26 09:04:05 -0700344// Helper function for determining the period used for calculating percent
345STATIC uint32_t compute_period(pyb_timer_obj_t *self) {
346 // In center mode, compare == period corresponds to 100%
347 // In edge mode, compare == (period + 1) corresponds to 100%
348 uint32_t period = (__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
349 if (period != 0xffffffff) {
350 if (self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ||
351 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN) {
352 // Edge mode
353 period++;
354 }
355 }
356 return period;
357}
358
Damien Georgee8ea0722014-09-25 15:44:10 +0100359// Helper function to compute PWM value from timer period and percent value.
Dave Hylands39296b42014-09-26 09:04:05 -0700360// 'percent_in' can be an int or a float between 0 and 100 (out of range
361// values are clamped).
362STATIC uint32_t compute_pwm_value_from_percent(uint32_t period, mp_obj_t percent_in) {
Damien Georgee8ea0722014-09-25 15:44:10 +0100363 uint32_t cmp;
364 if (0) {
365 #if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands39296b42014-09-26 09:04:05 -0700366 } else if (MP_OBJ_IS_TYPE(percent_in, &mp_type_float)) {
367 float percent = mp_obj_get_float(percent_in);
368 if (percent <= 0.0) {
369 cmp = 0;
370 } else if (percent >= 100.0) {
371 cmp = period;
372 } else {
373 cmp = percent / 100.0 * ((float)period);
374 }
Damien Georgee8ea0722014-09-25 15:44:10 +0100375 #endif
376 } else {
377 // For integer arithmetic, if period is large and 100*period will
378 // overflow, then divide period before multiplying by cmp. Otherwise
379 // do it the other way round to retain precision.
Dave Hylands39296b42014-09-26 09:04:05 -0700380 mp_int_t percent = mp_obj_get_int(percent_in);
381 if (percent <= 0) {
382 cmp = 0;
383 } else if (percent >= 100) {
384 cmp = period;
385 } else if (period > MAX_PERIOD_DIV_100) {
386 cmp = (uint32_t)percent * (period / 100);
Damien Georgee8ea0722014-09-25 15:44:10 +0100387 } else {
Dave Hylands39296b42014-09-26 09:04:05 -0700388 cmp = ((uint32_t)percent * period) / 100;
Damien Georgee8ea0722014-09-25 15:44:10 +0100389 }
390 }
Damien Georgee8ea0722014-09-25 15:44:10 +0100391 return cmp;
392}
393
Dave Hylands39296b42014-09-26 09:04:05 -0700394// Helper function to compute percentage from timer perion and PWM value.
395STATIC mp_obj_t compute_percent_from_pwm_value(uint32_t period, uint32_t cmp) {
396 #if MICROPY_PY_BUILTINS_FLOAT
397 float percent;
Damien Georgef042d7a2014-09-29 14:15:01 +0100398 if (cmp >= period) {
Dave Hylands39296b42014-09-26 09:04:05 -0700399 percent = 100.0;
400 } else {
401 percent = (float)cmp * 100.0 / ((float)period);
402 }
403 return mp_obj_new_float(percent);
404 #else
405 mp_int_t percent;
Damien Georgef042d7a2014-09-29 14:15:01 +0100406 if (cmp >= period) {
Dave Hylands39296b42014-09-26 09:04:05 -0700407 percent = 100;
Damien Georgef042d7a2014-09-29 14:15:01 +0100408 } else if (cmp > MAX_PERIOD_DIV_100) {
409 percent = cmp / (period / 100);
Dave Hylands39296b42014-09-26 09:04:05 -0700410 } else {
411 percent = cmp * 100 / period;
412 }
413 return mp_obj_new_int(percent);
414 #endif
415}
416
Damien George7fdfa932014-04-21 16:48:16 +0100417STATIC void pyb_timer_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
418 pyb_timer_obj_t *self = self_in;
Damien Georgea12be912014-04-02 15:09:36 +0100419
Damien George7fdfa932014-04-21 16:48:16 +0100420 if (self->tim.State == HAL_TIM_STATE_RESET) {
421 print(env, "Timer(%u)", self->tim_id);
422 } else {
Damien George97ef94d2014-10-04 14:36:39 +0100423 uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
424 uint32_t period = __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self);
425 // for efficiency, we compute and print freq as an int (not a float)
426 uint32_t freq = timer_get_source_freq(self->tim_id) / ((prescaler + 1) * (period + 1));
427 print(env, "Timer(%u, freq=%u, prescaler=%u, period=%u, mode=%s, div=%u)",
Damien George7fdfa932014-04-21 16:48:16 +0100428 self->tim_id,
Damien George97ef94d2014-10-04 14:36:39 +0100429 freq,
430 prescaler,
431 period,
Dave Hylandsbecbc872014-08-20 13:21:11 -0700432 self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ? "UP" :
433 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN ? "DOWN" : "CENTER",
434 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV4 ? 4 :
435 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV2 ? 2 : 1);
Damien George7fdfa932014-04-21 16:48:16 +0100436 }
437}
Damien Georgea12be912014-04-02 15:09:36 +0100438
Damien George3eb81632014-05-02 16:58:15 +0100439/// \method init(*, freq, prescaler, period)
440/// Initialise the timer. Initialisation must be either by frequency (in Hz)
441/// or by prescaler and period:
442///
443/// tim.init(freq=100) # set the timer to trigger at 100Hz
Dave Hylandsbecbc872014-08-20 13:21:11 -0700444/// tim.init(prescaler=83, period=999) # set the prescaler and period directly
445///
446/// Keyword arguments:
447///
448/// - `freq` - specifies the periodic frequency of the timer. You migh also
449/// view this as the frequency with which the timer goes through
450/// one complete cycle.
451///
452/// - `prescaler` [0-0xffff] - specifies the value to be loaded into the
453/// timer's Prescaler Register (PSC). The timer clock source is divided by
454/// (`prescaler + 1`) to arrive at the timer clock. Timers 2-7 and 12-14
455/// have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
456/// have a clock source of 168 MHz (pyb.freq()[3] * 2).
457///
458/// - `period` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5.
459/// Specifies the value to be loaded into the timer's AutoReload
460/// Register (ARR). This determines the period of the timer (i.e. when the
461/// counter cycles). The timer counter will roll-over after `period + 1`
462/// timer clock cycles.
463///
464/// - `mode` can be one of:
465/// - `Timer.UP` - configures the timer to count from 0 to ARR (default)
466/// - `Timer.DOWN` - configures the timer to count from ARR down to 0.
467/// - `Timer.CENTER` - confgures the timer to count from 0 to ARR and
468/// then back down to 0.
469///
470/// - `div` can be one of 1, 2, or 4. Divides the timer clock to determine
471/// the sampling clock used by the digital filters.
472///
473/// - `callback` - as per Timer.callback()
474///
475/// You must either specify freq or both of period and prescaler.
Damien George97ef94d2014-10-04 14:36:39 +0100476STATIC 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) {
477 static const mp_arg_t allowed_args[] = {
478 { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
479 { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
480 { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
481 { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_COUNTERMODE_UP} },
482 { MP_QSTR_div, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
483 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
484 };
Damien George7fdfa932014-04-21 16:48:16 +0100485
Damien George7fdfa932014-04-21 16:48:16 +0100486 // parse args
Damien George97ef94d2014-10-04 14:36:39 +0100487 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
488 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 +0100489
490 // set the TIM configuration values
491 TIM_Base_InitTypeDef *init = &self->tim.Init;
492
Damien George97ef94d2014-10-04 14:36:39 +0100493 if (args[0].u_obj != mp_const_none) {
494 // set prescaler and period from desired frequency
495 init->Prescaler = compute_prescaler_period_from_freq(self, args[0].u_obj, &init->Period);
496 } else if (args[1].u_int != 0xffffffff && args[2].u_int != 0xffffffff) {
Damien George7fdfa932014-04-21 16:48:16 +0100497 // set prescaler and period directly
Damien George97ef94d2014-10-04 14:36:39 +0100498 init->Prescaler = args[1].u_int;
499 init->Period = args[2].u_int;
Damien George7fdfa932014-04-21 16:48:16 +0100500 } else {
501 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "must specify either freq, or prescaler and period"));
502 }
503
Damien George97ef94d2014-10-04 14:36:39 +0100504 init->CounterMode = args[3].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700505 if (!IS_TIM_COUNTER_MODE(init->CounterMode)) {
Damien George97ef94d2014-10-04 14:36:39 +0100506 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid mode (%d)", init->CounterMode));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700507 }
508
Damien George97ef94d2014-10-04 14:36:39 +0100509 init->ClockDivision = args[4].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
510 args[4].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
511 TIM_CLOCKDIVISION_DIV1;
512
513 init->RepetitionCounter = 0;
514
515 // enable TIM clock
Damien George7fdfa932014-04-21 16:48:16 +0100516 switch (self->tim_id) {
517 case 1: __TIM1_CLK_ENABLE(); break;
518 case 2: __TIM2_CLK_ENABLE(); break;
519 case 3: __TIM3_CLK_ENABLE(); break;
520 case 4: __TIM4_CLK_ENABLE(); break;
521 case 5: __TIM5_CLK_ENABLE(); break;
522 case 6: __TIM6_CLK_ENABLE(); break;
523 case 7: __TIM7_CLK_ENABLE(); break;
524 case 8: __TIM8_CLK_ENABLE(); break;
525 case 9: __TIM9_CLK_ENABLE(); break;
526 case 10: __TIM10_CLK_ENABLE(); break;
527 case 11: __TIM11_CLK_ENABLE(); break;
528 case 12: __TIM12_CLK_ENABLE(); break;
529 case 13: __TIM13_CLK_ENABLE(); break;
530 case 14: __TIM14_CLK_ENABLE(); break;
531 }
Damien George97ef94d2014-10-04 14:36:39 +0100532
533 // set IRQ priority (if not a special timer)
Damien George7fdfa932014-04-21 16:48:16 +0100534 if (self->tim_id != 3 && self->tim_id != 5) {
535 HAL_NVIC_SetPriority(self->irqn, 0xe, 0xe); // next-to lowest priority
536 }
537
Damien George97ef94d2014-10-04 14:36:39 +0100538 // init TIM
Dave Hylandsbecbc872014-08-20 13:21:11 -0700539 HAL_TIM_Base_Init(&self->tim);
Damien George97ef94d2014-10-04 14:36:39 +0100540 if (args[5].u_obj == mp_const_none) {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700541 HAL_TIM_Base_Start(&self->tim);
542 } else {
Damien George97ef94d2014-10-04 14:36:39 +0100543 pyb_timer_callback(self, args[5].u_obj);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700544 }
545
Damien George7fdfa932014-04-21 16:48:16 +0100546 return mp_const_none;
547}
548
Damien George3eb81632014-05-02 16:58:15 +0100549/// \classmethod \constructor(id, ...)
550/// Construct a new timer object of the given id. If additional
551/// arguments are given, then the timer is initialised by `init(...)`.
552/// `id` can be 1 to 14, excluding 3.
Damien Georgeecc88e92014-08-30 00:35:11 +0100553STATIC 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 +0100554 // check arguments
555 mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
556
557 // create new Timer object
558 pyb_timer_obj_t *tim = m_new_obj(pyb_timer_obj_t);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700559 memset(tim, 0, sizeof(*tim));
560
Damien George7fdfa932014-04-21 16:48:16 +0100561 tim->base.type = &pyb_timer_type;
562 tim->callback = mp_const_none;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700563 tim->channel = NULL;
Damien George7fdfa932014-04-21 16:48:16 +0100564
565 // get TIM number
566 tim->tim_id = mp_obj_get_int(args[0]);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700567 tim->is_32bit = false;
Damien George7fdfa932014-04-21 16:48:16 +0100568
569 switch (tim->tim_id) {
570 case 1: tim->tim.Instance = TIM1; tim->irqn = TIM1_UP_TIM10_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700571 case 2: tim->tim.Instance = TIM2; tim->irqn = TIM2_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100572 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
573 case 4: tim->tim.Instance = TIM4; tim->irqn = TIM4_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700574 case 5: tim->tim.Instance = TIM5; tim->irqn = TIM5_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100575 case 6: tim->tim.Instance = TIM6; tim->irqn = TIM6_DAC_IRQn; break;
576 case 7: tim->tim.Instance = TIM7; tim->irqn = TIM7_IRQn; break;
577 case 8: tim->tim.Instance = TIM8; tim->irqn = TIM8_UP_TIM13_IRQn; break;
578 case 9: tim->tim.Instance = TIM9; tim->irqn = TIM1_BRK_TIM9_IRQn; break;
579 case 10: tim->tim.Instance = TIM10; tim->irqn = TIM1_UP_TIM10_IRQn; break;
580 case 11: tim->tim.Instance = TIM11; tim->irqn = TIM1_TRG_COM_TIM11_IRQn; break;
581 case 12: tim->tim.Instance = TIM12; tim->irqn = TIM8_BRK_TIM12_IRQn; break;
582 case 13: tim->tim.Instance = TIM13; tim->irqn = TIM8_UP_TIM13_IRQn; break;
583 case 14: tim->tim.Instance = TIM14; tim->irqn = TIM8_TRG_COM_TIM14_IRQn; break;
584 default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id));
585 }
586
587 if (n_args > 1 || n_kw > 0) {
588 // start the peripheral
589 mp_map_t kw_args;
590 mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
591 pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args);
592 }
593
594 // set the global variable for interrupt callbacks
595 if (tim->tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
596 pyb_timer_obj_all[tim->tim_id - 1] = tim;
597 }
598
599 return (mp_obj_t)tim;
600}
601
Damien Georgeecc88e92014-08-30 00:35:11 +0100602STATIC 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 +0100603 return pyb_timer_init_helper(args[0], n_args - 1, args + 1, kw_args);
604}
605STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
606
Damien George3eb81632014-05-02 16:58:15 +0100607/// \method deinit()
608/// Deinitialises the timer.
609///
Dave Hylands0d81c132014-06-30 07:55:54 -0700610/// Disables the callback (and the associated irq).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700611/// Disables any channel callbacks (and the associated irq).
Dave Hylands0d81c132014-06-30 07:55:54 -0700612/// Stops the timer, and disables the timer peripheral.
Damien George7fdfa932014-04-21 16:48:16 +0100613STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
Dave Hylands0d81c132014-06-30 07:55:54 -0700614 pyb_timer_obj_t *self = self_in;
615
Dave Hylandsbecbc872014-08-20 13:21:11 -0700616 // Disable the base interrupt
Dave Hylands0d81c132014-06-30 07:55:54 -0700617 pyb_timer_callback(self_in, mp_const_none);
618
Dave Hylandsbecbc872014-08-20 13:21:11 -0700619 pyb_timer_channel_obj_t *chan = self->channel;
620 self->channel = NULL;
621
622 // Disable the channel interrupts
623 while (chan != NULL) {
624 pyb_timer_channel_callback(chan, mp_const_none);
625 pyb_timer_channel_obj_t *prev_chan = chan;
626 chan = chan->next;
627 prev_chan->next = NULL;
628 }
629
Dave Hylands0d81c132014-06-30 07:55:54 -0700630 HAL_TIM_Base_DeInit(&self->tim);
Damien George7fdfa932014-04-21 16:48:16 +0100631 return mp_const_none;
632}
633STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);
634
Dave Hylandsbecbc872014-08-20 13:21:11 -0700635/// \method channel(channel, mode, ...)
636///
Damien George0e58c582014-09-21 22:54:02 +0100637/// If only a channel number is passed, then a previously initialized channel
638/// object is returned (or `None` if there is no previous channel).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700639///
640/// Othwerwise, a TimerChannel object is initialized and returned.
641///
642/// Each channel can be configured to perform pwm, output compare, or
643/// input capture. All channels share the same underlying timer, which means
644/// that they share the same timer clock.
645///
646/// Keyword arguments:
647///
648/// - `mode` can be one of:
649/// - `Timer.PWM` - configure the timer in PWM mode (active high).
650/// - `Timer.PWM_INVERTED` - configure the timer in PWM mode (active low).
651/// - `Timer.OC_TIMING` - indicates that no pin is driven.
652/// - `Timer.OC_ACTIVE` - the pin will be made active when a compare
653/// match occurs (active is determined by polarity)
654/// - `Timer.OC_INACTIVE` - the pin will be made inactive when a compare
655/// match occurs.
656/// - `Timer.OC_TOGGLE` - the pin will be toggled when an compare match occurs.
657/// - `Timer.OC_FORCED_ACTIVE` - the pin is forced active (compare match is ignored).
658/// - `Timer.OC_FORCED_INACTIVE` - the pin is forced inactive (compare match is ignored).
659/// - `Timer.IC` - configure the timer in Input Capture mode.
660///
661/// - `callback` - as per TimerChannel.callback()
662///
663/// - `pin` None (the default) or a Pin object. If specified (and not None)
664/// this will cause the alternate function of the the indicated pin
665/// to be configured for this timer channel. An error will be raised if
666/// the pin doesn't support any alternate functions for this timer channel.
667///
668/// Keyword arguments for Timer.PWM modes:
669///
Damien George0e58c582014-09-21 22:54:02 +0100670/// - `pulse_width` - determines the initial pulse width value to use.
Dave Hylands53d5fa62014-09-21 22:40:42 -0700671/// - `pulse_width_percent` - determines the initial pulse width percentage to use.
Dave Hylandsbecbc872014-08-20 13:21:11 -0700672///
673/// Keyword arguments for Timer.OC modes:
674///
675/// - `compare` - determines the initial value of the compare register.
676///
677/// - `polarity` can be one of:
678/// - `Timer.HIGH` - output is active high
679/// - `Timer.LOW` - output is acive low
680///
681/// Optional keyword arguments for Timer.IC modes:
682///
683/// - `polarity` can be one of:
684/// - `Timer.RISING` - captures on rising edge.
685/// - `Timer.FALLING` - captures on falling edge.
686/// - `Timer.BOTH` - captures on both edges.
687///
688/// PWM Example:
689///
690/// timer = pyb.Timer(2, freq=1000)
691/// ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
692/// ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
Damien Georgeba0383a2014-10-04 15:25:01 +0100693STATIC mp_obj_t pyb_timer_channel(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
694 static const mp_arg_t allowed_args[] = {
695 { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
696 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
697 { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
698 { MP_QSTR_pulse_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
699 { MP_QSTR_pulse_width_percent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
700 { MP_QSTR_compare, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
701 { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
702 };
Dave Hylandsbecbc872014-08-20 13:21:11 -0700703
Damien Georgeba0383a2014-10-04 15:25:01 +0100704 pyb_timer_obj_t *self = pos_args[0];
705 mp_int_t channel = mp_obj_get_int(pos_args[1]);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700706
707 if (channel < 1 || channel > 4) {
Damien Georgeba0383a2014-10-04 15:25:01 +0100708 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid channel (%d)", channel));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700709 }
710
711 pyb_timer_channel_obj_t *chan = self->channel;
712 pyb_timer_channel_obj_t *prev_chan = NULL;
713
714 while (chan != NULL) {
715 if (chan->channel == channel) {
716 break;
717 }
718 prev_chan = chan;
719 chan = chan->next;
720 }
Damien George0e58c582014-09-21 22:54:02 +0100721
722 // If only the channel number is given return the previously allocated
723 // channel (or None if no previous channel).
Damien Georgeba0383a2014-10-04 15:25:01 +0100724 if (n_args == 2 && kw_args->used == 0) {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700725 if (chan) {
726 return chan;
727 }
728 return mp_const_none;
729 }
730
731 // If there was already a channel, then remove it from the list. Note that
732 // the order we do things here is important so as to appear atomic to
733 // the IRQ handler.
734 if (chan) {
735 // Turn off any IRQ associated with the channel.
736 pyb_timer_channel_callback(chan, mp_const_none);
737
738 // Unlink the channel from the list.
739 if (prev_chan) {
740 prev_chan->next = chan->next;
741 }
742 self->channel = chan->next;
743 chan->next = NULL;
744 }
745
746 // Allocate and initialize a new channel
Damien Georgeba0383a2014-10-04 15:25:01 +0100747 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
748 mp_arg_parse_all(n_args - 2, pos_args + 2, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700749
750 chan = m_new_obj(pyb_timer_channel_obj_t);
751 memset(chan, 0, sizeof(*chan));
752 chan->base.type = &pyb_timer_channel_type;
753 chan->timer = self;
754 chan->channel = channel;
Damien Georgeba0383a2014-10-04 15:25:01 +0100755 chan->mode = args[0].u_int;
756 chan->callback = args[1].u_obj;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700757
Damien Georgeba0383a2014-10-04 15:25:01 +0100758 mp_obj_t pin_obj = args[2].u_obj;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700759 if (pin_obj != mp_const_none) {
760 if (!MP_OBJ_IS_TYPE(pin_obj, &pin_type)) {
761 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "pin argument needs to be be a Pin type"));
762 }
763 const pin_obj_t *pin = pin_obj;
764 const pin_af_obj_t *af = pin_find_af(pin, AF_FN_TIM, self->tim_id);
765 if (af == NULL) {
766 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));
767 }
768 // pin.init(mode=AF_PP, af=idx)
Damien Georgeba0383a2014-10-04 15:25:01 +0100769 const mp_obj_t args2[6] = {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700770 (mp_obj_t)&pin_init_obj,
771 pin_obj,
772 MP_OBJ_NEW_QSTR(MP_QSTR_mode), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP),
773 MP_OBJ_NEW_QSTR(MP_QSTR_af), MP_OBJ_NEW_SMALL_INT(af->idx)
774 };
Damien Georgeba0383a2014-10-04 15:25:01 +0100775 mp_call_method_n_kw(0, 2, args2);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700776 }
777
778 // Link the channel to the timer before we turn the channel on.
779 // Note that this needs to appear atomic to the IRQ handler (the write
780 // to self->channel is atomic, so we're good, but I thought I'd mention
781 // in case this was ever changed in the future).
782 chan->next = self->channel;
783 self->channel = chan;
784
785 switch (chan->mode) {
786
787 case CHANNEL_MODE_PWM_NORMAL:
788 case CHANNEL_MODE_PWM_INVERTED: {
789 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100790 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
Damien Georgeba0383a2014-10-04 15:25:01 +0100791 if (args[4].u_obj != mp_const_none) {
Dave Hylands53d5fa62014-09-21 22:40:42 -0700792 // pulse width percent given
Dave Hylands39296b42014-09-26 09:04:05 -0700793 uint32_t period = compute_period(self);
Damien Georgeba0383a2014-10-04 15:25:01 +0100794 oc_config.Pulse = compute_pwm_value_from_percent(period, args[4].u_obj);
Damien George0e58c582014-09-21 22:54:02 +0100795 } else {
Damien Georgee8ea0722014-09-25 15:44:10 +0100796 // use absolute pulse width value (defaults to 0 if nothing given)
Damien Georgeba0383a2014-10-04 15:25:01 +0100797 oc_config.Pulse = args[3].u_int;
Damien George0e58c582014-09-21 22:54:02 +0100798 }
Dave Hylandsbecbc872014-08-20 13:21:11 -0700799 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
800 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
801 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
802 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
803 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
804
805 HAL_TIM_PWM_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
806 if (chan->callback == mp_const_none) {
807 HAL_TIM_PWM_Start(&self->tim, TIMER_CHANNEL(chan));
808 } else {
809 HAL_TIM_PWM_Start_IT(&self->tim, TIMER_CHANNEL(chan));
810 }
811 break;
812 }
813
814 case CHANNEL_MODE_OC_TIMING:
815 case CHANNEL_MODE_OC_ACTIVE:
816 case CHANNEL_MODE_OC_INACTIVE:
817 case CHANNEL_MODE_OC_TOGGLE:
818 case CHANNEL_MODE_OC_FORCED_ACTIVE:
819 case CHANNEL_MODE_OC_FORCED_INACTIVE: {
820 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100821 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
Damien Georgeba0383a2014-10-04 15:25:01 +0100822 oc_config.Pulse = args[5].u_int;
823 oc_config.OCPolarity = args[6].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700824 if (oc_config.OCPolarity == 0xffffffff) {
825 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
826 }
827 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
828 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
829 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
830 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
831
832 if (!IS_TIM_OC_POLARITY(oc_config.OCPolarity)) {
Damien Georgeba0383a2014-10-04 15:25:01 +0100833 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", oc_config.OCPolarity));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700834 }
835 HAL_TIM_OC_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
836 if (chan->callback == mp_const_none) {
837 HAL_TIM_OC_Start(&self->tim, TIMER_CHANNEL(chan));
838 } else {
839 HAL_TIM_OC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
840 }
841 break;
842 }
843
844 case CHANNEL_MODE_IC: {
845 TIM_IC_InitTypeDef ic_config;
846
Damien Georgeba0383a2014-10-04 15:25:01 +0100847 ic_config.ICPolarity = args[6].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700848 if (ic_config.ICPolarity == 0xffffffff) {
849 ic_config.ICPolarity = TIM_ICPOLARITY_RISING;
850 }
851 ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
852 ic_config.ICPrescaler = TIM_ICPSC_DIV1;
853 ic_config.ICFilter = 0;
854
855 if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) {
Damien Georgeba0383a2014-10-04 15:25:01 +0100856 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", ic_config.ICPolarity));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700857 }
858 HAL_TIM_IC_ConfigChannel(&self->tim, &ic_config, TIMER_CHANNEL(chan));
859 if (chan->callback == mp_const_none) {
860 HAL_TIM_IC_Start(&self->tim, TIMER_CHANNEL(chan));
861 } else {
862 HAL_TIM_IC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
863 }
864 break;
865 }
866
867 default:
Damien Georgeba0383a2014-10-04 15:25:01 +0100868 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid mode (%d)", chan->mode));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700869 }
870
871 return chan;
872}
Damien George0e58c582014-09-21 22:54:02 +0100873STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700874
Damien George3eb81632014-05-02 16:58:15 +0100875/// \method counter([value])
876/// Get or set the timer counter.
Damien George0e58c582014-09-21 22:54:02 +0100877STATIC mp_obj_t pyb_timer_counter(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100878 pyb_timer_obj_t *self = args[0];
879 if (n_args == 1) {
880 // get
881 return mp_obj_new_int(self->tim.Instance->CNT);
882 } else {
883 // set
884 __HAL_TIM_SetCounter(&self->tim, mp_obj_get_int(args[1]));
885 return mp_const_none;
886 }
887}
888STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_counter_obj, 1, 2, pyb_timer_counter);
889
Damien George97ef94d2014-10-04 14:36:39 +0100890/// \method source_freq()
891/// Get the frequency of the source of the timer.
892STATIC mp_obj_t pyb_timer_source_freq(mp_obj_t self_in) {
893 pyb_timer_obj_t *self = self_in;
894 uint32_t source_freq = timer_get_source_freq(self->tim_id);
895 return mp_obj_new_int(source_freq);
896}
897STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_source_freq_obj, pyb_timer_source_freq);
898
899/// \method freq([value])
900/// Get or set the frequency for the timer (changes prescaler and period if set).
901STATIC mp_obj_t pyb_timer_freq(mp_uint_t n_args, const mp_obj_t *args) {
902 pyb_timer_obj_t *self = args[0];
903 if (n_args == 1) {
904 // get
905 uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
906 uint32_t period = __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self);
907 uint32_t source_freq = timer_get_source_freq(self->tim_id);
908 uint32_t divide = ((prescaler + 1) * (period + 1));
909 if (source_freq % divide == 0) {
910 return mp_obj_new_int(source_freq / divide);
911 } else {
912 return mp_obj_new_float((float)source_freq / (float)divide);
913 }
914 } else {
915 // set
916 uint32_t period;
917 uint32_t prescaler = compute_prescaler_period_from_freq(self, args[1], &period);
918 self->tim.Instance->PSC = prescaler;
919 __HAL_TIM_SetAutoreload(&self->tim, period);
920 return mp_const_none;
921 }
922}
923STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_freq_obj, 1, 2, pyb_timer_freq);
924
Damien George3eb81632014-05-02 16:58:15 +0100925/// \method prescaler([value])
926/// Get or set the prescaler for the timer.
Damien George0e58c582014-09-21 22:54:02 +0100927STATIC mp_obj_t pyb_timer_prescaler(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
931 return mp_obj_new_int(self->tim.Instance->PSC & 0xffff);
932 } else {
933 // set
Damien George97ef94d2014-10-04 14:36:39 +0100934 self->tim.Instance->PSC = mp_obj_get_int(args[1]) & 0xffff;
Damien George7fdfa932014-04-21 16:48:16 +0100935 return mp_const_none;
936 }
937}
938STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);
939
Damien George3eb81632014-05-02 16:58:15 +0100940/// \method period([value])
941/// Get or set the period of the timer.
Damien George0e58c582014-09-21 22:54:02 +0100942STATIC mp_obj_t pyb_timer_period(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100943 pyb_timer_obj_t *self = args[0];
944 if (n_args == 1) {
945 // get
Dave Hylandsbecbc872014-08-20 13:21:11 -0700946 return mp_obj_new_int(__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +0100947 } else {
948 // set
Dave Hylandsbecbc872014-08-20 13:21:11 -0700949 __HAL_TIM_SetAutoreload(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +0100950 return mp_const_none;
951 }
952}
953STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
954
Damien George3eb81632014-05-02 16:58:15 +0100955/// \method callback(fun)
956/// Set the function to be called when the timer triggers.
957/// `fun` is passed 1 argument, the timer object.
958/// If `fun` is `None` then the callback will be disabled.
Damien George7fdfa932014-04-21 16:48:16 +0100959STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
960 pyb_timer_obj_t *self = self_in;
961 if (callback == mp_const_none) {
962 // stop interrupt (but not timer)
963 __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
964 self->callback = mp_const_none;
965 } else if (mp_obj_is_callable(callback)) {
966 self->callback = callback;
967 HAL_NVIC_EnableIRQ(self->irqn);
968 // start timer, so that it interrupts on overflow
969 HAL_TIM_Base_Start_IT(&self->tim);
970 } else {
971 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
972 }
Damien Georgea12be912014-04-02 15:09:36 +0100973 return mp_const_none;
974}
Damien George7fdfa932014-04-21 16:48:16 +0100975STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);
Damien Georgea12be912014-04-02 15:09:36 +0100976
Damien George7fdfa932014-04-21 16:48:16 +0100977STATIC const mp_map_elem_t pyb_timer_locals_dict_table[] = {
978 // instance methods
979 { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_timer_init_obj },
980 { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_timer_deinit_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700981 { MP_OBJ_NEW_QSTR(MP_QSTR_channel), (mp_obj_t)&pyb_timer_channel_obj },
Damien George7fdfa932014-04-21 16:48:16 +0100982 { MP_OBJ_NEW_QSTR(MP_QSTR_counter), (mp_obj_t)&pyb_timer_counter_obj },
Damien George97ef94d2014-10-04 14:36:39 +0100983 { MP_OBJ_NEW_QSTR(MP_QSTR_source_freq), (mp_obj_t)&pyb_timer_source_freq_obj },
984 { MP_OBJ_NEW_QSTR(MP_QSTR_freq), (mp_obj_t)&pyb_timer_freq_obj },
Damien George7fdfa932014-04-21 16:48:16 +0100985 { MP_OBJ_NEW_QSTR(MP_QSTR_prescaler), (mp_obj_t)&pyb_timer_prescaler_obj },
986 { MP_OBJ_NEW_QSTR(MP_QSTR_period), (mp_obj_t)&pyb_timer_period_obj },
987 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_callback_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700988 { MP_OBJ_NEW_QSTR(MP_QSTR_UP), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_UP) },
989 { MP_OBJ_NEW_QSTR(MP_QSTR_DOWN), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_DOWN) },
990 { MP_OBJ_NEW_QSTR(MP_QSTR_CENTER), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_CENTERALIGNED1) },
991 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_NORMAL) },
992 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM_INVERTED), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_INVERTED) },
993 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TIMING), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TIMING) },
994 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_ACTIVE) },
995 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_INACTIVE) },
996 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TOGGLE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TOGGLE) },
997 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_ACTIVE) },
998 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_INACTIVE) },
999 { MP_OBJ_NEW_QSTR(MP_QSTR_IC), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_IC) },
1000 { MP_OBJ_NEW_QSTR(MP_QSTR_HIGH), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_HIGH) },
1001 { MP_OBJ_NEW_QSTR(MP_QSTR_LOW), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_LOW) },
1002 { MP_OBJ_NEW_QSTR(MP_QSTR_RISING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_RISING) },
1003 { MP_OBJ_NEW_QSTR(MP_QSTR_FALLING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_FALLING) },
1004 { MP_OBJ_NEW_QSTR(MP_QSTR_BOTH), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_BOTHEDGE) },
Damien George7fdfa932014-04-21 16:48:16 +01001005};
Damien George7fdfa932014-04-21 16:48:16 +01001006STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table);
Damien Georgea12be912014-04-02 15:09:36 +01001007
Damien George7fdfa932014-04-21 16:48:16 +01001008const mp_obj_type_t pyb_timer_type = {
1009 { &mp_type_type },
1010 .name = MP_QSTR_Timer,
1011 .print = pyb_timer_print,
1012 .make_new = pyb_timer_make_new,
1013 .locals_dict = (mp_obj_t)&pyb_timer_locals_dict,
1014};
Damien Georgea12be912014-04-02 15:09:36 +01001015
Dave Hylandsbecbc872014-08-20 13:21:11 -07001016/// \moduleref pyb
1017/// \class TimerChannel - setup a channel for a timer.
1018///
1019/// Timer channels are used to generate/capture a signal using a timer.
1020///
1021/// TimerChannel objects are created using the Timer.channel() method.
1022STATIC void pyb_timer_channel_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
1023 pyb_timer_channel_obj_t *self = self_in;
1024
1025 print(env, "TimerChannel(timer=%u, channel=%u, mode=%s)",
1026 self->timer->tim_id,
1027 self->channel,
Damien George0e58c582014-09-21 22:54:02 +01001028 qstr_str(channel_mode_info[self->mode].name));
Dave Hylandsbecbc872014-08-20 13:21:11 -07001029}
1030
1031/// \method capture([value])
1032/// Get or set the capture value associated with a channel.
1033/// capture, compare, and pulse_width are all aliases for the same function.
1034/// capture is the logical name to use when the channel is in input capture mode.
1035
1036/// \method compare([value])
1037/// Get or set the compare value associated with a channel.
1038/// capture, compare, and pulse_width are all aliases for the same function.
1039/// compare is the logical name to use when the channel is in output compare mode.
1040
1041/// \method pulse_width([value])
1042/// Get or set the pulse width value associated with a channel.
1043/// capture, compare, and pulse_width are all aliases for the same function.
1044/// pulse_width is the logical name to use when the channel is in PWM mode.
Dave Hylands39296b42014-09-26 09:04:05 -07001045///
1046/// In edge aligned mode, a pulse_width of `period + 1` corresponds to a duty cycle of 100%
1047/// In center aligned mode, a pulse width of `period` corresponds to a duty cycle of 100%
Damien George0e58c582014-09-21 22:54:02 +01001048STATIC 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 -07001049 pyb_timer_channel_obj_t *self = args[0];
Dave Hylandsbecbc872014-08-20 13:21:11 -07001050 if (n_args == 1) {
1051 // get
1052 return mp_obj_new_int(__HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer));
1053 } else {
1054 // set
1055 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self->timer));
1056 return mp_const_none;
1057 }
1058}
1059STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_capture_compare_obj, 1, 2, pyb_timer_channel_capture_compare);
1060
Damien Georgee8ea0722014-09-25 15:44:10 +01001061/// \method pulse_width_percent([value])
1062/// Get or set the pulse width percentage associated with a channel. The value
1063/// is a number between 0 and 100 and sets the percentage of the timer period
1064/// for which the pulse is active. The value can be an integer or
1065/// floating-point number for more accuracy. For example, a value of 25 gives
1066/// a duty cycle of 25%.
Dave Hylands53d5fa62014-09-21 22:40:42 -07001067STATIC 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 +01001068 pyb_timer_channel_obj_t *self = args[0];
Dave Hylands39296b42014-09-26 09:04:05 -07001069 uint32_t period = compute_period(self->timer);
Damien George0e58c582014-09-21 22:54:02 +01001070 if (n_args == 1) {
1071 // get
1072 uint32_t cmp = __HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer);
Dave Hylands39296b42014-09-26 09:04:05 -07001073 return compute_percent_from_pwm_value(period, cmp);
Damien George0e58c582014-09-21 22:54:02 +01001074 } else {
1075 // set
Damien Georgee8ea0722014-09-25 15:44:10 +01001076 uint32_t cmp = compute_pwm_value_from_percent(period, args[1]);
Damien George0e58c582014-09-21 22:54:02 +01001077 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), cmp & TIMER_CNT_MASK(self->timer));
1078 return mp_const_none;
1079 }
1080}
Dave Hylands53d5fa62014-09-21 22:40:42 -07001081STATIC 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 +01001082
Dave Hylandsbecbc872014-08-20 13:21:11 -07001083/// \method callback(fun)
1084/// Set the function to be called when the timer channel triggers.
1085/// `fun` is passed 1 argument, the timer object.
1086/// If `fun` is `None` then the callback will be disabled.
1087STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback) {
1088 pyb_timer_channel_obj_t *self = self_in;
1089 if (callback == mp_const_none) {
1090 // stop interrupt (but not timer)
1091 __HAL_TIM_DISABLE_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
1092 self->callback = mp_const_none;
1093 } else if (mp_obj_is_callable(callback)) {
1094 self->callback = callback;
1095 HAL_NVIC_EnableIRQ(self->timer->irqn);
1096 // start timer, so that it interrupts on overflow
1097 switch (self->mode) {
1098 case CHANNEL_MODE_PWM_NORMAL:
1099 case CHANNEL_MODE_PWM_INVERTED:
1100 HAL_TIM_PWM_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1101 break;
1102 case CHANNEL_MODE_OC_TIMING:
1103 case CHANNEL_MODE_OC_ACTIVE:
1104 case CHANNEL_MODE_OC_INACTIVE:
1105 case CHANNEL_MODE_OC_TOGGLE:
1106 case CHANNEL_MODE_OC_FORCED_ACTIVE:
1107 case CHANNEL_MODE_OC_FORCED_INACTIVE:
1108 HAL_TIM_OC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1109 break;
1110 case CHANNEL_MODE_IC:
1111 HAL_TIM_IC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1112 break;
1113 }
1114 } else {
1115 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
1116 }
1117 return mp_const_none;
1118}
1119STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_channel_callback_obj, pyb_timer_channel_callback);
1120
1121STATIC const mp_map_elem_t pyb_timer_channel_locals_dict_table[] = {
1122 // instance methods
1123 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_channel_callback_obj },
1124 { MP_OBJ_NEW_QSTR(MP_QSTR_pulse_width), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
Dave Hylands53d5fa62014-09-21 22:40:42 -07001125 { 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 -07001126 { MP_OBJ_NEW_QSTR(MP_QSTR_capture), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1127 { MP_OBJ_NEW_QSTR(MP_QSTR_compare), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1128};
1129STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);
1130
Damien George0e58c582014-09-21 22:54:02 +01001131STATIC const mp_obj_type_t pyb_timer_channel_type = {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001132 { &mp_type_type },
1133 .name = MP_QSTR_TimerChannel,
1134 .print = pyb_timer_channel_print,
1135 .locals_dict = (mp_obj_t)&pyb_timer_channel_locals_dict,
1136};
1137
Damien George0e58c582014-09-21 22:54:02 +01001138STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001139 uint32_t irq_mask = TIMER_IRQ_MASK(channel);
1140
1141 if (__HAL_TIM_GET_FLAG(&tim->tim, irq_mask) != RESET) {
1142 if (__HAL_TIM_GET_ITSTATUS(&tim->tim, irq_mask) != RESET) {
1143 // clear the interrupt
1144 __HAL_TIM_CLEAR_IT(&tim->tim, irq_mask);
1145
1146 // execute callback if it's set
1147 if (callback != mp_const_none) {
1148 // When executing code within a handler we must lock the GC to prevent
1149 // any memory allocations. We must also catch any exceptions.
1150 gc_lock();
1151 nlr_buf_t nlr;
1152 if (nlr_push(&nlr) == 0) {
1153 mp_call_function_1(callback, tim);
1154 nlr_pop();
1155 } else {
1156 // Uncaught exception; disable the callback so it doesn't run again.
1157 tim->callback = mp_const_none;
1158 __HAL_TIM_DISABLE_IT(&tim->tim, irq_mask);
1159 if (channel == 0) {
1160 printf("Uncaught exception in Timer(" UINT_FMT
1161 ") interrupt handler\n", tim->tim_id);
1162 } else {
1163 printf("Uncaught exception in Timer(" UINT_FMT ") channel "
1164 UINT_FMT " interrupt handler\n", tim->tim_id, channel);
1165 }
1166 mp_obj_print_exception((mp_obj_t)nlr.ret_val);
1167 }
1168 gc_unlock();
1169 }
1170 }
1171 }
1172}
1173
Damien George7fdfa932014-04-21 16:48:16 +01001174void timer_irq_handler(uint tim_id) {
1175 if (tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
1176 // get the timer object
1177 pyb_timer_obj_t *tim = pyb_timer_obj_all[tim_id - 1];
Damien Georgea12be912014-04-02 15:09:36 +01001178
Damien George7fdfa932014-04-21 16:48:16 +01001179 if (tim == NULL) {
Damien George0e58c582014-09-21 22:54:02 +01001180 // Timer object has not been set, so we can't do anything.
1181 // This can happen under normal circumstances for timers like
1182 // 1 & 10 which use the same IRQ.
Damien George7fdfa932014-04-21 16:48:16 +01001183 return;
1184 }
Damien Georgea12be912014-04-02 15:09:36 +01001185
Dave Hylandsbecbc872014-08-20 13:21:11 -07001186 // Check for timer (versus timer channel) interrupt.
1187 timer_handle_irq_channel(tim, 0, tim->callback);
1188 uint32_t handled = TIMER_IRQ_MASK(0);
Damien Georgea12be912014-04-02 15:09:36 +01001189
Dave Hylandsbecbc872014-08-20 13:21:11 -07001190 // Check to see if a timer channel interrupt was pending
1191 pyb_timer_channel_obj_t *chan = tim->channel;
1192 while (chan != NULL) {
1193 timer_handle_irq_channel(tim, chan->channel, chan->callback);
1194 handled |= TIMER_IRQ_MASK(chan->channel);
1195 chan = chan->next;
1196 }
1197
1198 // Finally, clear any remaining interrupt sources. Otherwise we'll
1199 // just get called continuously.
1200 uint32_t unhandled = __HAL_TIM_GET_ITSTATUS(&tim->tim, 0xff & ~handled);
1201 if (unhandled != 0) {
1202 __HAL_TIM_CLEAR_IT(&tim->tim, unhandled);
1203 printf("Unhandled interrupt SR=0x%02lx (now disabled)\n", unhandled);
Damien Georgea12be912014-04-02 15:09:36 +01001204 }
1205 }
1206}