blob: 5efecbc9d2df64ee627971c7aac48262e716f23e [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
Damien George24119172014-10-04 01:54:31 +0100184 TIM3_Handle.Init.Prescaler = 2 * HAL_RCC_GetPCLK1Freq() / 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 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
Dave Hylands39296b42014-09-26 09:04:05 -0700271// This is the largest value that we can multiply by 100 and have the result
272// fit in a uint32_t.
273#define MAX_PERIOD_DIV_100 42949672
274
275// Helper function for determining the period used for calculating percent
276STATIC uint32_t compute_period(pyb_timer_obj_t *self) {
277 // In center mode, compare == period corresponds to 100%
278 // In edge mode, compare == (period + 1) corresponds to 100%
279 uint32_t period = (__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
280 if (period != 0xffffffff) {
281 if (self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ||
282 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN) {
283 // Edge mode
284 period++;
285 }
286 }
287 return period;
288}
289
Damien Georgee8ea0722014-09-25 15:44:10 +0100290// Helper function to compute PWM value from timer period and percent value.
Dave Hylands39296b42014-09-26 09:04:05 -0700291// 'percent_in' can be an int or a float between 0 and 100 (out of range
292// values are clamped).
293STATIC uint32_t compute_pwm_value_from_percent(uint32_t period, mp_obj_t percent_in) {
Damien Georgee8ea0722014-09-25 15:44:10 +0100294 uint32_t cmp;
295 if (0) {
296 #if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands39296b42014-09-26 09:04:05 -0700297 } else if (MP_OBJ_IS_TYPE(percent_in, &mp_type_float)) {
298 float percent = mp_obj_get_float(percent_in);
299 if (percent <= 0.0) {
300 cmp = 0;
301 } else if (percent >= 100.0) {
302 cmp = period;
303 } else {
304 cmp = percent / 100.0 * ((float)period);
305 }
Damien Georgee8ea0722014-09-25 15:44:10 +0100306 #endif
307 } else {
308 // For integer arithmetic, if period is large and 100*period will
309 // overflow, then divide period before multiplying by cmp. Otherwise
310 // do it the other way round to retain precision.
Dave Hylands39296b42014-09-26 09:04:05 -0700311 mp_int_t percent = mp_obj_get_int(percent_in);
312 if (percent <= 0) {
313 cmp = 0;
314 } else if (percent >= 100) {
315 cmp = period;
316 } else if (period > MAX_PERIOD_DIV_100) {
317 cmp = (uint32_t)percent * (period / 100);
Damien Georgee8ea0722014-09-25 15:44:10 +0100318 } else {
Dave Hylands39296b42014-09-26 09:04:05 -0700319 cmp = ((uint32_t)percent * period) / 100;
Damien Georgee8ea0722014-09-25 15:44:10 +0100320 }
321 }
Damien Georgee8ea0722014-09-25 15:44:10 +0100322 return cmp;
323}
324
Dave Hylands39296b42014-09-26 09:04:05 -0700325// Helper function to compute percentage from timer perion and PWM value.
326STATIC mp_obj_t compute_percent_from_pwm_value(uint32_t period, uint32_t cmp) {
327 #if MICROPY_PY_BUILTINS_FLOAT
328 float percent;
Damien Georgef042d7a2014-09-29 14:15:01 +0100329 if (cmp >= period) {
Dave Hylands39296b42014-09-26 09:04:05 -0700330 percent = 100.0;
331 } else {
332 percent = (float)cmp * 100.0 / ((float)period);
333 }
334 return mp_obj_new_float(percent);
335 #else
336 mp_int_t percent;
Damien Georgef042d7a2014-09-29 14:15:01 +0100337 if (cmp >= period) {
Dave Hylands39296b42014-09-26 09:04:05 -0700338 percent = 100;
Damien Georgef042d7a2014-09-29 14:15:01 +0100339 } else if (cmp > MAX_PERIOD_DIV_100) {
340 percent = cmp / (period / 100);
Dave Hylands39296b42014-09-26 09:04:05 -0700341 } else {
342 percent = cmp * 100 / period;
343 }
344 return mp_obj_new_int(percent);
345 #endif
346}
347
Damien George7fdfa932014-04-21 16:48:16 +0100348STATIC void pyb_timer_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
349 pyb_timer_obj_t *self = self_in;
Damien Georgea12be912014-04-02 15:09:36 +0100350
Damien George7fdfa932014-04-21 16:48:16 +0100351 if (self->tim.State == HAL_TIM_STATE_RESET) {
352 print(env, "Timer(%u)", self->tim_id);
353 } else {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700354 print(env, "Timer(%u, prescaler=%u, period=%u, mode=%s, div=%u)",
Damien George7fdfa932014-04-21 16:48:16 +0100355 self->tim_id,
Dave Hylands53d5fa62014-09-21 22:40:42 -0700356 self->tim.Instance->PSC & 0xffff,
357 __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self),
Dave Hylandsbecbc872014-08-20 13:21:11 -0700358 self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ? "UP" :
359 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN ? "DOWN" : "CENTER",
360 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV4 ? 4 :
361 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV2 ? 2 : 1);
Damien George7fdfa932014-04-21 16:48:16 +0100362 }
363}
Damien Georgea12be912014-04-02 15:09:36 +0100364
Damien George3eb81632014-05-02 16:58:15 +0100365/// \method init(*, freq, prescaler, period)
366/// Initialise the timer. Initialisation must be either by frequency (in Hz)
367/// or by prescaler and period:
368///
369/// tim.init(freq=100) # set the timer to trigger at 100Hz
Dave Hylandsbecbc872014-08-20 13:21:11 -0700370/// tim.init(prescaler=83, period=999) # set the prescaler and period directly
371///
372/// Keyword arguments:
373///
374/// - `freq` - specifies the periodic frequency of the timer. You migh also
375/// view this as the frequency with which the timer goes through
376/// one complete cycle.
377///
378/// - `prescaler` [0-0xffff] - specifies the value to be loaded into the
379/// timer's Prescaler Register (PSC). The timer clock source is divided by
380/// (`prescaler + 1`) to arrive at the timer clock. Timers 2-7 and 12-14
381/// have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
382/// have a clock source of 168 MHz (pyb.freq()[3] * 2).
383///
384/// - `period` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5.
385/// Specifies the value to be loaded into the timer's AutoReload
386/// Register (ARR). This determines the period of the timer (i.e. when the
387/// counter cycles). The timer counter will roll-over after `period + 1`
388/// timer clock cycles.
389///
390/// - `mode` can be one of:
391/// - `Timer.UP` - configures the timer to count from 0 to ARR (default)
392/// - `Timer.DOWN` - configures the timer to count from ARR down to 0.
393/// - `Timer.CENTER` - confgures the timer to count from 0 to ARR and
394/// then back down to 0.
395///
396/// - `div` can be one of 1, 2, or 4. Divides the timer clock to determine
397/// the sampling clock used by the digital filters.
398///
399/// - `callback` - as per Timer.callback()
400///
401/// You must either specify freq or both of period and prescaler.
402 STATIC const mp_arg_t pyb_timer_init_args[] = {
403 { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
404 { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
405 { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
406 { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_COUNTERMODE_UP} },
407 { MP_QSTR_div, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
408 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
Damien George7fdfa932014-04-21 16:48:16 +0100409};
Emmanuel Blotf6932d62014-06-19 18:54:34 +0200410#define PYB_TIMER_INIT_NUM_ARGS MP_ARRAY_SIZE(pyb_timer_init_args)
Damien George7fdfa932014-04-21 16:48:16 +0100411
Damien Georgeecc88e92014-08-30 00:35:11 +0100412STATIC 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 +0100413 // parse args
Damien Georgedbc81df2014-04-26 11:19:17 +0100414 mp_arg_val_t vals[PYB_TIMER_INIT_NUM_ARGS];
415 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 +0100416
417 // set the TIM configuration values
418 TIM_Base_InitTypeDef *init = &self->tim.Init;
419
420 if (vals[0].u_int != 0xffffffff) {
421 // set prescaler and period from frequency
422
423 if (vals[0].u_int == 0) {
424 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't have 0 frequency"));
425 }
426
427 // work out TIM's clock source
428 uint tim_clock;
429 if (self->tim_id == 1 || (8 <= self->tim_id && self->tim_id <= 11)) {
430 // TIM{1,8,9,10,11} are on APB2
431 tim_clock = HAL_RCC_GetPCLK2Freq();
432 } else {
433 // TIM{2,3,4,5,6,7,12,13,14} are on APB1
434 tim_clock = HAL_RCC_GetPCLK1Freq();
435 }
436
Damien Georgebf133f72014-08-14 00:30:14 +0100437 // Compute the prescaler value so TIM triggers at freq-Hz
438 // On STM32F405/407/415/417 there are 2 cases for how the clock freq is set.
439 // If the APB prescaler is 1, then the timer clock is equal to its respective
440 // APB clock. Otherwise (APB prescaler > 1) the timer clock is twice its
441 // respective APB clock. See DM00031020 Rev 4, page 115.
Damien George7fdfa932014-04-21 16:48:16 +0100442 uint32_t period = MAX(1, 2 * tim_clock / vals[0].u_int);
443 uint32_t prescaler = 1;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700444 while (period > TIMER_CNT_MASK(self)) {
Damien George7fdfa932014-04-21 16:48:16 +0100445 period >>= 1;
446 prescaler <<= 1;
447 }
448 init->Prescaler = prescaler - 1;
449 init->Period = period - 1;
450 } else if (vals[1].u_int != 0xffffffff && vals[2].u_int != 0xffffffff) {
451 // set prescaler and period directly
452 init->Prescaler = vals[1].u_int;
453 init->Period = vals[2].u_int;
454 } else {
455 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "must specify either freq, or prescaler and period"));
456 }
457
458 init->CounterMode = vals[3].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700459
460 init->ClockDivision = vals[4].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
461 vals[4].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
462 TIM_CLOCKDIVISION_DIV1;
Damien George7fdfa932014-04-21 16:48:16 +0100463 init->RepetitionCounter = 0;
464
Dave Hylandsbecbc872014-08-20 13:21:11 -0700465 if (!IS_TIM_COUNTER_MODE(init->CounterMode)) {
466 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid counter_mode (%d)", init->CounterMode));
467 }
468
Damien George7fdfa932014-04-21 16:48:16 +0100469 // init the TIM peripheral
470 switch (self->tim_id) {
471 case 1: __TIM1_CLK_ENABLE(); break;
472 case 2: __TIM2_CLK_ENABLE(); break;
473 case 3: __TIM3_CLK_ENABLE(); break;
474 case 4: __TIM4_CLK_ENABLE(); break;
475 case 5: __TIM5_CLK_ENABLE(); break;
476 case 6: __TIM6_CLK_ENABLE(); break;
477 case 7: __TIM7_CLK_ENABLE(); break;
478 case 8: __TIM8_CLK_ENABLE(); break;
479 case 9: __TIM9_CLK_ENABLE(); break;
480 case 10: __TIM10_CLK_ENABLE(); break;
481 case 11: __TIM11_CLK_ENABLE(); break;
482 case 12: __TIM12_CLK_ENABLE(); break;
483 case 13: __TIM13_CLK_ENABLE(); break;
484 case 14: __TIM14_CLK_ENABLE(); break;
485 }
Damien George7fdfa932014-04-21 16:48:16 +0100486 // set the priority (if not a special timer)
487 if (self->tim_id != 3 && self->tim_id != 5) {
488 HAL_NVIC_SetPriority(self->irqn, 0xe, 0xe); // next-to lowest priority
489 }
490
Dave Hylandsbecbc872014-08-20 13:21:11 -0700491 HAL_TIM_Base_Init(&self->tim);
492 if (vals[5].u_obj == mp_const_none) {
493 HAL_TIM_Base_Start(&self->tim);
494 } else {
495 pyb_timer_callback(self, vals[5].u_obj);
496 }
497
Damien George7fdfa932014-04-21 16:48:16 +0100498 return mp_const_none;
499}
500
Damien George3eb81632014-05-02 16:58:15 +0100501/// \classmethod \constructor(id, ...)
502/// Construct a new timer object of the given id. If additional
503/// arguments are given, then the timer is initialised by `init(...)`.
504/// `id` can be 1 to 14, excluding 3.
Damien Georgeecc88e92014-08-30 00:35:11 +0100505STATIC 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 +0100506 // check arguments
507 mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
508
509 // create new Timer object
510 pyb_timer_obj_t *tim = m_new_obj(pyb_timer_obj_t);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700511 memset(tim, 0, sizeof(*tim));
512
Damien George7fdfa932014-04-21 16:48:16 +0100513 tim->base.type = &pyb_timer_type;
514 tim->callback = mp_const_none;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700515 tim->channel = NULL;
Damien George7fdfa932014-04-21 16:48:16 +0100516
517 // get TIM number
518 tim->tim_id = mp_obj_get_int(args[0]);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700519 tim->is_32bit = false;
Damien George7fdfa932014-04-21 16:48:16 +0100520
521 switch (tim->tim_id) {
522 case 1: tim->tim.Instance = TIM1; tim->irqn = TIM1_UP_TIM10_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700523 case 2: tim->tim.Instance = TIM2; tim->irqn = TIM2_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100524 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
525 case 4: tim->tim.Instance = TIM4; tim->irqn = TIM4_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700526 case 5: tim->tim.Instance = TIM5; tim->irqn = TIM5_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100527 case 6: tim->tim.Instance = TIM6; tim->irqn = TIM6_DAC_IRQn; break;
528 case 7: tim->tim.Instance = TIM7; tim->irqn = TIM7_IRQn; break;
529 case 8: tim->tim.Instance = TIM8; tim->irqn = TIM8_UP_TIM13_IRQn; break;
530 case 9: tim->tim.Instance = TIM9; tim->irqn = TIM1_BRK_TIM9_IRQn; break;
531 case 10: tim->tim.Instance = TIM10; tim->irqn = TIM1_UP_TIM10_IRQn; break;
532 case 11: tim->tim.Instance = TIM11; tim->irqn = TIM1_TRG_COM_TIM11_IRQn; break;
533 case 12: tim->tim.Instance = TIM12; tim->irqn = TIM8_BRK_TIM12_IRQn; break;
534 case 13: tim->tim.Instance = TIM13; tim->irqn = TIM8_UP_TIM13_IRQn; break;
535 case 14: tim->tim.Instance = TIM14; tim->irqn = TIM8_TRG_COM_TIM14_IRQn; break;
536 default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id));
537 }
538
539 if (n_args > 1 || n_kw > 0) {
540 // start the peripheral
541 mp_map_t kw_args;
542 mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
543 pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args);
544 }
545
546 // set the global variable for interrupt callbacks
547 if (tim->tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
548 pyb_timer_obj_all[tim->tim_id - 1] = tim;
549 }
550
551 return (mp_obj_t)tim;
552}
553
Damien Georgeecc88e92014-08-30 00:35:11 +0100554STATIC 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 +0100555 return pyb_timer_init_helper(args[0], n_args - 1, args + 1, kw_args);
556}
557STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
558
Damien George3eb81632014-05-02 16:58:15 +0100559/// \method deinit()
560/// Deinitialises the timer.
561///
Dave Hylands0d81c132014-06-30 07:55:54 -0700562/// Disables the callback (and the associated irq).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700563/// Disables any channel callbacks (and the associated irq).
Dave Hylands0d81c132014-06-30 07:55:54 -0700564/// Stops the timer, and disables the timer peripheral.
Damien George7fdfa932014-04-21 16:48:16 +0100565STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
Dave Hylands0d81c132014-06-30 07:55:54 -0700566 pyb_timer_obj_t *self = self_in;
567
Dave Hylandsbecbc872014-08-20 13:21:11 -0700568 // Disable the base interrupt
Dave Hylands0d81c132014-06-30 07:55:54 -0700569 pyb_timer_callback(self_in, mp_const_none);
570
Dave Hylandsbecbc872014-08-20 13:21:11 -0700571 pyb_timer_channel_obj_t *chan = self->channel;
572 self->channel = NULL;
573
574 // Disable the channel interrupts
575 while (chan != NULL) {
576 pyb_timer_channel_callback(chan, mp_const_none);
577 pyb_timer_channel_obj_t *prev_chan = chan;
578 chan = chan->next;
579 prev_chan->next = NULL;
580 }
581
Dave Hylands0d81c132014-06-30 07:55:54 -0700582 HAL_TIM_Base_DeInit(&self->tim);
Damien George7fdfa932014-04-21 16:48:16 +0100583 return mp_const_none;
584}
585STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);
586
Dave Hylandsbecbc872014-08-20 13:21:11 -0700587/// \method channel(channel, mode, ...)
588///
Damien George0e58c582014-09-21 22:54:02 +0100589/// If only a channel number is passed, then a previously initialized channel
590/// object is returned (or `None` if there is no previous channel).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700591///
592/// Othwerwise, a TimerChannel object is initialized and returned.
593///
594/// Each channel can be configured to perform pwm, output compare, or
595/// input capture. All channels share the same underlying timer, which means
596/// that they share the same timer clock.
597///
598/// Keyword arguments:
599///
600/// - `mode` can be one of:
601/// - `Timer.PWM` - configure the timer in PWM mode (active high).
602/// - `Timer.PWM_INVERTED` - configure the timer in PWM mode (active low).
603/// - `Timer.OC_TIMING` - indicates that no pin is driven.
604/// - `Timer.OC_ACTIVE` - the pin will be made active when a compare
605/// match occurs (active is determined by polarity)
606/// - `Timer.OC_INACTIVE` - the pin will be made inactive when a compare
607/// match occurs.
608/// - `Timer.OC_TOGGLE` - the pin will be toggled when an compare match occurs.
609/// - `Timer.OC_FORCED_ACTIVE` - the pin is forced active (compare match is ignored).
610/// - `Timer.OC_FORCED_INACTIVE` - the pin is forced inactive (compare match is ignored).
611/// - `Timer.IC` - configure the timer in Input Capture mode.
612///
613/// - `callback` - as per TimerChannel.callback()
614///
615/// - `pin` None (the default) or a Pin object. If specified (and not None)
616/// this will cause the alternate function of the the indicated pin
617/// to be configured for this timer channel. An error will be raised if
618/// the pin doesn't support any alternate functions for this timer channel.
619///
620/// Keyword arguments for Timer.PWM modes:
621///
Damien George0e58c582014-09-21 22:54:02 +0100622/// - `pulse_width` - determines the initial pulse width value to use.
Dave Hylands53d5fa62014-09-21 22:40:42 -0700623/// - `pulse_width_percent` - determines the initial pulse width percentage to use.
Dave Hylandsbecbc872014-08-20 13:21:11 -0700624///
625/// Keyword arguments for Timer.OC modes:
626///
627/// - `compare` - determines the initial value of the compare register.
628///
629/// - `polarity` can be one of:
630/// - `Timer.HIGH` - output is active high
631/// - `Timer.LOW` - output is acive low
632///
633/// Optional keyword arguments for Timer.IC modes:
634///
635/// - `polarity` can be one of:
636/// - `Timer.RISING` - captures on rising edge.
637/// - `Timer.FALLING` - captures on falling edge.
638/// - `Timer.BOTH` - captures on both edges.
639///
640/// PWM Example:
641///
642/// timer = pyb.Timer(2, freq=1000)
643/// ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
644/// ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
645STATIC const mp_arg_t pyb_timer_channel_args[] = {
Dave Hylands53d5fa62014-09-21 22:40:42 -0700646 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
647 { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
Damien Georgee8ea0722014-09-25 15:44:10 +0100648 { MP_QSTR_pulse_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
Dave Hylands53d5fa62014-09-21 22:40:42 -0700649 { MP_QSTR_pulse_width_percent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
650 { MP_QSTR_compare, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
651 { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700652};
653#define PYB_TIMER_CHANNEL_NUM_ARGS MP_ARRAY_SIZE(pyb_timer_channel_args)
654
655STATIC 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 -0700656 pyb_timer_obj_t *self = args[0];
657 mp_int_t channel = mp_obj_get_int(args[1]);
658
659 if (channel < 1 || channel > 4) {
660 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid channel (%d)", channel));
661 }
662
663 pyb_timer_channel_obj_t *chan = self->channel;
664 pyb_timer_channel_obj_t *prev_chan = NULL;
665
666 while (chan != NULL) {
667 if (chan->channel == channel) {
668 break;
669 }
670 prev_chan = chan;
671 chan = chan->next;
672 }
Damien George0e58c582014-09-21 22:54:02 +0100673
674 // If only the channel number is given return the previously allocated
675 // channel (or None if no previous channel).
676 if (n_args == 2) {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700677 if (chan) {
678 return chan;
679 }
680 return mp_const_none;
681 }
682
683 // If there was already a channel, then remove it from the list. Note that
684 // the order we do things here is important so as to appear atomic to
685 // the IRQ handler.
686 if (chan) {
687 // Turn off any IRQ associated with the channel.
688 pyb_timer_channel_callback(chan, mp_const_none);
689
690 // Unlink the channel from the list.
691 if (prev_chan) {
692 prev_chan->next = chan->next;
693 }
694 self->channel = chan->next;
695 chan->next = NULL;
696 }
697
698 // Allocate and initialize a new channel
699 mp_arg_val_t vals[PYB_TIMER_CHANNEL_NUM_ARGS];
700 mp_arg_parse_all(n_args - 3, args + 3, kw_args, PYB_TIMER_CHANNEL_NUM_ARGS, pyb_timer_channel_args, vals);
701
702 chan = m_new_obj(pyb_timer_channel_obj_t);
703 memset(chan, 0, sizeof(*chan));
704 chan->base.type = &pyb_timer_channel_type;
705 chan->timer = self;
706 chan->channel = channel;
707 chan->mode = mp_obj_get_int(args[2]);
708 chan->callback = vals[0].u_obj;
709
710 mp_obj_t pin_obj = vals[1].u_obj;
711 if (pin_obj != mp_const_none) {
712 if (!MP_OBJ_IS_TYPE(pin_obj, &pin_type)) {
713 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "pin argument needs to be be a Pin type"));
714 }
715 const pin_obj_t *pin = pin_obj;
716 const pin_af_obj_t *af = pin_find_af(pin, AF_FN_TIM, self->tim_id);
717 if (af == NULL) {
718 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));
719 }
720 // pin.init(mode=AF_PP, af=idx)
721 const mp_obj_t args[6] = {
722 (mp_obj_t)&pin_init_obj,
723 pin_obj,
724 MP_OBJ_NEW_QSTR(MP_QSTR_mode), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP),
725 MP_OBJ_NEW_QSTR(MP_QSTR_af), MP_OBJ_NEW_SMALL_INT(af->idx)
726 };
727 mp_call_method_n_kw(0, 2, args);
728 }
729
730 // Link the channel to the timer before we turn the channel on.
731 // Note that this needs to appear atomic to the IRQ handler (the write
732 // to self->channel is atomic, so we're good, but I thought I'd mention
733 // in case this was ever changed in the future).
734 chan->next = self->channel;
735 self->channel = chan;
736
737 switch (chan->mode) {
738
739 case CHANNEL_MODE_PWM_NORMAL:
740 case CHANNEL_MODE_PWM_INVERTED: {
741 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100742 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
Damien Georgee8ea0722014-09-25 15:44:10 +0100743 if (vals[3].u_obj != mp_const_none) {
Dave Hylands53d5fa62014-09-21 22:40:42 -0700744 // pulse width percent given
Dave Hylands39296b42014-09-26 09:04:05 -0700745 uint32_t period = compute_period(self);
Damien Georgee8ea0722014-09-25 15:44:10 +0100746 oc_config.Pulse = compute_pwm_value_from_percent(period, vals[3].u_obj);
Damien George0e58c582014-09-21 22:54:02 +0100747 } else {
Damien Georgee8ea0722014-09-25 15:44:10 +0100748 // use absolute pulse width value (defaults to 0 if nothing given)
749 oc_config.Pulse = vals[2].u_int;
Damien George0e58c582014-09-21 22:54:02 +0100750 }
Dave Hylandsbecbc872014-08-20 13:21:11 -0700751 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
752 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
753 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
754 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
755 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
756
757 HAL_TIM_PWM_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
758 if (chan->callback == mp_const_none) {
759 HAL_TIM_PWM_Start(&self->tim, TIMER_CHANNEL(chan));
760 } else {
761 HAL_TIM_PWM_Start_IT(&self->tim, TIMER_CHANNEL(chan));
762 }
763 break;
764 }
765
766 case CHANNEL_MODE_OC_TIMING:
767 case CHANNEL_MODE_OC_ACTIVE:
768 case CHANNEL_MODE_OC_INACTIVE:
769 case CHANNEL_MODE_OC_TOGGLE:
770 case CHANNEL_MODE_OC_FORCED_ACTIVE:
771 case CHANNEL_MODE_OC_FORCED_INACTIVE: {
772 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100773 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
774 oc_config.Pulse = vals[4].u_int;
775 oc_config.OCPolarity = vals[5].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700776 if (oc_config.OCPolarity == 0xffffffff) {
777 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
778 }
779 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
780 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
781 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
782 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
783
784 if (!IS_TIM_OC_POLARITY(oc_config.OCPolarity)) {
785 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", oc_config.OCPolarity));
786 }
787 HAL_TIM_OC_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
788 if (chan->callback == mp_const_none) {
789 HAL_TIM_OC_Start(&self->tim, TIMER_CHANNEL(chan));
790 } else {
791 HAL_TIM_OC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
792 }
793 break;
794 }
795
796 case CHANNEL_MODE_IC: {
797 TIM_IC_InitTypeDef ic_config;
798
Damien George0e58c582014-09-21 22:54:02 +0100799 ic_config.ICPolarity = vals[5].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700800 if (ic_config.ICPolarity == 0xffffffff) {
801 ic_config.ICPolarity = TIM_ICPOLARITY_RISING;
802 }
803 ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
804 ic_config.ICPrescaler = TIM_ICPSC_DIV1;
805 ic_config.ICFilter = 0;
806
807 if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) {
808 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", ic_config.ICPolarity));
809 }
810 HAL_TIM_IC_ConfigChannel(&self->tim, &ic_config, TIMER_CHANNEL(chan));
811 if (chan->callback == mp_const_none) {
812 HAL_TIM_IC_Start(&self->tim, TIMER_CHANNEL(chan));
813 } else {
814 HAL_TIM_IC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
815 }
816 break;
817 }
818
819 default:
820 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid mode (%d)", chan->mode));
821 }
822
823 return chan;
824}
Damien George0e58c582014-09-21 22:54:02 +0100825STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700826
Damien George3eb81632014-05-02 16:58:15 +0100827/// \method counter([value])
828/// Get or set the timer counter.
Damien George0e58c582014-09-21 22:54:02 +0100829STATIC mp_obj_t pyb_timer_counter(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100830 pyb_timer_obj_t *self = args[0];
831 if (n_args == 1) {
832 // get
833 return mp_obj_new_int(self->tim.Instance->CNT);
834 } else {
835 // set
836 __HAL_TIM_SetCounter(&self->tim, mp_obj_get_int(args[1]));
837 return mp_const_none;
838 }
839}
840STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_counter_obj, 1, 2, pyb_timer_counter);
841
Damien George3eb81632014-05-02 16:58:15 +0100842/// \method prescaler([value])
843/// Get or set the prescaler for the timer.
Damien George0e58c582014-09-21 22:54:02 +0100844STATIC mp_obj_t pyb_timer_prescaler(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100845 pyb_timer_obj_t *self = args[0];
846 if (n_args == 1) {
847 // get
848 return mp_obj_new_int(self->tim.Instance->PSC & 0xffff);
849 } else {
850 // set
851 self->tim.Init.Prescaler = self->tim.Instance->PSC = mp_obj_get_int(args[1]) & 0xffff;
852 return mp_const_none;
853 }
854}
855STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);
856
Damien George3eb81632014-05-02 16:58:15 +0100857/// \method period([value])
858/// Get or set the period of the timer.
Damien George0e58c582014-09-21 22:54:02 +0100859STATIC mp_obj_t pyb_timer_period(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100860 pyb_timer_obj_t *self = args[0];
861 if (n_args == 1) {
862 // get
Dave Hylandsbecbc872014-08-20 13:21:11 -0700863 return mp_obj_new_int(__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +0100864 } else {
865 // set
Dave Hylandsbecbc872014-08-20 13:21:11 -0700866 __HAL_TIM_SetAutoreload(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +0100867 return mp_const_none;
868 }
869}
870STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
871
Damien George3eb81632014-05-02 16:58:15 +0100872/// \method callback(fun)
873/// Set the function to be called when the timer triggers.
874/// `fun` is passed 1 argument, the timer object.
875/// If `fun` is `None` then the callback will be disabled.
Damien George7fdfa932014-04-21 16:48:16 +0100876STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
877 pyb_timer_obj_t *self = self_in;
878 if (callback == mp_const_none) {
879 // stop interrupt (but not timer)
880 __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
881 self->callback = mp_const_none;
882 } else if (mp_obj_is_callable(callback)) {
883 self->callback = callback;
884 HAL_NVIC_EnableIRQ(self->irqn);
885 // start timer, so that it interrupts on overflow
886 HAL_TIM_Base_Start_IT(&self->tim);
887 } else {
888 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
889 }
Damien Georgea12be912014-04-02 15:09:36 +0100890 return mp_const_none;
891}
Damien George7fdfa932014-04-21 16:48:16 +0100892STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);
Damien Georgea12be912014-04-02 15:09:36 +0100893
Damien George7fdfa932014-04-21 16:48:16 +0100894STATIC const mp_map_elem_t pyb_timer_locals_dict_table[] = {
895 // instance methods
896 { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_timer_init_obj },
897 { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_timer_deinit_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700898 { MP_OBJ_NEW_QSTR(MP_QSTR_channel), (mp_obj_t)&pyb_timer_channel_obj },
Damien George7fdfa932014-04-21 16:48:16 +0100899 { MP_OBJ_NEW_QSTR(MP_QSTR_counter), (mp_obj_t)&pyb_timer_counter_obj },
900 { MP_OBJ_NEW_QSTR(MP_QSTR_prescaler), (mp_obj_t)&pyb_timer_prescaler_obj },
901 { MP_OBJ_NEW_QSTR(MP_QSTR_period), (mp_obj_t)&pyb_timer_period_obj },
902 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_callback_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -0700903 { MP_OBJ_NEW_QSTR(MP_QSTR_UP), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_UP) },
904 { MP_OBJ_NEW_QSTR(MP_QSTR_DOWN), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_DOWN) },
905 { MP_OBJ_NEW_QSTR(MP_QSTR_CENTER), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_CENTERALIGNED1) },
906 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_NORMAL) },
907 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM_INVERTED), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_INVERTED) },
908 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TIMING), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TIMING) },
909 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_ACTIVE) },
910 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_INACTIVE) },
911 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TOGGLE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TOGGLE) },
912 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_ACTIVE) },
913 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_INACTIVE) },
914 { MP_OBJ_NEW_QSTR(MP_QSTR_IC), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_IC) },
915 { MP_OBJ_NEW_QSTR(MP_QSTR_HIGH), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_HIGH) },
916 { MP_OBJ_NEW_QSTR(MP_QSTR_LOW), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_LOW) },
917 { MP_OBJ_NEW_QSTR(MP_QSTR_RISING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_RISING) },
918 { MP_OBJ_NEW_QSTR(MP_QSTR_FALLING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_FALLING) },
919 { MP_OBJ_NEW_QSTR(MP_QSTR_BOTH), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_BOTHEDGE) },
Damien George7fdfa932014-04-21 16:48:16 +0100920};
Damien George7fdfa932014-04-21 16:48:16 +0100921STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table);
Damien Georgea12be912014-04-02 15:09:36 +0100922
Damien George7fdfa932014-04-21 16:48:16 +0100923const mp_obj_type_t pyb_timer_type = {
924 { &mp_type_type },
925 .name = MP_QSTR_Timer,
926 .print = pyb_timer_print,
927 .make_new = pyb_timer_make_new,
928 .locals_dict = (mp_obj_t)&pyb_timer_locals_dict,
929};
Damien Georgea12be912014-04-02 15:09:36 +0100930
Dave Hylandsbecbc872014-08-20 13:21:11 -0700931/// \moduleref pyb
932/// \class TimerChannel - setup a channel for a timer.
933///
934/// Timer channels are used to generate/capture a signal using a timer.
935///
936/// TimerChannel objects are created using the Timer.channel() method.
937STATIC void pyb_timer_channel_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
938 pyb_timer_channel_obj_t *self = self_in;
939
940 print(env, "TimerChannel(timer=%u, channel=%u, mode=%s)",
941 self->timer->tim_id,
942 self->channel,
Damien George0e58c582014-09-21 22:54:02 +0100943 qstr_str(channel_mode_info[self->mode].name));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700944}
945
946/// \method capture([value])
947/// Get or set the capture value associated with a channel.
948/// capture, compare, and pulse_width are all aliases for the same function.
949/// capture is the logical name to use when the channel is in input capture mode.
950
951/// \method compare([value])
952/// Get or set the compare value associated with a channel.
953/// capture, compare, and pulse_width are all aliases for the same function.
954/// compare is the logical name to use when the channel is in output compare mode.
955
956/// \method pulse_width([value])
957/// Get or set the pulse width value associated with a channel.
958/// capture, compare, and pulse_width are all aliases for the same function.
959/// pulse_width is the logical name to use when the channel is in PWM mode.
Dave Hylands39296b42014-09-26 09:04:05 -0700960///
961/// In edge aligned mode, a pulse_width of `period + 1` corresponds to a duty cycle of 100%
962/// In center aligned mode, a pulse width of `period` corresponds to a duty cycle of 100%
Damien George0e58c582014-09-21 22:54:02 +0100963STATIC 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 -0700964 pyb_timer_channel_obj_t *self = args[0];
Dave Hylandsbecbc872014-08-20 13:21:11 -0700965 if (n_args == 1) {
966 // get
967 return mp_obj_new_int(__HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer));
968 } else {
969 // set
970 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self->timer));
971 return mp_const_none;
972 }
973}
974STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_capture_compare_obj, 1, 2, pyb_timer_channel_capture_compare);
975
Damien Georgee8ea0722014-09-25 15:44:10 +0100976/// \method pulse_width_percent([value])
977/// Get or set the pulse width percentage associated with a channel. The value
978/// is a number between 0 and 100 and sets the percentage of the timer period
979/// for which the pulse is active. The value can be an integer or
980/// floating-point number for more accuracy. For example, a value of 25 gives
981/// a duty cycle of 25%.
Dave Hylands53d5fa62014-09-21 22:40:42 -0700982STATIC 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 +0100983 pyb_timer_channel_obj_t *self = args[0];
Dave Hylands39296b42014-09-26 09:04:05 -0700984 uint32_t period = compute_period(self->timer);
Damien George0e58c582014-09-21 22:54:02 +0100985 if (n_args == 1) {
986 // get
987 uint32_t cmp = __HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer);
Dave Hylands39296b42014-09-26 09:04:05 -0700988 return compute_percent_from_pwm_value(period, cmp);
Damien George0e58c582014-09-21 22:54:02 +0100989 } else {
990 // set
Damien Georgee8ea0722014-09-25 15:44:10 +0100991 uint32_t cmp = compute_pwm_value_from_percent(period, args[1]);
Damien George0e58c582014-09-21 22:54:02 +0100992 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), cmp & TIMER_CNT_MASK(self->timer));
993 return mp_const_none;
994 }
995}
Dave Hylands53d5fa62014-09-21 22:40:42 -0700996STATIC 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 +0100997
Dave Hylandsbecbc872014-08-20 13:21:11 -0700998/// \method callback(fun)
999/// Set the function to be called when the timer channel triggers.
1000/// `fun` is passed 1 argument, the timer object.
1001/// If `fun` is `None` then the callback will be disabled.
1002STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback) {
1003 pyb_timer_channel_obj_t *self = self_in;
1004 if (callback == mp_const_none) {
1005 // stop interrupt (but not timer)
1006 __HAL_TIM_DISABLE_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
1007 self->callback = mp_const_none;
1008 } else if (mp_obj_is_callable(callback)) {
1009 self->callback = callback;
1010 HAL_NVIC_EnableIRQ(self->timer->irqn);
1011 // start timer, so that it interrupts on overflow
1012 switch (self->mode) {
1013 case CHANNEL_MODE_PWM_NORMAL:
1014 case CHANNEL_MODE_PWM_INVERTED:
1015 HAL_TIM_PWM_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1016 break;
1017 case CHANNEL_MODE_OC_TIMING:
1018 case CHANNEL_MODE_OC_ACTIVE:
1019 case CHANNEL_MODE_OC_INACTIVE:
1020 case CHANNEL_MODE_OC_TOGGLE:
1021 case CHANNEL_MODE_OC_FORCED_ACTIVE:
1022 case CHANNEL_MODE_OC_FORCED_INACTIVE:
1023 HAL_TIM_OC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1024 break;
1025 case CHANNEL_MODE_IC:
1026 HAL_TIM_IC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1027 break;
1028 }
1029 } else {
1030 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
1031 }
1032 return mp_const_none;
1033}
1034STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_channel_callback_obj, pyb_timer_channel_callback);
1035
1036STATIC const mp_map_elem_t pyb_timer_channel_locals_dict_table[] = {
1037 // instance methods
1038 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_channel_callback_obj },
1039 { MP_OBJ_NEW_QSTR(MP_QSTR_pulse_width), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
Dave Hylands53d5fa62014-09-21 22:40:42 -07001040 { 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 -07001041 { MP_OBJ_NEW_QSTR(MP_QSTR_capture), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1042 { MP_OBJ_NEW_QSTR(MP_QSTR_compare), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1043};
1044STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);
1045
Damien George0e58c582014-09-21 22:54:02 +01001046STATIC const mp_obj_type_t pyb_timer_channel_type = {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001047 { &mp_type_type },
1048 .name = MP_QSTR_TimerChannel,
1049 .print = pyb_timer_channel_print,
1050 .locals_dict = (mp_obj_t)&pyb_timer_channel_locals_dict,
1051};
1052
Damien George0e58c582014-09-21 22:54:02 +01001053STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001054 uint32_t irq_mask = TIMER_IRQ_MASK(channel);
1055
1056 if (__HAL_TIM_GET_FLAG(&tim->tim, irq_mask) != RESET) {
1057 if (__HAL_TIM_GET_ITSTATUS(&tim->tim, irq_mask) != RESET) {
1058 // clear the interrupt
1059 __HAL_TIM_CLEAR_IT(&tim->tim, irq_mask);
1060
1061 // execute callback if it's set
1062 if (callback != mp_const_none) {
1063 // When executing code within a handler we must lock the GC to prevent
1064 // any memory allocations. We must also catch any exceptions.
1065 gc_lock();
1066 nlr_buf_t nlr;
1067 if (nlr_push(&nlr) == 0) {
1068 mp_call_function_1(callback, tim);
1069 nlr_pop();
1070 } else {
1071 // Uncaught exception; disable the callback so it doesn't run again.
1072 tim->callback = mp_const_none;
1073 __HAL_TIM_DISABLE_IT(&tim->tim, irq_mask);
1074 if (channel == 0) {
1075 printf("Uncaught exception in Timer(" UINT_FMT
1076 ") interrupt handler\n", tim->tim_id);
1077 } else {
1078 printf("Uncaught exception in Timer(" UINT_FMT ") channel "
1079 UINT_FMT " interrupt handler\n", tim->tim_id, channel);
1080 }
1081 mp_obj_print_exception((mp_obj_t)nlr.ret_val);
1082 }
1083 gc_unlock();
1084 }
1085 }
1086 }
1087}
1088
Damien George7fdfa932014-04-21 16:48:16 +01001089void timer_irq_handler(uint tim_id) {
1090 if (tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
1091 // get the timer object
1092 pyb_timer_obj_t *tim = pyb_timer_obj_all[tim_id - 1];
Damien Georgea12be912014-04-02 15:09:36 +01001093
Damien George7fdfa932014-04-21 16:48:16 +01001094 if (tim == NULL) {
Damien George0e58c582014-09-21 22:54:02 +01001095 // Timer object has not been set, so we can't do anything.
1096 // This can happen under normal circumstances for timers like
1097 // 1 & 10 which use the same IRQ.
Damien George7fdfa932014-04-21 16:48:16 +01001098 return;
1099 }
Damien Georgea12be912014-04-02 15:09:36 +01001100
Dave Hylandsbecbc872014-08-20 13:21:11 -07001101 // Check for timer (versus timer channel) interrupt.
1102 timer_handle_irq_channel(tim, 0, tim->callback);
1103 uint32_t handled = TIMER_IRQ_MASK(0);
Damien Georgea12be912014-04-02 15:09:36 +01001104
Dave Hylandsbecbc872014-08-20 13:21:11 -07001105 // Check to see if a timer channel interrupt was pending
1106 pyb_timer_channel_obj_t *chan = tim->channel;
1107 while (chan != NULL) {
1108 timer_handle_irq_channel(tim, chan->channel, chan->callback);
1109 handled |= TIMER_IRQ_MASK(chan->channel);
1110 chan = chan->next;
1111 }
1112
1113 // Finally, clear any remaining interrupt sources. Otherwise we'll
1114 // just get called continuously.
1115 uint32_t unhandled = __HAL_TIM_GET_ITSTATUS(&tim->tim, 0xff & ~handled);
1116 if (unhandled != 0) {
1117 __HAL_TIM_CLEAR_IT(&tim->tim, unhandled);
1118 printf("Unhandled interrupt SR=0x%02lx (now disabled)\n", unhandled);
Damien Georgea12be912014-04-02 15:09:36 +01001119 }
1120 }
1121}