timer.c 43.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
 * This file is part of the Micro Python project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013, 2014 Damien P. George
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

27
28
29
30
31
32
33
34
35
36
37
38
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include <stm32f4xx_hal.h>
#include "usbd_cdc_msc_hid.h"
#include "usbd_cdc_interface.h"

#include "nlr.h"
#include "misc.h"
#include "mpconfig.h"
#include "qstr.h"
39
#include "gc.h"
40
41
42
43
#include "obj.h"
#include "runtime.h"
#include "timer.h"
#include "servo.h"
44
#include "pin.h"
45

46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/// \moduleref pyb
/// \class Timer - periodically call a function
///
/// Timers can be used for a great variety of tasks.  At the moment, only
/// the simplest case is implemented: that of calling a function periodically.
///
/// Each timer consists of a counter that counts up at a certain rate.  The rate
/// at which it counts is the peripheral clock frequency (in Hz) divided by the
/// timer prescaler.  When the counter reaches the timer period it triggers an
/// event, and the counter resets back to zero.  By using the callback method,
/// the timer event can call a Python function.
///
/// Example usage to toggle an LED at a fixed frequency:
///
///     tim = pyb.Timer(4)              # create a timer object using timer 4
///     tim.init(freq=2)                # trigger at 2Hz
///     tim.callback(lambda t:pyb.LED(1).toggle())
///
/// Further examples:
///
///     tim = pyb.Timer(4, freq=100)    # freq in Hz
67
///     tim = pyb.Timer(4, prescaler=0, period=99)
68
69
///     tim.counter()                   # get counter (can also set)
///     tim.prescaler(2)                # set prescaler (can also get)
70
///     tim.period(199)                 # set period (can also get)
71
72
73
74
75
76
77
///     tim.callback(lambda t: ...)     # set callback for update interrupt (t=tim instance)
///     tim.callback(None)              # clear callback
///
/// *Note:* Timer 3 is reserved for internal use.  Timer 5 controls
/// the servo driver, and Timer 6 is used for timed ADC/DAC reading/writing.
/// It is recommended to use the other timers in your programs.

78
79
80
81
// The timers can be used by multiple drivers, and need a common point for
// the interrupts to be dispatched, so they are all collected here.
//
// TIM3:
82
//  - flash storage controller, to flush the cache
83
84
85
86
87
//  - USB CDC interface, interval, to check for new data
//  - LED 4, PWM to set the LED intensity
//
// TIM5:
//  - servo controller, PWM
88
89
90
91
//
// TIM6:
//  - ADC, DAC for read_timed and write_timed

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
typedef enum {
    CHANNEL_MODE_PWM_NORMAL,
    CHANNEL_MODE_PWM_INVERTED,
    CHANNEL_MODE_OC_TIMING,
    CHANNEL_MODE_OC_ACTIVE,
    CHANNEL_MODE_OC_INACTIVE,
    CHANNEL_MODE_OC_TOGGLE,
    CHANNEL_MODE_OC_FORCED_ACTIVE,
    CHANNEL_MODE_OC_FORCED_INACTIVE,
    CHANNEL_MODE_IC,
} pyb_channel_mode;

STATIC const struct {
    qstr        name;
    uint32_t    oc_mode;
107
} channel_mode_info[] = {
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
    { MP_QSTR_PWM,                TIM_OCMODE_PWM1 },
    { MP_QSTR_PWM_INVERTED,       TIM_OCMODE_PWM2 },
    { MP_QSTR_OC_TIMING,          TIM_OCMODE_TIMING },
    { MP_QSTR_OC_ACTIVE,          TIM_OCMODE_ACTIVE },
    { MP_QSTR_OC_INACTIVE,        TIM_OCMODE_INACTIVE },
    { MP_QSTR_OC_TOGGLE,          TIM_OCMODE_TOGGLE },
    { MP_QSTR_OC_FORCED_ACTIVE,   TIM_OCMODE_FORCED_ACTIVE },
    { MP_QSTR_OC_FORCED_INACTIVE, TIM_OCMODE_FORCED_INACTIVE },
    { MP_QSTR_IC,                 0 },
};

typedef struct _pyb_timer_channel_obj_t {
    mp_obj_base_t base;
    struct _pyb_timer_obj_t *timer;
    uint8_t channel;
    uint8_t mode;
    mp_obj_t callback;
    struct _pyb_timer_channel_obj_t *next;
} pyb_timer_channel_obj_t;

128
129
typedef struct _pyb_timer_obj_t {
    mp_obj_base_t base;
130
131
    uint8_t tim_id;
    uint8_t is_32bit;
132
133
134
    mp_obj_t callback;
    TIM_HandleTypeDef tim;
    IRQn_Type irqn;
135
136
    pyb_timer_channel_obj_t *channel;

137
} pyb_timer_obj_t;
138

139
140
141
142
143
144
// The following yields TIM_IT_UPDATE when channel is zero and
// TIM_IT_CC1..TIM_IT_CC4 when channel is 1..4
#define TIMER_IRQ_MASK(channel) (1 << (channel))
#define TIMER_CNT_MASK(self)    ((self)->is_32bit ? 0x3fffffff : 0xffff)
#define TIMER_CHANNEL(self)     ((((self)->channel) - 1) << 2)

145
146
TIM_HandleTypeDef TIM3_Handle;
TIM_HandleTypeDef TIM5_Handle;
147
TIM_HandleTypeDef TIM6_Handle;
148

149
// Used to divide down TIM3 and periodically call the flash storage IRQ
150
STATIC uint32_t tim3_counter = 0;
151

