timer.c 56.6 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
#include <stdint.h>
#include <stdio.h>
#include <string.h>

#include "usbd_cdc_msc_hid.h"
#include "usbd_cdc_interface.h"

34
35
#include "py/runtime.h"
#include "py/gc.h"
36
37
#include "timer.h"
#include "servo.h"
38
#include "pin.h"
39
#include "irq.h"
40

41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/// \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
62
///     tim = pyb.Timer(4, prescaler=0, period=99)
63
64
///     tim.counter()                   # get counter (can also set)
///     tim.prescaler(2)                # set prescaler (can also get)
65
///     tim.period(199)                 # set period (can also get)
66
67
68
///     tim.callback(lambda t: ...)     # set callback for update interrupt (t=tim instance)
///     tim.callback(None)              # clear callback
///
69
/// *Note:* Timer 3 is used for fading the blue LED.  Timer 5 controls
70
71
72
/// 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.

73
74
75
76
77
78
79
80
// 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:
//  - LED 4, PWM to set the LED intensity
//
// TIM5:
//  - servo controller, PWM
81
82
83
84
//
// TIM6:
//  - ADC, DAC for read_timed and write_timed

85
86
87
88
89
90
91
92
93
94
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,
95
96
97
    CHANNEL_MODE_ENC_A,
    CHANNEL_MODE_ENC_B,
    CHANNEL_MODE_ENC_AB,
98
99
100
101
102
} pyb_channel_mode;

STATIC const struct {
    qstr        name;
    uint32_t    oc_mode;
103
} channel_mode_info[] = {
104
105
106
107
108
109
110
111
112
    { 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 },
113
114
115
    { MP_QSTR_ENC_A,              TIM_ENCODERMODE_TI1 },
    { MP_QSTR_ENC_B,              TIM_ENCODERMODE_TI2 },
    { MP_QSTR_ENC_AB,             TIM_ENCODERMODE_TI12 },
116
117
118
119
120
121
122
123
124
125
126
};

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;

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

137
138
139
// 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))
140
#define TIMER_CNT_MASK(self)    ((self)->is_32bit ? 0xffffffff : 0xffff)
141
142
#define TIMER_CHANNEL(self)     ((((self)->channel) - 1) << 2)

143
TIM_HandleTypeDef TIM5_Handle;
144
TIM_HandleTypeDef TIM6_Handle;
145

146
#define PYB_TIMER_OBJ_ALL_NUM MP_ARRAY_SIZE(MP_STATE_PORT(pyb_timer_obj_all))
147

148
149
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);
150
STATIC mp_obj_t pyb_timer_channel_callback(mp_obj_t self_in, mp_obj_t callback);
151

152
153
void timer_init0(void) {
    for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
154
        MP_STATE_PORT(pyb_timer_obj_all)[i] = NULL;
155
156
157
    }
}

158
159
160
// unregister all interrupt sources
void timer_deinit(void) {
    for (uint i = 0; i < PYB_TIMER_OBJ_ALL_NUM; i++) {
161
        pyb_timer_obj_t *tim = MP_STATE_PORT(pyb_timer_obj_all)[i];
162
163
164
165
166
167
        if (tim != NULL) {
            pyb_timer_deinit(tim);
        }
    }
}

168
// TIM5 is set-up for the servo controller
169
// This function inits but does not start the timer
170
171
172
173
174
void timer_tim5_init(void) {
    // TIM5 clock enable
    __TIM5_CLK_ENABLE();

    // set up and enable interrupt
175
    HAL_NVIC_SetPriority(TIM5_IRQn, IRQ_PRI_TIM5, IRQ_SUBPRI_TIM5);
176
177
178
179
    HAL_NVIC_EnableIRQ(TIM5_IRQn);

    // PWM clock configuration
    TIM5_Handle.Instance = TIM5;
180
    TIM5_Handle.Init.Period = 2000 - 1; // timer cycles at 50Hz
181
    TIM5_Handle.Init.Prescaler = (timer_get_source_freq(5) / 100000) - 1; // timer runs at 100kHz
182
    TIM5_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
183
    TIM5_Handle.Init.CounterMode = TIM_COUNTERMODE_UP;
184

185
186
187
    HAL_TIM_PWM_Init(&TIM5_Handle);
}

188
#if defined(TIM6)
189
190
191
// 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
192
TIM_HandleTypeDef *timer_tim6_init(uint freq) {
193
194
195
196
197
    // TIM6 clock enable
    __TIM6_CLK_ENABLE();

    // Timer runs at SystemCoreClock / 2
    // Compute the prescaler value so TIM6 triggers at freq-Hz
198
    uint32_t period = MAX(1, timer_get_source_freq(6) / freq);
199
200
201
202
203
204
205
206
207
208
    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;
209
    TIM6_Handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; // unused for TIM6
210
211
    TIM6_Handle.Init.CounterMode = TIM_COUNTERMODE_UP; // unused for TIM6
    HAL_TIM_Base_Init(&TIM6_Handle);
212
213

    return &TIM6_Handle;
214
}
215
#endif
216

217
218
// Interrupt dispatch
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
219
    if (htim == &TIM5_Handle) {
220
221
222
223
        servo_timer_irq_callback();
    }
}

