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

31
#include "mpconfig.h"
32
#include "nlr.h"
33
34
35
#include "misc.h"
#include "qstr.h"
#include "obj.h"
36
#include "runtime.h"
37
#include MICROPY_HAL_H
38
39
#include "pin.h"

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/// \moduleref pyb
/// \class Pin - control I/O pins
///
/// A pin is the basic object to control I/O pins.  It has methods to set
/// the mode of the pin (input, output, etc) and methods to get and set the
/// digital logic level.  For analog control of a pin, see the ADC class.
///
/// Usage Model:
///
/// All Board Pins are predefined as pyb.Pin.board.Name
///
///     x1_pin = pyb.Pin.board.X1
///
///     g = pyb.Pin(pyb.Pin.board.X1, pyb.Pin.IN)
///
/// CPU pins which correspond to the board pins are available
/// as `pyb.cpu.Name`. For the CPU pins, the names are the port letter
/// followed by the pin number. On the PYBv1.0, `pyb.Pin.board.X1` and
/// `pyb.Pin.cpu.B6` are the same pin.
///
/// You can also use strings:
///
///     g = pyb.Pin('X1', pyb.Pin.OUT_PP)
///
/// Users can add their own names:
///
66
67
///     MyMapperDict = { 'LeftMotorDir' : pyb.Pin.cpu.C12 }
///     pyb.Pin.dict(MyMapperDict)
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
///     g = pyb.Pin("LeftMotorDir", pyb.Pin.OUT_OD)
///
/// and can query mappings
///
///     pin = pyb.Pin("LeftMotorDir")
///
/// Users can also add their own mapping function:
///
///     def MyMapper(pin_name):
///        if pin_name == "LeftMotorDir":
///            return pyb.Pin.cpu.A0
///
///     pyb.Pin.mapper(MyMapper)
///
/// So, if you were to call: `pyb.Pin("LeftMotorDir", pyb.Pin.OUT_PP)`
/// then `"LeftMotorDir"` is passed directly to the mapper function.
///
/// To summarise, the following order determines how things get mapped into
/// an ordinal pin number:
///
/// 1. Directly specify a pin object
/// 2. User supplied mapping function
/// 3. User supplied mapping (object must be usable as a dictionary key)
/// 4. Supply a string which matches a board pin
/// 5. Supply a string which matches a CPU port/pin
///
/// You can set `pyb.Pin.debug(True)` to get some debug information about
/// how a particular object gets mapped to a pin.
96
97
98
99
100
101

// Pin class variables
STATIC mp_obj_t pin_class_mapper;
STATIC mp_obj_t pin_class_map_dict;
STATIC bool pin_class_debug;

102
void pin_init0(void) {
103
104
    pin_class_mapper = mp_const_none;
    pin_class_map_dict = mp_const_none;
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
    pin_class_debug = false;
}

// C API used to convert a user-supplied pin name into an ordinal pin number.
const pin_obj_t *pin_find(mp_obj_t user_obj) {
    const pin_obj_t *pin_obj;

    // If a pin was provided, then use it
    if (MP_OBJ_IS_TYPE(user_obj, &pin_type)) {
        pin_obj = user_obj;
        if (pin_class_debug) {
            printf("Pin map passed pin ");
            mp_obj_print((mp_obj_t)pin_obj, PRINT_STR);
            printf("\n");
        }
        return pin_obj;
    }

123
    if (pin_class_mapper != mp_const_none) {
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
        pin_obj = mp_call_function_1(pin_class_mapper, user_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.mapper didn't return a Pin object"));
            }
            if (pin_class_debug) {
                printf("Pin.mapper maps ");
                mp_obj_print(user_obj, PRINT_REPR);
                printf(" to ");
                mp_obj_print((mp_obj_t)pin_obj, PRINT_STR);
                printf("\n");
            }
            return pin_obj;
        }
        // The pin mapping function returned mp_const_none, fall through to
        // other lookup methods.
    }