152
153
// Used to do callbacks to Python code on interrupt
STATIC pyb_timer_obj_t *pyb_timer_obj_all[14];
154
#define PYB_TIMER_OBJ_ALL_NUM MP_ARRAY_SIZE(pyb_timer_obj_all)
155

156
157
STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in);
STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback);
158
STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback);
159

160
161
162
163
164
165
166
void timer_init0(void) {
    tim3_counter = 0;
    for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
        pyb_timer_obj_all[i] = NULL;
    }
}

167
168
169
170
171
172
173
174
175
176
// unregister all interrupt sources
void timer_deinit(void) {
    for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
        pyb_timer_obj_t *tim = pyb_timer_obj_all[i];
        if (tim != NULL) {
            pyb_timer_deinit(tim);
        }
    }
}

177
178
179
180
181
182
// TIM3 is set-up for the USB CDC interface
void timer_tim3_init(void) {
    // set up the timer for USBD CDC
    __TIM3_CLK_ENABLE();

    TIM3_Handle.Instance = TIM3;
183
184
    TIM3_Handle.Init.Period = (USBD_CDC_POLLING_INTERVAL*1000) - 1; // TIM3 fires every USBD_CDC_POLLING_INTERVAL ms
    TIM3_Handle.Init.Prescaler = 84-1; // for System clock at 168MHz, TIM3 runs at 1MHz
185
    TIM3_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    TIM3_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
    HAL_TIM_Base_Init(&TIM3_Handle);

    HAL_NVIC_SetPriority(TIM3_IRQn, 6, 0);
    HAL_NVIC_EnableIRQ(TIM3_IRQn);

    if (HAL_TIM_Base_Start(&TIM3_Handle) != HAL_OK) {
        /* Starting Error */
    }
}

/* unused
void timer_tim3_deinit(void) {
    // reset TIM3 timer
    __TIM3_FORCE_RESET();
    __TIM3_RELEASE_RESET();
}
*/

// TIM5 is set-up for the servo controller
206
// This function inits but does not start the timer
207
208
209
210
211
212
213
214
215
216
void timer_tim5_init(void) {
    // TIM5 clock enable
    __TIM5_CLK_ENABLE();

    // set up and enable interrupt
    HAL_NVIC_SetPriority(TIM5_IRQn, 6, 0);
    HAL_NVIC_EnableIRQ(TIM5_IRQn);

    // PWM clock configuration
    TIM5_Handle.Instance = TIM5;
217
    TIM5_Handle.Init.Period = 2000 - 1; // timer cycles at 50Hz
218
    TIM5_Handle.Init.Prescaler = ((SystemCoreClock / 2) / 100000) - 1; // timer runs at 100kHz
219
    TIM5_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
220
    TIM5_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
221

222
223
224
    HAL_TIM_PWM_Init(&TIM5_Handle);
}

225
226
227
228
229
230
231
232
233
// Init TIM6 with a counter-overflow at the given frequency (given in Hz)
// TIM6 is used by the DAC and ADC for auto sampling at a given frequency
// This function inits but does not start the timer
void timer_tim6_init(uint freq) {
    // TIM6 clock enable
    __TIM6_CLK_ENABLE();

    // Timer runs at SystemCoreClock / 2
    // Compute the prescaler value so TIM6 triggers at freq-Hz
234
    uint32_t period = MAX(1, (SystemCoreClock / 2) / freq);
235
236
237
238
239
240
241
242
243
244
    uint32_t prescaler = 1;
    while (period > 0xffff) {
        period >>= 1;
        prescaler <<= 1;
    }

    // Time base clock configuration
    TIM6_Handle.Instance = TIM6;
    TIM6_Handle.Init.Period = period - 1;
    TIM6_Handle.Init.Prescaler = prescaler - 1;
245
    TIM6_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; // unused for TIM6
246
247
248
249
    TIM6_Handle.Init.CounterMode = TIM_COUNTERMODE_UP; // unused for TIM6
    HAL_TIM_Base_Init(&TIM6_Handle);
}

250
251
252
253
// Interrupt dispatch
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
    if (htim == &TIM3_Handle) {
        USBD_CDC_HAL_TIM_PeriodElapsedCallback();
254
255
256
257
258
259
260

        // Periodically raise a flash IRQ for the flash storage controller
        if (tim3_counter++ >= 500 / USBD_CDC_POLLING_INTERVAL) {
            tim3_counter = 0;
            NVIC->STIR = FLASH_IRQn;
        }

261
262
263
264
265
    } else if (htim == &TIM5_Handle) {
        servo_timer_irq_callback();
    }
}

266
267
268
/******************************************************************************/
/* Micro Python bindings                                                      */

269
270
STATIC const mp_obj_type_t pyb_timer_channel_type;

271
272
273
274
275
276
STATIC void pyb_timer_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
    pyb_timer_obj_t *self = self_in;

    if (self->tim.State == HAL_TIM_STATE_RESET) {
        print(env, "Timer(%u)", self->tim_id);
    } else {
277
        print(env, "Timer(%u, prescaler=%u, period=%u, mode=%s, div=%u)",
278
279
280
            self->tim_id,
            self->tim.Init.Prescaler,
            self->tim.Init.Period,
281
282
283
284
            self->tim.Init.CounterMode == TIM_COUNTERMODE_UP     ? "UP" :
            self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN   ? "DOWN" : "CENTER",
            self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV4 ? 4 :
            self->tim.Init.ClockDivision == TIM_CLOCKDIVISION_DIV2 ? 2 : 1);
285
286
    }
}
287