224
225
226
227
228
// Get the frequency (in Hz) of the source clock for the given timer.
// 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.
229
uint32_t timer_get_source_freq(uint32_t tim_id) {
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
    uint32_t source;
    if (tim_id == 1 || (8 <= tim_id && tim_id <= 11)) {
        // TIM{1,8,9,10,11} are on APB2
        source = HAL_RCC_GetPCLK2Freq();
        if ((uint32_t)((RCC->CFGR & RCC_CFGR_PPRE2) >> 3) != RCC_HCLK_DIV1) {
            source *= 2;
        }
    } else {
        // TIM{2,3,4,5,6,7,12,13,14} are on APB1
        source = HAL_RCC_GetPCLK1Freq();
        if ((uint32_t)(RCC->CFGR & RCC_CFGR_PPRE1) != RCC_HCLK_DIV1) {
            source *= 2;
        }
    }
    return source;
}

247
248
249
/******************************************************************************/
/* Micro Python bindings                                                      */

250
251
STATIC const mp_obj_type_t pyb_timer_channel_type;

Dave Hylands's avatar
Dave Hylands committed
252
253
254
255
// This is the largest value that we can multiply by 100 and have the result
// fit in a uint32_t.
#define MAX_PERIOD_DIV_100  42949672

256
257
258
259
260
261
262
263
264
265
266
267
// computes prescaler and period so TIM triggers at freq-Hz
STATIC uint32_t compute_prescaler_period_from_freq(pyb_timer_obj_t *self, mp_obj_t freq_in, uint32_t *period_out) {
    uint32_t source_freq = timer_get_source_freq(self->tim_id);
    uint32_t prescaler = 1;
    uint32_t period;
    if (0) {
    #if MICROPY_PY_BUILTINS_FLOAT
    } else if (MP_OBJ_IS_TYPE(freq_in, &mp_type_float)) {
        float freq = mp_obj_get_float(freq_in);
        if (freq <= 0) {
            goto bad_freq;
        }
268
269
270
271
272
        while (freq < 1 && prescaler < 6553) {
            prescaler *= 10;
            freq *= 10;
        }
        period = (float)source_freq / freq;
273
274
275
276
277
278
279
280
    #endif
    } else {
        mp_int_t freq = mp_obj_get_int(freq_in);
        if (freq <= 0) {
            goto bad_freq;
            bad_freq:
            nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "must have positive freq"));
        }
281
        period = source_freq / freq;
282
    }
283
    period = MAX(1, period);
284
    while (period > TIMER_CNT_MASK(self)) {
285
286
287
288
289
290
291
292
293
294
295
296
        // if we can divide exactly, do that first
        if (period % 5 == 0) {
            prescaler *= 5;
            period /= 5;
        } else if (period % 3 == 0) {
            prescaler *= 3;
            period /= 3;
        } else {
            // may not divide exactly, but loses minimal precision
            prescaler <<= 1;
            period >>= 1;
        }
297
298
299
300
301
    }
    *period_out = (period - 1) & TIMER_CNT_MASK(self);
    return (prescaler - 1) & 0xffff;
}

