glennrub 002f7d1ad7 nrf: Replace custom-HAL with nrfx-HAL
Summarized this squashed PR replaces the hal/ folder in the port. This has been replaced the official
HAL layer from Nordic Semiconductor; https://github.com/NordicSemiconductor/nrfx.

A Git submodule has been added under lib/nrfx, for the nrfx dependency.

The drivers / modules has been updated to use this new HAL layer; nrfx at v1.0.0.

Also, header files and system files for nrf51/nrf52x chip variants has been deleted from the device/ folder, only keeping back the startup files written in C. All other files are now fetched from nrfx.

3 new header files in the ports/nrf/ folder has been added to configure nrfx (nrfx_config.h), logging (nrfx_log.h) and glue nrfx together with the drivers and modules from micropython (nrfx_glue.h).

The PR has been a joint effort from @aykevl (Ayke van Laethem) and @glennrub.

For reference, the commit log will be kept to get an overview of the changes done:

* ports/nrf: Initial commit for moving hal to Nordic Semiconductor BSD-3 licensed nrfx-hal.

* ports/nrf: Adding nrfx, Nordic Semiconductor BSD-3 hal layer, as git submodule checked out at lib/nrfx.

* ports/nrf/modules/machine/uart: Fixing bug which set hwfc to parity excluded, always resulting in no flow control, hence corrupted output. Also adding an extra loop on uart_tx_char to prevent any tx when any ongoing tx is in progress.

* ports/nrf/i2c: Moving I2C over to nrfx driver.

* ports/nrf/modules/machine/i2c: Alignment. Renaming print function param 'o' to 'self_in'

* ports/nrf/spi: Updating SPI machine module to use nrfx drivers.

* ports/nrf: Renaming modules/machine/rtc.c/.h to rtcounter.c/.h to not confuse the peripheral with Real-Time Clock:

* ports/nrf: Updating various files after renaming machine module RTC to RTCounter.

* ports/nrf: Renaming RTC to RTCounter in modmachine globals dict table. Also updating object type name to reflect new module name.

* ports/nrf: Fixing leftovers after renaming rtc to rtcounter.

* ports/nrf: Early untested adoption of nrfx_rtc in RTCounter. Untested.

* nrf/modules/machine/i2c: Improve keyword argument handling

* ports/nrf/modules/temp: Updating Temp machine module to use nrfx defined hal nrf_temp.h. Moving logic of BLE stack awareness to machine module.

* ports/nrf/boards/pca10040: Enable machine Temp module.

* nrf/modules/machine/rtcounter: Remove magic constants.

* ports/nrf: Adding base support for nrfx module logging. Adding option to disable logging of UART as it might log its own setup over UART while the peripheral is not yet set up. Logging of UART could make sense if other transport of log is used.

* ports/nrf: updating nrfx_log.h with more correct parenthisis on macro grouping.

* ports/nrf: Updating nrfx logging with configuration to disable logging of UART module. The pattern can be used to turn off other modules as well. However, for now UART is the only module locking itself by logging before the peripheral is configured. Logging is turned off by default, can be enabled in nrfx_config.h by setting NRFX_LOG_ENABLED=1.

* ports/nrf/modules/random: Updating modrandom to use nrfx hal for rng. Not using nrfx-driver for this peripheral as its blocking mode would do the trick on RNG. Moving softdevice aware code from legacy hal to modrandom.c.

* nrf: Enable Peripheral Resource Sharing.

This enables TWI and SPI to be enabled at the same time.

* nrf/Makefile: Define MCU sub variant (e.g. NRF51822/NRF51422)

* nrf: Port TIMER peripheral to nrfx HAL.

* nrf/modules/machine/uart: Optimize UART module

For a nRF51, this results in a size reduction of:
.text: -68 bytes
.data: -56 bytes

* nrf/modules/machine/uart: Don't use magic index numbers.

* nrf/modules/machine/uart: Fix off-by-one error.

For nrf51:
.text: -40 bytes

* nrf/modules/machine/rtcounter: Update for nrfx HAL.

* nrf/modules/machine/i2c: Reduce RAM consumption.

Reductions for the nrf51:
flash: -108 bytes
RAM:   -72 bytes

* nrf/mpconfigport: Avoid unnecessary root pointers.

This saves 92 bytes of RAM.

* nrf: Support SoftDevice with nrfx HAL.

* nrf: Add NVMC peripheral (microbitfs) support.

There is no support yet for a SoftDevice.

It also fixes a potentially serious bug in start_index generation.