288
289
290
291
292
/// \method init(*, freq, prescaler, period)
/// Initialise the timer.  Initialisation must be either by frequency (in Hz)
/// or by prescaler and period:
///
///     tim.init(freq=100)                  # set the timer to trigger at 100Hz
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
///     tim.init(prescaler=83, period=999)  # set the prescaler and period directly
///
/// Keyword arguments:
///
///   - `freq` - specifies the periodic frequency of the timer. You migh also
///              view this as the frequency with which the timer goes through
///              one complete cycle.
///
///   - `prescaler` [0-0xffff] - specifies the value to be loaded into the
///                 timer's Prescaler Register (PSC). The timer clock source is divided by
///     (`prescaler + 1`) to arrive at the timer clock. Timers 2-7 and 12-14
///     have a clock source of 84 MHz (pyb.freq()[2] * 2), and Timers 1, and 8-11
///     have a clock source of 168 MHz (pyb.freq()[3] * 2).
///
///   - `period` [0-0xffff] for timers 1, 3, 4, and 6-15. [0-0x3fffffff] for timers 2 & 5.
///              Specifies the value to be loaded into the timer's AutoReload
///     Register (ARR). This determines the period of the timer (i.e. when the
///     counter cycles). The timer counter will roll-over after `period + 1`
///     timer clock cycles.
///
///   - `mode` can be one of:
///     - `Timer.UP` - configures the timer to count from 0 to ARR (default)
///     - `Timer.DOWN` - configures the timer to count from ARR down to 0.
///     - `Timer.CENTER` - confgures the timer to count from 0 to ARR and
///       then back down to 0.
///
///   - `div` can be one of 1, 2, or 4. Divides the timer clock to determine
///       the sampling clock used by the digital filters.
///
///   - `callback` - as per Timer.callback()
///
///  You must either specify freq or both of period and prescaler.
    STATIC const mp_arg_t pyb_timer_init_args[] = {
    { MP_QSTR_freq,         MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
    { MP_QSTR_prescaler,    MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
    { MP_QSTR_period,       MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
    { MP_QSTR_mode,         MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TIM_COUNTERMODE_UP} },
    { MP_QSTR_div,          MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} },
    { MP_QSTR_callback,     MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
332
};
333
#define PYB_TIMER_INIT_NUM_ARGS MP_ARRAY_SIZE(pyb_timer_init_args)
334

335
STATIC 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) {
336
    // parse args
337
338
    mp_arg_val_t vals[PYB_TIMER_INIT_NUM_ARGS];
    mp_arg_parse_all(n_args, args, kw_args, PYB_TIMER_INIT_NUM_ARGS, pyb_timer_init_args, vals);
339

340
341
    // set the TIM configuration values
    TIM_Base_InitTypeDef *init = &self->tim.Init;
342

343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    if (vals[0].u_int != 0xffffffff) {
        // set prescaler and period from frequency

        if (vals[0].u_int == 0) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't have 0 frequency"));
        }

        // work out TIM's clock source
        uint tim_clock;
        if (self->tim_id == 1 || (8 <= self->tim_id && self->tim_id <= 11)) {
            // TIM{1,8,9,10,11} are on APB2
            tim_clock = HAL_RCC_GetPCLK2Freq();
        } else {
            // TIM{2,3,4,5,6,7,12,13,14} are on APB1
            tim_clock = HAL_RCC_GetPCLK1Freq();
        }

360
361
362
363
364
        // Compute the prescaler value so TIM triggers at freq-Hz
        // On STM32F405/407/415/417 there are 2 cases for how the clock freq is set.
        // If the APB prescaler is 1, then the timer clock is equal to its respective
        // APB clock.  Otherwise (APB prescaler > 1) the timer clock is twice its
        // respective APB clock.  See DM00031020 Rev 4, page 115.
365
366
        uint32_t period = MAX(1, 2 * tim_clock / vals[0].u_int);
        uint32_t prescaler = 1;
367
        while (period > TIMER_CNT_MASK(self)) {
368
369
370
371
372
373
374
375
376
377
378
379
380
381
            period >>= 1;
            prescaler <<= 1;
        }
        init->Prescaler = prescaler - 1;
        init->Period = period - 1;
    } else if (vals[1].u_int != 0xffffffff && vals[2].u_int != 0xffffffff) {
        // set prescaler and period directly
        init->Prescaler = vals[1].u_int;
        init->Period = vals[2].u_int;
    } else {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "must specify either freq, or prescaler and period"));
    }

    init->CounterMode = vals[3].u_int;
382
383
384
385

    init->ClockDivision = vals[4].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
                          vals[4].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
                                               TIM_CLOCKDIVISION_DIV1;
386
387
    init->RepetitionCounter = 0;

388
389
390
391
    if (!IS_TIM_COUNTER_MODE(init->CounterMode)) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid counter_mode (%d)", init->CounterMode));
    }

392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
    // init the TIM peripheral
    switch (self->tim_id) {
        case 1: __TIM1_CLK_ENABLE(); break;
        case 2: __TIM2_CLK_ENABLE(); break;
        case 3: __TIM3_CLK_ENABLE(); break;
        case 4: __TIM4_CLK_ENABLE(); break;
        case 5: __TIM5_CLK_ENABLE(); break;
        case 6: __TIM6_CLK_ENABLE(); break;
        case 7: __TIM7_CLK_ENABLE(); break;
        case 8: __TIM8_CLK_ENABLE(); break;
        case 9: __TIM9_CLK_ENABLE(); break;
        case 10: __TIM10_CLK_ENABLE(); break;
        case 11: __TIM11_CLK_ENABLE(); break;
        case 12: __TIM12_CLK_ENABLE(); break;
        case 13: __TIM13_CLK_ENABLE(); break;
        case 14: __TIM14_CLK_ENABLE(); break;
    }
    // set the priority (if not a special timer)
    if (self->tim_id != 3 && self->tim_id != 5) {
        HAL_NVIC_SetPriority(self->irqn, 0xe, 0xe); // next-to lowest priority
    }
