diff options
author | Malcolm McKellips <malcolm.mckellips@sparkfun.com> | 2025-01-24 09:36:02 -0700 |
---|---|---|
committer | Damien George <damien@micropython.org> | 2025-02-28 15:17:34 +1100 |
commit | bb4ec886f8994ad7b2db6f80c7b46e6eedbc40e7 (patch) | |
tree | 359e04e5a4c7b94d8a2f38ae64ad56989d6ba8e5 | |
parent | cad62c20f2971b1248f55f27ab9f6d9bf8ccdafa (diff) | |
download | micropython-bb4ec886f8994ad7b2db6f80c7b46e6eedbc40e7.tar.gz micropython-bb4ec886f8994ad7b2db6f80c7b46e6eedbc40e7.zip |
rp2/machine_i2c: Make I2C bus ID arg optional with default.
This commit gives the option to not pass an I2C Bus ID when creating a
machine I2C object. If the ID is not provided, the default bus ID (which
is `PICO_DEFAULT_I2C`) is used.
This allows users to simply declare an I2C object with `machine.I2C()`
without passing any arguments, thus creating an object with the default I2C
ID, SCL, and SDA.
Signed-off-by: Malcolm McKellips <malcolm.mckellips@sparkfun.com>
-rw-r--r-- | ports/rp2/machine_i2c.c | 11 |
1 files changed, 8 insertions, 3 deletions
diff --git a/ports/rp2/machine_i2c.c b/ports/rp2/machine_i2c.c index 28032e8085..e97a852b24 100644 --- a/ports/rp2/machine_i2c.c +++ b/ports/rp2/machine_i2c.c @@ -97,7 +97,11 @@ static void machine_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_prin mp_obj_t machine_i2c_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { enum { ARG_id, ARG_freq, ARG_scl, ARG_sda, ARG_timeout }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_id, MP_ARG_REQUIRED | MP_ARG_OBJ }, + #ifdef PICO_DEFAULT_I2C + { MP_QSTR_id, MP_ARG_INT, {.u_int = PICO_DEFAULT_I2C} }, + #else + { MP_QSTR_id, MP_ARG_INT, {.u_int = -1} }, + #endif { MP_QSTR_freq, MP_ARG_INT, {.u_int = DEFAULT_I2C_FREQ} }, { MP_QSTR_scl, MICROPY_I2C_PINS_ARG_OPTS | MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_sda, MICROPY_I2C_PINS_ARG_OPTS | MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, @@ -108,8 +112,9 @@ mp_obj_t machine_i2c_make_new(const mp_obj_type_t *type, size_t n_args, size_t n mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - // Get I2C bus. - int i2c_id = mp_obj_get_int(args[ARG_id].u_obj); + int i2c_id = args[ARG_id].u_int; + + // Check if the I2C bus is valid if (i2c_id < 0 || i2c_id >= MP_ARRAY_SIZE(machine_i2c_obj)) { mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("I2C(%d) doesn't exist"), i2c_id); } |