* nrf/modules/machine/spi: Optimize SPI peripheral.

nrf51:
text: -340 bytes
data: -72  bytes

nrf52:
text: -352 bytes
data: -108 bytes

* nrf/modules/random: Forgot to commit header file.

* nrf: Make nrfx_config.h universal for all boards.

* nrf: Use SoftDevice API for flash access when built for SD

* nrf/drivers/bluetooth: Remove legacy HAL driver includes.

These were not used anymore so can be removed.

* ports/nrf/microbit: Port microbit targets to nrfx HAL

Initial port of microbit modules to use nrfx HAL layer.
Tested display/image and modmusic on micro:bit to verify that
softpwm and ticker for nrf51 is working as expected.

Changing IRQ priority on timer to priority 2, as 1 might collide if
used side by side of SD110 BLE stack.

The patch reserves Timer1 peripheral compile time. This is not ideal
and should be resolved in seperate task.

* nrf/boards/microbit: Remove custom nrfx_config.h from microbit target, adding disablement of timer1 if softpwm is enabled.

* nrf/adc: Update ADC module to use nrfx

* nrf/modules/machine/pwm: Updating machine PWM module to use nrfx HAL driver.

examples/nrf52_pwm.py and examples/nrf52_servo.py tested on pca10040.

* nrf: Removing hal folder and boards nrf5x_hal_conf.h headers.

* nrf/nrfx_glue: Adding direct NVIC access for S110 BLE stack

If SoftDevice s110 has not yet been initialized, the IRQ will not be forwarded to
the application using the sd_nvic* function calls. Hence, direct access to cmsi
nvic functions are used instead if SoftDevice is not enabled.

* nrf/drivers/ticker: Setting IRQ priority 3 on Timer1

SoftDevice fails to initilize if Timer1 has been configured to priority
level 2 before enabling the SD. The timer is set to priority 1, higher than BLE
stack in order to provide better quality of music rendering when used with the
music module. This might be too high, time will show.

* nrf/examples: Updating ubluepy_temp after moving RTCounter to nrfx.

* nrf: delete duplicate files from device folder which can be located in nrfx/mdk.

* nrf/Makefile: Fetch system files from nrfx.

Testing on each device sub-variant to figure out which system file to
use. Reason for this is that nrf52.c is actually defining nrf52832.

Removing NRF_DEFINES parameter setting the device in use into the
same sub-variant test, as NRF52 is unique to nrf52832 when using nrfx.
Without this exclusion of -DNRF52 in compilation for nrf52840, the
device will be interpreted as a nrf52, hence nrf52832.

Also, changing name on variable SRC_NRF_HAL to SRC_NRFX_HAL to
explicitly tell the origin of the file.

* nrf: Updating device #ifdefs to be more open to non-nrf51 targets.

* nrf/modules/machine/uart: Removing second instance of UART for nrf52840 as it only has one non-DMA variant.

* nrf/device: Removing system files as these are now used from nrfx/mdk

* nrf: Moving startup files in device one level up as there is no need for deep hierarchy.

* nrf: Use NRF52_SERIES defined in nrfx/mdk/nrf.h as define value when testing for both nrf52(832) and nrf52840 variants.

* nrf/modules/machine/uart: Enable UART RX by default

Enable rx by default after intiialization of the peripheral.
Else, the nrfx driver will re-enable rx for each byte read
on uart REPL, clearing the EVENT_RXDRDY before second byte,
which again will make second byte get lost and read will get stuck.

This happens if the bytes are transmitted nrf(51) while still
processing the previous byte. Not seen on nrf52, but should
also become an issue at higher speeds.

This patch sets rx to always be enabled. Hence, not clearing the event
between read bytes, and it will be able to detect next byte recieved
upon finishing the first.

* nrf/modules/machine/timer: Fixing defines excluding Timer1 if ticker/softpwm is used.

* nrf: Switching import form mpconfigboard.h to mpconfigport.h in nrfx_config.h as mpconfigboard.h might define default values for defines not set by board specific header.

* nrf/modules/machine/i2c: nrfx integration fixes

Increasing speed to 400K.

Returning Address NACK's as MP error code; MP_ENODEV.

Returning MP_ETIMEOUT on all other error codes from TWI nrfx driver
except the ANACK.

Enabling and disabling the TWI peripheral before and after each transaction.

* nrf/examples: Updating ssd1306_mod.py to split framebuffer transfer into multiple chunks

* nrf/modules/machine/i2c: Return MP_EIO error if Data NACK occurs.