Dave Hylands's avatar
Dave Hylands committed
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// Helper function for determining the period used for calculating percent
STATIC uint32_t compute_period(pyb_timer_obj_t *self) {
    // In center mode,  compare == period corresponds to 100%
    // In edge mode, compare == (period + 1) corresponds to 100%
    uint32_t period = (__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
    if (period != 0xffffffff) {
        if (self->tim.Init.CounterMode == TIM_COUNTERMODE_UP ||
            self->tim.Init.CounterMode == TIM_COUNTERMODE_DOWN) {
            // Edge mode
            period++;
        }
    }
    return period;
}

317
// Helper function to compute PWM value from timer period and percent value.
Dave Hylands's avatar
Dave Hylands committed
318
319
320
// 'percent_in' can be an int or a float between 0 and 100 (out of range
// values are clamped).
STATIC uint32_t compute_pwm_value_from_percent(uint32_t period, mp_obj_t percent_in) {
321
322
323
    uint32_t cmp;
    if (0) {
    #if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands's avatar
Dave Hylands committed
324
    } else if (MP_OBJ_IS_TYPE(percent_in, &mp_type_float)) {
325
        mp_float_t percent = mp_obj_get_float(percent_in);
Dave Hylands's avatar
Dave Hylands committed
326
327
328
329
330
        if (percent <= 0.0) {
            cmp = 0;
        } else if (percent >= 100.0) {
            cmp = period;
        } else {
331
            cmp = percent / 100.0 * ((mp_float_t)period);
Dave Hylands's avatar
Dave Hylands committed
332
        }
333
334
335
336
337
    #endif
    } else {
        // For integer arithmetic, if period is large and 100*period will
        // overflow, then divide period before multiplying by cmp.  Otherwise
        // do it the other way round to retain precision.
Dave Hylands's avatar
Dave Hylands committed
338
339
340
341
342
343
344
        mp_int_t percent = mp_obj_get_int(percent_in);
        if (percent <= 0) {
            cmp = 0;
        } else if (percent >= 100) {
            cmp = period;
        } else if (period > MAX_PERIOD_DIV_100) {
            cmp = (uint32_t)percent * (period / 100);
345
        } else {
Dave Hylands's avatar
Dave Hylands committed
346
            cmp = ((uint32_t)percent * period) / 100;
347
348
349
350
351
        }
    }
    return cmp;
}

Dave Hylands's avatar
Dave Hylands committed
352
353
354
// Helper function to compute percentage from timer perion and PWM value.
STATIC mp_obj_t compute_percent_from_pwm_value(uint32_t period, uint32_t cmp) {
    #if MICROPY_PY_BUILTINS_FLOAT
355
    mp_float_t percent;
356
    if (cmp >= period) {
Dave Hylands's avatar
Dave Hylands committed
357
358
        percent = 100.0;
    } else {
359
        percent = (mp_float_t)cmp * 100.0 / ((mp_float_t)period);
Dave Hylands's avatar
Dave Hylands committed
360
361
362
363
    }
    return mp_obj_new_float(percent);
    #else
    mp_int_t percent;
364
    if (cmp >= period) {
Dave Hylands's avatar
Dave Hylands committed
365
        percent = 100;
366
367
    } else if (cmp > MAX_PERIOD_DIV_100) {
        percent = cmp / (period / 100);
Dave Hylands's avatar
Dave Hylands committed
368
369
370
371
372
373
374
    } else {
        percent = cmp * 100 / period;
    }
    return mp_obj_new_int(percent);
    #endif
}

375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Computes the 8-bit value for the DTG field in the BDTR register.
//
// 1 tick = 1 count of the timer's clock (source_freq) divided by div.
// 0-128 ticks in inrements of 1
// 128-256 ticks in increments of 2
// 256-512 ticks in increments of 8
// 512-1008 ticks in increments of 16
STATIC uint32_t compute_dtg_from_ticks(mp_int_t ticks) {
    if (ticks <= 0) {
        return 0;
    }
    if (ticks < 128) {
        return ticks;
    }
    if (ticks < 256) {
        return 0x80 | ((ticks - 128) / 2);
    }
    if (ticks < 512) {
        return 0xC0 | ((ticks - 256) / 8);
    }
    if (ticks < 1008) {
        return 0xE0 | ((ticks - 512) / 16);
    }
    return 0xFF;
}

// Given the 8-bit value stored in the DTG field of the BDTR register, compute
// the number of ticks.
STATIC mp_int_t compute_ticks_from_dtg(uint32_t dtg) {
    if ((dtg & 0x80) == 0) {
        return dtg & 0x7F;
    }
    if ((dtg & 0xC0) == 0x80) {
        return 128 + ((dtg & 0x3F) * 2);
    }
    if ((dtg & 0xE0) == 0xC0) {
        return 256 + ((dtg & 0x1F) * 8);
    }
    return 512 + ((dtg & 0x1F) * 16);
}

STATIC void config_deadtime(pyb_timer_obj_t *self, mp_int_t ticks) {
    TIM_BreakDeadTimeConfigTypeDef deadTimeConfig;
    deadTimeConfig.OffStateRunMode  = TIM_OSSR_DISABLE;
    deadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
    deadTimeConfig.LockLevel        = TIM_LOCKLEVEL_OFF;
    deadTimeConfig.DeadTime         = compute_dtg_from_ticks(ticks);
    deadTimeConfig.BreakState       = TIM_BREAK_DISABLE;
    deadTimeConfig.BreakPolarity    = TIM_BREAKPOLARITY_LOW;
    deadTimeConfig.AutomaticOutput  = TIM_AUTOMATICOUTPUT_DISABLE;
    HAL_TIMEx_ConfigBreakDeadTime(&self->tim, &deadTimeConfig);
}

428
TIM_HandleTypeDef *pyb_timer_get_handle(mp_obj_t timer) {
429
430
431
    if (mp_obj_get_type(timer) != &pyb_timer_type) {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "need a Timer object"));
    }
432
433
434
435
    pyb_timer_obj_t *self = timer;
    return &self->tim;
}

436
STATIC void pyb_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
437
438
439
    pyb_timer_obj_t *self = self_in;

    if (self->tim.State == HAL_TIM_STATE_RESET) {
440
        mp_printf(print, "Timer(%u)", self->tim_id);
441
    } else {
442
443
444
445
        uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
        uint32_t period = __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self);
        // for efficiency, we compute and print freq as an int (not a float)
        uint32_t freq = timer_get_source_freq(self->tim_id) / ((prescaler + 1) * (period + 1));
446
        mp_printf(print, "Timer(%u, freq=%u, prescaler=%u, period=%u, mode=%s, div=%u",
447
            self->tim_id,
448
449
450
            freq,
            prescaler,
            period,
451
452
453
454
            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);
455
456
457
458
459
460
461
462
463

        #if defined(IS_TIM_ADVANCED_INSTANCE)
        if (IS_TIM_ADVANCED_INSTANCE(self->tim.Instance))
        #elif defined(IS_TIM_BREAK_INSTANCE)
        if (IS_TIM_BREAK_INSTANCE(self->tim.Instance))
        #else
        if (0)
        #endif
        {
464
465
            mp_printf(print, ", deadtime=%u",
                compute_ticks_from_dtg(self->tim.Instance->BDTR & TIM_BDTR_DTG));
466
        }
467
        mp_print_str(print, ")");
468
469
    }
}
470