142
    if (pin_class_map_dict != mp_const_none) {
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        mp_map_t *pin_map_map = mp_obj_dict_get_map(pin_class_map_dict);
        mp_map_elem_t *elem = mp_map_lookup(pin_map_map, user_obj, MP_MAP_LOOKUP);
        if (elem != NULL && elem->value != NULL) {
            pin_obj = elem->value;
            if (pin_class_debug) {
                printf("Pin.map_dict maps ");
                mp_obj_print(user_obj, PRINT_REPR);
                printf(" to ");
                mp_obj_print((mp_obj_t)pin_obj, PRINT_STR);
                printf("\n");
            }
            return pin_obj;
        }
    }

    // See if the pin name matches a board pin
159
    pin_obj = pin_find_named_pin(&pin_board_pins_locals_dict, user_obj);
160
161
162
163
164
165
166
167
168
169
170
171
    if (pin_obj) {
        if (pin_class_debug) {
            printf("Pin.board maps ");
            mp_obj_print(user_obj, PRINT_REPR);
            printf(" to ");
            mp_obj_print((mp_obj_t)pin_obj, PRINT_STR);
            printf("\n");
        }
        return pin_obj;
    }

    // See if the pin name matches a cpu pin
172
    pin_obj = pin_find_named_pin(&pin_cpu_pins_locals_dict, user_obj);
173
174
175
176
177
178
179
180
181
182
183
    if (pin_obj) {
        if (pin_class_debug) {
            printf("Pin.cpu maps ");
            mp_obj_print(user_obj, PRINT_REPR);
            printf(" to ");
            mp_obj_print((mp_obj_t)pin_obj, PRINT_STR);
            printf("\n");
        }
        return pin_obj;
    }

184
    nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "pin '%s' not a valid pin identifier", mp_obj_str_get_str(user_obj)));
185
186
}

187
188
/// \method __str__()
/// Return a string describing the pin object.
189
STATIC void pin_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
190
    pin_obj_t *self = self_in;
191

192
193
    // pin name
    print(env, "Pin(Pin.cpu.%s, mode=Pin.", qstr_str(self->name));
194
195

    uint32_t mode = pin_get_mode(self);
196

197
    if (mode == GPIO_MODE_ANALOG) {
198
199
200
        // analog
        print(env, "ANALOG)");

201
    } else {
202
203
204
        // IO mode
        bool af = false;
        qstr mode_qst;
205
        if (mode == GPIO_MODE_INPUT) {
206
207
208
209
210
            mode_qst = MP_QSTR_IN;
        } else if (mode == GPIO_MODE_OUTPUT_PP) {
            mode_qst = MP_QSTR_OUT_PP;
        } else if (mode == GPIO_MODE_OUTPUT_OD) {
            mode_qst = MP_QSTR_OUT_OD;
211
        } else {
212
            af = true;
213
            if (mode == GPIO_MODE_AF_PP) {
214
                mode_qst = MP_QSTR_AF_PP;
215
            } else {
216
                mode_qst = MP_QSTR_AF_OD;
217
            }
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
        }
        print(env, qstr_str(mode_qst)); // safe because mode_qst has no formating chars

        // pull mode
        qstr pull_qst = MP_QSTR_NULL;
        uint32_t pull = pin_get_pull(self);
        if (pull == GPIO_PULLUP) {
            pull_qst = MP_QSTR_PULL_UP;
        } else if (pull == GPIO_PULLDOWN) {
            pull_qst = MP_QSTR_PULL_DOWN;
        }
        if (pull_qst != MP_QSTR_NULL) {
            print(env, ", pull=Pin.%s", qstr_str(pull_qst));
        }

        // AF mode
        if (af) {
235
            mp_uint_t af_idx = pin_get_af(self);
236
237
238
            const pin_af_obj_t *af_obj = pin_find_af_by_index(self, af_idx);
            if (af_obj == NULL) {
                print(env, ", af=%d)", af_idx);
239
            } else {
240
                print(env, ", af=Pin.%s)", qstr_str(af_obj->name));
241
            }
242
243
        } else {
            print(env, ")");
244
245
        }
    }