* nrf: Addressing review comments.

* nrf: Updating git submodule and users to nrfx v1.0.0.

* nrf/modules/machine/adc: Update adc module to follow v1.0.0 nrfx API.

* nrf/modules/machine/spi: Implement init and deinit functions

Extending SPI objects with a config member such that
configuration can be kept between new() and init().

Moving initialization done in new() to common init
function shared between the module functions.

If SPI is already configured, the SPI peripheral will
be uninitialized before initalized again.

Adding logic to handle initialization of polarity and
phase. As well, updating default speed to 1M from 500K.

* nrf/modules/machine: Removing unused nrfx includes in machine module header files
2018-07-18 17:12:26 +10:00

713 lines
25 KiB
C

/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013, 2014 Damien P. George
* Copyright (c) 2016 Glenn Ruben Bakke
*
* 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.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/mphal.h"
#include "pin.h"
#include "nrf_gpio.h"
/// \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:
///
/// MyMapperDict = { 'LeftMotorDir' : pyb.Pin.cpu.C12 }
/// pyb.Pin.dict(MyMapperDict)
/// 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.
#define PIN_DEBUG (0)
// Pin class variables
#if PIN_DEBUG
STATIC bool pin_class_debug;
#else
#define pin_class_debug (0)
#endif
void pin_init0(void) {
MP_STATE_PORT(pin_class_mapper) = mp_const_none;
MP_STATE_PORT(pin_class_map_dict) = mp_const_none;
#if PIN_DEBUG
pin_class_debug = false;
#endif
}
// 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;
}
if (MP_STATE_PORT(pin_class_mapper) != mp_const_none) {
pin_obj = mp_call_function_1(MP_STATE_PORT(pin_class_mapper), user_obj);
if (pin_obj != mp_const_none) {
if (!MP_OBJ_IS_TYPE(pin_obj, &pin_type)) {
mp_raise_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.
}
if (MP_STATE_PORT(pin_class_map_dict) != mp_const_none) {
mp_map_t *pin_map_map = mp_obj_dict_get_map(MP_STATE_PORT(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
pin_obj = pin_find_named_pin(&pin_board_pins_locals_dict, user_obj);
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
pin_obj = pin_find_named_pin(&pin_cpu_pins_locals_dict, user_obj);
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;
}
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)));
}
/// \method __str__()
/// Return a string describing the pin object.
STATIC void pin_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
pin_obj_t *self = self_in;
// pin name
mp_printf(print, "Pin(Pin.cpu.%q, mode=Pin.", self->name);
mp_printf(print, "port=0x%x, ", self->port);
mp_printf(print, "pin=0x%x, ", self->pin);
mp_printf(print, "pin_mask=0x%x,", self->pin_mask);
/*
uint32_t mode = pin_get_mode(self);
if (mode == GPIO_MODE_ANALOG) {
// analog
mp_print_str(print, "ANALOG)");
} else {
// IO mode
bool af = false;
qstr mode_qst;
if (mode == GPIO_MODE_INPUT) {
mode_qst = MP_QSTR_IN;
} else if (mode == GPIO_MODE_OUTPUT_PP) {
mode_qst = MP_QSTR_OUT;
} else if (mode == GPIO_MODE_OUTPUT_OD) {
mode_qst = MP_QSTR_OPEN_DRAIN;
} else {
af = true;
if (mode == GPIO_MODE_AF_PP) {
mode_qst = MP_QSTR_ALT;
} else {
mode_qst = MP_QSTR_ALT_OPEN_DRAIN;
}
}
mp_print_str(print, qstr_str(mode_qst));
// 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) {
mp_printf(print, ", pull=Pin.%q", pull_qst);
}
// AF mode
if (af) {
mp_uint_t af_idx = pin_get_af(self);
const pin_af_obj_t *af_obj = pin_find_af_by_index(self, af_idx);
if (af_obj == NULL) {
mp_printf(print, ", af=%d)", af_idx);
} else {
mp_printf(print, ", af=Pin.%q)", af_obj->name);
}
} else {
*/
mp_print_str(print, ")");
/* }
}*/
}
STATIC mp_obj_t pin_obj_init_helper(const pin_obj_t *pin, mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args);
/// \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`.
STATIC mp_obj_t pin_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
// Run an argument through the mapper and return the result.
const pin_obj_t *pin = pin_find(args[0]);
if (n_args > 1 || n_kw > 0) {
// pin mode given, so configure this GPIO
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);
}
return (mp_obj_t)pin;
}
// fast method for getting/setting pin value
STATIC mp_obj_t pin_call(mp_obj_t self_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 0, 1, false);
pin_obj_t *self = self_in;
if (n_args == 0) {
// get pin
return MP_OBJ_NEW_SMALL_INT(mp_hal_pin_read(self));
} else {
// set pin
mp_hal_pin_write(self, mp_obj_is_true(args[0]));
return mp_const_none;
}
}
STATIC mp_obj_t pin_off(mp_obj_t self_in) {
pin_obj_t *self = self_in;
mp_hal_pin_low(self);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_off_obj, pin_off);
STATIC mp_obj_t pin_on(mp_obj_t self_in) {
pin_obj_t *self = self_in;
mp_hal_pin_high(self);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_on_obj, pin_on);
/// \classmethod mapper([fun])
/// Get or set the pin mapper function.
STATIC mp_obj_t pin_mapper(mp_uint_t n_args, const mp_obj_t *args) {
if (n_args > 1) {
MP_STATE_PORT(pin_class_mapper) = args[1];
return mp_const_none;
}
return MP_STATE_PORT(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);
/// \classmethod dict([dict])
/// Get or set the pin mapper dictionary.
STATIC mp_obj_t pin_map_dict(mp_uint_t n_args, const mp_obj_t *args) {
if (n_args > 1) {
MP_STATE_PORT(pin_class_map_dict) = args[1];
return mp_const_none;
}
return MP_STATE_PORT(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);
/// \classmethod af_list()
/// 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);
#if PIN_DEBUG
/// \classmethod debug([state])
/// Get or set the debugging state (`True` or `False` for on or off).
STATIC mp_obj_t pin_debug(mp_uint_t n_args, const mp_obj_t *args) {
if (n_args > 1) {
pin_class_debug = mp_obj_is_true(args[1]);
return mp_const_none;
}
return mp_obj_new_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);
#endif
// init(mode, pull=None, af=-1, *, value, alt)
STATIC mp_obj_t pin_obj_init_helper(const pin_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_mode, MP_ARG_REQUIRED | MP_ARG_INT },
{ MP_QSTR_pull, MP_ARG_OBJ, {.u_obj = mp_const_none}},
{ MP_QSTR_af, MP_ARG_INT, {.u_int = -1}}, // legacy
{ MP_QSTR_value, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}},
{ MP_QSTR_alt, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1}},
};
// parse args
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);
// get pull mode
nrf_gpio_pin_pull_t pull = NRF_GPIO_PIN_NOPULL;
if (args[1].u_obj != mp_const_none) {
pull = (nrf_gpio_pin_pull_t)mp_obj_get_int(args[1].u_obj);
}
// if given, set the pin value before initialising to prevent glitches
if (args[3].u_obj != MP_OBJ_NULL) {
mp_hal_pin_write(self, mp_obj_is_true(args[3].u_obj));
}
// get io mode
nrf_gpio_pin_dir_t mode = (nrf_gpio_pin_dir_t)args[0].u_int;
// Connect input or not
nrf_gpio_pin_input_t input = (mode == NRF_GPIO_PIN_DIR_INPUT) ? NRF_GPIO_PIN_INPUT_CONNECT
: NRF_GPIO_PIN_INPUT_DISCONNECT;
if (mode == NRF_GPIO_PIN_DIR_OUTPUT || mode == NRF_GPIO_PIN_DIR_INPUT) {
nrf_gpio_cfg(self->pin,
mode,
input,
pull,
NRF_GPIO_PIN_S0S1,
NRF_GPIO_PIN_NOSENSE);
} else {
nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid pin mode: %d", mode));
}
return mp_const_none;
}
STATIC mp_obj_t pin_obj_init(mp_uint_t 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);
}
MP_DEFINE_CONST_FUN_OBJ_KW(pin_init_obj, 1, pin_obj_init);
/// \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.
STATIC mp_obj_t pin_value(mp_uint_t n_args, const mp_obj_t *args) {
return pin_call(args[0], n_args - 1, 0, args + 1);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_value_obj, 1, 2, pin_value);
/// \method low()
/// Set the pin to a low logic level.
STATIC mp_obj_t pin_low(mp_obj_t self_in) {
pin_obj_t *self = self_in;
mp_hal_pin_low(self);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_low_obj, pin_low);
/// \method high()
/// Set the pin to a high logic level.
STATIC mp_obj_t pin_high(mp_obj_t self_in) {
pin_obj_t *self = self_in;
mp_hal_pin_high(self);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_high_obj, pin_high);
/// \method name()
/// Get the pin name.
STATIC mp_obj_t pin_name(mp_obj_t self_in) {
pin_obj_t *self = self_in;
return MP_OBJ_NEW_QSTR(self->name);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_name_obj, pin_name);
/// \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);
/// \method port()
/// Get the pin port.
STATIC mp_obj_t pin_port(mp_obj_t self_in) {
pin_obj_t *self = self_in;
return MP_OBJ_NEW_SMALL_INT(self->port);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_port_obj, pin_port);
/// \method pin()
/// Get the pin number.
STATIC mp_obj_t pin_pin(mp_obj_t self_in) {
pin_obj_t *self = self_in;
return MP_OBJ_NEW_SMALL_INT(self->pin);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_pin_obj, pin_pin);
/// \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);
/// \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_const_none; // TODO: 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_const_none; // TODO: 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 alternate-function 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_const_none; // TODO: MP_OBJ_NEW_SMALL_INT(pin_get_af(self_in));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_af_obj, pin_af);
/*
STATIC mp_obj_t pin_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_handler, MP_ARG_OBJ, {.u_obj = mp_const_none} },
{ MP_QSTR_trigger, MP_ARG_INT, {.u_int = HAL_GPIO_POLARITY_EVENT_TOGGLE} },
{ MP_QSTR_wake, MP_ARG_BOOL, {.u_bool = false} },
};
pin_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
(void)self;
// return the irq object
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pin_irq_obj, 1, pin_irq);
*/
STATIC const mp_rom_map_elem_t pin_locals_dict_table[] = {
// instance methods
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pin_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&pin_value_obj) },
{ MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&pin_off_obj) },
{ MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&pin_on_obj) },
{ MP_ROM_QSTR(MP_QSTR_low), MP_ROM_PTR(&pin_low_obj) },
{ MP_ROM_QSTR(MP_QSTR_high), MP_ROM_PTR(&pin_high_obj) },
{ MP_ROM_QSTR(MP_QSTR_name), MP_ROM_PTR(&pin_name_obj) },
{ MP_ROM_QSTR(MP_QSTR_names), MP_ROM_PTR(&pin_names_obj) },
{ MP_ROM_QSTR(MP_QSTR_af_list), MP_ROM_PTR(&pin_af_list_obj) },
{ MP_ROM_QSTR(MP_QSTR_port), MP_ROM_PTR(&pin_port_obj) },
{ MP_ROM_QSTR(MP_QSTR_pin), MP_ROM_PTR(&pin_pin_obj) },
{ MP_ROM_QSTR(MP_QSTR_gpio), MP_ROM_PTR(&pin_gpio_obj) },
{ MP_ROM_QSTR(MP_QSTR_mode), MP_ROM_PTR(&pin_mode_obj) },
{ MP_ROM_QSTR(MP_QSTR_pull), MP_ROM_PTR(&pin_pull_obj) },
{ MP_ROM_QSTR(MP_QSTR_af), MP_ROM_PTR(&pin_af_obj) },
// { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&pin_irq_obj) },
// class methods
{ MP_ROM_QSTR(MP_QSTR_mapper), MP_ROM_PTR(&pin_mapper_obj) },
{ MP_ROM_QSTR(MP_QSTR_dict), MP_ROM_PTR(&pin_map_dict_obj) },
#if PIN_DEBUG
{ MP_ROM_QSTR(MP_QSTR_debug), MP_ROM_PTR(&pin_debug_obj) },
#endif
// class attributes
{ MP_ROM_QSTR(MP_QSTR_board), MP_ROM_PTR(&pin_board_pins_obj_type) },
{ MP_ROM_QSTR(MP_QSTR_cpu), MP_ROM_PTR(&pin_cpu_pins_obj_type) },
// class constants
{ MP_ROM_QSTR(MP_QSTR_IN), MP_ROM_INT(NRF_GPIO_PIN_DIR_INPUT) },
{ MP_ROM_QSTR(MP_QSTR_OUT), MP_ROM_INT(NRF_GPIO_PIN_DIR_OUTPUT) },
/*
{ MP_ROM_QSTR(MP_QSTR_OPEN_DRAIN), MP_ROM_INT(GPIO_MODE_OUTPUT_OD) },
{ MP_ROM_QSTR(MP_QSTR_ALT), MP_ROM_INT(GPIO_MODE_AF_PP) },
{ MP_ROM_QSTR(MP_QSTR_ALT_OPEN_DRAIN), MP_ROM_INT(GPIO_MODE_AF_OD) },
{ MP_ROM_QSTR(MP_QSTR_ANALOG), MP_ROM_INT(GPIO_MODE_ANALOG) },
*/
{ MP_ROM_QSTR(MP_QSTR_PULL_DISABLED), MP_ROM_INT(NRF_GPIO_PIN_NOPULL) },
{ MP_ROM_QSTR(MP_QSTR_PULL_UP), MP_ROM_INT(NRF_GPIO_PIN_PULLUP) },
{ MP_ROM_QSTR(MP_QSTR_PULL_DOWN), MP_ROM_INT(NRF_GPIO_PIN_PULLDOWN) },
/*
// IRQ triggers, can be or'd together
{ MP_ROM_QSTR(MP_QSTR_IRQ_RISING), MP_ROM_INT(HAL_GPIO_POLARITY_EVENT_LOW_TO_HIGH) },
{ MP_ROM_QSTR(MP_QSTR_IRQ_FALLING), MP_ROM_INT(HAL_GPIO_POLARITY_EVENT_HIGH_TO_LOW) },
// legacy class constants
{ MP_ROM_QSTR(MP_QSTR_OUT_PP), MP_ROM_INT(GPIO_MODE_OUTPUT_PP) },
{ MP_ROM_QSTR(MP_QSTR_OUT_OD), MP_ROM_INT(GPIO_MODE_OUTPUT_OD) },
{ MP_ROM_QSTR(MP_QSTR_AF_PP), MP_ROM_INT(GPIO_MODE_AF_PP) },
{ MP_ROM_QSTR(MP_QSTR_AF_OD), MP_ROM_INT(GPIO_MODE_AF_OD) },
{ MP_ROM_QSTR(MP_QSTR_PULL_NONE), MP_ROM_INT(GPIO_NOPULL) },
*/
#include "genhdr/pins_af_const.h"
};
STATIC MP_DEFINE_CONST_DICT(pin_locals_dict, pin_locals_dict_table);
const mp_obj_type_t pin_type = {
{ &mp_type_type },
.name = MP_QSTR_Pin,
.print = pin_print,
.make_new = pin_make_new,
.call = pin_call,
.locals_dict = (mp_obj_dict_t*)&pin_locals_dict,
};
/// \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.
STATIC void pin_af_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
pin_af_obj_t *self = self_in;
mp_printf(print, "Pin.%q", self->name);
}
/// \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);
/// \method name()
/// 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);
/// \method reg()
/// Return the base register associated with the peripheral assigned to this
/// alternate function.
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_rom_map_elem_t pin_af_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&pin_af_index_obj) },
{ MP_ROM_QSTR(MP_QSTR_name), MP_ROM_PTR(&pin_af_name_obj) },
{ MP_ROM_QSTR(MP_QSTR_reg), MP_ROM_PTR(&pin_af_reg_obj) },
};
STATIC MP_DEFINE_CONST_DICT(pin_af_locals_dict, pin_af_locals_dict_table);
const mp_obj_type_t pin_af_type = {
{ &mp_type_type },
.name = MP_QSTR_PinAF,
.print = pin_af_obj_print,
.locals_dict = (mp_obj_dict_t*)&pin_af_locals_dict,
};
/******************************************************************************/
// Pin IRQ object
typedef struct _pin_irq_obj_t {
mp_obj_base_t base;
pin_obj_t pin;
} pin_irq_obj_t;
// STATIC const mp_obj_type_t pin_irq_type;
/*STATIC mp_obj_t pin_irq_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
pin_irq_obj_t *self = self_in;
(void)self;
return mp_const_none;
}*/
/*STATIC mp_obj_t pin_irq_trigger(size_t n_args, const mp_obj_t *args) {
pin_irq_obj_t *self = args[0];
(void)self;
return mp_const_none;
}*/
// STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_irq_trigger_obj, 1, 2, pin_irq_trigger);
// STATIC const mp_rom_map_elem_t pin_irq_locals_dict_table[] = {
// { MP_ROM_QSTR(MP_QSTR_trigger), MP_ROM_PTR(&pin_irq_trigger_obj) },
// };
// STATIC MP_DEFINE_CONST_DICT(pin_irq_locals_dict, pin_irq_locals_dict_table);
/*STATIC const mp_obj_type_t pin_irq_type = {
{ &mp_type_type },
.name = MP_QSTR_IRQ,
.call = pin_irq_call,
.locals_dict = (mp_obj_dict_t*)&pin_irq_locals_dict,
};*/