413

414
415
416
417
418
419
420
    HAL_TIM_Base_Init(&self->tim);
    if (vals[5].u_obj == mp_const_none) {
        HAL_TIM_Base_Start(&self->tim);
    } else {
        pyb_timer_callback(self, vals[5].u_obj);
    }

421
422
423
    return mp_const_none;
}

424
425
426
427
/// \classmethod \constructor(id, ...)
/// Construct a new timer object of the given id.  If additional
/// arguments are given, then the timer is initialised by `init(...)`.
/// `id` can be 1 to 14, excluding 3.
428
STATIC 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) {
429
430
431
432
433
    // check arguments
    mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);

    // create new Timer object
    pyb_timer_obj_t *tim = m_new_obj(pyb_timer_obj_t);
434
435
    memset(tim, 0, sizeof(*tim));

436
437
    tim->base.type = &pyb_timer_type;
    tim->callback = mp_const_none;
438
    tim->channel = NULL;
439
440
441

    // get TIM number
    tim->tim_id = mp_obj_get_int(args[0]);
442
    tim->is_32bit = false;
443
444
445

    switch (tim->tim_id) {
        case 1: tim->tim.Instance = TIM1; tim->irqn = TIM1_UP_TIM10_IRQn; break;
446
        case 2: tim->tim.Instance = TIM2; tim->irqn = TIM2_IRQn; tim->is_32bit = true; break;
447
448
        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
        case 4: tim->tim.Instance = TIM4; tim->irqn = TIM4_IRQn; break;
449
        case 5: tim->tim.Instance = TIM5; tim->irqn = TIM5_IRQn; tim->is_32bit = true; break;
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
        case 6: tim->tim.Instance = TIM6; tim->irqn = TIM6_DAC_IRQn; break;
        case 7: tim->tim.Instance = TIM7; tim->irqn = TIM7_IRQn; break;
        case 8: tim->tim.Instance = TIM8; tim->irqn = TIM8_UP_TIM13_IRQn; break;
        case 9: tim->tim.Instance = TIM9; tim->irqn = TIM1_BRK_TIM9_IRQn; break;
        case 10: tim->tim.Instance = TIM10; tim->irqn = TIM1_UP_TIM10_IRQn; break;
        case 11: tim->tim.Instance = TIM11; tim->irqn = TIM1_TRG_COM_TIM11_IRQn; break;
        case 12: tim->tim.Instance = TIM12; tim->irqn = TIM8_BRK_TIM12_IRQn; break;
        case 13: tim->tim.Instance = TIM13; tim->irqn = TIM8_UP_TIM13_IRQn; break;
        case 14: tim->tim.Instance = TIM14; tim->irqn = TIM8_TRG_COM_TIM14_IRQn; break;
        default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d does not exist", tim->tim_id));
    }

    if (n_args > 1 || n_kw > 0) {
        // start the peripheral
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
        pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args);
    }

    // set the global variable for interrupt callbacks
    if (tim->tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
        pyb_timer_obj_all[tim->tim_id - 1] = tim;
    }

    return (mp_obj_t)tim;
475
476
}

477
STATIC mp_obj_t pyb_timer_init(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
478
    return pyb_timer_init_helper(args[0], n_args - 1, args + 1, kw_args);
479
}
480
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
481

482
483
484
/// \method deinit()
/// Deinitialises the timer.
///
485
/// Disables the callback (and the associated irq).
486
/// Disables any channel callbacks (and the associated irq).
487
/// Stops the timer, and disables the timer peripheral.
488
STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
489
490
    pyb_timer_obj_t *self = self_in;

491
    // Disable the base interrupt
492
493
    pyb_timer_callback(self_in, mp_const_none);

494
495
496
497
498
499
500
501
502
503
504
    pyb_timer_channel_obj_t *chan = self->channel;
    self->channel = NULL;

    // Disable the channel interrupts
    while (chan != NULL) {
        pyb_timer_channel_callback(chan, mp_const_none);
        pyb_timer_channel_obj_t *prev_chan = chan;
        chan = chan->next;
        prev_chan->next = NULL;
    }

505
    HAL_TIM_Base_DeInit(&self->tim);
506
507
508
509
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);