471
472
473
474
475
/// \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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
///     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()
///
507
508
509
510
511
512
513
514
///   - `deadtime` - specifies the amount of "dead" or inactive time between
///       transitions on complimentary channels (both channels will be inactive)
///       for this time). `deadtime` may be an integer between 0 and 1008, with
///       the following restrictions: 0-128 in steps of 1. 128-256 in steps of
///       2, 256-512 in steps of 8, and 512-1008 in steps of 16. `deadime`
///       measures ticks of `source_freq` divided by `div` clock ticks.
///       `deadtime` is only available on timers 1 and 8.
///
515
///  You must either specify freq or both of period and prescaler.
516
517
518
519
520
521
522
523
STATIC 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) {
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_freq,         MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
        { 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} },
524
        { MP_QSTR_deadtime,     MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
525
    };
526

527
    // parse args
528
529
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
530

531
532
    // set the TIM configuration values
    TIM_Base_InitTypeDef *init = &self->tim.Init;
533

534
535
536
537
    if (args[0].u_obj != mp_const_none) {
        // set prescaler and period from desired frequency
        init->Prescaler = compute_prescaler_period_from_freq(self, args[0].u_obj, &init->Period);
    } else if (args[1].u_int != 0xffffffff && args[2].u_int != 0xffffffff) {
538
        // set prescaler and period directly
539
540
        init->Prescaler = args[1].u_int;
        init->Period = args[2].u_int;
541
542
543
544
    } else {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "must specify either freq, or prescaler and period"));
    }

545
546
547
548
    init->CounterMode = args[3].u_int;
    if (!IS_TIM_COUNTER_MODE(init->CounterMode)) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid mode (%d)", init->CounterMode));
    }
549

550
551
    init->ClockDivision = args[4].u_int == 2 ? TIM_CLOCKDIVISION_DIV2 :
                          args[4].u_int == 4 ? TIM_CLOCKDIVISION_DIV4 :
552
                                               TIM_CLOCKDIVISION_DIV1;
553

554
    init->RepetitionCounter = 0;
555

556
    // enable TIM clock
557
558
559
560
561
562
    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;
563
        #if defined(TIM6)
564
        case 6: __TIM6_CLK_ENABLE(); break;
565
566
        #endif
        #if defined(TIM7)
567
        case 7: __TIM7_CLK_ENABLE(); break;
568
569
        #endif
        #if defined(TIM8)
570
        case 8: __TIM8_CLK_ENABLE(); break;
571
        #endif
572
        #if defined(TIM9)
573
        case 9: __TIM9_CLK_ENABLE(); break;
574
575
        #endif
        #if defined(TIM10)
576
        case 10: __TIM10_CLK_ENABLE(); break;
577
578
        #endif
        #if defined(TIM11)
579
        case 11: __TIM11_CLK_ENABLE(); break;
580
        #endif
581
        #if defined(TIM12)
582
        case 12: __TIM12_CLK_ENABLE(); break;
583
584
        #endif
        #if defined(TIM13)
585
        case 13: __TIM13_CLK_ENABLE(); break;
586
587
        #endif
        #if defined(TIM14)
588
        case 14: __TIM14_CLK_ENABLE(); break;
589
        #endif
590
591
592
593
594
595
596
597
598
        #if defined(TIM15)
        case 15: __TIM15_CLK_ENABLE(); break;
        #endif
        #if defined(TIM16)
        case 16: __TIM16_CLK_ENABLE(); break;
        #endif
        #if defined(TIM17)
        case 17: __TIM17_CLK_ENABLE(); break;
        #endif
599
    }
600
601

    // set IRQ priority (if not a special timer)
602
    if (self->tim_id != 5) {
603
        HAL_NVIC_SetPriority(self->irqn, IRQ_PRI_TIMX, IRQ_SUBPRI_TIMX);
604
605
606
607
608
609
610
        if (self->tim_id == 1) {
            HAL_NVIC_SetPriority(TIM1_CC_IRQn, IRQ_PRI_TIMX, IRQ_SUBPRI_TIMX);
        #if defined(TIM8)
        } else if (self->tim_id == 8) {
            HAL_NVIC_SetPriority(TIM8_CC_IRQn, IRQ_PRI_TIMX, IRQ_SUBPRI_TIMX);
        #endif
        }
611
    }
612

613
    // init TIM
614
    HAL_TIM_Base_Init(&self->tim);
615
    #if defined(IS_TIM_ADVANCED_INSTANCE)