246
247
}

248
STATIC mp_obj_t pin_obj_init_helper(const pin_obj_t *pin, uint n_args, const mp_obj_t *args, mp_map_t *kw_args);
249

250
251
252
/// \classmethod \constructor(id, ...)
/// Create a new Pin object associated with the id.  If additional arguments are given,
/// they are used to initialise the pin.  See `init`.
253
STATIC mp_obj_t pin_make_new(mp_obj_t self_in, uint n_args, uint n_kw, const mp_obj_t *args) {
254
    mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
255
256
257
258

    // Run an argument through the mapper and return the result.
    const pin_obj_t *pin = pin_find(args[0]);

259
    if (n_args > 1 || n_kw > 0) {
260
        // pin mode given, so configure this GPIO
261
262
263
        mp_map_t kw_args;
        mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
        pin_obj_init_helper(pin, n_args - 1, args + 1, &kw_args);
264
265
266
267
268
    }

    return (mp_obj_t)pin;
}

269
270
/// \classmethod mapper([fun])
/// Get or set the pin mapper function.
271
272
273
274
275
276
277
278
279
280
STATIC mp_obj_t pin_mapper(uint n_args, mp_obj_t *args) {
    if (n_args > 1) {
        pin_class_mapper = args[1];
        return mp_const_none;
    }
    return pin_class_mapper;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_mapper_fun_obj, 1, 2, pin_mapper);
STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(pin_mapper_obj, (mp_obj_t)&pin_mapper_fun_obj);

281
282
/// \classmethod dict([dict])
/// Get or set the pin mapper dictionary.
283
284
285
286
287
288
289
290
291
292
STATIC mp_obj_t pin_map_dict(uint n_args, mp_obj_t *args) {
    if (n_args > 1) {
        pin_class_map_dict = args[1];
        return mp_const_none;
    }
    return pin_class_map_dict;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_map_dict_fun_obj, 1, 2, pin_map_dict);
STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(pin_map_dict_obj, (mp_obj_t)&pin_map_dict_fun_obj);

293
/// \classmethod af_list()
294
295
296
297
298
299
300
301
302
303
304
305
306
/// Returns an array of alternate functions available for this pin.
STATIC mp_obj_t pin_af_list(mp_obj_t self_in) {
    pin_obj_t *self = self_in;
    mp_obj_t result = mp_obj_new_list(0, NULL);

    const pin_af_obj_t *af = self->af;
    for (mp_uint_t i = 0; i < self->num_af; i++, af++) {
        mp_obj_list_append(result, (mp_obj_t)af);
    }
    return result;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_af_list_obj, pin_af_list);

307
308
/// \classmethod debug([state])
/// Get or set the debugging state (`True` or `False` for on or off).
309
310
311
312
313
314
315
316
317
318
STATIC mp_obj_t pin_debug(uint n_args, mp_obj_t *args) {
    if (n_args > 1) {
        pin_class_debug = mp_obj_is_true(args[1]);
        return mp_const_none;
    }
    return MP_BOOL(pin_class_debug);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_debug_fun_obj, 1, 2, pin_debug);
STATIC MP_DEFINE_CONST_CLASSMETHOD_OBJ(pin_debug_obj, (mp_obj_t)&pin_debug_fun_obj);