510
511
/// \method channel(channel, mode, ...)
///
512
513
/// If only a channel number is passed, then a previously initialized channel
/// object is returned (or `None` if there is no previous channel).
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
///
/// Othwerwise, a TimerChannel object is initialized and returned.
///
/// Each channel can be configured to perform pwm, output compare, or
/// input capture. All channels share the same underlying timer, which means
/// that they share the same timer clock.
///
/// Keyword arguments:
///
///   - `mode` can be one of:
///     - `Timer.PWM` - configure the timer in PWM mode (active high).
///     - `Timer.PWM_INVERTED` - configure the timer in PWM mode (active low).
///     - `Timer.OC_TIMING` - indicates that no pin is driven.
///     - `Timer.OC_ACTIVE` - the pin will be made active when a compare
///        match occurs (active is determined by polarity)
///     - `Timer.OC_INACTIVE` - the pin will be made inactive when a compare
///        match occurs.
///     - `Timer.OC_TOGGLE` - the pin will be toggled when an compare match occurs.
///     - `Timer.OC_FORCED_ACTIVE` - the pin is forced active (compare match is ignored).
///     - `Timer.OC_FORCED_INACTIVE` - the pin is forced inactive (compare match is ignored).
///     - `Timer.IC` - configure the timer in Input Capture mode.
///
///   - `callback` - as per TimerChannel.callback()
///
///   - `pin` None (the default) or a Pin object. If specified (and not None)
///           this will cause the alternate function of the the indicated pin
///      to be configured for this timer channel. An error will be raised if
///      the pin doesn't support any alternate functions for this timer channel.
///
/// Keyword arguments for Timer.PWM modes:
///
545
546
///   - `pulse_width` - determines the initial pulse width value to use.
///   - `pulse_width_ratio` - determines the initial pulse width ratio to use.
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
///
/// Keyword arguments for Timer.OC modes:
///
///   - `compare` - determines the initial value of the compare register.
///
///   - `polarity` can be one of:
///     - `Timer.HIGH` - output is active high
///     - `Timer.LOW` - output is acive low
///
/// Optional keyword arguments for Timer.IC modes:
///
///   - `polarity` can be one of:
///     - `Timer.RISING` - captures on rising edge.
///     - `Timer.FALLING` - captures on falling edge.
///     - `Timer.BOTH` - captures on both edges.
///
/// PWM Example:
///
///     timer = pyb.Timer(2, freq=1000)
///     ch2 = timer.channel(2, pyb.Timer.PWM, pin=pyb.Pin.board.X2, pulse_width=210000)
///     ch3 = timer.channel(3, pyb.Timer.PWM, pin=pyb.Pin.board.X3, pulse_width=420000)
STATIC const mp_arg_t pyb_timer_channel_args[] = {
569
570
571
572
573
574
    { MP_QSTR_callback,          MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
    { MP_QSTR_pin,               MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
    { MP_QSTR_pulse_width,       MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
    { MP_QSTR_pulse_width_ratio, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
    { MP_QSTR_compare,           MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
    { MP_QSTR_polarity,          MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
};
#define PYB_TIMER_CHANNEL_NUM_ARGS MP_ARRAY_SIZE(pyb_timer_channel_args)

STATIC mp_obj_t pyb_timer_channel(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    pyb_timer_obj_t *self = args[0];
    mp_int_t channel = mp_obj_get_int(args[1]);

    if (channel < 1 || channel > 4) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid channel (%d)", channel));
    }

    pyb_timer_channel_obj_t *chan = self->channel;
    pyb_timer_channel_obj_t *prev_chan = NULL;

    while (chan != NULL) {
        if (chan->channel == channel) {
            break;
        }
        prev_chan = chan;
        chan = chan->next;
    }
596
597
598
599

    // If only the channel number is given return the previously allocated
    // channel (or None if no previous channel).
    if (n_args == 2) {
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
        if (chan) {
            return chan;
        }
        return mp_const_none;
    }

    // If there was already a channel, then remove it from the list. Note that
    // the order we do things here is important so as to appear atomic to
    // the IRQ handler.
    if (chan) {
        // Turn off any IRQ associated with the channel.
        pyb_timer_channel_callback(chan, mp_const_none);

        // Unlink the channel from the list.
        if (prev_chan) {
            prev_chan->next = chan->next;
        }
        self->channel = chan->next;
        chan->next = NULL;
    }

    // Allocate and initialize a new channel
    mp_arg_val_t vals[PYB_TIMER_CHANNEL_NUM_ARGS];
    mp_arg_parse_all(n_args - 3, args + 3, kw_args, PYB_TIMER_CHANNEL_NUM_ARGS, pyb_timer_channel_args, vals);

    chan = m_new_obj(pyb_timer_channel_obj_t);
    memset(chan, 0, sizeof(*chan));
    chan->base.type = &pyb_timer_channel_type;
    chan->timer = self;
    chan->channel = channel;
    chan->mode = mp_obj_get_int(args[2]);
    chan->callback = vals[0].u_obj;

    mp_obj_t pin_obj = vals[1].u_obj;
    if (pin_obj != mp_const_none) {
        if (!MP_OBJ_IS_TYPE(pin_obj, &pin_type)) {
            nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "pin argument needs to be be a Pin type"));
        }
        const pin_obj_t *pin = pin_obj;
        const pin_af_obj_t *af = pin_find_af(pin, AF_FN_TIM, self->tim_id);
        if (af == NULL) {
            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));
        }
        // pin.init(mode=AF_PP, af=idx)
        const mp_obj_t args[6] = {
            (mp_obj_t)&pin_init_obj,
            pin_obj,
            MP_OBJ_NEW_QSTR(MP_QSTR_mode),  MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP),
            MP_OBJ_NEW_QSTR(MP_QSTR_af),    MP_OBJ_NEW_SMALL_INT(af->idx)
        };
        mp_call_method_n_kw(0, 2, args);
    }

    // Link the channel to the timer before we turn the channel on.
    // Note that this needs to appear atomic to the IRQ handler (the write
    // to self->channel is atomic, so we're good, but I thought I'd mention
    // in case this was ever changed in the future).
    chan->next = self->channel;
    self->channel = chan;

    switch (chan->mode) {

        case CHANNEL_MODE_PWM_NORMAL:
        case CHANNEL_MODE_PWM_INVERTED: {
            TIM_OC_InitTypeDef oc_config;
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
            oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
            if (vals[2].u_int != 0xffffffff) {
                // absolute pulse width value given
                oc_config.Pulse = vals[2].u_int;
            } else if (vals[3].u_obj != mp_const_none) {
                // pulse width ratio given
                uint32_t period = (__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self)) + 1;
                uint32_t cmp = mp_obj_get_float(vals[3].u_obj) * period;
                if (cmp < 0) {
                    cmp = 0;
                } else if (cmp > period) {
                    cmp = period;
                }
                oc_config.Pulse = cmp;
            } else {
                // nothing given, default to pulse width of 0
                oc_config.Pulse = 0;
            }
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
            oc_config.OCPolarity   = TIM_OCPOLARITY_HIGH;
            oc_config.OCNPolarity  = TIM_OCNPOLARITY_HIGH;
            oc_config.OCFastMode   = TIM_OCFAST_DISABLE;
            oc_config.OCIdleState  = TIM_OCIDLESTATE_SET;
            oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;

            HAL_TIM_PWM_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
            if (chan->callback == mp_const_none) {
                HAL_TIM_PWM_Start(&self->tim, TIMER_CHANNEL(chan));
            } else {
                HAL_TIM_PWM_Start_IT(&self->tim, TIMER_CHANNEL(chan));
            }
            break;
        }

        case CHANNEL_MODE_OC_TIMING:
        case CHANNEL_MODE_OC_ACTIVE:
        case CHANNEL_MODE_OC_INACTIVE:
        case CHANNEL_MODE_OC_TOGGLE:
        case CHANNEL_MODE_OC_FORCED_ACTIVE:
        case CHANNEL_MODE_OC_FORCED_INACTIVE: {
            TIM_OC_InitTypeDef oc_config;
705
706
707
            oc_config.OCMode       = channel_mode_info[chan->mode].oc_mode;
            oc_config.Pulse        = vals[4].u_int;
            oc_config.OCPolarity   = vals[5].u_int;
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
            if (oc_config.OCPolarity == 0xffffffff) {
                oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
            }
            oc_config.OCNPolarity  = TIM_OCNPOLARITY_HIGH;
            oc_config.OCFastMode   = TIM_OCFAST_DISABLE;
            oc_config.OCIdleState  = TIM_OCIDLESTATE_SET;
            oc_config.OCNIdleState = TIM_OCNIDLESTATE_SET;

            if (!IS_TIM_OC_POLARITY(oc_config.OCPolarity)) {
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", oc_config.OCPolarity));
            }
            HAL_TIM_OC_ConfigChannel(&self->tim, &oc_config, TIMER_CHANNEL(chan));
            if (chan->callback == mp_const_none) {
                HAL_TIM_OC_Start(&self->tim, TIMER_CHANNEL(chan));
            } else {
                HAL_TIM_OC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
            }
            break;
        }

        case CHANNEL_MODE_IC: {
            TIM_IC_InitTypeDef ic_config;

731
            ic_config.ICPolarity  = vals[5].u_int;
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
            if (ic_config.ICPolarity == 0xffffffff) {
                ic_config.ICPolarity = TIM_ICPOLARITY_RISING;
            }
            ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;
            ic_config.ICPrescaler = TIM_ICPSC_DIV1;
            ic_config.ICFilter    = 0;

            if (!IS_TIM_IC_POLARITY(ic_config.ICPolarity)) {
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid polarity (%d)", ic_config.ICPolarity));
            }
            HAL_TIM_IC_ConfigChannel(&self->tim, &ic_config, TIMER_CHANNEL(chan));
            if (chan->callback == mp_const_none) {
                HAL_TIM_IC_Start(&self->tim, TIMER_CHANNEL(chan));
            } else {
                HAL_TIM_IC_Start_IT(&self->tim, TIMER_CHANNEL(chan));
            }
            break;
        }

        default:
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Invalid mode (%d)", chan->mode));
    }

    return chan;
}
757
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
758