616
    if (IS_TIM_ADVANCED_INSTANCE(self->tim.Instance)) {
617
618
619
620
621
    #elif defined(IS_TIM_BREAK_INSTANCE)
    if (IS_TIM_BREAK_INSTANCE(self->tim.Instance)) {
    #else
    if (0) {
    #endif
622
623
        config_deadtime(self, args[6].u_int);
    }
624
    if (args[5].u_obj == mp_const_none) {
625
626
        HAL_TIM_Base_Start(&self->tim);
    } else {
627
        pyb_timer_callback(self, args[5].u_obj);
628
629
    }

630
631
632
    return mp_const_none;
}

633
634
635
636
/// \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.
637
STATIC mp_obj_t pyb_timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
638
639
640
641
642
    // 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);
643
644
    memset(tim, 0, sizeof(*tim));

645
646
    tim->base.type = &pyb_timer_type;
    tim->callback = mp_const_none;
647
    tim->channel = NULL;
648
649
650

    // get TIM number
    tim->tim_id = mp_obj_get_int(args[0]);
651
    tim->is_32bit = false;
652
653

    switch (tim->tim_id) {
654
        #if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
655
        case 1: tim->tim.Instance = TIM1; tim->irqn = TIM1_UP_TIM10_IRQn; break;
656
657
658
        #elif defined(MCU_SERIES_L4)
        case 1: tim->tim.Instance = TIM1; tim->irqn = TIM1_UP_TIM16_IRQn; break;
        #endif
659
        case 2: tim->tim.Instance = TIM2; tim->irqn = TIM2_IRQn; tim->is_32bit = true; break;
660
        case 3: tim->tim.Instance = TIM3; tim->irqn = TIM3_IRQn; break;
661
        case 4: tim->tim.Instance = TIM4; tim->irqn = TIM4_IRQn; break;
662
        case 5: tim->tim.Instance = TIM5; tim->irqn = TIM5_IRQn; tim->is_32bit = true; break;
663
        #if defined(TIM6)
664
        case 6: tim->tim.Instance = TIM6; tim->irqn = TIM6_DAC_IRQn; break;
665
666
        #endif
        #if defined(TIM7)
667
        case 7: tim->tim.Instance = TIM7; tim->irqn = TIM7_IRQn; break;
668
669
        #endif
        #if defined(TIM8)
670
        #if defined(MCU_SERIES_F4) || defined(MCU_SERIES_F7)
671
        case 8: tim->tim.Instance = TIM8; tim->irqn = TIM8_UP_TIM13_IRQn; break;
672
673
674
        #elif defined(MCU_SERIES_L4)
        case 8: tim->tim.Instance = TIM8; tim->irqn = TIM8_UP_IRQn; break;
        #endif
675
        #endif
676
        #if defined(TIM9)
677
        case 9: tim->tim.Instance = TIM9; tim->irqn = TIM1_BRK_TIM9_IRQn; break;
678
679
        #endif
        #if defined(TIM10)
680
        case 10: tim->tim.Instance = TIM10; tim->irqn = TIM1_UP_TIM10_IRQn; break;
681
682
        #endif
        #if defined(TIM11)
683
        case 11: tim->tim.Instance = TIM11; tim->irqn = TIM1_TRG_COM_TIM11_IRQn; break;
684
        #endif
685
        #if defined(TIM12)
686
        case 12: tim->tim.Instance = TIM12; tim->irqn = TIM8_BRK_TIM12_IRQn; break;
687
688
        #endif
        #if defined(TIM13)
689
        case 13: tim->tim.Instance = TIM13; tim->irqn = TIM8_UP_TIM13_IRQn; break;
690
691
        #endif
        #if defined(TIM14)
692
        case 14: tim->tim.Instance = TIM14; tim->irqn = TIM8_TRG_COM_TIM14_IRQn; break;
693
        #endif
694
695
696
697
698
699
700
701
702
        #if defined(TIM15)
        case 15: tim->tim.Instance = TIM15; tim->irqn = TIM1_BRK_TIM15_IRQn; break;
        #endif
        #if defined(TIM16)
        case 16: tim->tim.Instance = TIM16; tim->irqn = TIM1_UP_TIM16_IRQn; break;
        #endif
        #if defined(TIM17)
        case 17: tim->tim.Instance = TIM17; tim->irqn = TIM1_TRG_COM_TIM17_IRQn; break;
        #endif
703
        default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Timer(%d) doesn't exist", tim->tim_id));
704
705
    }

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

711
712
713
714
715
716
717
718
    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);
    }

    return (mp_obj_t)tim;
719
720
}

721
STATIC mp_obj_t pyb_timer_init(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
722
    return pyb_timer_init_helper(args[0], n_args - 1, args + 1, kw_args);
723
}
724
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init);
725

726
// timer.deinit()
727
STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) {
728
729
    pyb_timer_obj_t *self = self_in;

730
    // Disable the base interrupt
731
732
    pyb_timer_callback(self_in, mp_const_none);

733
734
735
736
737
738
739
740
741
742
743
    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;
    }

744
    self->tim.State = HAL_TIM_STATE_RESET;
745
746
747
    self->tim.Instance->CCER = 0x0000; // disable all capture/compare outputs
    self->tim.Instance->CR1 = 0x0000; // disable the timer and reset its state

748
749
750
751
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit);

752
753
/// \method channel(channel, mode, ...)
///
754
755
/// If only a channel number is passed, then a previously initialized channel
/// object is returned (or `None` if there is no previous channel).
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
///
/// 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.
777
778
779
///     - `Timer.ENC_A` --- configure the timer in Encoder mode. The counter only changes when CH1 changes.
///     - `Timer.ENC_B` --- configure the timer in Encoder mode. The counter only changes when CH2 changes.
///     - `Timer.ENC_AB` --- configure the timer in Encoder mode. The counter changes when CH1 or CH2 changes.
780
781
782
783
784
785
786
787
788
789
///
///   - `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:
///
790
///   - `pulse_width` - determines the initial pulse width value to use.
791
///   - `pulse_width_percent` - determines the initial pulse width percentage to use.
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
///
/// 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.
///
808
809
810
///   Note that capture only works on the primary channel, and not on the
///   complimentary channels.
///
811
812
813
814
815
816
817
818
/// Notes for Timer.ENC modes:
///
///   - Requires 2 pins, so one or both pins will need to be configured to use
///     the appropriate timer AF using the Pin API.
///   - Read the encoder value using the timer.counter() method.
///   - Only works on CH1 and CH2 (and not on CH1N or CH2N)
///   - The channel number is ignored when setting the encoder mode.
///
819
820
821
822
823
/// 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)
824
825
826
827
828
829
830
831
832
833
STATIC mp_obj_t pyb_timer_channel(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
    static const mp_arg_t allowed_args[] = {
        { MP_QSTR_mode,                MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} },
        { 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 = 0} },
        { MP_QSTR_pulse_width_percent, 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} },
    };
