blob: 93f66c6314c9cde35a60b084ce7660b901eebe38 [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;
136
Damien George7fdfa932014-04-21 16:48:16 +0100137} pyb_timer_obj_t;
Damien Georgea12be912014-04-02 15:09:36 +0100138
Dave Hylandsbecbc872014-08-20 13:21:11 -0700139// The following yields TIM_IT_UPDATE when channel is zero and
140// TIM_IT_CC1..TIM_IT_CC4 when channel is 1..4
141#define TIMER_IRQ_MASK(channel) (1 << (channel))
Damien Georgee8ea0722014-09-25 15:44:10 +0100142#define TIMER_CNT_MASK(self) ((self)->is_32bit ? 0xffffffff : 0xffff)
Dave Hylandsbecbc872014-08-20 13:21:11 -0700143#define TIMER_CHANNEL(self) ((((self)->channel) - 1) << 2)
144
Damien Georgea12be912014-04-02 15:09:36 +0100145TIM_HandleTypeDef TIM3_Handle;
146TIM_HandleTypeDef TIM5_Handle;
Damien George4d7f4eb2014-04-15 19:52:56 +0100147TIM_HandleTypeDef TIM6_Handle;
Damien Georgea12be912014-04-02 15:09:36 +0100148
Damien George6d983532014-04-16 23:08:36 +0100149// Used to divide down TIM3 and periodically call the flash storage IRQ
Damien George0e58c582014-09-21 22:54:02 +0100150STATIC uint32_t tim3_counter = 0;
Damien George6d983532014-04-16 23:08:36 +0100151
Damien George7fdfa932014-04-21 16:48:16 +0100152// Used to do callbacks to Python code on interrupt
153STATIC pyb_timer_obj_t *pyb_timer_obj_all[14];
Emmanuel Blotf6932d62014-06-19 18:54:34 +0200154#define PYB_TIMER_OBJ_ALL_NUM MP_ARRAY_SIZE(pyb_timer_obj_all)
Damien George7fdfa932014-04-21 16:48:16 +0100155
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
184 TIM3_Handle.Init.Prescaler = 84-1; // for System clock at 168MHz, 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 Georgea12be912014-04-02 15:09:36 +0100218 TIM5_Handle.Init.Prescaler = ((SystemCoreClock / 2) / 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 George7fdfa932014-04-21 16:48:16 +0100234 uint32_t period = MAX(1, (SystemCoreClock / 2) / 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 George7fdfa932014-04-21 16:48:16 +0100266/******************************************************************************/
267/* Micro Python bindings */
Damien Georgea12be912014-04-02 15:09:36 +0100268
Damien George0e58c582014-09-21 22:54:02 +0100269STATIC const mp_obj_type_t pyb_timer_channel_type;
270
Damien Georgee8ea0722014-09-25 15:44:10 +0100271// Helper function to compute PWM value from timer period and percent value.
272// 'val' can be an int or a float between 0 and 100 (out of range values are
273// clamped).
274STATIC uint32_t compute_pwm_value_from_percent(uint32_t period, mp_obj_t val) {
275 uint32_t cmp;
276 if (0) {
277 #if MICROPY_PY_BUILTINS_FLOAT
278 } else if (MP_OBJ_IS_TYPE(val, &mp_type_float)) {
279 cmp = mp_obj_get_float(val) / 100.0 * period;
280 #endif
281 } else {
282 // For integer arithmetic, if period is large and 100*period will
283 // overflow, then divide period before multiplying by cmp. Otherwise
284 // do it the other way round to retain precision.
285 // TODO we really need an mp_obj_get_uint_clamped function here so
286 // that we can get long-int values as large as 0xffffffff.
287 cmp = mp_obj_get_int(val);
288 if (period > (1 << 31) / 100) {
289 cmp = cmp * (period / 100);
290 } else {
291 cmp = (cmp * period) / 100;
292 }
293 }
294 if (cmp < 0) {
295 cmp = 0;
296 } else if (cmp > period) {
297 cmp = period;
298 }
299 return cmp;
300}
301
Damien George7fdfa932014-04-21 16:48:16 +0100302STATIC void pyb_timer_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
303 pyb_timer_obj_t *self = self_in;
Damien Georgea12be912014-04-02 15:09:36 +0100304
Damien George7fdfa932014-04-21 16:48:16 +0100305 if (self->tim.State == HAL_TIM_STATE_RESET) {
306 print(env, "Timer(%u)", self->tim_id);
307 } else {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700308 print(env, "Timer(%u, prescaler=%u, period=%u, mode=%s, div=%u)",
Damien George7fdfa932014-04-21 16:48:16 +0100309 self->tim_id,
Dave Hylands53d5fa62014-09-21 22:40:42 -0700310 self->tim.Instance->PSC & 0xffff,
311 __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self),
Dave Hylandsbecbc872014-08-20 13:21:11 -0700312 self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ? "UP" :
313 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN ? "DOWN" : "CENTER",
314 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV4 ? 4 :
315 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV2 ? 2 : 1);
Damien George7fdfa932014-04-21 16:48:16 +0100316 }
317}
Damien Georgea12be912014-04-02 15:09:36 +0100318
Damien George3eb81632014-05-02 16:58:15 +0100319/// \method init(*, freq, prescaler, period)
320/// Initialise the timer. Initialisation must be either by frequency (in Hz)
321/// or by prescaler and period:
322///
323/// tim.init(freq=100) # set the timer to trigger at 100Hz
Dave Hylandsbecbc872014-08-20 13:21:11 -0700324/// tim.init(prescaler=83, period=999) # set the prescaler and period directly
325///
326/// Keyword arguments:
327///
328/// - `freq` - specifies the periodic frequency of the timer. You migh also
329/// view this as the frequency with which the timer goes through
330/// one complete cycle.
331///
332/// - `prescaler` [0-0xffff] - specifies the value to be loaded into the
333/// timer's Prescaler Register (PSC). The timer clock source is divided by
334/// (`prescaler + 1`) to arrive at the timer clock. Timers 2-7 and 12-14
335/// have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
336/// have a clock source of 168 MHz (pyb.freq()[3] * 2).
337///
338/// - `period` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5.
339/// Specifies the value to be loaded into the timer's AutoReload
340/// Register (ARR). This determines the period of the timer (i.e. when the
341/// counter cycles). The timer counter will roll-over after `period + 1`
342/// timer clock cycles.
343///
344/// - `mode` can be one of:
345/// - `Timer.UP` - configures the timer to count from 0 to ARR (default)
346/// - `Timer.DOWN` - configures the timer to count from ARR down to 0.
347/// - `Timer.CENTER` - confgures the timer to count from 0 to ARR and
348/// then back down to 0.
349///
350/// - `div` can be one of 1, 2, or 4. Divides the timer clock to determine
351/// the sampling clock used by the digital filters.
352///
353/// - `callback` - as per Timer.callback()
354///
355/// You must either specify freq or both of period and prescaler.
356 STATIC const mp_arg_t pyb_timer_init_args[] = {
357 { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
358 { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
359 { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
360 { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_COUNTERMODE_UP} },
361 { MP_QSTR_div, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
362 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
Damien George7fdfa932014-04-21 16:48:16 +0100363};
Emmanuel Blotf6932d62014-06-19 18:54:34 +0200364#define PYB_TIMER_INIT_NUM_ARGS MP_ARRAY_SIZE(pyb_timer_init_args)
Damien George7fdfa932014-04-21 16:48:16 +0100365
Damien Georgeecc88e92014-08-30 00:35:11 +0100366STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
Damien George7fdfa932014-04-21 16:48:16 +0100367 // parse args
Damien Georgedbc81df2014-04-26 11:19:17 +0100368 mp_arg_val_t vals[PYB_TIMER_INIT_NUM_ARGS];
369 mp_arg_parse_all(n_args, args, kw_args, PYB_TIMER_INIT_NUM_ARGS, pyb_timer_init_args, vals);
Damien George7fdfa932014-04-21 16:48:16 +0100370
371 // set the TIM configuration values
372 TIM_Base_InitTypeDef *init = &self->tim.Init;
373
374 if (vals[0].u_int != 0xffffffff) {
375 // set prescaler and period from frequency
376
377 if (vals[0].u_int == 0) {
378 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't have 0 frequency"));
379 }
380
381 // work out TIM's clock source
382 uint tim_clock;
383 if (self->tim_id == 1 || (8 <= self->tim_id && self->tim_id <= 11)) {
384 // TIM{1,8,9,10,11} are on APB2
385 tim_clock = HAL_RCC_GetPCLK2Freq();
386 } else {
387 // TIM{2,3,4,5,6,7,12,13,14} are on APB1
388 tim_clock = HAL_RCC_GetPCLK1Freq();
389 }
390
Damien Georgebf133f72014-08-14 00:30:14 +0100391 // Compute the prescaler value so TIM triggers at freq-Hz
392 // On STM32F405/407/415/417 there are 2 cases for how the clock freq is set.
393 // If the APB prescaler is 1, then the timer clock is equal to its respective
394 // APB clock. Otherwise (APB prescaler > 1) the timer clock is twice its
395 // respective APB clock. See DM00031020 Rev 4, page 115.
Damien George7fdfa932014-04-21 16:48:16 +0100396 uint32_t period = MAX(1, 2 * tim_clock / vals[0].u_int);
397 uint32_t prescaler = 1;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700398 while (period > TIMER_CNT_MASK(self)) {
Damien George7fdfa932014-04-21 16:48:16 +0100399 period >>= 1;
400 prescaler <<= 1;
401 }
402 init->Prescaler = prescaler - 1;
403 init->Period = period - 1;
404 } else if (vals[1].u_int != 0xffffffff && vals[2].u_int != 0xffffffff) {
405 // set prescaler and period directly
406 init->Prescaler = vals[1].u_int;
407 init->Period = vals[2].u_int;
408 } else {
409 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "must specify either freq, or prescaler and period"));
410 }
411
412 init->CounterMode = vals[3].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700413
414 init->ClockDivision = vals[4].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
415 vals[4].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
416 TIM_CLOCKDIVISION_DIV1;
Damien George7fdfa932014-04-21 16:48:16 +0100417 init->RepetitionCounter = 0;
418
Dave Hylandsbecbc872014-08-20 13:21:11 -0700419 if (!IS_TIM_COUNTER_MODE(init->CounterMode)) {
420 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid counter_mode (%d)", init->CounterMode));
421 }
422
Damien George7fdfa932014-04-21 16:48:16 +0100423 // init the TIM peripheral
424 switch (self->tim_id) {
425 case 1: __TIM1_CLK_ENABLE(); break;
426 case 2: __TIM2_CLK_ENABLE(); break;
427 case 3: __TIM3_CLK_ENABLE(); break;
428 case 4: __TIM4_CLK_ENABLE(); break;
429 case 5: __TIM5_CLK_ENABLE(); break;
430 case 6: __TIM6_CLK_ENABLE(); break;
431 case 7: __TIM7_CLK_ENABLE(); break;
432 case 8: __TIM8_CLK_ENABLE(); break;
433 case 9: __TIM9_CLK_ENABLE(); break;
434 case 10: __TIM10_CLK_ENABLE(); break;
435 case 11: __TIM11_CLK_ENABLE(); break;
436 case 12: __TIM12_CLK_ENABLE(); break;
437 case 13: __TIM13_CLK_ENABLE(); break;
438 case 14: __TIM14_CLK_ENABLE(); break;
439 }
Damien George7fdfa932014-04-21 16:48:16 +0100440 // set the priority (if not a special timer)
441 if (self->tim_id != 3 && self->tim_id != 5) {
442 HAL_NVIC_SetPriority(self->irqn, 0xe, 0xe); // next-to lowest priority
443 }
444
Dave Hylandsbecbc872014-08-20 13:21:11 -0700445 HAL_TIM_Base_Init(&self->tim);
446 if (vals[5].u_obj == mp_const_none) {
447 HAL_TIM_Base_Start(&self->tim);
448 } else {
449 pyb_timer_callback(self, vals[5].u_obj);
450 }
451
Damien George7fdfa932014-04-21 16:48:16 +0100452 return mp_const_none;
453}
454
Damien George3eb81632014-05-02 16:58:15 +0100455/// \classmethod \constructor(id, ...)
456/// Construct a new timer object of the given id. If additional
457/// arguments are given, then the timer is initialised by `init(...)`.
458/// `id` can be 1 to 14, excluding 3.
Damien Georgeecc88e92014-08-30 00:35:11 +0100459STATIC 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 +0100460 // check arguments
461 mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
462
463 // create new Timer object
464 pyb_timer_obj_t *tim = m_new_obj(pyb_timer_obj_t);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700465 memset(tim, 0, sizeof(*tim));
466
Damien George7fdfa932014-04-21 16:48:16 +0100467 tim->base.type = &pyb_timer_type;
468 tim->callback = mp_const_none;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700469 tim->channel = NULL;
Damien George7fdfa932014-04-21 16:48:16 +0100470
471 // get TIM number
472 tim->tim_id = mp_obj_get_int(args[0]);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700473 tim->is_32bit = false;
Damien George7fdfa932014-04-21 16:48:16 +0100474
475 switch (tim->tim_id) {
476 case 1: tim->tim.Instance = TIM1; tim->irqn = TIM1_UP_TIM10_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700477 case 2: tim->tim.Instance = TIM2; tim->irqn = TIM2_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100478 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
479 case 4: tim->tim.Instance = TIM4; tim->irqn = TIM4_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700480 case 5: tim->tim.Instance = TIM5; tim->irqn = TIM5_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100481 case 6: tim->tim.Instance = TIM6; tim->irqn = TIM6_DAC_IRQn; break;
482 case 7: tim->tim.Instance = TIM7; tim->irqn = TIM7_IRQn; break;
483 case 8: tim->tim.Instance = TIM8; tim->irqn = TIM8_UP_TIM13_IRQn; break;
484 case 9: tim->tim.Instance = TIM9; tim->irqn = TIM1_BRK_TIM9_IRQn; break;
485 case 10: tim->tim.Instance = TIM10; tim->irqn = TIM1_UP_TIM10_IRQn; break;
486 case 11: tim->tim.Instance = TIM11; tim->irqn = TIM1_TRG_COM_TIM11_IRQn; break;
487 case 12: tim->tim.Instance = TIM12; tim->irqn = TIM8_BRK_TIM12_IRQn; break;
488 case 13: tim->tim.Instance = TIM13; tim->irqn = TIM8_UP_TIM13_IRQn; break;
489 case 14: tim->tim.Instance = TIM14; tim->irqn = TIM8_TRG_COM_TIM14_IRQn; break;
490 default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id));
491 }
492
493 if (n_args > 1 || n_kw > 0) {
494 // start the peripheral
495 mp_map_t kw_args;
496 mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
497 pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args);
498 }
499
500 // set the global variable for interrupt callbacks
501 if (tim->tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
502 pyb_timer_obj_all[tim->tim_id - 1] = tim;
503 }
504
505 return (mp_obj_t)tim;
506}
507
Damien Georgeecc88e92014-08-30 00:35:11 +0100508STATIC 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 +0100509 return pyb_timer_init_helper(args[0], n_args - 1, args + 1, kw_args);
510}
511STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
512
Damien George3eb81632014-05-02 16:58:15 +0100513/// \method deinit()
514/// Deinitialises the timer.
515///
Dave Hylands0d81c132014-06-30 07:55:54 -0700516/// Disables the callback (and the associated irq).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700517/// Disables any channel callbacks (and the associated irq).
Dave Hylands0d81c132014-06-30 07:55:54 -0700518/// Stops the timer, and disables the timer peripheral.
Damien George7fdfa932014-04-21 16:48:16 +0100519STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
Dave Hylands0d81c132014-06-30 07:55:54 -0700520 pyb_timer_obj_t *self = self_in;
521
Dave Hylandsbecbc872014-08-20 13:21:11 -0700522 // Disable the base interrupt
Dave Hylands0d81c132014-06-30 07:55:54 -0700523 pyb_timer_callback(self_in, mp_const_none);
524
Dave Hylandsbecbc872014-08-20 13:21:11 -0700525 pyb_timer_channel_obj_t *chan = self->channel;
526 self->channel = NULL;
527
528 // Disable the channel interrupts
529 while (chan != NULL) {
530 pyb_timer_channel_callback(chan, mp_const_none);
531 pyb_timer_channel_obj_t *prev_chan = chan;
532 chan = chan->next;
533 prev_chan->next = NULL;
534 }
535
Dave Hylands0d81c132014-06-30 07:55:54 -0700536 HAL_TIM_Base_DeInit(&self->tim);
Damien George7fdfa932014-04-21 16:48:16 +0100537 return mp_const_none;
538}
539STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);
540
Dave Hylandsbecbc872014-08-20 13:21:11 -0700541/// \method channel(channel, mode, ...)
542///
Damien George0e58c582014-09-21 22:54:02 +0100543/// If only a channel number is passed, then a previously initialized channel
544/// object is returned (or `None` if there is no previous channel).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700545///
546/// Othwerwise, a TimerChannel object is initialized and returned.
547///
548/// Each channel can be configured to perform pwm, output compare, or
549/// input capture. All channels share the same underlying timer, which means
550/// that they share the same timer clock.
551///
552/// Keyword arguments:
553///
554/// - `mode` can be one of:
555/// - `Timer.PWM` - configure the timer in PWM mode (active high).
556/// - `Timer.PWM_INVERTED` - configure the timer in PWM mode (active low).
557/// - `Timer.OC_TIMING` - indicates that no pin is driven.
558/// - `Timer.OC_ACTIVE` - the pin will be made active when a compare
559/// match occurs (active is determined by polarity)
560/// - `Timer.OC_INACTIVE` - the pin will be made inactive when a compare
561/// match occurs.
562/// - `Timer.OC_TOGGLE` - the pin will be toggled when an compare match occurs.
563/// - `Timer.OC_FORCED_ACTIVE` - the pin is forced active (compare match is ignored).
564/// - `Timer.OC_FORCED_INACTIVE` - the pin is forced inactive (compare match is ignored).
565/// - `Timer.IC` - configure the timer in Input Capture mode.
566///
567/// - `callback` - as per TimerChannel.callback()
568///
569/// - `pin` None (the default) or a Pin object. If specified (and not None)
570/// this will cause the alternate function of the the indicated pin
571/// to be configured for this timer channel. An error will be raised if
572/// the pin doesn't support any alternate functions for this timer channel.
573///
574/// Keyword arguments for Timer.PWM modes:
575///
Damien George0e58c582014-09-21 22:54:02 +0100576/// - `pulse_width` - determines the initial pulse width value to use.
Dave Hylands53d5fa62014-09-21 22:40:42 -0700577/// - `pulse_width_percent` - determines the initial pulse width percentage to use.
Dave Hylandsbecbc872014-08-20 13:21:11 -0700578///
579/// Keyword arguments for Timer.OC modes:
580///
581/// - `compare` - determines the initial value of the compare register.
582///
583/// - `polarity` can be one of:
584/// - `Timer.HIGH` - output is active high
585/// - `Timer.LOW` - output is acive low
586///
587/// Optional keyword arguments for Timer.IC modes:
588///
589/// - `polarity` can be one of:
590/// - `Timer.RISING` - captures on rising edge.
591/// - `Timer.FALLING` - captures on falling edge.
592/// - `Timer.BOTH` - captures on both edges.
593///
594/// PWM Example:
595///
596/// timer = pyb.Timer(2, freq=1000)
597/// ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
598/// ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
599STATIC const mp_arg_t pyb_timer_channel_args[] = {
Dave Hylands53d5fa62014-09-21 22:40:42 -0700600 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
601 { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
Damien Georgee8ea0722014-09-25 15:44:10 +0100602 { MP_QSTR_pulse_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
Dave Hylands53d5fa62014-09-21 22:40:42 -0700603 { MP_QSTR_pulse_width_percent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
604 { MP_QSTR_compare, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
605 { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700606};
607#define PYB_TIMER_CHANNEL_NUM_ARGS MP_ARRAY_SIZE(pyb_timer_channel_args)
608
609STATIC 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 -0700610 pyb_timer_obj_t *self = args[0];
611 mp_int_t channel = mp_obj_get_int(args[1]);
612
613 if (channel < 1 || channel > 4) {
614 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid channel (%d)", channel));
615 }
616
617 pyb_timer_channel_obj_t *chan = self->channel;
618 pyb_timer_channel_obj_t *prev_chan = NULL;
619
620 while (chan != NULL) {
621 if (chan->channel == channel) {
622 break;
623 }
624 prev_chan = chan;
625 chan = chan->next;
626 }
Damien George0e58c582014-09-21 22:54:02 +0100627
628 // If only the channel number is given return the previously allocated
629 // channel (or None if no previous channel).
630 if (n_args == 2) {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700631 if (chan) {
632 return chan;
633 }
634 return mp_const_none;
635 }
636
637 // If there was already a channel, then remove it from the list. Note that
638 // the order we do things here is important so as to appear atomic to
639 // the IRQ handler.
640 if (chan) {
641 // Turn off any IRQ associated with the channel.
642 pyb_timer_channel_callback(chan, mp_const_none);
643
644 // Unlink the channel from the list.
645 if (prev_chan) {
646 prev_chan->next = chan->next;
647 }
648 self->channel = chan->next;
649 chan->next = NULL;
650 }
651
652 // Allocate and initialize a new channel
653 mp_arg_val_t vals[PYB_TIMER_CHANNEL_NUM_ARGS];
654 mp_arg_parse_all(n_args - 3, args + 3, kw_args, PYB_TIMER_CHANNEL_NUM_ARGS, pyb_timer_channel_args, vals);
655
656 chan = m_new_obj(pyb_timer_channel_obj_t);
657 memset(chan, 0, sizeof(*chan));
658 chan->base.type = &pyb_timer_channel_type;
659 chan->timer = self;
660 chan->channel = channel;
661 chan->mode = mp_obj_get_int(args[2]);
662 chan->callback = vals[0].u_obj;
663
664 mp_obj_t pin_obj = vals[1].u_obj;
665 if (pin_obj != mp_const_none) {
666 if (!MP_OBJ_IS_TYPE(pin_obj, &pin_type)) {
667 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "pin argument needs to be be a Pin type"));
668 }
669 const pin_obj_t *pin = pin_obj;
670 const pin_af_obj_t *af = pin_find_af(pin, AF_FN_TIM, self->tim_id);
671 if (af == NULL) {
672 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));
673 }
674 // pin.init(mode=AF_PP, af=idx)
675 const mp_obj_t args[6] = {
676 (mp_obj_t)&pin_init_obj,
677 pin_obj,
678 MP_OBJ_NEW_QSTR(MP_QSTR_mode), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP),
679 MP_OBJ_NEW_QSTR(MP_QSTR_af), MP_OBJ_NEW_SMALL_INT(af->idx)
680 };
681 mp_call_method_n_kw(0, 2, args);
682 }
683
684 // Link the channel to the timer before we turn the channel on.
685 // Note that this needs to appear atomic to the IRQ handler (the write
686 // to self->channel is atomic, so we're good, but I thought I'd mention
687 // in case this was ever changed in the future).
688 chan->next = self->channel;
689 self->channel = chan;
690
691 switch (chan->mode) {
692
693 case CHANNEL_MODE_PWM_NORMAL:
694 case CHANNEL_MODE_PWM_INVERTED: {
695 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100696 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
Damien Georgee8ea0722014-09-25 15:44:10 +0100697 if (vals[3].u_obj != mp_const_none) {
Dave Hylands53d5fa62014-09-21 22:40:42 -0700698 // pulse width percent given
Damien George0e58c582014-09-21 22:54:02 +0100699 uint32_t period = (__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self)) + 1;
Damien Georgee8ea0722014-09-25 15:44:10 +0100700 // For 32-bit timer, maximum period + 1 will overflow. In that
701 // case we set the period back to 0xffffffff which will give very
702 // close to the correct result for the percentage calculation.
703 if (period == 0) {
704 period = 0xffffffff;
Dave Hylands53d5fa62014-09-21 22:40:42 -0700705 }
Damien Georgee8ea0722014-09-25 15:44:10 +0100706 oc_config.Pulse = compute_pwm_value_from_percent(period, vals[3].u_obj);
Damien George0e58c582014-09-21 22:54:02 +0100707 } else {
Damien Georgee8ea0722014-09-25 15:44:10 +0100708 // use absolute pulse width value (defaults to 0 if nothing given)
709 oc_config.Pulse = vals[2].u_int;
Damien George0e58c582014-09-21 22:54:02 +0100710 }
Dave Hylandsbecbc872014-08-20 13:21:11 -0700711 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
712 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
713 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
714 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
715 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
716
717 HAL_TIM_PWM_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
718 if (chan->callback == mp_const_none) {
719 HAL_TIM_PWM_Start(&self->tim, TIMER_CHANNEL(chan));
720 } else {
721 HAL_TIM_PWM_Start_IT(&self->tim, TIMER_CHANNEL(chan));
722 }
723 break;
724 }
725
726 case CHANNEL_MODE_OC_TIMING:
727 case CHANNEL_MODE_OC_ACTIVE:
728 case CHANNEL_MODE_OC_INACTIVE:
729 case CHANNEL_MODE_OC_TOGGLE:
730 case CHANNEL_MODE_OC_FORCED_ACTIVE:
731 case CHANNEL_MODE_OC_FORCED_INACTIVE: {
732 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100733 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
734 oc_config.Pulse = vals[4].u_int;
735 oc_config.OCPolarity = vals[5].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700736 if (oc_config.OCPolarity == 0xffffffff) {
737 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
738 }
739 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
740 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
741 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
742 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
743
744 if (!IS_TIM_OC_POLARITY(oc_config.OCPolarity)) {
745 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", oc_config.OCPolarity));
746 }
747 HAL_TIM_OC_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
748 if (chan->callback == mp_const_none) {
749 HAL_TIM_OC_Start(&self->tim, TIMER_CHANNEL(chan));
750 } else {
751 HAL_TIM_OC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
752 }
753 break;
754 }
755
756 case CHANNEL_MODE_IC: {
757 TIM_IC_InitTypeDef ic_config;
758
Damien George0e58c582014-09-21 22:54:02 +0100759 ic_config.ICPolarity = vals[5].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700760 if (ic_config.ICPolarity == 0xffffffff) {
761 ic_config.ICPolarity = TIM_ICPOLARITY_RISING;
762 }
763 ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
764 ic_config.ICPrescaler = TIM_ICPSC_DIV1;
765 ic_config.ICFilter = 0;
766
767 if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) {
768 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", ic_config.ICPolarity));
769 }
770 HAL_TIM_IC_ConfigChannel(&self->tim, &ic_config, TIMER_CHANNEL(chan));
771 if (chan->callback == mp_const_none) {
772 HAL_TIM_IC_Start(&self->tim, TIMER_CHANNEL(chan));
773 } else {
774 HAL_TIM_IC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
775 }
776 break;
777 }
778
779 default:
780 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid mode (%d)", chan->mode));
781 }
782
783 return chan;
784}
Damien George0e58c582014-09-21 22:54:02 +0100785STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700786
Damien George3eb81632014-05-02 16:58:15 +0100787/// \method counter([value])
788/// Get or set the timer counter.
Damien George0e58c582014-09-21 22:54:02 +0100789STATIC mp_obj_t pyb_timer_counter(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100790 pyb_timer_obj_t *self = args[0];
791 if (n_args == 1) {
792 // get
793 return mp_obj_new_int(self->tim.Instance->CNT);
794 } else {
795 // set
796 __HAL_TIM_SetCounter(&self->tim, mp_obj_get_int(args[1]));
797 return mp_const_none;
798 }
799}
800STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_counter_obj, 1, 2, pyb_timer_counter);
801
Damien George3eb81632014-05-02 16:58:15 +0100802/// \method prescaler([value])
803/// Get or set the prescaler for the timer.
Damien George0e58c582014-09-21 22:54:02 +0100804STATIC mp_obj_t pyb_timer_prescaler(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100805 pyb_timer_obj_t *self = args[0];
806 if (n_args == 1) {
807 // get
808 return mp_obj_new_int(self->tim.Instance->PSC & 0xffff);
809 } else {
810 // set
811 self->tim.Init.Prescaler = self->tim.Instance->PSC = mp_obj_get_int(args[1]) & 0xffff;
812 return mp_const_none;
813 }
814}
815STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);
816
Damien George3eb81632014-05-02 16:58:15 +0100817/// \method period([value])
818/// Get or set the period of the timer.
Damien George0e58c582014-09-21 22:54:02 +0100819STATIC mp_obj_t pyb_timer_period(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100820 pyb_timer_obj_t *self = args[0];
821 if (n_args == 1) {
822 // get
Dave Hylandsbecbc872014-08-20 13:21:11 -0700823 return mp_obj_new_int(__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +0100824 } else {
825 // set
Dave Hylandsbecbc872014-08-20 13:21:11 -0700826 __HAL_TIM_SetAutoreload(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +0100827 return mp_const_none;
828 }
829}
830STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
831
Damien George3eb81632014-05-02 16:58:15 +0100832/// \method callback(fun)
833/// Set the function to be called when the timer triggers.
834/// `fun` is passed 1 argument, the timer object.
835/// If `fun` is `None` then the callback will be disabled.
Damien George7fdfa932014-04-21 16:48:16 +0100836STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
837 pyb_timer_obj_t *self = self_in;
838 if (callback == mp_const_none) {
839 // stop interrupt (but not timer)
840 __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
841 self->callback = mp_const_none;
842 } else if (mp_obj_is_callable(callback)) {
843 self->callback = callback;
844 HAL_NVIC_EnableIRQ(self->irqn);
845 // start timer, so that it interrupts on overflow
846 HAL_TIM_Base_Start_IT(&self->tim);
847 } else {
848 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
849 }
Damien Georgea12be912014-04-02 15:09:36 +0100850 return mp_const_none;
851}
Damien George7fdfa932014-04-21 16:48:16 +0100852STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);
Damien Georgea12be912014-04-02 15:09:36 +0100853
Damien George7fdfa932014-04-21 16:48:16 +0100854STATIC const mp_map_elem_t pyb_timer_locals_dict_table[] = {
855 // instance methods
856 { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_timer_init_obj },
857 { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_timer_deinit_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700858 { MP_OBJ_NEW_QSTR(MP_QSTR_channel), (mp_obj_t)&pyb_timer_channel_obj },
Damien George7fdfa932014-04-21 16:48:16 +0100859 { MP_OBJ_NEW_QSTR(MP_QSTR_counter), (mp_obj_t)&pyb_timer_counter_obj },
860 { MP_OBJ_NEW_QSTR(MP_QSTR_prescaler), (mp_obj_t)&pyb_timer_prescaler_obj },
861 { MP_OBJ_NEW_QSTR(MP_QSTR_period), (mp_obj_t)&pyb_timer_period_obj },
862 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_callback_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700863 { MP_OBJ_NEW_QSTR(MP_QSTR_UP), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_UP) },
864 { MP_OBJ_NEW_QSTR(MP_QSTR_DOWN), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_DOWN) },
865 { MP_OBJ_NEW_QSTR(MP_QSTR_CENTER), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_CENTERALIGNED1) },
866 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_NORMAL) },
867 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM_INVERTED), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_INVERTED) },
868 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TIMING), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TIMING) },
869 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_ACTIVE) },
870 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_INACTIVE) },
871 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TOGGLE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TOGGLE) },
872 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_ACTIVE) },
873 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_INACTIVE) },
874 { MP_OBJ_NEW_QSTR(MP_QSTR_IC), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_IC) },
875 { MP_OBJ_NEW_QSTR(MP_QSTR_HIGH), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_HIGH) },
876 { MP_OBJ_NEW_QSTR(MP_QSTR_LOW), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_LOW) },
877 { MP_OBJ_NEW_QSTR(MP_QSTR_RISING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_RISING) },
878 { MP_OBJ_NEW_QSTR(MP_QSTR_FALLING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_FALLING) },
879 { MP_OBJ_NEW_QSTR(MP_QSTR_BOTH), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_BOTHEDGE) },
Damien George7fdfa932014-04-21 16:48:16 +0100880};
Damien George7fdfa932014-04-21 16:48:16 +0100881STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table);
Damien Georgea12be912014-04-02 15:09:36 +0100882
Damien George7fdfa932014-04-21 16:48:16 +0100883const mp_obj_type_t pyb_timer_type = {
884 { &mp_type_type },
885 .name = MP_QSTR_Timer,
886 .print = pyb_timer_print,
887 .make_new = pyb_timer_make_new,
888 .locals_dict = (mp_obj_t)&pyb_timer_locals_dict,
889};
Damien Georgea12be912014-04-02 15:09:36 +0100890
Dave Hylandsbecbc872014-08-20 13:21:11 -0700891/// \moduleref pyb
892/// \class TimerChannel - setup a channel for a timer.
893///
894/// Timer channels are used to generate/capture a signal using a timer.
895///
896/// TimerChannel objects are created using the Timer.channel() method.
897STATIC void pyb_timer_channel_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
898 pyb_timer_channel_obj_t *self = self_in;
899
900 print(env, "TimerChannel(timer=%u, channel=%u, mode=%s)",
901 self->timer->tim_id,
902 self->channel,
Damien George0e58c582014-09-21 22:54:02 +0100903 qstr_str(channel_mode_info[self->mode].name));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700904}
905
906/// \method capture([value])
907/// Get or set the capture value associated with a channel.
908/// capture, compare, and pulse_width are all aliases for the same function.
909/// capture is the logical name to use when the channel is in input capture mode.
910
911/// \method compare([value])
912/// Get or set the compare value associated with a channel.
913/// capture, compare, and pulse_width are all aliases for the same function.
914/// compare is the logical name to use when the channel is in output compare mode.
915
916/// \method pulse_width([value])
917/// Get or set the pulse width value associated with a channel.
918/// capture, compare, and pulse_width are all aliases for the same function.
919/// pulse_width is the logical name to use when the channel is in PWM mode.
Damien George0e58c582014-09-21 22:54:02 +0100920STATIC 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 -0700921 pyb_timer_channel_obj_t *self = args[0];
Dave Hylandsbecbc872014-08-20 13:21:11 -0700922 if (n_args == 1) {
923 // get
924 return mp_obj_new_int(__HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer));
925 } else {
926 // set
927 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self->timer));
928 return mp_const_none;
929 }
930}
931STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_capture_compare_obj, 1, 2, pyb_timer_channel_capture_compare);
932
Damien Georgee8ea0722014-09-25 15:44:10 +0100933/// \method pulse_width_percent([value])
934/// Get or set the pulse width percentage associated with a channel. The value
935/// is a number between 0 and 100 and sets the percentage of the timer period
936/// for which the pulse is active. The value can be an integer or
937/// floating-point number for more accuracy. For example, a value of 25 gives
938/// a duty cycle of 25%.
Dave Hylands53d5fa62014-09-21 22:40:42 -0700939STATIC 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 +0100940 pyb_timer_channel_obj_t *self = args[0];
Damien George0e58c582014-09-21 22:54:02 +0100941 uint32_t period = (__HAL_TIM_GetAutoreload(&self->timer->tim) & TIMER_CNT_MASK(self->timer)) + 1;
Damien Georgee8ea0722014-09-25 15:44:10 +0100942 // For 32-bit timer, maximum period + 1 will overflow. In that case we set
943 // the period back to 0xffffffff which will give very close to the correct
944 // result for the percentage calculation.
945 if (period == 0) {
946 period = 0xffffffff;
947 }
Damien George0e58c582014-09-21 22:54:02 +0100948 if (n_args == 1) {
949 // get
950 uint32_t cmp = __HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer);
Damien Georgee8ea0722014-09-25 15:44:10 +0100951 #if MICROPY_PY_BUILTINS_FLOAT
952 return mp_obj_new_float((float)cmp / (float)period * 100.0);
953 #else
954 // TODO handle overflow of multiplication for 32-bit timer
Dave Hylands53d5fa62014-09-21 22:40:42 -0700955 return mp_obj_new_int(cmp * 100 / period);
Damien Georgee8ea0722014-09-25 15:44:10 +0100956 #endif
Damien George0e58c582014-09-21 22:54:02 +0100957 } else {
958 // set
Damien Georgee8ea0722014-09-25 15:44:10 +0100959 uint32_t cmp = compute_pwm_value_from_percent(period, args[1]);
Damien George0e58c582014-09-21 22:54:02 +0100960 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), cmp & TIMER_CNT_MASK(self->timer));
961 return mp_const_none;
962 }
963}
Dave Hylands53d5fa62014-09-21 22:40:42 -0700964STATIC 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 +0100965
Dave Hylandsbecbc872014-08-20 13:21:11 -0700966/// \method callback(fun)
967/// Set the function to be called when the timer channel triggers.
968/// `fun` is passed 1 argument, the timer object.
969/// If `fun` is `None` then the callback will be disabled.
970STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback) {
971 pyb_timer_channel_obj_t *self = self_in;
972 if (callback == mp_const_none) {
973 // stop interrupt (but not timer)
974 __HAL_TIM_DISABLE_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
975 self->callback = mp_const_none;
976 } else if (mp_obj_is_callable(callback)) {
977 self->callback = callback;
978 HAL_NVIC_EnableIRQ(self->timer->irqn);
979 // start timer, so that it interrupts on overflow
980 switch (self->mode) {
981 case CHANNEL_MODE_PWM_NORMAL:
982 case CHANNEL_MODE_PWM_INVERTED:
983 HAL_TIM_PWM_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
984 break;
985 case CHANNEL_MODE_OC_TIMING:
986 case CHANNEL_MODE_OC_ACTIVE:
987 case CHANNEL_MODE_OC_INACTIVE:
988 case CHANNEL_MODE_OC_TOGGLE:
989 case CHANNEL_MODE_OC_FORCED_ACTIVE:
990 case CHANNEL_MODE_OC_FORCED_INACTIVE:
991 HAL_TIM_OC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
992 break;
993 case CHANNEL_MODE_IC:
994 HAL_TIM_IC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
995 break;
996 }
997 } else {
998 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
999 }
1000 return mp_const_none;
1001}
1002STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_channel_callback_obj, pyb_timer_channel_callback);
1003
1004STATIC const mp_map_elem_t pyb_timer_channel_locals_dict_table[] = {
1005 // instance methods
1006 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_channel_callback_obj },
1007 { MP_OBJ_NEW_QSTR(MP_QSTR_pulse_width), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
Dave Hylands53d5fa62014-09-21 22:40:42 -07001008 { 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 -07001009 { MP_OBJ_NEW_QSTR(MP_QSTR_capture), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1010 { MP_OBJ_NEW_QSTR(MP_QSTR_compare), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1011};
1012STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);
1013
Damien George0e58c582014-09-21 22:54:02 +01001014STATIC const mp_obj_type_t pyb_timer_channel_type = {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001015 { &mp_type_type },
1016 .name = MP_QSTR_TimerChannel,
1017 .print = pyb_timer_channel_print,
1018 .locals_dict = (mp_obj_t)&pyb_timer_channel_locals_dict,
1019};
1020
Damien George0e58c582014-09-21 22:54:02 +01001021STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001022 uint32_t irq_mask = TIMER_IRQ_MASK(channel);
1023
1024 if (__HAL_TIM_GET_FLAG(&tim->tim, irq_mask) != RESET) {
1025 if (__HAL_TIM_GET_ITSTATUS(&tim->tim, irq_mask) != RESET) {
1026 // clear the interrupt
1027 __HAL_TIM_CLEAR_IT(&tim->tim, irq_mask);
1028
1029 // execute callback if it's set
1030 if (callback != mp_const_none) {
1031 // When executing code within a handler we must lock the GC to prevent
1032 // any memory allocations. We must also catch any exceptions.
1033 gc_lock();
1034 nlr_buf_t nlr;
1035 if (nlr_push(&nlr) == 0) {
1036 mp_call_function_1(callback, tim);
1037 nlr_pop();
1038 } else {
1039 // Uncaught exception; disable the callback so it doesn't run again.
1040 tim->callback = mp_const_none;
1041 __HAL_TIM_DISABLE_IT(&tim->tim, irq_mask);
1042 if (channel == 0) {
1043 printf("Uncaught exception in Timer(" UINT_FMT
1044 ") interrupt handler\n", tim->tim_id);
1045 } else {
1046 printf("Uncaught exception in Timer(" UINT_FMT ") channel "
1047 UINT_FMT " interrupt handler\n", tim->tim_id, channel);
1048 }
1049 mp_obj_print_exception((mp_obj_t)nlr.ret_val);
1050 }
1051 gc_unlock();
1052 }
1053 }
1054 }
1055}
1056
Damien George7fdfa932014-04-21 16:48:16 +01001057void timer_irq_handler(uint tim_id) {
1058 if (tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
1059 // get the timer object
1060 pyb_timer_obj_t *tim = pyb_timer_obj_all[tim_id - 1];
Damien Georgea12be912014-04-02 15:09:36 +01001061
Damien George7fdfa932014-04-21 16:48:16 +01001062 if (tim == NULL) {
Damien George0e58c582014-09-21 22:54:02 +01001063 // Timer object has not been set, so we can't do anything.
1064 // This can happen under normal circumstances for timers like
1065 // 1 & 10 which use the same IRQ.
Damien George7fdfa932014-04-21 16:48:16 +01001066 return;
1067 }
Damien Georgea12be912014-04-02 15:09:36 +01001068
Dave Hylandsbecbc872014-08-20 13:21:11 -07001069 // Check for timer (versus timer channel) interrupt.
1070 timer_handle_irq_channel(tim, 0, tim->callback);
1071 uint32_t handled = TIMER_IRQ_MASK(0);
Damien Georgea12be912014-04-02 15:09:36 +01001072
Dave Hylandsbecbc872014-08-20 13:21:11 -07001073 // Check to see if a timer channel interrupt was pending
1074 pyb_timer_channel_obj_t *chan = tim->channel;
1075 while (chan != NULL) {
1076 timer_handle_irq_channel(tim, chan->channel, chan->callback);
1077 handled |= TIMER_IRQ_MASK(chan->channel);
1078 chan = chan->next;
1079 }
1080
1081 // Finally, clear any remaining interrupt sources. Otherwise we'll
1082 // just get called continuously.
1083 uint32_t unhandled = __HAL_TIM_GET_ITSTATUS(&tim->tim, 0xff & ~handled);
1084 if (unhandled != 0) {
1085 __HAL_TIM_CLEAR_IT(&tim->tim, unhandled);
1086 printf("Unhandled interrupt SR=0x%02lx (now disabled)\n", unhandled);
Damien Georgea12be912014-04-02 15:09:36 +01001087 }
1088 }
1089}