led.c 12.1 KB
Newer Older
1
/*
2
 * This file is part of the MicroPython project, http://micropython.org/
3
4
5
 *
 * The MIT License (MIT)
 *
6
 * Copyright (c) 2013-2016 Damien P. George
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 *
 * 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
#include <stdio.h>

29
30
#include "py/nlr.h"
#include "py/runtime.h"
31
#include "py/mphal.h"
32
#include "timer.h"
33
34
#include "led.h"
#include "pin.h"
35
#include "genhdr/pins.h"
36

37
38
#if defined(MICROPY_HW_LED1)

39
40
41
42
43
/// \moduleref pyb
/// \class LED - LED object
///
/// The LED object controls an individual LED (Light Emitting Diode).

44
45
46
47
48
// the default is that LEDs are not inverted, and pin driven high turns them on
#ifndef MICROPY_HW_LED_INVERTED
#define MICROPY_HW_LED_INVERTED (0)
#endif

49
50
typedef struct _pyb_led_obj_t {
    mp_obj_base_t base;
51
    mp_uint_t led_id;
52
53
54
55
56
    const pin_obj_t *led_pin;
} pyb_led_obj_t;

STATIC const pyb_led_obj_t pyb_led_obj[] = {
    {{&pyb_led_type}, 1, &MICROPY_HW_LED1},
57
#if defined(MICROPY_HW_LED2)
58
    {{&pyb_led_type}, 2, &MICROPY_HW_LED2},
59
#if defined(MICROPY_HW_LED3)
60
    {{&pyb_led_type}, 3, &MICROPY_HW_LED3},
61
#if defined(MICROPY_HW_LED4)
62
    {{&pyb_led_type}, 4, &MICROPY_HW_LED4},
63
64
65
66
#endif
#endif
#endif
};
67
#define NUM_LEDS MP_ARRAY_SIZE(pyb_led_obj)
68
69
70
71
72
73
74

void led_init(void) {
    /* GPIO structure */
    GPIO_InitTypeDef GPIO_InitStructure;

    /* Configure I/O speed, mode, output type and pull */
    GPIO_InitStructure.Speed = GPIO_SPEED_LOW;
75
    GPIO_InitStructure.Mode = MICROPY_HW_LED_OTYPE;
76
77
78
79
    GPIO_InitStructure.Pull = GPIO_NOPULL;

    /* Turn off LEDs and initialize */
    for (int led = 0; led < NUM_LEDS; led++) {
80
        const pin_obj_t *led_pin = pyb_led_obj[led].led_pin;
81
        mp_hal_gpio_clock_enable(led_pin->gpio);
82
83
84
        MICROPY_HW_LED_OFF(led_pin);
        GPIO_InitStructure.Pin = led_pin->pin_mask;
        HAL_GPIO_Init(led_pin->gpio, &GPIO_InitStructure);
85
86
87
    }
}

88
89
90
91
92
93
#if defined(MICROPY_HW_LED1_PWM) \
    || defined(MICROPY_HW_LED2_PWM) \
    || defined(MICROPY_HW_LED3_PWM) \
    || defined(MICROPY_HW_LED4_PWM)

// The following is semi-generic code to control LEDs using PWM.
94
// It currently supports TIM1, TIM2 and TIM3, channels 1-4.
95
96
97
98
99
100
// Configure by defining the relevant MICROPY_HW_LEDx_PWM macros in mpconfigboard.h.
// If they are not defined then PWM will not be available for that LED.

#define LED_PWM_ENABLED (1)

#ifndef MICROPY_HW_LED1_PWM
101
#define MICROPY_HW_LED1_PWM { NULL, 0, 0, 0 }
102
103
#endif
#ifndef MICROPY_HW_LED2_PWM
104
#define MICROPY_HW_LED2_PWM { NULL, 0, 0, 0 }
105
106
#endif
#ifndef MICROPY_HW_LED3_PWM
107
#define MICROPY_HW_LED3_PWM { NULL, 0, 0, 0 }
108
109
#endif
#ifndef MICROPY_HW_LED4_PWM
110
#define MICROPY_HW_LED4_PWM { NULL, 0, 0, 0 }
111
112
113
114
#endif