834

835
836
    pyb_timer_obj_t *self = pos_args[0];
    mp_int_t channel = mp_obj_get_int(pos_args[1]);
837
838

    if (channel < 1 || channel > 4) {
839
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid channel (%d)", channel));
840
841
842
843
844
845
846
847
848
849
850
851
    }

    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;
    }
852
853
854

    // If only the channel number is given return the previously allocated
    // channel (or None if no previous channel).
855
    if (n_args == 2 && kw_args->used == 0) {
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
        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
878
879
    mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
    mp_arg_parse_all(n_args - 2, pos_args + 2, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
880
881
882
883
884
885

    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;
886
887
    chan->mode = args[0].u_int;
    chan->callback = args[1].u_obj;
888

889
    mp_obj_t pin_obj = args[2].u_obj;
890
891
892
893
894
895
896
    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) {
897
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Pin(%q) doesn't have an af for Timer(%d)", pin->name, self->tim_id));
898
899
        }
        // pin.init(mode=AF_PP, af=idx)
900
        const mp_obj_t args2[6] = {
901
902
903
904
905
            (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)
        };
906
        mp_call_method_n_kw(0, 2, args2);
907
908
909
910
911
912
913
914
915
916
917
918
919
920
    }

    // 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;
921
            oc_config.OCMode = channel_mode_info[chan->mode].oc_mode;
922
            if (args[4].u_obj != mp_const_none) {
923
                // pulse width percent given
Dave Hylands's avatar
Dave Hylands committed
924
                uint32_t period = compute_period(self);
925
                oc_config.Pulse = compute_pwm_value_from_percent(period, args[4].u_obj);
926
            } else {
927
                // use absolute pulse width value (defaults to 0 if nothing given)
928
                oc_config.Pulse = args[3].u_int;
929
            }
930
931
932
933
934
935
936
937
938
939
            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 {
940
                pyb_timer_channel_callback(chan, chan->callback);
941
            }
942
943
944
945
            // Start the complimentary channel too (if its supported)
            if (IS_TIM_CCXN_INSTANCE(self->tim.Instance, TIMER_CHANNEL(chan))) {
                HAL_TIMEx_PWMN_Start(&self->tim, TIMER_CHANNEL(chan));
            }
946
947
948
949
950
951
952
953
954
955
            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;
956
            oc_config.OCMode       = channel_mode_info[chan->mode].oc_mode;
957
958
            oc_config.Pulse        = args[5].u_int;
            oc_config.OCPolarity   = args[6].u_int;
959
960
961
            if (oc_config.OCPolarity == 0xffffffff) {
                oc_config.OCPolarity = TIM_OCPOLARITY_HIGH;
            }
962
963
964
965
966
            if (oc_config.OCPolarity == TIM_OCPOLARITY_HIGH) {
                oc_config.OCNPolarity  = TIM_OCNPOLARITY_HIGH;
            } else {
                oc_config.OCNPolarity  = TIM_OCNPOLARITY_LOW;
            }
967
968
969
970
971
            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)) {
972
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", oc_config.OCPolarity));
973
974
975
976
977
            }
            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 {
978
                pyb_timer_channel_callback(chan, chan->callback);
979
            }
980
981
982
983
            // Start the complimentary channel too (if its supported)
            if (IS_TIM_CCXN_INSTANCE(self->tim.Instance, TIMER_CHANNEL(chan))) {
                HAL_TIMEx_OCN_Start(&self->tim, TIMER_CHANNEL(chan));
            }
984
985
986
987
988
989
            break;
        }

        case CHANNEL_MODE_IC: {
            TIM_IC_InitTypeDef ic_config;

990
            ic_config.ICPolarity  = args[6].u_int;
991
992
993
994
995
996
997
998
            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)) {
999
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", ic_config.ICPolarity));
1000
1001
1002
1003
1004
            }
            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 {
1005
                pyb_timer_channel_callback(chan, chan->callback);
1006
1007
1008
1009
            }
            break;
        }