759
760
/// \method counter([value])
/// Get or set the timer counter.
761
STATIC mp_obj_t pyb_timer_counter(mp_uint_t n_args, const mp_obj_t *args) {
762
763
764
765
766
767
768
769
770
771
772
773
    pyb_timer_obj_t *self = args[0];
    if (n_args == 1) {
        // get
        return mp_obj_new_int(self->tim.Instance->CNT);
    } else {
        // set
        __HAL_TIM_SetCounter(&self->tim, mp_obj_get_int(args[1]));
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_counter_obj, 1, 2, pyb_timer_counter);

774
775
/// \method prescaler([value])
/// Get or set the prescaler for the timer.
776
STATIC mp_obj_t pyb_timer_prescaler(mp_uint_t n_args, const mp_obj_t *args) {
777
778
779
780
781
782
783
784
785
786
787
788
    pyb_timer_obj_t *self = args[0];
    if (n_args == 1) {
        // get
        return mp_obj_new_int(self->tim.Instance->PSC & 0xffff);
    } else {
        // set
        self->tim.Init.Prescaler = self->tim.Instance->PSC = mp_obj_get_int(args[1]) & 0xffff;
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);

789
790
/// \method period([value])
/// Get or set the period of the timer.
791
STATIC mp_obj_t pyb_timer_period(mp_uint_t n_args, const mp_obj_t *args) {
792
793
794
    pyb_timer_obj_t *self = args[0];
    if (n_args == 1) {
        // get
795
        return mp_obj_new_int(__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
796
797
    } else {
        // set
798
        __HAL_TIM_SetAutoreload(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
799
800
801
802
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
803

804
805
806
807
/// \method callback(fun)
/// Set the function to be called when the timer triggers.
/// `fun` is passed 1 argument, the timer object.
/// If `fun` is `None` then the callback will be disabled.
808
809
810
811
812
813
814
815
816
817
818
819
820
STATIC mp_obj_t pyb_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
    pyb_timer_obj_t *self = self_in;
    if (callback == mp_const_none) {
        // stop interrupt (but not timer)
        __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
        self->callback = mp_const_none;
    } else if (mp_obj_is_callable(callback)) {
        self->callback = callback;
        HAL_NVIC_EnableIRQ(self->irqn);
        // start timer, so that it interrupts on overflow
        HAL_TIM_Base_Start_IT(&self->tim);
    } else {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
821
    }
822
    return mp_const_none;
823
}
824
825
826
827
828
829
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);

STATIC const mp_map_elem_t pyb_timer_locals_dict_table[] = {
    // instance methods
    { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)&pyb_timer_init_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)&pyb_timer_deinit_obj },
830
    { MP_OBJ_NEW_QSTR(MP_QSTR_channel), (mp_obj_t)&pyb_timer_channel_obj },
831
832
833
834
    { MP_OBJ_NEW_QSTR(MP_QSTR_counter), (mp_obj_t)&pyb_timer_counter_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_prescaler), (mp_obj_t)&pyb_timer_prescaler_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_period), (mp_obj_t)&pyb_timer_period_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_callback_obj },
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
    { MP_OBJ_NEW_QSTR(MP_QSTR_UP),                  MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_UP) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_DOWN),                MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_DOWN) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_CENTER),              MP_OBJ_NEW_SMALL_INT(TIM_COUNTERMODE_CENTERALIGNED1) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_PWM),                 MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_NORMAL) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_PWM_INVERTED),        MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_PWM_INVERTED) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TIMING),           MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TIMING) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_OC_ACTIVE),           MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_ACTIVE) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_OC_INACTIVE),         MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_INACTIVE) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_OC_TOGGLE),           MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_TOGGLE) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_ACTIVE),    MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_ACTIVE) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_OC_FORCED_INACTIVE),  MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_OC_FORCED_INACTIVE) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_IC),                  MP_OBJ_NEW_SMALL_INT(CHANNEL_MODE_IC) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_HIGH),                MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_HIGH) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_LOW),                 MP_OBJ_NEW_SMALL_INT(TIM_OCPOLARITY_LOW) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_RISING),              MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_RISING) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_FALLING),             MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_FALLING) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_BOTH),                MP_OBJ_NEW_SMALL_INT(TIM_ICPOLARITY_BOTHEDGE) },