#define LED_PWM_TIM_PERIOD (10000) // TIM runs at 1MHz and fires every 10ms

115
116
117
// this gives the address of the CCR register for channels 1-4
#define LED_PWM_CCR(pwm_cfg) ((volatile uint32_t*)&(pwm_cfg)->tim->CCR1 + ((pwm_cfg)->tim_channel >> 2))

118
119
120
typedef struct _led_pwm_config_t {
    TIM_TypeDef *tim;
    uint8_t tim_id;
121
    uint8_t tim_channel;
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
    uint8_t alt_func;
} led_pwm_config_t;

STATIC const led_pwm_config_t led_pwm_config[] = {
    MICROPY_HW_LED1_PWM,
    MICROPY_HW_LED2_PWM,
    MICROPY_HW_LED3_PWM,
    MICROPY_HW_LED4_PWM,
};

STATIC uint8_t led_pwm_state = 0;

static inline bool led_pwm_is_enabled(int led) {
    return (led_pwm_state & (1 << led)) != 0;
}

// this function has a large stack so it should not be inlined
STATIC void led_pwm_init(int led) __attribute__((noinline));
STATIC void led_pwm_init(int led) {
    const pin_obj_t *led_pin = pyb_led_obj[led - 1].led_pin;
    const led_pwm_config_t *pwm_cfg = &led_pwm_config[led - 1];

    // GPIO configuration
    GPIO_InitTypeDef gpio_init;
    gpio_init.Pin = led_pin->pin_mask;
    gpio_init.Mode = GPIO_MODE_AF_PP;
    gpio_init.Speed = GPIO_SPEED_FAST;
    gpio_init.Pull = GPIO_NOPULL;
    gpio_init.Alternate = pwm_cfg->alt_func;
    HAL_GPIO_Init(led_pin->gpio, &gpio_init);

    // TIM configuration
    switch (pwm_cfg->tim_id) {
155
        case 1: __TIM1_CLK_ENABLE(); break;
156
157
158
159
160
161
162
163
164
165
        case 2: __TIM2_CLK_ENABLE(); break;
        case 3: __TIM3_CLK_ENABLE(); break;
        default: assert(0);
    }
    TIM_HandleTypeDef tim;
    tim.Instance = pwm_cfg->tim;
    tim.Init.Period = LED_PWM_TIM_PERIOD - 1;
    tim.Init.Prescaler = timer_get_source_freq(pwm_cfg->tim_id) / 1000000 - 1; // TIM runs at 1MHz
    tim.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
    tim.Init.CounterMode = TIM_COUNTERMODE_UP;
166
    tim.Init.RepetitionCounter = 0;
167
168
    HAL_TIM_PWM_Init(&tim);

169
    // PWM configuration
170
171
172
    TIM_OC_InitTypeDef oc_init;
    oc_init.OCMode = TIM_OCMODE_PWM1;
    oc_init.Pulse = 0; // off
173
    oc_init.OCPolarity = MICROPY_HW_LED_INVERTED ? TIM_OCPOLARITY_LOW : TIM_OCPOLARITY_HIGH;
174
    oc_init.OCFastMode = TIM_OCFAST_DISABLE;
175
176
177
178
179
    oc_init.OCNPolarity = TIM_OCNPOLARITY_HIGH; // needed for TIM1 and TIM8
    oc_init.OCIdleState = TIM_OCIDLESTATE_SET; // needed for TIM1 and TIM8
    oc_init.OCNIdleState = TIM_OCNIDLESTATE_SET; // needed for TIM1 and TIM8
    HAL_TIM_PWM_ConfigChannel(&tim, &oc_init, pwm_cfg->tim_channel);
    HAL_TIM_PWM_Start(&tim, pwm_cfg->tim_channel);
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200

    // indicate that this LED is using PWM
    led_pwm_state |= 1 << led;
}