1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
        case CHANNEL_MODE_ENC_A:
        case CHANNEL_MODE_ENC_B:
        case CHANNEL_MODE_ENC_AB: {
            TIM_Encoder_InitTypeDef enc_config;

            enc_config.EncoderMode = channel_mode_info[chan->mode].oc_mode;
            enc_config.IC1Polarity  = args[6].u_int;
            if (enc_config.IC1Polarity == 0xffffffff) {
                enc_config.IC1Polarity = TIM_ICPOLARITY_RISING;
            }
            enc_config.IC2Polarity  = enc_config.IC1Polarity;
            enc_config.IC1Selection = TIM_ICSELECTION_DIRECTTI;
            enc_config.IC2Selection = TIM_ICSELECTION_DIRECTTI;
            enc_config.IC1Prescaler = TIM_ICPSC_DIV1;
            enc_config.IC2Prescaler = TIM_ICPSC_DIV1;
            enc_config.IC1Filter    = 0;
            enc_config.IC2Filter    = 0;

            if (!IS_TIM_IC_POLARITY(enc_config.IC1Polarity)) {
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid polarity (%d)", enc_config.IC1Polarity));
            }
            // Only Timers 1, 2, 3, 4, 5, and 8 support encoder mode
            if (self->tim.Instance != TIM1
            &&  self->tim.Instance != TIM2
            &&  self->tim.Instance != TIM3
            &&  self->tim.Instance != TIM4
            &&  self->tim.Instance != TIM5
1037
1038
1039
1040
            #if defined(TIM8)
            &&  self->tim.Instance != TIM8
            #endif
            ) {
1041
1042
                nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "encoder not supported on timer %d", self->tim_id));
            }
1043
1044
1045
1046

            // Disable & clear the timer interrupt so that we don't trigger
            // an interrupt by initializing the timer.
            __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
1047
1048
            HAL_TIM_Encoder_Init(&self->tim, &enc_config);
            __HAL_TIM_SetCounter(&self->tim, 0);
1049
1050
1051
1052
1053
            if (self->callback != mp_const_none) {
                __HAL_TIM_CLEAR_FLAG(&self->tim, TIM_IT_UPDATE);
                __HAL_TIM_ENABLE_IT(&self->tim, TIM_IT_UPDATE);
            }
            HAL_TIM_Encoder_Start(&self->tim, TIM_CHANNEL_ALL);
1054
1055
1056
            break;
        }

1057
        default:
1058
            nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid mode (%d)", chan->mode));
1059
1060
1061
1062
    }

    return chan;
}
1063
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel);
1064

1065
1066
/// \method counter([value])
/// Get or set the timer counter.
1067
STATIC mp_obj_t pyb_timer_counter(mp_uint_t n_args, const mp_obj_t *args) {
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
    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);

1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
/// \method source_freq()
/// Get the frequency of the source of the timer.
STATIC mp_obj_t pyb_timer_source_freq(mp_obj_t self_in) {
    pyb_timer_obj_t *self = self_in;
    uint32_t source_freq = timer_get_source_freq(self->tim_id);
    return mp_obj_new_int(source_freq);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_source_freq_obj, pyb_timer_source_freq);

/// \method freq([value])
/// Get or set the frequency for the timer (changes prescaler and period if set).
STATIC mp_obj_t pyb_timer_freq(mp_uint_t n_args, const mp_obj_t *args) {
    pyb_timer_obj_t *self = args[0];
    if (n_args == 1) {
        // get
        uint32_t prescaler = self->tim.Instance->PSC & 0xffff;
        uint32_t period = __HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self);
        uint32_t source_freq = timer_get_source_freq(self->tim_id);
        uint32_t divide = ((prescaler + 1) * (period + 1));
1099
1100
        #if MICROPY_PY_BUILTINS_FLOAT
        if (source_freq % divide != 0) {
1101
            return mp_obj_new_float((float)source_freq / (float)divide);
1102
1103
1104
1105
        } else
        #endif
        {
            return mp_obj_new_int(source_freq / divide);
1106
1107
1108
1109
1110
1111
1112
        }
    } else {
        // set
        uint32_t period;
        uint32_t prescaler = compute_prescaler_period_from_freq(self, args[1], &period);
        self->tim.Instance->PSC = prescaler;
        __HAL_TIM_SetAutoreload(&self->tim, period);
1113
1114
1115
1116
        // Reset the counter to zero. Otherwise, if counter >= period it will
        // continue counting until it wraps (at either 16 or 32 bits depending
        // on the timer).
        __HAL_TIM_SetCounter(&self->tim, 0);
1117
1118
1119
1120
1121
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_freq_obj, 1, 2, pyb_timer_freq);

1122
1123
/// \method prescaler([value])
/// Get or set the prescaler for the timer.
1124
STATIC mp_obj_t pyb_timer_prescaler(mp_uint_t n_args, const mp_obj_t *args) {
1125
1126
1127
1128
1129
1130
    pyb_timer_obj_t *self = args[0];
    if (n_args == 1) {
        // get
        return mp_obj_new_int(self->tim.Instance->PSC & 0xffff);
    } else {
        // set
1131
        self->tim.Instance->PSC = mp_obj_get_int(args[1]) & 0xffff;
1132
1133
1134
1135
1136
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_prescaler_obj, 1, 2, pyb_timer_prescaler);

1137
1138
/// \method period([value])
/// Get or set the period of the timer.
1139
STATIC mp_obj_t pyb_timer_period(mp_uint_t n_args, const mp_obj_t *args) {
1140
1141
1142
    pyb_timer_obj_t *self = args[0];
    if (n_args == 1) {
        // get
1143
        return mp_obj_new_int(__HAL_TIM_GetAutoreload(&self->tim) & TIMER_CNT_MASK(self));
1144
1145
    } else {
        // set
1146
        __HAL_TIM_SetAutoreload(&self->tim, mp_obj_get_int(args[1]) & TIMER_CNT_MASK(self));
1147
1148
1149
1150
        // Reset the counter to zero. Otherwise, if counter >= period it will
        // continue counting until it wraps (at either 16 or 32 bits depending
        // on the timer).
        __HAL_TIM_SetCounter(&self->tim, 0); 
1151
1152
1153
1154
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_period_obj, 1, 2, pyb_timer_period);
1155

1156
1157
1158
1159
/// \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.
1160
1161
1162
1163
1164
1165
1166
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)) {
1167
        __HAL_TIM_DISABLE_IT(&self->tim, TIM_IT_UPDATE);
1168
        self->callback = callback;
1169
1170
1171
1172
        // start timer, so that it interrupts on overflow, but clear any
        // pending interrupts which may have been set by initializing it.
        __HAL_TIM_CLEAR_FLAG(&self->tim, TIM_IT_UPDATE);
        HAL_TIM_Base_Start_IT(&self->tim); // This will re-enable the IRQ
1173
        HAL_NVIC_EnableIRQ(self->irqn);
1174
1175
    } else {
        nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "callback must be None or a callable object"));