852
853
854
855
856
857
858
859
860
861
862
};
STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table);

const mp_obj_type_t pyb_timer_type = {
    { &mp_type_type },
    .name = MP_QSTR_Timer,
    .print = pyb_timer_print,
    .make_new = pyb_timer_make_new,
    .locals_dict = (mp_obj_t)&pyb_timer_locals_dict,
};

863
864
865
866
867
868
869
870
871
872
873
874
/// \moduleref pyb
/// \class TimerChannel - setup a channel for a timer.
///
/// Timer channels are used to generate/capture a signal using a timer.
///
/// TimerChannel objects are created using the Timer.channel() method.
STATIC void pyb_timer_channel_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
    pyb_timer_channel_obj_t *self = self_in;

    print(env, "TimerChannel(timer=%u, channel=%u, mode=%s)",
          self->timer->tim_id,
          self->channel,
875
          qstr_str(channel_mode_info[self->mode].name));
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
}

/// \method capture([value])
/// Get or set the capture value associated with a channel.
/// capture, compare, and pulse_width are all aliases for the same function.
/// capture is the logical name to use when the channel is in input capture mode.

/// \method compare([value])
/// Get or set the compare value associated with a channel.
/// capture, compare, and pulse_width are all aliases for the same function.
/// compare is the logical name to use when the channel is in output compare mode.

/// \method pulse_width([value])
/// Get or set the pulse width value associated with a channel.
/// capture, compare, and pulse_width are all aliases for the same function.
/// pulse_width is the logical name to use when the channel is in PWM mode.
892
STATIC mp_obj_t pyb_timer_channel_capture_compare(mp_uint_t n_args, const mp_obj_t *args) {
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
    pyb_timer_channel_obj_t *self = args[0];
    if (self->channel == 0) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d no channel specified", self->timer->tim_id));
    }
    if (n_args == 1) {
        // get
        return mp_obj_new_int(__HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer));
    } else {
        // set
        __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self->timer));
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_capture_compare_obj, 1, 2, pyb_timer_channel_capture_compare);

908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
/// \method pulse_width_ratio([value])
/// Get or set the pulse width ratio associated with a channel.  The value is
/// a floating-point number between 0.0 and 1.0, and is relative to the period
/// of the timer associated with this channel.  For example, a ratio of 0.5
/// would be a 50% duty cycle.
STATIC mp_obj_t pyb_timer_channel_pulse_width_ratio(mp_uint_t n_args, const mp_obj_t *args) {
    pyb_timer_channel_obj_t *self = args[0];
    if (self->channel == 0) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer %d no channel specified", self->timer->tim_id));
    }
    uint32_t period = (__HAL_TIM_GetAutoreload(&self->timer->tim) & TIMER_CNT_MASK(self->timer)) + 1;
    if (n_args == 1) {
        // get
        uint32_t cmp = __HAL_TIM_GetCompare(&self->timer->tim, TIMER_CHANNEL(self)) & TIMER_CNT_MASK(self->timer);
        return mp_obj_new_float((float)cmp / (float)period);
    } else {
        // set
        uint32_t cmp = mp_obj_get_float(args[1]) * period;
        if (cmp < 0) {
            cmp = 0;
        } else if (cmp > period) {
            cmp = period;
        }
        __HAL_TIM_SetCompare(&self->timer->tim, TIMER_CHANNEL(self), cmp & TIMER_CNT_MASK(self->timer));
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_pulse_width_ratio_obj, 1, 2, pyb_timer_channel_pulse_width_ratio);