319
/// \method init(mode, pull=Pin.PULL_NONE, af=-1)
320
321
322
323
324
325
326
327
328
329
330
331
332
/// Initialise the pin:
///
///   - `mode` can be one of:
///     - `Pin.IN` - configure the pin for input;
///     - `Pin.OUT_PP` - configure the pin for output, with push-pull control;
///     - `Pin.OUT_OD` - configure the pin for output, with open-drain control;
///     - `Pin.AF_PP` - configure the pin for alternate function, pull-pull;
///     - `Pin.AF_OD` - configure the pin for alternate function, open-drain;
///     - `Pin.ANALOG` - configure the pin for analog.
///   - `pull` can be one of:
///     - `Pin.PULL_NONE` - no pull up or down resistors;
///     - `Pin.PULL_UP` - enable the pull-up resistor;
///     - `Pin.PULL_DOWN` - enable the pull-down resistor.
333
334
///   - when mode is Pin.AF_PP or Pin.AF_OD, then af can be the index or name
///     of one of the alternate functions associated with a pin.
335
336
///
/// Returns: `None`.
337
338
339
STATIC const mp_arg_t pin_init_args[] = {
    { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT },
    { MP_QSTR_pull,                   MP_ARG_INT, {.u_int = GPIO_NOPULL}},
340
    { MP_QSTR_af,                     MP_ARG_INT, {.u_int = -1}},
341
342
343
344
345
346
347
};
#define PIN_INIT_NUM_ARGS MP_ARRAY_SIZE(pin_init_args)

STATIC mp_obj_t pin_obj_init_helper(const pin_obj_t *self, uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    // parse args
    mp_arg_val_t vals[PIN_INIT_NUM_ARGS];
    mp_arg_parse_all(n_args, args, kw_args, PIN_INIT_NUM_ARGS, pin_init_args, vals);
348
349

    // get io mode
350
    uint mode = vals[0].u_int;
351
352
353
354
355
    if (!IS_GPIO_MODE(mode)) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid pin mode: %d", mode));
    }

    // get pull mode
356
357
358
359
360
361
    uint pull = vals[1].u_int;
    if (!IS_GPIO_PULL(pull)) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid pin pull: %d", pull));
    }

    // get af (alternate function)
362
363
364
    mp_int_t af = vals[2].u_int;
    if ((mode == GPIO_MODE_AF_PP || mode == GPIO_MODE_AF_OD) && !IS_GPIO_AF(af)) {
        nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid pin af: %d", af));
365
    }
366

367
368
    // enable the peripheral clock for the port of this pin
    switch (self->port) {
369
        #ifdef __GPIOA_CLK_ENABLE
370
        case PORT_A: __GPIOA_CLK_ENABLE(); break;
371
372
        #endif
        #ifdef __GPIOB_CLK_ENABLE
373
        case PORT_B: __GPIOB_CLK_ENABLE(); break;
374
375
        #endif
        #ifdef __GPIOC_CLK_ENABLE
376
        case PORT_C: __GPIOC_CLK_ENABLE(); break;
377
378
        #endif
        #ifdef __GPIOD_CLK_ENABLE
379
        case PORT_D: __GPIOD_CLK_ENABLE(); break;
380
        #endif
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
        #ifdef __GPIOE_CLK_ENABLE
        case PORT_E: __GPIOE_CLK_ENABLE(); break;
        #endif
        #ifdef __GPIOF_CLK_ENABLE
        case PORT_F: __GPIOF_CLK_ENABLE(); break;
        #endif
        #ifdef __GPIOG_CLK_ENABLE
        case PORT_G: __GPIOG_CLK_ENABLE(); break;
        #endif
        #ifdef __GPIOH_CLK_ENABLE
        case PORT_H: __GPIOH_CLK_ENABLE(); break;
        #endif
        #ifdef __GPIOI_CLK_ENABLE
        case PORT_I: __GPIOI_CLK_ENABLE(); break;
        #endif
        #ifdef __GPIOJ_CLK_ENABLE
        case PORT_J: __GPIOJ_CLK_ENABLE(); break;
        #endif
    }

401
402
403
404
405
406
    // configure the GPIO as requested
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.Pin = self->pin_mask;
    GPIO_InitStructure.Mode = mode;
    GPIO_InitStructure.Pull = pull;
    GPIO_InitStructure.Speed = GPIO_SPEED_FAST;
407
    GPIO_InitStructure.Alternate = af;
408
409
410
411
    HAL_GPIO_Init(self->gpio, &GPIO_InitStructure);

    return mp_const_none;
}
412