1176
    }
1177
    return mp_const_none;
1178
}
1179
1180
STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_timer_callback_obj, pyb_timer_callback);

1181
STATIC const mp_rom_map_elem_t pyb_timer_locals_dict_table[] = {
1182
    // instance methods
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
    { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_timer_init_obj) },
    { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_timer_deinit_obj) },
    { MP_ROM_QSTR(MP_QSTR_channel), MP_ROM_PTR(&pyb_timer_channel_obj) },
    { MP_ROM_QSTR(MP_QSTR_counter), MP_ROM_PTR(&pyb_timer_counter_obj) },
    { MP_ROM_QSTR(MP_QSTR_source_freq), MP_ROM_PTR(&pyb_timer_source_freq_obj) },
    { MP_ROM_QSTR(MP_QSTR_freq), MP_ROM_PTR(&pyb_timer_freq_obj) },
    { MP_ROM_QSTR(MP_QSTR_prescaler), MP_ROM_PTR(&pyb_timer_prescaler_obj) },
    { MP_ROM_QSTR(MP_QSTR_period), MP_ROM_PTR(&pyb_timer_period_obj) },
    { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&pyb_timer_callback_obj) },
    { MP_ROM_QSTR(MP_QSTR_UP), MP_ROM_INT(TIM_COUNTERMODE_UP) },
    { MP_ROM_QSTR(MP_QSTR_DOWN), MP_ROM_INT(TIM_COUNTERMODE_DOWN) },
    { MP_ROM_QSTR(MP_QSTR_CENTER), MP_ROM_INT(TIM_COUNTERMODE_CENTERALIGNED1) },
    { MP_ROM_QSTR(MP_QSTR_PWM), MP_ROM_INT(CHANNEL_MODE_PWM_NORMAL) },
    { MP_ROM_QSTR(MP_QSTR_PWM_INVERTED), MP_ROM_INT(CHANNEL_MODE_PWM_INVERTED) },
    { MP_ROM_QSTR(MP_QSTR_OC_TIMING), MP_ROM_INT(CHANNEL_MODE_OC_TIMING) },
    { MP_ROM_QSTR(MP_QSTR_OC_ACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_ACTIVE) },
    { MP_ROM_QSTR(MP_QSTR_OC_INACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_INACTIVE) },
    { MP_ROM_QSTR(MP_QSTR_OC_TOGGLE), MP_ROM_INT(CHANNEL_MODE_OC_TOGGLE) },
    { MP_ROM_QSTR(MP_QSTR_OC_FORCED_ACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_FORCED_ACTIVE) },
    { MP_ROM_QSTR(MP_QSTR_OC_FORCED_INACTIVE), MP_ROM_INT(CHANNEL_MODE_OC_FORCED_INACTIVE) },
    { MP_ROM_QSTR(MP_QSTR_IC), MP_ROM_INT(CHANNEL_MODE_IC) },
    { MP_ROM_QSTR(MP_QSTR_ENC_A), MP_ROM_INT(CHANNEL_MODE_ENC_A) },
    { MP_ROM_QSTR(MP_QSTR_ENC_B), MP_ROM_INT(CHANNEL_MODE_ENC_B) },
    { MP_ROM_QSTR(MP_QSTR_ENC_AB), MP_ROM_INT(CHANNEL_MODE_ENC_AB) },
    { MP_ROM_QSTR(MP_QSTR_HIGH), MP_ROM_INT(TIM_OCPOLARITY_HIGH) },
    { MP_ROM_QSTR(MP_QSTR_LOW), MP_ROM_INT(TIM_OCPOLARITY_LOW) },
    { MP_ROM_QSTR(MP_QSTR_RISING), MP_ROM_INT(TIM_ICPOLARITY_RISING) },
    { MP_ROM_QSTR(MP_QSTR_FALLING), MP_ROM_INT(TIM_ICPOLARITY_FALLING) },
    { MP_ROM_QSTR(MP_QSTR_BOTH), MP_ROM_INT(TIM_ICPOLARITY_BOTHEDGE) },
1212
1213
1214
1215
1216
1217
1218
1219
};
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,
1220
    .locals_dict = (mp_obj_dict_t*)&pyb_timer_locals_dict,
1221
1222
};

1223
1224
1225
1226
1227
1228
/// \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.
1229
STATIC void pyb_timer_channel_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {