blob: 5c99d51f19df8571402b92c15e16328cd4f21f52 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
Damien Georgea12be912014-04-02 15:09:36 +010027#include <stdint.h>
28#include <stdio.h>
29#include <string.h>
30
31#include <stm32f4xx_hal.h>
32#include "usbd_cdc_msc_hid.h"
33#include "usbd_cdc_interface.h"
34
35#include "nlr.h"
36#include "misc.h"
37#include "mpconfig.h"
38#include "qstr.h"
Damien George7fdfa932014-04-21 16:48:16 +010039#include "gc.h"
Damien Georgea12be912014-04-02 15:09:36 +010040#include "obj.h"
41#include "runtime.h"
42#include "timer.h"
43#include "servo.h"
Dave Hylandsbecbc872014-08-20 13:21:11 -070044#include "pin.h"
Damien Georgea12be912014-04-02 15:09:36 +010045
Damien George3eb81632014-05-02 16:58:15 +010046/// \moduleref pyb
47/// \class Timer - periodically call a function
48///
49/// Timers can be used for a great variety of tasks. At the moment, only
50/// the simplest case is implemented: that of calling a function periodically.
51///
52/// Each timer consists of a counter that counts up at a certain rate. The rate
53/// at which it counts is the peripheral clock frequency (in Hz) divided by the
54/// timer prescaler. When the counter reaches the timer period it triggers an
55/// event, and the counter resets back to zero. By using the callback method,
56/// the timer event can call a Python function.
57///
58/// Example usage to toggle an LED at a fixed frequency:
59///
60/// tim = pyb.Timer(4) # create a timer object using timer 4
61/// tim.init(freq=2) # trigger at 2Hz
62/// tim.callback(lambda t:pyb.LED(1).toggle())
63///
64/// Further examples:
65///
66/// tim = pyb.Timer(4, freq=100) # freq in Hz
Dave Hylandsbecbc872014-08-20 13:21:11 -070067/// tim = pyb.Timer(4, prescaler=0, period=99)
Damien George3eb81632014-05-02 16:58:15 +010068/// tim.counter() # get counter (can also set)
69/// tim.prescaler(2) # set prescaler (can also get)
Dave Hylandsbecbc872014-08-20 13:21:11 -070070/// tim.period(199) # set period (can also get)
Damien George3eb81632014-05-02 16:58:15 +010071/// tim.callback(lambda t: ...) # set callback for update interrupt (t=tim instance)
72/// tim.callback(None) # clear callback
73///
74/// *Note:* Timer 3 is reserved for internal use. Timer 5 controls
75/// the servo driver, and Timer 6 is used for timed ADC/DAC reading/writing.
76/// It is recommended to use the other timers in your programs.
77
Damien Georgea12be912014-04-02 15:09:36 +010078// The timers can be used by multiple drivers, and need a common point for
79// the interrupts to be dispatched, so they are all collected here.
80//
81// TIM3:
Damien George6d983532014-04-16 23:08:36 +010082// - flash storage controller, to flush the cache
Damien Georgea12be912014-04-02 15:09:36 +010083// - USB CDC interface, interval, to check for new data
84// - LED 4, PWM to set the LED intensity
85//
86// TIM5:
87// - servo controller, PWM
Damien George7fdfa932014-04-21 16:48:16 +010088//
89// TIM6:
90// - ADC, DAC for read_timed and write_timed
Damien George7fdfa932014-04-21 16:48:16 +010091
Dave Hylandsbecbc872014-08-20 13:21:11 -070092typedef enum {
93 CHANNEL_MODE_PWM_NORMAL,
94 CHANNEL_MODE_PWM_INVERTED,
95 CHANNEL_MODE_OC_TIMING,
96 CHANNEL_MODE_OC_ACTIVE,
97 CHANNEL_MODE_OC_INACTIVE,
98 CHANNEL_MODE_OC_TOGGLE,
99 CHANNEL_MODE_OC_FORCED_ACTIVE,
100 CHANNEL_MODE_OC_FORCED_INACTIVE,
101 CHANNEL_MODE_IC,
102} pyb_channel_mode;
103
104STATIC const struct {
105 qstr name;
106 uint32_t oc_mode;
Damien George0e58c582014-09-21 22:54:02 +0100107} channel_mode_info[] = {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700108 { MP_QSTR_PWM, TIM_OCMODE_PWM1 },
109 { MP_QSTR_PWM_INVERTED, TIM_OCMODE_PWM2 },
110 { MP_QSTR_OC_TIMING, TIM_OCMODE_TIMING },
111 { MP_QSTR_OC_ACTIVE, TIM_OCMODE_ACTIVE },
112 { MP_QSTR_OC_INACTIVE, TIM_OCMODE_INACTIVE },
113 { MP_QSTR_OC_TOGGLE, TIM_OCMODE_TOGGLE },
114 { MP_QSTR_OC_FORCED_ACTIVE, TIM_OCMODE_FORCED_ACTIVE },
115 { MP_QSTR_OC_FORCED_INACTIVE, TIM_OCMODE_FORCED_INACTIVE },
116 { MP_QSTR_IC, 0 },
117};
118
119typedef struct _pyb_timer_channel_obj_t {
120 mp_obj_base_t base;
121 struct _pyb_timer_obj_t *timer;
122 uint8_t channel;
123 uint8_t mode;
124 mp_obj_t callback;
125 struct _pyb_timer_channel_obj_t *next;
126} pyb_timer_channel_obj_t;
127
Damien George7fdfa932014-04-21 16:48:16 +0100128typedef struct _pyb_timer_obj_t {
129 mp_obj_base_t base;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700130 uint8_t tim_id;
131 uint8_t is_32bit;
Damien George7fdfa932014-04-21 16:48:16 +0100132 mp_obj_t callback;
133 TIM_HandleTypeDef tim;
134 IRQn_Type irqn;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700135 pyb_timer_channel_obj_t *channel;
Damien George7fdfa932014-04-21 16:48:16 +0100136} pyb_timer_obj_t;
Damien Georgea12be912014-04-02 15:09:36 +0100137
Dave Hylandsbecbc872014-08-20 13:21:11 -0700138// The following yields TIM_IT_UPDATE when channel is zero and
139// TIM_IT_CC1..TIM_IT_CC4 when channel is 1..4
140#define TIMER_IRQ_MASK(channel) (1 << (channel))
Damien Georgee8ea0722014-09-25 15:44:10 +0100141#define TIMER_CNT_MASK(self) ((self)->is_32bit ? 0xffffffff : 0xffff)
Dave Hylandsbecbc872014-08-20 13:21:11 -0700142#define TIMER_CHANNEL(self) ((((self)->channel) - 1) << 2)
143
Damien Georgea12be912014-04-02 15:09:36 +0100144TIM_HandleTypeDef TIM3_Handle;
145TIM_HandleTypeDef TIM5_Handle;
Damien George4d7f4eb2014-04-15 19:52:56 +0100146TIM_HandleTypeDef TIM6_Handle;
Damien Georgea12be912014-04-02 15:09:36 +0100147
Damien George6d983532014-04-16 23:08:36 +0100148// Used to divide down TIM3 and periodically call the flash storage IRQ
Damien George0e58c582014-09-21 22:54:02 +0100149STATIC uint32_t tim3_counter = 0;
Damien George6d983532014-04-16 23:08:36 +0100150
Damien George7fdfa932014-04-21 16:48:16 +0100151// Used to do callbacks to Python code on interrupt
152STATIC pyb_timer_obj_t *pyb_timer_obj_all[14];
Emmanuel Blotf6932d62014-06-19 18:54:34 +0200153#define PYB_TIMER_OBJ_ALL_NUM MP_ARRAY_SIZE(pyb_timer_obj_all)
Damien George7fdfa932014-04-21 16:48:16 +0100154
Damien George97ef94d2014-10-04 14:36:39 +0100155STATIC uint32_t timer_get_source_freq(uint32_t tim_id);
Damien Georgee70b5db2014-07-02 14:09:44 +0100156STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in);
157STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700158STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback);
Damien Georgee70b5db2014-07-02 14:09:44 +0100159
Damien George7fdfa932014-04-21 16:48:16 +0100160void timer_init0(void) {
161 tim3_counter = 0;
162 for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
163 pyb_timer_obj_all[i] = NULL;
164 }
165}
166
Damien Georgee70b5db2014-07-02 14:09:44 +0100167// unregister all interrupt sources
168void timer_deinit(void) {
169 for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
170 pyb_timer_obj_t *tim = pyb_timer_obj_all[i];
171 if (tim != NULL) {
172 pyb_timer_deinit(tim);
173 }
174 }
175}
176
Damien Georgea12be912014-04-02 15:09:36 +0100177// TIM3 is set-up for the USB CDC interface
178void timer_tim3_init(void) {
179 // set up the timer for USBD CDC
180 __TIM3_CLK_ENABLE();
181
182 TIM3_Handle.Instance = TIM3;
Damien George6d983532014-04-16 23:08:36 +0100183 TIM3_Handle.Init.Period = (USBD_CDC_POLLING_INTERVAL*1000) - 1; // TIM3 fires every USBD_CDC_POLLING_INTERVAL ms
Damien George97ef94d2014-10-04 14:36:39 +0100184 TIM3_Handle.Init.Prescaler = timer_get_source_freq(3) / 1000000 - 1; // TIM3 runs at 1MHz
Dave Hylandsbecbc872014-08-20 13:21:11 -0700185 TIM3_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
Damien Georgea12be912014-04-02 15:09:36 +0100186 TIM3_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
187 HAL_TIM_Base_Init(&TIM3_Handle);
188
189 HAL_NVIC_SetPriority(TIM3_IRQn, 6, 0);
190 HAL_NVIC_EnableIRQ(TIM3_IRQn);
191
192 if (HAL_TIM_Base_Start(&TIM3_Handle) != HAL_OK) {
193 /* Starting Error */
194 }
195}
196
197/* unused
198void timer_tim3_deinit(void) {
199 // reset TIM3 timer
200 __TIM3_FORCE_RESET();
201 __TIM3_RELEASE_RESET();
202}
203*/
204
205// TIM5 is set-up for the servo controller
Damien George4d7f4eb2014-04-15 19:52:56 +0100206// This function inits but does not start the timer
Damien Georgea12be912014-04-02 15:09:36 +0100207void timer_tim5_init(void) {
208 // TIM5 clock enable
209 __TIM5_CLK_ENABLE();
210
211 // set up and enable interrupt
212 HAL_NVIC_SetPriority(TIM5_IRQn, 6, 0);
213 HAL_NVIC_EnableIRQ(TIM5_IRQn);
214
215 // PWM clock configuration
216 TIM5_Handle.Instance = TIM5;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700217 TIM5_Handle.Init.Period = 2000 - 1; // timer cycles at 50Hz
Damien George97ef94d2014-10-04 14:36:39 +0100218 TIM5_Handle.Init.Prescaler = (timer_get_source_freq(5) / 100000) - 1; // timer runs at 100kHz
Dave Hylandsbecbc872014-08-20 13:21:11 -0700219 TIM5_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
Damien Georgea12be912014-04-02 15:09:36 +0100220 TIM5_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700221
Damien Georgea12be912014-04-02 15:09:36 +0100222 HAL_TIM_PWM_Init(&TIM5_Handle);
223}
224
Damien George4d7f4eb2014-04-15 19:52:56 +0100225// Init TIM6 with a counter-overflow at the given frequency (given in Hz)
226// TIM6 is used by the DAC and ADC for auto sampling at a given frequency
227// This function inits but does not start the timer
228void timer_tim6_init(uint freq) {
229 // TIM6 clock enable
230 __TIM6_CLK_ENABLE();
231
232 // Timer runs at SystemCoreClock / 2
233 // Compute the prescaler value so TIM6 triggers at freq-Hz
Damien George97ef94d2014-10-04 14:36:39 +0100234 uint32_t period = MAX(1, timer_get_source_freq(6) / freq);
Damien George4d7f4eb2014-04-15 19:52:56 +0100235 uint32_t prescaler = 1;
236 while (period > 0xffff) {
237 period >>= 1;
238 prescaler <<= 1;
239 }
240
241 // Time base clock configuration
242 TIM6_Handle.Instance = TIM6;
243 TIM6_Handle.Init.Period = period - 1;
244 TIM6_Handle.Init.Prescaler = prescaler - 1;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700245 TIM6_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; // unused for TIM6
Damien George4d7f4eb2014-04-15 19:52:56 +0100246 TIM6_Handle.Init.CounterMode = TIM_COUNTERMODE_UP; // unused for TIM6
247 HAL_TIM_Base_Init(&TIM6_Handle);
248}
249
Damien Georgea12be912014-04-02 15:09:36 +0100250// Interrupt dispatch
251void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
252 if (htim == &TIM3_Handle) {
253 USBD_CDC_HAL_TIM_PeriodElapsedCallback();
Damien George6d983532014-04-16 23:08:36 +0100254
255 // Periodically raise a flash IRQ for the flash storage controller
256 if (tim3_counter++ >= 500 / USBD_CDC_POLLING_INTERVAL) {
257 tim3_counter = 0;
258 NVIC->STIR = FLASH_IRQn;
259 }
260
Damien Georgea12be912014-04-02 15:09:36 +0100261 } else if (htim == &TIM5_Handle) {
262 servo_timer_irq_callback();
263 }
264}
265
Damien George97ef94d2014-10-04 14:36:39 +0100266// Get the frequency (in Hz) of the source clock for the given timer.
267// On STM32F405/407/415/417 there are 2 cases for how the clock freq is set.
268// If the APB prescaler is 1, then the timer clock is equal to its respective
269// APB clock. Otherwise (APB prescaler > 1) the timer clock is twice its
270// respective APB clock. See DM00031020 Rev 4, page 115.
271STATIC uint32_t timer_get_source_freq(uint32_t tim_id) {
272 uint32_t source;
273 if (tim_id == 1 || (8 <= tim_id && tim_id <= 11)) {
274 // TIM{1,8,9,10,11} are on APB2
275 source = HAL_RCC_GetPCLK2Freq();
276 if ((uint32_t)((RCC->CFGR & RCC_CFGR_PPRE2) >> 3) != RCC_HCLK_DIV1) {
277 source *= 2;
278 }
279 } else {
280 // TIM{2,3,4,5,6,7,12,13,14} are on APB1
281 source = HAL_RCC_GetPCLK1Freq();
282 if ((uint32_t)(RCC->CFGR & RCC_CFGR_PPRE1) != RCC_HCLK_DIV1) {
283 source *= 2;
284 }
285 }
286 return source;
287}
288
Damien George7fdfa932014-04-21 16:48:16 +0100289/******************************************************************************/
290/* Micro Python bindings */
Damien Georgea12be912014-04-02 15:09:36 +0100291
Damien George0e58c582014-09-21 22:54:02 +0100292STATIC const mp_obj_type_t pyb_timer_channel_type;
293
Dave Hylands39296b42014-09-26 09:04:05 -0700294// This is the largest value that we can multiply by 100 and have the result
295// fit in a uint32_t.
296#define MAX_PERIOD_DIV_100 42949672
297
Damien George97ef94d2014-10-04 14:36:39 +0100298// computes prescaler and period so TIM triggers at freq-Hz
299STATIC uint32_t compute_prescaler_period_from_freq(pyb_timer_obj_t *self, mp_obj_t freq_in, uint32_t *period_out) {
300 uint32_t source_freq = timer_get_source_freq(self->tim_id);
301 uint32_t prescaler = 1;
302 uint32_t period;
303 if (0) {
304 #if MICROPY_PY_BUILTINS_FLOAT
305 } else if (MP_OBJ_IS_TYPE(freq_in, &mp_type_float)) {
306 float freq = mp_obj_get_float(freq_in);
307 if (freq <= 0) {
308 goto bad_freq;
309 }
Damien George55f68b32014-10-04 14:59:35 +0100310 while (freq < 1 && prescaler < 6553) {
311 prescaler *= 10;
312 freq *= 10;
313 }
314 period = (float)source_freq / freq;
Damien George97ef94d2014-10-04 14:36:39 +0100315 #endif
316 } else {
317 mp_int_t freq = mp_obj_get_int(freq_in);
318 if (freq <= 0) {
319 goto bad_freq;
320 bad_freq:
321 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "must have positive freq"));
322 }
Damien George55f68b32014-10-04 14:59:35 +0100323 period = source_freq / freq;
Damien George97ef94d2014-10-04 14:36:39 +0100324 }
Damien George55f68b32014-10-04 14:59:35 +0100325 period = MAX(1, period);
Damien George97ef94d2014-10-04 14:36:39 +0100326 while (period > TIMER_CNT_MASK(self)) {
Damien George55f68b32014-10-04 14:59:35 +0100327 // if we can divide exactly, do that first
328 if (period % 5 == 0) {
329 prescaler *= 5;
330 period /= 5;
331 } else if (period % 3 == 0) {
332 prescaler *= 3;
333 period /= 3;
334 } else {
335 // may not divide exactly, but loses minimal precision
336 prescaler <<= 1;
337 period >>= 1;
338 }
Damien George97ef94d2014-10-04 14:36:39 +0100339 }
340 *period_out = (period - 1) & TIMER_CNT_MASK(self);
341 return (prescaler - 1) & 0xffff;
342}
343
Dave Hylands39296b42014-09-26 09:04:05 -0700344// Helper function for determining the period used for calculating percent
345STATIC uint32_t compute_period(pyb_timer_obj_t *self) {
346 // In center mode, compare == period corresponds to 100%
347 // In edge mode, compare == (period + 1) corresponds to 100%
348 uint32_t period = (__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
349 if (period != 0xffffffff) {
350 if (self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ||
351 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN) {
352 // Edge mode
353 period++;
354 }
355 }
356 return period;
357}
358
Damien Georgee8ea0722014-09-25 15:44:10 +0100359// Helper function to compute PWM value from timer period and percent value.
Dave Hylands39296b42014-09-26 09:04:05 -0700360// 'percent_in' can be an int or a float between 0 and 100 (out of range
361// values are clamped).
362STATIC uint32_t compute_pwm_value_from_percent(uint32_t period, mp_obj_t percent_in) {
Damien Georgee8ea0722014-09-25 15:44:10 +0100363 uint32_t cmp;
364 if (0) {
365 #if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands39296b42014-09-26 09:04:05 -0700366 } else if (MP_OBJ_IS_TYPE(percent_in, &mp_type_float)) {
367 float percent = mp_obj_get_float(percent_in);
368 if (percent <= 0.0) {
369 cmp = 0;
370 } else if (percent >= 100.0) {
371 cmp = period;
372 } else {
373 cmp = percent / 100.0 * ((float)period);
374 }
Damien Georgee8ea0722014-09-25 15:44:10 +0100375 #endif
376 } else {
377 // For integer arithmetic, if period is large and 100*period will
378 // overflow, then divide period before multiplying by cmp. Otherwise
379 // do it the other way round to retain precision.
Dave Hylands39296b42014-09-26 09:04:05 -0700380 mp_int_t percent = mp_obj_get_int(percent_in);
381 if (percent <= 0) {
382 cmp = 0;
383 } else if (percent >= 100) {
384 cmp = period;
385 } else if (period > MAX_PERIOD_DIV_100) {
386 cmp = (uint32_t)percent * (period / 100);
Damien Georgee8ea0722014-09-25 15:44:10 +0100387 } else {
Dave Hylands39296b42014-09-26 09:04:05 -0700388 cmp = ((uint32_t)percent * period) / 100;
Damien Georgee8ea0722014-09-25 15:44:10 +0100389 }
390 }
Damien Georgee8ea0722014-09-25 15:44:10 +0100391 return cmp;
392}
393
Dave Hylands39296b42014-09-26 09:04:05 -0700394// Helper function to compute percentage from timer perion and PWM value.
395STATIC mp_obj_t compute_percent_from_pwm_value(uint32_t period, uint32_t cmp) {
396 #if MICROPY_PY_BUILTINS_FLOAT
397 float percent;
Damien Georgef042d7a2014-09-29 14:15:01 +0100398 if (cmp >= period) {
Dave Hylands39296b42014-09-26 09:04:05 -0700399 percent = 100.0;
400 } else {
401 percent = (float)cmp * 100.0 / ((float)period);
402 }
403 return mp_obj_new_float(percent);
404 #else
405 mp_int_t percent;
Damien Georgef042d7a2014-09-29 14:15:01 +0100406 if (cmp >= period) {
Dave Hylands39296b42014-09-26 09:04:05 -0700407 percent = 100;
Damien Georgef042d7a2014-09-29 14:15:01 +0100408 } else if (cmp > MAX_PERIOD_DIV_100) {
409 percent = cmp / (period / 100);
Dave Hylands39296b42014-09-26 09:04:05 -0700410 } else {
411 percent = cmp * 100 / period;
412 }
413 return mp_obj_new_int(percent);
414 #endif
415}
416
Dave Hylands1c795442014-10-10 09:56:41 -0700417// Computes the 8-bit value for the DTG field in the BDTR register.
418//
419// 1 tick = 1 count of the timer's clock (source_freq) divided by div.
420// 0-128 ticks in inrements of 1
421// 128-256 ticks in increments of 2
422// 256-512 ticks in increments of 8
423// 512-1008 ticks in increments of 16
424STATIC uint32_t compute_dtg_from_ticks(mp_int_t ticks) {
425 if (ticks <= 0) {
426 return 0;
427 }
428 if (ticks < 128) {
429 return ticks;
430 }
431 if (ticks < 256) {
432 return 0x80 | ((ticks - 128) / 2);
433 }
434 if (ticks < 512) {
435 return 0xC0 | ((ticks - 256) / 8);
436 }
437 if (ticks < 1008) {
438 return 0xE0 | ((ticks - 512) / 16);
439 }
440 return 0xFF;
441}
442
443// Given the 8-bit value stored in the DTG field of the BDTR register, compute
444// the number of ticks.
445STATIC mp_int_t compute_ticks_from_dtg(uint32_t dtg) {
446 if ((dtg & 0x80) == 0) {
447 return dtg & 0x7F;
448 }
449 if ((dtg & 0xC0) == 0x80) {
450 return 128 + ((dtg & 0x3F) * 2);
451 }
452 if ((dtg & 0xE0) == 0xC0) {
453 return 256 + ((dtg & 0x1F) * 8);
454 }
455 return 512 + ((dtg & 0x1F) * 16);
456}
457
458STATIC void config_deadtime(pyb_timer_obj_t *self, mp_int_t ticks) {
459 TIM_BreakDeadTimeConfigTypeDef deadTimeConfig;
460 deadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
461 deadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
462 deadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
463 deadTimeConfig.DeadTime = compute_dtg_from_ticks(ticks);
464 deadTimeConfig.BreakState = TIM_BREAK_DISABLE;
465 deadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_LOW;
466 deadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
467 HAL_TIMEx_ConfigBreakDeadTime(&self->tim, &deadTimeConfig);
468}
469
Damien George7fdfa932014-04-21 16:48:16 +0100470STATIC void pyb_timer_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
471 pyb_timer_obj_t *self = self_in;
Damien Georgea12be912014-04-02 15:09:36 +0100472
Damien George7fdfa932014-04-21 16:48:16 +0100473 if (self->tim.State == HAL_TIM_STATE_RESET) {
474 print(env, "Timer(%u)", self->tim_id);
475 } else {
Damien George97ef94d2014-10-04 14:36:39 +0100476 uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
477 uint32_t period = __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self);
478 // for efficiency, we compute and print freq as an int (not a float)
479 uint32_t freq = timer_get_source_freq(self->tim_id) / ((prescaler + 1) * (period + 1));
Dave Hylands1c795442014-10-10 09:56:41 -0700480 print(env, "Timer(%u, freq=%u, prescaler=%u, period=%u, mode=%s, div=%u",
Damien George7fdfa932014-04-21 16:48:16 +0100481 self->tim_id,
Damien George97ef94d2014-10-04 14:36:39 +0100482 freq,
483 prescaler,
484 period,
Dave Hylandsbecbc872014-08-20 13:21:11 -0700485 self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ? "UP" :
486 self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN ? "DOWN" : "CENTER",
487 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV4 ? 4 :
488 self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV2 ? 2 : 1);
Dave Hylands1c795442014-10-10 09:56:41 -0700489 if (IS_TIM_ADVANCED_INSTANCE(self->tim.Instance)) {
490 print(env, ", deadtime=%u", compute_ticks_from_dtg(self->tim.Instance->BDTR & TIM_BDTR_DTG));
491 }
492 print(env, ")");
Damien George7fdfa932014-04-21 16:48:16 +0100493 }
494}
Damien Georgea12be912014-04-02 15:09:36 +0100495
Damien George3eb81632014-05-02 16:58:15 +0100496/// \method init(*, freq, prescaler, period)
497/// Initialise the timer. Initialisation must be either by frequency (in Hz)
498/// or by prescaler and period:
499///
500/// tim.init(freq=100) # set the timer to trigger at 100Hz
Dave Hylandsbecbc872014-08-20 13:21:11 -0700501/// tim.init(prescaler=83, period=999) # set the prescaler and period directly
502///
503/// Keyword arguments:
504///
505/// - `freq` - specifies the periodic frequency of the timer. You migh also
506/// view this as the frequency with which the timer goes through
507/// one complete cycle.
508///
509/// - `prescaler` [0-0xffff] - specifies the value to be loaded into the
510/// timer's Prescaler Register (PSC). The timer clock source is divided by
511/// (`prescaler + 1`) to arrive at the timer clock. Timers 2-7 and 12-14
512/// have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
513/// have a clock source of 168 MHz (pyb.freq()[3] * 2).
514///
515/// - `period` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5.
516/// Specifies the value to be loaded into the timer's AutoReload
517/// Register (ARR). This determines the period of the timer (i.e. when the
518/// counter cycles). The timer counter will roll-over after `period + 1`
519/// timer clock cycles.
520///
521/// - `mode` can be one of:
522/// - `Timer.UP` - configures the timer to count from 0 to ARR (default)
523/// - `Timer.DOWN` - configures the timer to count from ARR down to 0.
524/// - `Timer.CENTER` - confgures the timer to count from 0 to ARR and
525/// then back down to 0.
526///
527/// - `div` can be one of 1, 2, or 4. Divides the timer clock to determine
528/// the sampling clock used by the digital filters.
529///
530/// - `callback` - as per Timer.callback()
531///
Dave Hylands1c795442014-10-10 09:56:41 -0700532/// - `deadtime` - specifies the amount of "dead" or inactive time between
533/// transitions on complimentary channels (both channels will be inactive)
534/// for this time). `deadtime` may be an integer between 0 and 1008, with
535/// the following restrictions: 0-128 in steps of 1. 128-256 in steps of
536/// 2, 256-512 in steps of 8, and 512-1008 in steps of 16. `deadime`
537/// measures ticks of `source_freq` divided by `div` clock ticks.
538/// `deadtime` is only available on timers 1 and 8.
539///
Dave Hylandsbecbc872014-08-20 13:21:11 -0700540/// You must either specify freq or both of period and prescaler.
Damien George97ef94d2014-10-04 14:36:39 +0100541STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
542 static const mp_arg_t allowed_args[] = {
543 { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
544 { MP_QSTR_prescaler, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
545 { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
546 { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_COUNTERMODE_UP} },
547 { MP_QSTR_div, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
548 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
Dave Hylands1c795442014-10-10 09:56:41 -0700549 { MP_QSTR_deadtime, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
Damien George97ef94d2014-10-04 14:36:39 +0100550 };
Damien George7fdfa932014-04-21 16:48:16 +0100551
Damien George7fdfa932014-04-21 16:48:16 +0100552 // parse args
Damien George97ef94d2014-10-04 14:36:39 +0100553 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
554 mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
Damien George7fdfa932014-04-21 16:48:16 +0100555
556 // set the TIM configuration values
557 TIM_Base_InitTypeDef *init = &self->tim.Init;
558
Damien George97ef94d2014-10-04 14:36:39 +0100559 if (args[0].u_obj != mp_const_none) {
560 // set prescaler and period from desired frequency
561 init->Prescaler = compute_prescaler_period_from_freq(self, args[0].u_obj, &init->Period);
562 } else if (args[1].u_int != 0xffffffff && args[2].u_int != 0xffffffff) {
Damien George7fdfa932014-04-21 16:48:16 +0100563 // set prescaler and period directly
Damien George97ef94d2014-10-04 14:36:39 +0100564 init->Prescaler = args[1].u_int;
565 init->Period = args[2].u_int;
Damien George7fdfa932014-04-21 16:48:16 +0100566 } else {
567 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "must specify either freq, or prescaler and period"));
568 }
569
Damien George97ef94d2014-10-04 14:36:39 +0100570 init->CounterMode = args[3].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700571 if (!IS_TIM_COUNTER_MODE(init->CounterMode)) {
Damien George97ef94d2014-10-04 14:36:39 +0100572 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid mode (%d)", init->CounterMode));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700573 }
574
Damien George97ef94d2014-10-04 14:36:39 +0100575 init->ClockDivision = args[4].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
576 args[4].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
577 TIM_CLOCKDIVISION_DIV1;
578
579 init->RepetitionCounter = 0;
580
581 // enable TIM clock
Damien George7fdfa932014-04-21 16:48:16 +0100582 switch (self->tim_id) {
583 case 1: __TIM1_CLK_ENABLE(); break;
584 case 2: __TIM2_CLK_ENABLE(); break;
585 case 3: __TIM3_CLK_ENABLE(); break;
586 case 4: __TIM4_CLK_ENABLE(); break;
587 case 5: __TIM5_CLK_ENABLE(); break;
588 case 6: __TIM6_CLK_ENABLE(); break;
589 case 7: __TIM7_CLK_ENABLE(); break;
590 case 8: __TIM8_CLK_ENABLE(); break;
591 case 9: __TIM9_CLK_ENABLE(); break;
592 case 10: __TIM10_CLK_ENABLE(); break;
593 case 11: __TIM11_CLK_ENABLE(); break;
594 case 12: __TIM12_CLK_ENABLE(); break;
595 case 13: __TIM13_CLK_ENABLE(); break;
596 case 14: __TIM14_CLK_ENABLE(); break;
597 }
Damien George97ef94d2014-10-04 14:36:39 +0100598
599 // set IRQ priority (if not a special timer)
Damien George7fdfa932014-04-21 16:48:16 +0100600 if (self->tim_id != 3 && self->tim_id != 5) {
601 HAL_NVIC_SetPriority(self->irqn, 0xe, 0xe); // next-to lowest priority
602 }
603
Damien George97ef94d2014-10-04 14:36:39 +0100604 // init TIM
Dave Hylandsbecbc872014-08-20 13:21:11 -0700605 HAL_TIM_Base_Init(&self->tim);
Dave Hylands1c795442014-10-10 09:56:41 -0700606 if (IS_TIM_ADVANCED_INSTANCE(self->tim.Instance)) {
607 config_deadtime(self, args[6].u_int);
608 }
Damien George97ef94d2014-10-04 14:36:39 +0100609 if (args[5].u_obj == mp_const_none) {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700610 HAL_TIM_Base_Start(&self->tim);
611 } else {
Damien George97ef94d2014-10-04 14:36:39 +0100612 pyb_timer_callback(self, args[5].u_obj);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700613 }
614
Damien George7fdfa932014-04-21 16:48:16 +0100615 return mp_const_none;
616}
617
Damien George3eb81632014-05-02 16:58:15 +0100618/// \classmethod \constructor(id, ...)
619/// Construct a new timer object of the given id. If additional
620/// arguments are given, then the timer is initialised by `init(...)`.
621/// `id` can be 1 to 14, excluding 3.
Damien Georgeecc88e92014-08-30 00:35:11 +0100622STATIC 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 +0100623 // check arguments
624 mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
625
626 // create new Timer object
627 pyb_timer_obj_t *tim = m_new_obj(pyb_timer_obj_t);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700628 memset(tim, 0, sizeof(*tim));
629
Damien George7fdfa932014-04-21 16:48:16 +0100630 tim->base.type = &pyb_timer_type;
631 tim->callback = mp_const_none;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700632 tim->channel = NULL;
Damien George7fdfa932014-04-21 16:48:16 +0100633
634 // get TIM number
635 tim->tim_id = mp_obj_get_int(args[0]);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700636 tim->is_32bit = false;
Damien George7fdfa932014-04-21 16:48:16 +0100637
638 switch (tim->tim_id) {
639 case 1: tim->tim.Instance = TIM1; tim->irqn = TIM1_UP_TIM10_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700640 case 2: tim->tim.Instance = TIM2; tim->irqn = TIM2_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100641 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
642 case 4: tim->tim.Instance = TIM4; tim->irqn = TIM4_IRQn; break;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700643 case 5: tim->tim.Instance = TIM5; tim->irqn = TIM5_IRQn; tim->is_32bit = true; break;
Damien George7fdfa932014-04-21 16:48:16 +0100644 case 6: tim->tim.Instance = TIM6; tim->irqn = TIM6_DAC_IRQn; break;
645 case 7: tim->tim.Instance = TIM7; tim->irqn = TIM7_IRQn; break;
646 case 8: tim->tim.Instance = TIM8; tim->irqn = TIM8_UP_TIM13_IRQn; break;
647 case 9: tim->tim.Instance = TIM9; tim->irqn = TIM1_BRK_TIM9_IRQn; break;
648 case 10: tim->tim.Instance = TIM10; tim->irqn = TIM1_UP_TIM10_IRQn; break;
649 case 11: tim->tim.Instance = TIM11; tim->irqn = TIM1_TRG_COM_TIM11_IRQn; break;
650 case 12: tim->tim.Instance = TIM12; tim->irqn = TIM8_BRK_TIM12_IRQn; break;
651 case 13: tim->tim.Instance = TIM13; tim->irqn = TIM8_UP_TIM13_IRQn; break;
652 case 14: tim->tim.Instance = TIM14; tim->irqn = TIM8_TRG_COM_TIM14_IRQn; break;
653 default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id));
654 }
655
656 if (n_args > 1 || n_kw > 0) {
657 // start the peripheral
658 mp_map_t kw_args;
659 mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
660 pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args);
661 }
662
663 // set the global variable for interrupt callbacks
664 if (tim->tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
665 pyb_timer_obj_all[tim->tim_id - 1] = tim;
666 }
667
668 return (mp_obj_t)tim;
669}
670
Damien Georgeecc88e92014-08-30 00:35:11 +0100671STATIC 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 +0100672 return pyb_timer_init_helper(args[0], n_args - 1, args + 1, kw_args);
673}
674STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
675
Damien George3eb81632014-05-02 16:58:15 +0100676/// \method deinit()
677/// Deinitialises the timer.
678///
Dave Hylands0d81c132014-06-30 07:55:54 -0700679/// Disables the callback (and the associated irq).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700680/// Disables any channel callbacks (and the associated irq).
Dave Hylands0d81c132014-06-30 07:55:54 -0700681/// Stops the timer, and disables the timer peripheral.
Damien George7fdfa932014-04-21 16:48:16 +0100682STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
Dave Hylands0d81c132014-06-30 07:55:54 -0700683 pyb_timer_obj_t *self = self_in;
684
Dave Hylandsbecbc872014-08-20 13:21:11 -0700685 // Disable the base interrupt
Dave Hylands0d81c132014-06-30 07:55:54 -0700686 pyb_timer_callback(self_in, mp_const_none);
687
Dave Hylandsbecbc872014-08-20 13:21:11 -0700688 pyb_timer_channel_obj_t *chan = self->channel;
689 self->channel = NULL;
690
691 // Disable the channel interrupts
692 while (chan != NULL) {
693 pyb_timer_channel_callback(chan, mp_const_none);
694 pyb_timer_channel_obj_t *prev_chan = chan;
695 chan = chan->next;
696 prev_chan->next = NULL;
697 }
698
Dave Hylands0d81c132014-06-30 07:55:54 -0700699 HAL_TIM_Base_DeInit(&self->tim);
Damien George7fdfa932014-04-21 16:48:16 +0100700 return mp_const_none;
701}
702STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);
703
Dave Hylandsbecbc872014-08-20 13:21:11 -0700704/// \method channel(channel, mode, ...)
705///
Damien George0e58c582014-09-21 22:54:02 +0100706/// If only a channel number is passed, then a previously initialized channel
707/// object is returned (or `None` if there is no previous channel).
Dave Hylandsbecbc872014-08-20 13:21:11 -0700708///
709/// Othwerwise, a TimerChannel object is initialized and returned.
710///
711/// Each channel can be configured to perform pwm, output compare, or
712/// input capture. All channels share the same underlying timer, which means
713/// that they share the same timer clock.
714///
715/// Keyword arguments:
716///
717/// - `mode` can be one of:
718/// - `Timer.PWM` - configure the timer in PWM mode (active high).
719/// - `Timer.PWM_INVERTED` - configure the timer in PWM mode (active low).
720/// - `Timer.OC_TIMING` - indicates that no pin is driven.
721/// - `Timer.OC_ACTIVE` - the pin will be made active when a compare
722/// match occurs (active is determined by polarity)
723/// - `Timer.OC_INACTIVE` - the pin will be made inactive when a compare
724/// match occurs.
725/// - `Timer.OC_TOGGLE` - the pin will be toggled when an compare match occurs.
726/// - `Timer.OC_FORCED_ACTIVE` - the pin is forced active (compare match is ignored).
727/// - `Timer.OC_FORCED_INACTIVE` - the pin is forced inactive (compare match is ignored).
728/// - `Timer.IC` - configure the timer in Input Capture mode.
729///
730/// - `callback` - as per TimerChannel.callback()
731///
732/// - `pin` None (the default) or a Pin object. If specified (and not None)
733/// this will cause the alternate function of the the indicated pin
734/// to be configured for this timer channel. An error will be raised if
735/// the pin doesn't support any alternate functions for this timer channel.
736///
737/// Keyword arguments for Timer.PWM modes:
738///
Damien George0e58c582014-09-21 22:54:02 +0100739/// - `pulse_width` - determines the initial pulse width value to use.
Dave Hylands53d5fa62014-09-21 22:40:42 -0700740/// - `pulse_width_percent` - determines the initial pulse width percentage to use.
Dave Hylandsbecbc872014-08-20 13:21:11 -0700741///
742/// Keyword arguments for Timer.OC modes:
743///
744/// - `compare` - determines the initial value of the compare register.
745///
746/// - `polarity` can be one of:
747/// - `Timer.HIGH` - output is active high
748/// - `Timer.LOW` - output is acive low
749///
750/// Optional keyword arguments for Timer.IC modes:
751///
752/// - `polarity` can be one of:
753/// - `Timer.RISING` - captures on rising edge.
754/// - `Timer.FALLING` - captures on falling edge.
755/// - `Timer.BOTH` - captures on both edges.
756///
Dave Hylands1c795442014-10-10 09:56:41 -0700757/// Note that capture only works on the primary channel, and not on the
758/// complimentary channels.
759///
Dave Hylandsbecbc872014-08-20 13:21:11 -0700760/// PWM Example:
761///
762/// timer = pyb.Timer(2, freq=1000)
763/// ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
764/// ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
Damien Georgeba0383a2014-10-04 15:25:01 +0100765STATIC mp_obj_t pyb_timer_channel(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
766 static const mp_arg_t allowed_args[] = {
767 { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
768 { MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
769 { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
770 { MP_QSTR_pulse_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
771 { MP_QSTR_pulse_width_percent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
772 { MP_QSTR_compare, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
773 { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
774 };
Dave Hylandsbecbc872014-08-20 13:21:11 -0700775
Damien Georgeba0383a2014-10-04 15:25:01 +0100776 pyb_timer_obj_t *self = pos_args[0];
777 mp_int_t channel = mp_obj_get_int(pos_args[1]);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700778
779 if (channel < 1 || channel > 4) {
Damien Georgeba0383a2014-10-04 15:25:01 +0100780 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid channel (%d)", channel));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700781 }
782
783 pyb_timer_channel_obj_t *chan = self->channel;
784 pyb_timer_channel_obj_t *prev_chan = NULL;
785
786 while (chan != NULL) {
787 if (chan->channel == channel) {
788 break;
789 }
790 prev_chan = chan;
791 chan = chan->next;
792 }
Damien George0e58c582014-09-21 22:54:02 +0100793
794 // If only the channel number is given return the previously allocated
795 // channel (or None if no previous channel).
Damien Georgeba0383a2014-10-04 15:25:01 +0100796 if (n_args == 2 && kw_args->used == 0) {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700797 if (chan) {
798 return chan;
799 }
800 return mp_const_none;
801 }
802
803 // If there was already a channel, then remove it from the list. Note that
804 // the order we do things here is important so as to appear atomic to
805 // the IRQ handler.
806 if (chan) {
807 // Turn off any IRQ associated with the channel.
808 pyb_timer_channel_callback(chan, mp_const_none);
809
810 // Unlink the channel from the list.
811 if (prev_chan) {
812 prev_chan->next = chan->next;
813 }
814 self->channel = chan->next;
815 chan->next = NULL;
816 }
817
818 // Allocate and initialize a new channel
Damien Georgeba0383a2014-10-04 15:25:01 +0100819 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
820 mp_arg_parse_all(n_args - 2, pos_args + 2, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700821
822 chan = m_new_obj(pyb_timer_channel_obj_t);
823 memset(chan, 0, sizeof(*chan));
824 chan->base.type = &pyb_timer_channel_type;
825 chan->timer = self;
826 chan->channel = channel;
Damien Georgeba0383a2014-10-04 15:25:01 +0100827 chan->mode = args[0].u_int;
828 chan->callback = args[1].u_obj;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700829
Damien Georgeba0383a2014-10-04 15:25:01 +0100830 mp_obj_t pin_obj = args[2].u_obj;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700831 if (pin_obj != mp_const_none) {
832 if (!MP_OBJ_IS_TYPE(pin_obj, &pin_type)) {
833 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "pin argument needs to be be a Pin type"));
834 }
835 const pin_obj_t *pin = pin_obj;
836 const pin_af_obj_t *af = pin_find_af(pin, AF_FN_TIM, self->tim_id);
837 if (af == NULL) {
838 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));
839 }
840 // pin.init(mode=AF_PP, af=idx)
Damien Georgeba0383a2014-10-04 15:25:01 +0100841 const mp_obj_t args2[6] = {
Dave Hylandsbecbc872014-08-20 13:21:11 -0700842 (mp_obj_t)&pin_init_obj,
843 pin_obj,
844 MP_OBJ_NEW_QSTR(MP_QSTR_mode), MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP),
845 MP_OBJ_NEW_QSTR(MP_QSTR_af), MP_OBJ_NEW_SMALL_INT(af->idx)
846 };
Damien Georgeba0383a2014-10-04 15:25:01 +0100847 mp_call_method_n_kw(0, 2, args2);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700848 }
849
850 // Link the channel to the timer before we turn the channel on.
851 // Note that this needs to appear atomic to the IRQ handler (the write
852 // to self->channel is atomic, so we're good, but I thought I'd mention
853 // in case this was ever changed in the future).
854 chan->next = self->channel;
855 self->channel = chan;
856
857 switch (chan->mode) {
858
859 case CHANNEL_MODE_PWM_NORMAL:
860 case CHANNEL_MODE_PWM_INVERTED: {
861 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100862 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
Damien Georgeba0383a2014-10-04 15:25:01 +0100863 if (args[4].u_obj != mp_const_none) {
Dave Hylands53d5fa62014-09-21 22:40:42 -0700864 // pulse width percent given
Dave Hylands39296b42014-09-26 09:04:05 -0700865 uint32_t period = compute_period(self);
Damien Georgeba0383a2014-10-04 15:25:01 +0100866 oc_config.Pulse = compute_pwm_value_from_percent(period, args[4].u_obj);
Damien George0e58c582014-09-21 22:54:02 +0100867 } else {
Damien Georgee8ea0722014-09-25 15:44:10 +0100868 // use absolute pulse width value (defaults to 0 if nothing given)
Damien Georgeba0383a2014-10-04 15:25:01 +0100869 oc_config.Pulse = args[3].u_int;
Damien George0e58c582014-09-21 22:54:02 +0100870 }
Dave Hylandsbecbc872014-08-20 13:21:11 -0700871 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
872 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
873 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
874 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
875 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
876
877 HAL_TIM_PWM_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
878 if (chan->callback == mp_const_none) {
879 HAL_TIM_PWM_Start(&self->tim, TIMER_CHANNEL(chan));
880 } else {
881 HAL_TIM_PWM_Start_IT(&self->tim, TIMER_CHANNEL(chan));
882 }
Dave Hylands1c795442014-10-10 09:56:41 -0700883 // Start the complimentary channel too (if its supported)
884 if (IS_TIM_CCXN_INSTANCE(self->tim.Instance, TIMER_CHANNEL(chan))) {
885 HAL_TIMEx_PWMN_Start(&self->tim, TIMER_CHANNEL(chan));
886 }
Dave Hylandsbecbc872014-08-20 13:21:11 -0700887 break;
888 }
889
890 case CHANNEL_MODE_OC_TIMING:
891 case CHANNEL_MODE_OC_ACTIVE:
892 case CHANNEL_MODE_OC_INACTIVE:
893 case CHANNEL_MODE_OC_TOGGLE:
894 case CHANNEL_MODE_OC_FORCED_ACTIVE:
895 case CHANNEL_MODE_OC_FORCED_INACTIVE: {
896 TIM_OC_InitTypeDef oc_config;
Damien George0e58c582014-09-21 22:54:02 +0100897 oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
Damien Georgeba0383a2014-10-04 15:25:01 +0100898 oc_config.Pulse = args[5].u_int;
899 oc_config.OCPolarity = args[6].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700900 if (oc_config.OCPolarity == 0xffffffff) {
901 oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
902 }
Dave Hylands1c795442014-10-10 09:56:41 -0700903 if (oc_config.OCPolarity == TIM_OCPOLARITY_HIGH) {
904 oc_config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
905 } else {
906 oc_config.OCNPolarity = TIM_OCNPOLARITY_LOW;
907 }
Dave Hylandsbecbc872014-08-20 13:21:11 -0700908 oc_config.OCFastMode = TIM_OCFAST_DISABLE;
909 oc_config.OCIdleState = TIM_OCIDLESTATE_SET;
910 oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;
911
912 if (!IS_TIM_OC_POLARITY(oc_config.OCPolarity)) {
Damien Georgeba0383a2014-10-04 15:25:01 +0100913 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", oc_config.OCPolarity));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700914 }
915 HAL_TIM_OC_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
916 if (chan->callback == mp_const_none) {
917 HAL_TIM_OC_Start(&self->tim, TIMER_CHANNEL(chan));
918 } else {
919 HAL_TIM_OC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
920 }
Dave Hylands1c795442014-10-10 09:56:41 -0700921 // Start the complimentary channel too (if its supported)
922 if (IS_TIM_CCXN_INSTANCE(self->tim.Instance, TIMER_CHANNEL(chan))) {
923 HAL_TIMEx_OCN_Start(&self->tim, TIMER_CHANNEL(chan));
924 }
Dave Hylandsbecbc872014-08-20 13:21:11 -0700925 break;
926 }
927
928 case CHANNEL_MODE_IC: {
929 TIM_IC_InitTypeDef ic_config;
930
Damien Georgeba0383a2014-10-04 15:25:01 +0100931 ic_config.ICPolarity = args[6].u_int;
Dave Hylandsbecbc872014-08-20 13:21:11 -0700932 if (ic_config.ICPolarity == 0xffffffff) {
933 ic_config.ICPolarity = TIM_ICPOLARITY_RISING;
934 }
935 ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
936 ic_config.ICPrescaler = TIM_ICPSC_DIV1;
937 ic_config.ICFilter = 0;
938
939 if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) {
Damien Georgeba0383a2014-10-04 15:25:01 +0100940 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", ic_config.ICPolarity));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700941 }
942 HAL_TIM_IC_ConfigChannel(&self->tim, &ic_config, TIMER_CHANNEL(chan));
943 if (chan->callback == mp_const_none) {
944 HAL_TIM_IC_Start(&self->tim, TIMER_CHANNEL(chan));
945 } else {
946 HAL_TIM_IC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
947 }
948 break;
949 }
950
951 default:
Damien Georgeba0383a2014-10-04 15:25:01 +0100952 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid mode (%d)", chan->mode));
Dave Hylandsbecbc872014-08-20 13:21:11 -0700953 }
954
955 return chan;
956}
Damien George0e58c582014-09-21 22:54:02 +0100957STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
Dave Hylandsbecbc872014-08-20 13:21:11 -0700958
Damien George3eb81632014-05-02 16:58:15 +0100959/// \method counter([value])
960/// Get or set the timer counter.
Damien George0e58c582014-09-21 22:54:02 +0100961STATIC mp_obj_t pyb_timer_counter(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +0100962 pyb_timer_obj_t *self = args[0];
963 if (n_args == 1) {
964 // get
965 return mp_obj_new_int(self->tim.Instance->CNT);
966 } else {
967 // set
968 __HAL_TIM_SetCounter(&self->tim, mp_obj_get_int(args[1]));
969 return mp_const_none;
970 }
971}
972STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_counter_obj, 1, 2, pyb_timer_counter);
973
Damien George97ef94d2014-10-04 14:36:39 +0100974/// \method source_freq()
975/// Get the frequency of the source of the timer.
976STATIC mp_obj_t pyb_timer_source_freq(mp_obj_t self_in) {
977 pyb_timer_obj_t *self = self_in;
978 uint32_t source_freq = timer_get_source_freq(self->tim_id);
979 return mp_obj_new_int(source_freq);
980}
981STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_source_freq_obj, pyb_timer_source_freq);
982
983/// \method freq([value])
984/// Get or set the frequency for the timer (changes prescaler and period if set).
985STATIC mp_obj_t pyb_timer_freq(mp_uint_t n_args, const mp_obj_t *args) {
986 pyb_timer_obj_t *self = args[0];
987 if (n_args == 1) {
988 // get
989 uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
990 uint32_t period = __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self);
991 uint32_t source_freq = timer_get_source_freq(self->tim_id);
992 uint32_t divide = ((prescaler + 1) * (period + 1));
993 if (source_freq % divide == 0) {
994 return mp_obj_new_int(source_freq / divide);
995 } else {
996 return mp_obj_new_float((float)source_freq / (float)divide);
997 }
998 } else {
999 // set
1000 uint32_t period;
1001 uint32_t prescaler = compute_prescaler_period_from_freq(self, args[1], &period);
1002 self->tim.Instance->PSC = prescaler;
1003 __HAL_TIM_SetAutoreload(&self->tim, period);
1004 return mp_const_none;
1005 }
1006}
1007STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_freq_obj, 1, 2, pyb_timer_freq);
1008
Damien George3eb81632014-05-02 16:58:15 +01001009/// \method prescaler([value])
1010/// Get or set the prescaler for the timer.
Damien George0e58c582014-09-21 22:54:02 +01001011STATIC mp_obj_t pyb_timer_prescaler(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +01001012 pyb_timer_obj_t *self = args[0];
1013 if (n_args == 1) {
1014 // get
1015 return mp_obj_new_int(self->tim.Instance->PSC & 0xffff);
1016 } else {
1017 // set
Damien George97ef94d2014-10-04 14:36:39 +01001018 self->tim.Instance->PSC = mp_obj_get_int(args[1]) & 0xffff;
Damien George7fdfa932014-04-21 16:48:16 +01001019 return mp_const_none;
1020 }
1021}
1022STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);
1023
Damien George3eb81632014-05-02 16:58:15 +01001024/// \method period([value])
1025/// Get or set the period of the timer.
Damien George0e58c582014-09-21 22:54:02 +01001026STATIC mp_obj_t pyb_timer_period(mp_uint_t n_args, const mp_obj_t *args) {
Damien George7fdfa932014-04-21 16:48:16 +01001027 pyb_timer_obj_t *self = args[0];
1028 if (n_args == 1) {
1029 // get
Dave Hylandsbecbc872014-08-20 13:21:11 -07001030 return mp_obj_new_int(__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +01001031 } else {
1032 // set
Dave Hylandsbecbc872014-08-20 13:21:11 -07001033 __HAL_TIM_SetAutoreload(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
Damien George7fdfa932014-04-21 16:48:16 +01001034 return mp_const_none;
1035 }
1036}
1037STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
1038
Damien George3eb81632014-05-02 16:58:15 +01001039/// \method callback(fun)
1040/// Set the function to be called when the timer triggers.
1041/// `fun` is passed 1 argument, the timer object.
1042/// If `fun` is `None` then the callback will be disabled.
Damien George7fdfa932014-04-21 16:48:16 +01001043STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
1044 pyb_timer_obj_t *self = self_in;
1045 if (callback == mp_const_none) {
1046 // stop interrupt (but not timer)
1047 __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
1048 self->callback = mp_const_none;
1049 } else if (mp_obj_is_callable(callback)) {
1050 self->callback = callback;
1051 HAL_NVIC_EnableIRQ(self->irqn);
1052 // start timer, so that it interrupts on overflow
1053 HAL_TIM_Base_Start_IT(&self->tim);
1054 } else {
1055 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
1056 }
Damien Georgea12be912014-04-02 15:09:36 +01001057 return mp_const_none;
1058}
Damien George7fdfa932014-04-21 16:48:16 +01001059STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);
Damien Georgea12be912014-04-02 15:09:36 +01001060
Damien George7fdfa932014-04-21 16:48:16 +01001061STATIC const mp_map_elem_t pyb_timer_locals_dict_table[] = {
1062 // instance methods
1063 { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_timer_init_obj },
1064 { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_timer_deinit_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -07001065 { MP_OBJ_NEW_QSTR(MP_QSTR_channel), (mp_obj_t)&pyb_timer_channel_obj },
Damien George7fdfa932014-04-21 16:48:16 +01001066 { MP_OBJ_NEW_QSTR(MP_QSTR_counter), (mp_obj_t)&pyb_timer_counter_obj },
Damien George97ef94d2014-10-04 14:36:39 +01001067 { MP_OBJ_NEW_QSTR(MP_QSTR_source_freq), (mp_obj_t)&pyb_timer_source_freq_obj },
1068 { MP_OBJ_NEW_QSTR(MP_QSTR_freq), (mp_obj_t)&pyb_timer_freq_obj },
Damien George7fdfa932014-04-21 16:48:16 +01001069 { MP_OBJ_NEW_QSTR(MP_QSTR_prescaler), (mp_obj_t)&pyb_timer_prescaler_obj },
1070 { MP_OBJ_NEW_QSTR(MP_QSTR_period), (mp_obj_t)&pyb_timer_period_obj },
1071 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_callback_obj },
Dave Hylandsbecbc872014-08-20 13:21:11 -07001072 { MP_OBJ_NEW_QSTR(MP_QSTR_UP), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_UP) },
1073 { MP_OBJ_NEW_QSTR(MP_QSTR_DOWN), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_DOWN) },
1074 { MP_OBJ_NEW_QSTR(MP_QSTR_CENTER), MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_CENTERALIGNED1) },
1075 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_NORMAL) },
1076 { MP_OBJ_NEW_QSTR(MP_QSTR_PWM_INVERTED), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_INVERTED) },
1077 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TIMING), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TIMING) },
1078 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_ACTIVE) },
1079 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_INACTIVE) },
1080 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TOGGLE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TOGGLE) },
1081 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_ACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_ACTIVE) },
1082 { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_INACTIVE), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_INACTIVE) },
1083 { MP_OBJ_NEW_QSTR(MP_QSTR_IC), MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_IC) },
1084 { MP_OBJ_NEW_QSTR(MP_QSTR_HIGH), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_HIGH) },
1085 { MP_OBJ_NEW_QSTR(MP_QSTR_LOW), MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_LOW) },
1086 { MP_OBJ_NEW_QSTR(MP_QSTR_RISING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_RISING) },
1087 { MP_OBJ_NEW_QSTR(MP_QSTR_FALLING), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_FALLING) },
1088 { MP_OBJ_NEW_QSTR(MP_QSTR_BOTH), MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_BOTHEDGE) },
Damien George7fdfa932014-04-21 16:48:16 +01001089};
Damien George7fdfa932014-04-21 16:48:16 +01001090STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table);
Damien Georgea12be912014-04-02 15:09:36 +01001091
Damien George7fdfa932014-04-21 16:48:16 +01001092const mp_obj_type_t pyb_timer_type = {
1093 { &mp_type_type },
1094 .name = MP_QSTR_Timer,
1095 .print = pyb_timer_print,
1096 .make_new = pyb_timer_make_new,
1097 .locals_dict = (mp_obj_t)&pyb_timer_locals_dict,
1098};
Damien Georgea12be912014-04-02 15:09:36 +01001099
Dave Hylandsbecbc872014-08-20 13:21:11 -07001100/// \moduleref pyb
1101/// \class TimerChannel - setup a channel for a timer.
1102///
1103/// Timer channels are used to generate/capture a signal using a timer.
1104///
1105/// TimerChannel objects are created using the Timer.channel() method.
1106STATIC void pyb_timer_channel_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
1107 pyb_timer_channel_obj_t *self = self_in;
1108
1109 print(env, "TimerChannel(timer=%u, channel=%u, mode=%s)",
1110 self->timer->tim_id,
1111 self->channel,
Damien George0e58c582014-09-21 22:54:02 +01001112 qstr_str(channel_mode_info[self->mode].name));
Dave Hylandsbecbc872014-08-20 13:21:11 -07001113}
1114
1115/// \method capture([value])
1116/// Get or set the capture value associated with a channel.
1117/// capture, compare, and pulse_width are all aliases for the same function.
1118/// capture is the logical name to use when the channel is in input capture mode.
1119
1120/// \method compare([value])
1121/// Get or set the compare value associated with a channel.
1122/// capture, compare, and pulse_width are all aliases for the same function.
1123/// compare is the logical name to use when the channel is in output compare mode.
1124
1125/// \method pulse_width([value])
1126/// Get or set the pulse width value associated with a channel.
1127/// capture, compare, and pulse_width are all aliases for the same function.
1128/// pulse_width is the logical name to use when the channel is in PWM mode.
Dave Hylands39296b42014-09-26 09:04:05 -07001129///
1130/// In edge aligned mode, a pulse_width of `period + 1` corresponds to a duty cycle of 100%
1131/// In center aligned mode, a pulse width of `period` corresponds to a duty cycle of 100%
Damien George0e58c582014-09-21 22:54:02 +01001132STATIC 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 -07001133 pyb_timer_channel_obj_t *self = args[0];
Dave Hylandsbecbc872014-08-20 13:21:11 -07001134 if (n_args == 1) {
1135 // get
1136 return mp_obj_new_int(__HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer));
1137 } else {
1138 // set
1139 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self->timer));
1140 return mp_const_none;
1141 }
1142}
1143STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_capture_compare_obj, 1, 2, pyb_timer_channel_capture_compare);
1144
Damien Georgee8ea0722014-09-25 15:44:10 +01001145/// \method pulse_width_percent([value])
1146/// Get or set the pulse width percentage associated with a channel. The value
1147/// is a number between 0 and 100 and sets the percentage of the timer period
1148/// for which the pulse is active. The value can be an integer or
1149/// floating-point number for more accuracy. For example, a value of 25 gives
1150/// a duty cycle of 25%.
Dave Hylands53d5fa62014-09-21 22:40:42 -07001151STATIC 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 +01001152 pyb_timer_channel_obj_t *self = args[0];
Dave Hylands39296b42014-09-26 09:04:05 -07001153 uint32_t period = compute_period(self->timer);
Damien George0e58c582014-09-21 22:54:02 +01001154 if (n_args == 1) {
1155 // get
1156 uint32_t cmp = __HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer);
Dave Hylands39296b42014-09-26 09:04:05 -07001157 return compute_percent_from_pwm_value(period, cmp);
Damien George0e58c582014-09-21 22:54:02 +01001158 } else {
1159 // set
Damien Georgee8ea0722014-09-25 15:44:10 +01001160 uint32_t cmp = compute_pwm_value_from_percent(period, args[1]);
Damien George0e58c582014-09-21 22:54:02 +01001161 __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), cmp & TIMER_CNT_MASK(self->timer));
1162 return mp_const_none;
1163 }
1164}
Dave Hylands53d5fa62014-09-21 22:40:42 -07001165STATIC 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 +01001166
Dave Hylandsbecbc872014-08-20 13:21:11 -07001167/// \method callback(fun)
1168/// Set the function to be called when the timer channel triggers.
1169/// `fun` is passed 1 argument, the timer object.
1170/// If `fun` is `None` then the callback will be disabled.
1171STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback) {
1172 pyb_timer_channel_obj_t *self = self_in;
1173 if (callback == mp_const_none) {
1174 // stop interrupt (but not timer)
1175 __HAL_TIM_DISABLE_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
1176 self->callback = mp_const_none;
1177 } else if (mp_obj_is_callable(callback)) {
1178 self->callback = callback;
1179 HAL_NVIC_EnableIRQ(self->timer->irqn);
1180 // start timer, so that it interrupts on overflow
1181 switch (self->mode) {
1182 case CHANNEL_MODE_PWM_NORMAL:
1183 case CHANNEL_MODE_PWM_INVERTED:
1184 HAL_TIM_PWM_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1185 break;
1186 case CHANNEL_MODE_OC_TIMING:
1187 case CHANNEL_MODE_OC_ACTIVE:
1188 case CHANNEL_MODE_OC_INACTIVE:
1189 case CHANNEL_MODE_OC_TOGGLE:
1190 case CHANNEL_MODE_OC_FORCED_ACTIVE:
1191 case CHANNEL_MODE_OC_FORCED_INACTIVE:
1192 HAL_TIM_OC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1193 break;
1194 case CHANNEL_MODE_IC:
1195 HAL_TIM_IC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
1196 break;
1197 }
1198 } else {
1199 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
1200 }
1201 return mp_const_none;
1202}
1203STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_channel_callback_obj, pyb_timer_channel_callback);
1204
1205STATIC const mp_map_elem_t pyb_timer_channel_locals_dict_table[] = {
1206 // instance methods
1207 { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_channel_callback_obj },
1208 { MP_OBJ_NEW_QSTR(MP_QSTR_pulse_width), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
Dave Hylands53d5fa62014-09-21 22:40:42 -07001209 { 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 -07001210 { MP_OBJ_NEW_QSTR(MP_QSTR_capture), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1211 { MP_OBJ_NEW_QSTR(MP_QSTR_compare), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
1212};
1213STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);
1214
Damien George0e58c582014-09-21 22:54:02 +01001215STATIC const mp_obj_type_t pyb_timer_channel_type = {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001216 { &mp_type_type },
1217 .name = MP_QSTR_TimerChannel,
1218 .print = pyb_timer_channel_print,
1219 .locals_dict = (mp_obj_t)&pyb_timer_channel_locals_dict,
1220};
1221
Damien George0e58c582014-09-21 22:54:02 +01001222STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) {
Dave Hylandsbecbc872014-08-20 13:21:11 -07001223 uint32_t irq_mask = TIMER_IRQ_MASK(channel);
1224
1225 if (__HAL_TIM_GET_FLAG(&tim->tim, irq_mask) != RESET) {
1226 if (__HAL_TIM_GET_ITSTATUS(&tim->tim, irq_mask) != RESET) {
1227 // clear the interrupt
1228 __HAL_TIM_CLEAR_IT(&tim->tim, irq_mask);
1229
1230 // execute callback if it's set
1231 if (callback != mp_const_none) {
1232 // When executing code within a handler we must lock the GC to prevent
1233 // any memory allocations. We must also catch any exceptions.
1234 gc_lock();
1235 nlr_buf_t nlr;
1236 if (nlr_push(&nlr) == 0) {
1237 mp_call_function_1(callback, tim);
1238 nlr_pop();
1239 } else {
1240 // Uncaught exception; disable the callback so it doesn't run again.
1241 tim->callback = mp_const_none;
1242 __HAL_TIM_DISABLE_IT(&tim->tim, irq_mask);
1243 if (channel == 0) {
Damien Georged03c6812014-10-05 21:51:54 +01001244 printf("uncaught exception in Timer(%u) interrupt handler\n", tim->tim_id);
Dave Hylandsbecbc872014-08-20 13:21:11 -07001245 } else {
Damien Georged03c6812014-10-05 21:51:54 +01001246 printf("uncaught exception in Timer(%u) channel %u interrupt handler\n", tim->tim_id, channel);
Dave Hylandsbecbc872014-08-20 13:21:11 -07001247 }
1248 mp_obj_print_exception((mp_obj_t)nlr.ret_val);
1249 }
1250 gc_unlock();
1251 }
1252 }
1253 }
1254}
1255
Damien George7fdfa932014-04-21 16:48:16 +01001256void timer_irq_handler(uint tim_id) {
1257 if (tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
1258 // get the timer object
1259 pyb_timer_obj_t *tim = pyb_timer_obj_all[tim_id - 1];
Damien Georgea12be912014-04-02 15:09:36 +01001260
Damien George7fdfa932014-04-21 16:48:16 +01001261 if (tim == NULL) {
Damien George0e58c582014-09-21 22:54:02 +01001262 // Timer object has not been set, so we can't do anything.
1263 // This can happen under normal circumstances for timers like
1264 // 1 & 10 which use the same IRQ.
Damien George7fdfa932014-04-21 16:48:16 +01001265 return;
1266 }
Damien Georgea12be912014-04-02 15:09:36 +01001267
Dave Hylandsbecbc872014-08-20 13:21:11 -07001268 // Check for timer (versus timer channel) interrupt.
1269 timer_handle_irq_channel(tim, 0, tim->callback);
1270 uint32_t handled = TIMER_IRQ_MASK(0);
Damien Georgea12be912014-04-02 15:09:36 +01001271
Dave Hylandsbecbc872014-08-20 13:21:11 -07001272 // Check to see if a timer channel interrupt was pending
1273 pyb_timer_channel_obj_t *chan = tim->channel;
1274 while (chan != NULL) {
1275 timer_handle_irq_channel(tim, chan->channel, chan->callback);
1276 handled |= TIMER_IRQ_MASK(chan->channel);
1277 chan = chan->next;
1278 }
1279
1280 // Finally, clear any remaining interrupt sources. Otherwise we'll
1281 // just get called continuously.
1282 uint32_t unhandled = __HAL_TIM_GET_ITSTATUS(&tim->tim, 0xff & ~handled);
1283 if (unhandled != 0) {
1284 __HAL_TIM_CLEAR_IT(&tim->tim, unhandled);
1285 printf("Unhandled interrupt SR=0x%02lx (now disabled)\n", unhandled);
Damien Georgea12be912014-04-02 15:09:36 +01001286 }
1287 }
1288}