413
414
415
416
STATIC mp_obj_t pin_obj_init(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) {
    return pin_obj_init_helper(args[0], n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pin_init_obj, 1, pin_obj_init);
417

418
419
420
421
422
423
424
/// \method value([value])
/// Get or set the digital logic level of the pin:
///
///   - With no argument, return 0 or 1 depending on the logic level of the pin.
///   - With `value` given, set the logic level of the pin.  `value` can be
///   anything that converts to a boolean.  If it converts to `True`, the pin
///   is set high, otherwise it is set low.
425
426
427
428
STATIC mp_obj_t pin_value(uint n_args, mp_obj_t *args) {
    pin_obj_t *self = args[0];
    if (n_args == 1) {
        // get pin
Dave Hylands's avatar
Dave Hylands committed
429
        return MP_OBJ_NEW_SMALL_INT(GPIO_read_pin(self->gpio, self->pin));
430
431
432
    } else {
        // set pin
        if (mp_obj_is_true(args[1])) {
Dave Hylands's avatar
Dave Hylands committed
433
            GPIO_set_pin(self->gpio, self->pin_mask);
434
        } else {
Dave Hylands's avatar
Dave Hylands committed
435
            GPIO_clear_pin(self->gpio, self->pin_mask);
436
437
438
439
440
441
        }
        return mp_const_none;
    }
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_value_obj, 1, 2, pin_value);

442
443
/// \method low()
/// Set the pin to a low logic level.
444
445
STATIC mp_obj_t pin_low(mp_obj_t self_in) {
    pin_obj_t *self = self_in;
Dave Hylands's avatar
Dave Hylands committed
446
    GPIO_clear_pin(self->gpio, self->pin_mask);;
447
448
449
450
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_low_obj, pin_low);

451
452
/// \method high()
/// Set the pin to a high logic level.
453
454
STATIC mp_obj_t pin_high(mp_obj_t self_in) {
    pin_obj_t *self = self_in;
Dave Hylands's avatar
Dave Hylands committed
455
    GPIO_set_pin(self->gpio, self->pin_mask);;
456
457
458
459
    return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_high_obj, pin_high);

460
461
/// \method name()
/// Get the pin name.
462
STATIC mp_obj_t pin_name(mp_obj_t self_in) {
463
    pin_obj_t *self = self_in;
464
    return MP_OBJ_NEW_QSTR(self->name);
465
}
466
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_name_obj, pin_name);
467

468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/// \method names()
/// Returns the cpu and board names for this pin.
STATIC mp_obj_t pin_names(mp_obj_t self_in) {
    pin_obj_t *self = self_in;
    mp_obj_t result = mp_obj_new_list(0, NULL);
    mp_obj_list_append(result, MP_OBJ_NEW_QSTR(self->name));

    mp_map_t *map = mp_obj_dict_get_map((mp_obj_t)&pin_board_pins_locals_dict);
    mp_map_elem_t *elem = map->table;

    for (mp_uint_t i = 0; i < map->used; i++, elem++) {
        if (elem->value == self) {
            mp_obj_list_append(result, elem->key);
        }
    }
    return result;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_names_obj, pin_names);

487
488
/// \method port()
/// Get the pin port.
489
STATIC mp_obj_t pin_port(mp_obj_t self_in) {
490
    pin_obj_t *self = self_in;
491
    return MP_OBJ_NEW_SMALL_INT(self->port);
492
}
493
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_port_obj, pin_port);
494

495
496
/// \method pin()
/// Get the pin number.
497
STATIC mp_obj_t pin_pin(mp_obj_t self_in) {
498
    pin_obj_t *self = self_in;
499
    return MP_OBJ_NEW_SMALL_INT(self->pin);
500
}
501
502
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_pin_obj, pin_pin);

503
504
505
506
507
508
509
510
/// \method gpio()
/// Returns the base address of the GPIO block associated with this pin.
STATIC mp_obj_t pin_gpio(mp_obj_t self_in) {
    pin_obj_t *self = self_in;
    return MP_OBJ_NEW_SMALL_INT((mp_int_t)self->gpio);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_gpio_obj, pin_gpio);

