Skip to content

Commit bb4ec88

Browse files
malcolm-sparkfundpgeorge
authored andcommitted
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 <[email protected]>
1 parent cad62c2 commit bb4ec88

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

ports/rp2/machine_i2c.c

+8-3
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,11 @@ static void machine_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_prin
9797
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) {
9898
enum { ARG_id, ARG_freq, ARG_scl, ARG_sda, ARG_timeout };
9999
static const mp_arg_t allowed_args[] = {
100-
{ MP_QSTR_id, MP_ARG_REQUIRED | MP_ARG_OBJ },
100+
#ifdef PICO_DEFAULT_I2C
101+
{ MP_QSTR_id, MP_ARG_INT, {.u_int = PICO_DEFAULT_I2C} },
102+
#else
103+
{ MP_QSTR_id, MP_ARG_INT, {.u_int = -1} },
104+
#endif
101105
{ MP_QSTR_freq, MP_ARG_INT, {.u_int = DEFAULT_I2C_FREQ} },
102106
{ MP_QSTR_scl, MICROPY_I2C_PINS_ARG_OPTS | MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
103107
{ 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
108112
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
109113
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
110114

111-
// Get I2C bus.
112-
int i2c_id = mp_obj_get_int(args[ARG_id].u_obj);
115+
int i2c_id = args[ARG_id].u_int;
116+
117+
// Check if the I2C bus is valid
113118
if (i2c_id < 0 || i2c_id >= MP_ARRAY_SIZE(machine_i2c_obj)) {
114119
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("I2C(%d) doesn't exist"), i2c_id);
115120
}

0 commit comments

Comments
 (0)