STATIC void led_pwm_deinit(int led) {
    // make the LED's pin a standard GPIO output pin
    const pin_obj_t *led_pin = pyb_led_obj[led - 1].led_pin;
    GPIO_TypeDef *g = led_pin->gpio;
    uint32_t pin = led_pin->pin;
    static const int mode = 1; // output
    static const int alt = 0; // no alt func
    g->MODER = (g->MODER & ~(3 << (2 * pin))) | (mode << (2 * pin));
    g->AFR[pin >> 3] = (g->AFR[pin >> 3] & ~(15 << (4 * (pin & 7)))) | (alt << (4 * (pin & 7)));
    led_pwm_state &= ~(1 << led);
}

#else
#define LED_PWM_ENABLED (0)
#endif

201
202
203
204
void led_state(pyb_led_t led, int state) {
    if (led < 1 || led > NUM_LEDS) {
        return;
    }
205

206
    const pin_obj_t *led_pin = pyb_led_obj[led - 1].led_pin;
207
    //printf("led_state(%d,%d)\n", led, state);
208
209
    if (state == 0) {
        // turn LED off
210
        MICROPY_HW_LED_OFF(led_pin);
211
212
    } else {
        // turn LED on
213
        MICROPY_HW_LED_ON(led_pin);
214
    }
215
216
217
218
219
220

    #if LED_PWM_ENABLED
    if (led_pwm_is_enabled(led)) {
        led_pwm_deinit(led);
    }
    #endif
221
222
223
224
225
226
}

void led_toggle(pyb_led_t led) {
    if (led < 1 || led > NUM_LEDS) {
        return;
    }
227

228
229
230
231
232
233
234
235
    #if LED_PWM_ENABLED
    if (led_pwm_is_enabled(led)) {
        // if PWM is enabled then LED has non-zero intensity, so turn it off
        led_state(led, 0);
        return;
    }
    #endif

236
    // toggle the output data register to toggle the LED state
237
    const pin_obj_t *led_pin = pyb_led_obj[led - 1].led_pin;
238
    led_pin->gpio->ODR ^= led_pin->pin_mask;
239
240
}

241
int led_get_intensity(pyb_led_t led) {
242
243
244
    if (led < 1 || led > NUM_LEDS) {
        return 0;
    }
245

246
247
    #if LED_PWM_ENABLED
    if (led_pwm_is_enabled(led)) {
248
249
        const led_pwm_config_t *pwm_cfg = &led_pwm_config[led - 1];
        mp_uint_t i = (*LED_PWM_CCR(pwm_cfg) * 255 + LED_PWM_TIM_PERIOD - 2) / (LED_PWM_TIM_PERIOD - 1);
250
251
252
253
254
255
256
        if (i > 255) {
            i = 255;
        }
        return i;
    }
    #endif

257
    const pin_obj_t *led_pin = pyb_led_obj[led - 1].led_pin;
258
259
260
261
    GPIO_TypeDef *gpio = led_pin->gpio;

    if (gpio->ODR & led_pin->pin_mask) {
        // pin is high
262
        return MICROPY_HW_LED_INVERTED ? 0 : 255;
263
264
    } else {
        // pin is low
265
        return MICROPY_HW_LED_INVERTED ? 255 : 0;
266
267
268
    }
}

269
void led_set_intensity(pyb_led_t led, mp_int_t intensity) {
270
271
    #if LED_PWM_ENABLED
    if (intensity > 0 && intensity < 255) {
272
273
        const led_pwm_config_t *pwm_cfg = &led_pwm_config[led - 1];
        if (pwm_cfg->tim != NULL) {
274
275
276
277
            // set intensity using PWM pulse width
            if (!led_pwm_is_enabled(led)) {
                led_pwm_init(led);
            }
278
            *LED_PWM_CCR(pwm_cfg) = intensity * (LED_PWM_TIM_PERIOD - 1) / 255;
279
280
281
282
283
            return;
        }
    }
    #endif

284
285
286
287
    // intensity not supported for this LED; just turn it on/off
    led_state(led, intensity > 0);
}

288
289
290
291
292
293
294
295
void led_debug(int n, int delay) {
    led_state(1, n & 1);
    led_state(2, n & 2);
    led_state(3, n & 4);
    led_state(4, n & 8);
    HAL_Delay(delay);
}