511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
/// \method mode()
/// Returns the currently configured mode of the pin. The integer returned
/// will match one of the allowed constants for the mode argument to the init
/// function.
STATIC mp_obj_t pin_mode(mp_obj_t self_in) {
    return MP_OBJ_NEW_SMALL_INT(pin_get_mode(self_in));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_mode_obj, pin_mode);

/// \method pull()
/// Returns the currently configured pull of the pin. The integer returned
/// will match one of the allowed constants for the pull argument to the init
/// function.
STATIC mp_obj_t pin_pull(mp_obj_t self_in) {
    return MP_OBJ_NEW_SMALL_INT(pin_get_pull(self_in));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_pull_obj, pin_pull);

/// \method af()
/// Returns the currently configured af of the pin. The integer returned
/// will match one of the allowed constants for the af argument to the init
/// function.
STATIC mp_obj_t pin_af(mp_obj_t self_in) {
    return MP_OBJ_NEW_SMALL_INT(pin_get_af(self_in));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_af_obj, pin_af);

538
539
STATIC const mp_map_elem_t pin_locals_dict_table[] = {
    // instance methods
540
    { MP_OBJ_NEW_QSTR(MP_QSTR_init),    (mp_obj_t)&pin_init_obj },
541
542
543
544
    { MP_OBJ_NEW_QSTR(MP_QSTR_value),   (mp_obj_t)&pin_value_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_low),     (mp_obj_t)&pin_low_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_high),    (mp_obj_t)&pin_high_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_name),    (mp_obj_t)&pin_name_obj },
545
546
    { MP_OBJ_NEW_QSTR(MP_QSTR_names),   (mp_obj_t)&pin_names_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_af_list), (mp_obj_t)&pin_af_list_obj },
547
548
    { MP_OBJ_NEW_QSTR(MP_QSTR_port),    (mp_obj_t)&pin_port_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_pin),     (mp_obj_t)&pin_pin_obj },
549
    { MP_OBJ_NEW_QSTR(MP_QSTR_gpio),    (mp_obj_t)&pin_gpio_obj },
550
551
552
    { MP_OBJ_NEW_QSTR(MP_QSTR_mode),    (mp_obj_t)&pin_mode_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_pull),    (mp_obj_t)&pin_pull_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_af),      (mp_obj_t)&pin_af_obj },
553
554
555
556
557

    // class methods
    { MP_OBJ_NEW_QSTR(MP_QSTR_mapper),  (mp_obj_t)&pin_mapper_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_dict),    (mp_obj_t)&pin_map_dict_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_debug),   (mp_obj_t)&pin_debug_obj },
558

559
    // class attributes
560
561
    { MP_OBJ_NEW_QSTR(MP_QSTR_board),   (mp_obj_t)&pin_board_pins_obj_type },
    { MP_OBJ_NEW_QSTR(MP_QSTR_cpu),     (mp_obj_t)&pin_cpu_pins_obj_type },
562

563
    // class constants
564
565
566
567
568
569
    /// \constant IN - initialise the pin to input mode
    /// \constant OUT_PP - initialise the pin to output mode with a push-pull drive
    /// \constant OUT_OD - initialise the pin to output mode with an open-drain drive
    /// \constant PULL_NONE - don't enable any pull up or down resistors on the pin
    /// \constant PULL_UP - enable the pull-up resistor on the pin
    /// \constant PULL_DOWN - enable the pull-down resistor on the pin
570
571
572
573
574
575
576
577
578
    { MP_OBJ_NEW_QSTR(MP_QSTR_IN),        MP_OBJ_NEW_SMALL_INT(GPIO_MODE_INPUT) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_OUT_PP),    MP_OBJ_NEW_SMALL_INT(GPIO_MODE_OUTPUT_PP) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_OUT_OD),    MP_OBJ_NEW_SMALL_INT(GPIO_MODE_OUTPUT_OD) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_AF_PP),     MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_PP) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_AF_OD),     MP_OBJ_NEW_SMALL_INT(GPIO_MODE_AF_OD) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_ANALOG),    MP_OBJ_NEW_SMALL_INT(GPIO_MODE_ANALOG) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_PULL_NONE), MP_OBJ_NEW_SMALL_INT(GPIO_NOPULL) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_PULL_UP),   MP_OBJ_NEW_SMALL_INT(GPIO_PULLUP) },
    { MP_OBJ_NEW_QSTR(MP_QSTR_PULL_DOWN), MP_OBJ_NEW_SMALL_INT(GPIO_PULLDOWN) },