937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
/// \method callback(fun)
/// Set the function to be called when the timer channel triggers.
/// `fun` is passed 1 argument, the timer object.
/// If `fun` is `None` then the callback will be disabled.
STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback) {
    pyb_timer_channel_obj_t *self = self_in;
    if (callback == mp_const_none) {
        // stop interrupt (but not timer)
        __HAL_TIM_DISABLE_IT(&self->timer->tim, TIMER_IRQ_MASK(self->channel));
        self->callback = mp_const_none;
    } else if (mp_obj_is_callable(callback)) {
        self->callback = callback;
        HAL_NVIC_EnableIRQ(self->timer->irqn);
        // start timer, so that it interrupts on overflow
        switch (self->mode) {
            case CHANNEL_MODE_PWM_NORMAL:
            case CHANNEL_MODE_PWM_INVERTED:
                HAL_TIM_PWM_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
                break;
            case CHANNEL_MODE_OC_TIMING:
            case CHANNEL_MODE_OC_ACTIVE:
            case CHANNEL_MODE_OC_INACTIVE:
            case CHANNEL_MODE_OC_TOGGLE:
            case CHANNEL_MODE_OC_FORCED_ACTIVE:
            case CHANNEL_MODE_OC_FORCED_INACTIVE:
                HAL_TIM_OC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
                break;
            case CHANNEL_MODE_IC:
                HAL_TIM_IC_Start_IT(&self->timer->tim, TIMER_CHANNEL(self));
                break;
        }
    } else {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
    }
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_channel_callback_obj, pyb_timer_channel_callback);

STATIC const mp_map_elem_t pyb_timer_channel_locals_dict_table[] = {
    // instance methods
    { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&pyb_timer_channel_callback_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_pulse_width), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
979
    { MP_OBJ_NEW_QSTR(MP_QSTR_pulse_width_ratio), (mp_obj_t)&pyb_timer_channel_pulse_width_ratio_obj },
980
981
982
983
984
    { MP_OBJ_NEW_QSTR(MP_QSTR_capture), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_compare), (mp_obj_t)&pyb_timer_channel_capture_compare_obj },
};
STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table);

985
STATIC const mp_obj_type_t pyb_timer_channel_type = {
986
987
988
989
990
991
    { &mp_type_type },
    .name = MP_QSTR_TimerChannel,
    .print = pyb_timer_channel_print,
    .locals_dict = (mp_obj_t)&pyb_timer_channel_locals_dict,
};

992
STATIC void timer_handle_irq_channel(pyb_timer_obj_t *tim, uint8_t channel, mp_obj_t callback) {
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
    uint32_t irq_mask = TIMER_IRQ_MASK(channel);

    if (__HAL_TIM_GET_FLAG(&tim->tim, irq_mask) != RESET) {
        if (__HAL_TIM_GET_ITSTATUS(&tim->tim, irq_mask) != RESET) {
            // clear the interrupt
            __HAL_TIM_CLEAR_IT(&tim->tim, irq_mask);

            // execute callback if it's set
            if (callback != mp_const_none) {
                // When executing code within a handler we must lock the GC to prevent
                // any memory allocations.  We must also catch any exceptions.
                gc_lock();
                nlr_buf_t nlr;
                if (nlr_push(&nlr) == 0) {
                    mp_call_function_1(callback, tim);
                    nlr_pop();
                } else {
                    // Uncaught exception; disable the callback so it doesn't run again.
                    tim->callback = mp_const_none;
                    __HAL_TIM_DISABLE_IT(&tim->tim, irq_mask);
                    if (channel == 0) {
                        printf("Uncaught exception in Timer(" UINT_FMT
                               ") interrupt handler\n", tim->tim_id);
                    } else {
                        printf("Uncaught exception in Timer(" UINT_FMT ") channel "
                               UINT_FMT " interrupt handler\n", tim->tim_id, channel);
                    }
                    mp_obj_print_exception((mp_obj_t)nlr.ret_val);
                }
                gc_unlock();
            }
        }
    }
}

1028
1029
1030
1031
1032
1033
void timer_irq_handler(uint tim_id) {
    if (tim_id - 1 < PYB_TIMER_OBJ_ALL_NUM) {
        // get the timer object
        pyb_timer_obj_t *tim = pyb_timer_obj_all[tim_id - 1];

        if (tim == NULL) {
1034
1035
1036
            // Timer object has not been set, so we can't do anything.
            // This can happen under normal circumstances for timers like
            // 1 & 10 which use the same IRQ.
1037
1038
            return;
        }
1039

1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
        // Check for timer (versus timer channel) interrupt.
        timer_handle_irq_channel(tim, 0, tim->callback);
        uint32_t handled = TIMER_IRQ_MASK(0);

        // Check to see if a timer channel interrupt was pending
        pyb_timer_channel_obj_t *chan = tim->channel;
        while (chan != NULL) {
            timer_handle_irq_channel(tim, chan->channel, chan->callback);
            handled |= TIMER_IRQ_MASK(chan->channel);
            chan = chan->next;
        }

        // Finally, clear any remaining interrupt sources. Otherwise we'll
        // just get called continuously.
        uint32_t unhandled = __HAL_TIM_GET_ITSTATUS(&tim->tim, 0xff & ~handled);
        if (unhandled != 0) {
            __HAL_TIM_CLEAR_IT(&tim->tim, unhandled);
            printf("Unhandled interrupt SR=0x%02lx (now disabled)\n", unhandled);
1058
        }
1059
1060
    }
}