296
297
298
/******************************************************************************/
/* Micro Python bindings                                                      */

299
void led_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
300
    pyb_led_obj_t *self = self_in;
301
    mp_printf(print, "LED(%lu)", self->led_id);
302
303
}

304
305
306
307
/// \classmethod \constructor(id)
/// Create an LED object associated with the given LED:
///
///   - `id` is the LED number, 1-4.
308
STATIC mp_obj_t led_obj_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
309
    // check arguments
Damien George's avatar
Damien George committed
310
    mp_arg_check_num(n_args, n_kw, 1, 1, false);
311
312

    // get led number
313
    mp_int_t led_id = mp_obj_get_int(args[0]);
314
315

    // check led number
316
    if (!(1 <= led_id && led_id <= NUM_LEDS)) {
317
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "LED(%d) does not exist", led_id));
318
319
320
    }

    // return static led object
321
    return (mp_obj_t)&pyb_led_obj[led_id - 1];
322
323
}

324
325
/// \method on()
/// Turn the LED on.
326
327
328
329
330
331
mp_obj_t led_obj_on(mp_obj_t self_in) {
    pyb_led_obj_t *self = self_in;
    led_state(self->led_id, 1);
    return mp_const_none;
}

332
333
/// \method off()
/// Turn the LED off.
334
335
336
337
338
339
mp_obj_t led_obj_off(mp_obj_t self_in) {
    pyb_led_obj_t *self = self_in;
    led_state(self->led_id, 0);
    return mp_const_none;
}

340
341
/// \method toggle()
/// Toggle the LED between on and off.
342
343
344
345
346
347
mp_obj_t led_obj_toggle(mp_obj_t self_in) {
    pyb_led_obj_t *self = self_in;
    led_toggle(self->led_id);
    return mp_const_none;
}

348
349
350
351
/// \method intensity([value])
/// Get or set the LED intensity.  Intensity ranges between 0 (off) and 255 (full on).
/// If no argument is given, return the LED intensity.
/// If an argument is given, set the LED intensity and return `None`.
352
mp_obj_t led_obj_intensity(mp_uint_t n_args, const mp_obj_t *args) {
353
    pyb_led_obj_t *self = args[0];
354
355
    if (n_args == 1) {
        return mp_obj_new_int(led_get_intensity(self->led_id));
356
    } else {
357
        led_set_intensity(self->led_id, mp_obj_get_int(args[1]));
358
359
360
361
362
363
364
        return mp_const_none;
    }
}

STATIC MP_DEFINE_CONST_FUN_OBJ_1(led_obj_on_obj, led_obj_on);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(led_obj_off_obj, led_obj_off);
STATIC MP_DEFINE_CONST_FUN_OBJ_1(led_obj_toggle_obj, led_obj_toggle);
365
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(led_obj_intensity_obj, 1, 2, led_obj_intensity);
366

367
368
369
370
371
STATIC const mp_map_elem_t led_locals_dict_table[] = {
    { MP_OBJ_NEW_QSTR(MP_QSTR_on), (mp_obj_t)&led_obj_on_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_off), (mp_obj_t)&led_obj_off_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_toggle), (mp_obj_t)&led_obj_toggle_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_intensity), (mp_obj_t)&led_obj_intensity_obj },
372
373
};

374
375
STATIC MP_DEFINE_CONST_DICT(led_locals_dict, led_locals_dict_table);

376
const mp_obj_type_t pyb_led_type = {
377
    { &mp_type_type },
378
    .name = MP_QSTR_LED,
379
    .print = led_obj_print,
380
    .make_new = led_obj_make_new,
381
    .locals_dict = (mp_obj_t)&led_locals_dict,
382
};
383
384
385
386
387
388
389
390
391
392
393

#else
// For boards with no LEDs, we leave an empty function here so that we don't
// have to put conditionals everywhere.
void led_init(void) {
}
void led_state(pyb_led_t led, int state) {
}
void led_toggle(pyb_led_t led) {
}
#endif  // defined(MICROPY_HW_LED1)