579

580
#include "genhdr/pins_af_const.h"
581
582
};

583
584
585
STATIC MP_DEFINE_CONST_DICT(pin_locals_dict, pin_locals_dict_table);

const mp_obj_type_t pin_type = {
586
587
    { &mp_type_type },
    .name = MP_QSTR_Pin,
588
589
590
    .print = pin_print,
    .make_new = pin_make_new,
    .locals_dict = (mp_obj_t)&pin_locals_dict,
591
592
};

593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/// \moduleref pyb
/// \class PinAF - Pin Alternate Functions
///
/// A Pin represents a physical pin on the microcprocessor. Each pin
/// can have a variety of functions (GPIO, I2C SDA, etc). Each PinAF
/// object represents a particular function for a pin.
///
/// Usage Model:
///
///     x3 = pyb.Pin.board.X3
///     x3_af = x3.af_list()
///
/// x3_af will now contain an array of PinAF objects which are availble on
/// pin X3.
///
/// For the pyboard, x3_af would contain:
///     [Pin.AF1_TIM2, Pin.AF2_TIM5, Pin.AF3_TIM9, Pin.AF7_USART2]
///
/// Normally, each peripheral would configure the af automatically, but sometimes
/// the same function is available on multiple pins, and having more control
/// is desired.
///
/// To configure X3 to expose TIM2_CH3, you could use:
///    pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=pyb.Pin.AF1_TIM2)
/// or:
///    pin = pyb.Pin(pyb.Pin.board.X3, mode=pyb.Pin.AF_PP, af=1)

/// \method __str__()
/// Return a string describing the alternate function.
622
STATIC void pin_af_obj_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
623
    pin_af_obj_t *self = self_in;
624
    print(env, "Pin.%s", qstr_str(self->name));
625
626
}

627
628
629
630
631
632
633
634
/// \method index()
/// Return the alternate function index.
STATIC mp_obj_t pin_af_index(mp_obj_t self_in) {
    pin_af_obj_t *af = self_in;
    return MP_OBJ_NEW_SMALL_INT(af->idx);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_af_index_obj, pin_af_index);

635
/// \method name()
636
637
638
639
640
641
642
/// Return the name of the alternate function.
STATIC mp_obj_t pin_af_name(mp_obj_t self_in) {
    pin_af_obj_t *af = self_in;
    return MP_OBJ_NEW_QSTR(af->name);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_af_name_obj, pin_af_name);

643
/// \method reg()
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
/// Return the base register associated with the peripheral assigned to this
/// alternate function. For example, if the alternate function were TIM2_CH3
/// this would return stm.TIM2
STATIC mp_obj_t pin_af_reg(mp_obj_t self_in) {
    pin_af_obj_t *af = self_in;
    return MP_OBJ_NEW_SMALL_INT((mp_uint_t)af->reg);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_af_reg_obj, pin_af_reg);

STATIC const mp_map_elem_t pin_af_locals_dict_table[] = {
    { MP_OBJ_NEW_QSTR(MP_QSTR_index),   (mp_obj_t)&pin_af_index_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_name),    (mp_obj_t)&pin_af_name_obj },
    { MP_OBJ_NEW_QSTR(MP_QSTR_reg),     (mp_obj_t)&pin_af_reg_obj },
};
STATIC MP_DEFINE_CONST_DICT(pin_af_locals_dict, pin_af_locals_dict_table);

660
const mp_obj_type_t pin_af_type = {
661
662
663
    { &mp_type_type },
    .name = MP_QSTR_PinAF,
    .print = pin_af_obj_print,
664
    .locals_dict = (mp_obj_t)&pin_af_locals_dict,
665
};