Skip to content

Commit c143eb5

Browse files
malcolm-sparkfundpgeorge
authored andcommitted
esp32/machine_i2c: Make I2C bus ID arg optional with default.
Similar to the previous commit, this allows constructing an I2C instance without specifying an ID. The default ID is I2C_NUM_0. Signed-off-by: Malcolm McKellips <[email protected]>
1 parent bb4ec88 commit c143eb5

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

ports/esp32/machine_i2c.c

+8-3
Original file line numberDiff line numberDiff line change
@@ -146,12 +146,15 @@ static void machine_hw_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_p
146146
}
147147

148148
mp_obj_t machine_hw_i2c_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) {
149-
MP_MACHINE_I2C_CHECK_FOR_LEGACY_SOFTI2C_CONSTRUCTION(n_args, n_kw, all_args);
149+
// Create a SoftI2C instance if no id is specified (or is -1) but other arguments are given
150+
if (n_args != 0) {
151+
MP_MACHINE_I2C_CHECK_FOR_LEGACY_SOFTI2C_CONSTRUCTION(n_args, n_kw, all_args);
152+
}
150153

151154
// Parse args
152155
enum { ARG_id, ARG_scl, ARG_sda, ARG_freq, ARG_timeout };
153156
static const mp_arg_t allowed_args[] = {
154-
{ MP_QSTR_id, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
157+
{ MP_QSTR_id, MP_ARG_INT, {.u_int = I2C_NUM_0} },
155158
{ MP_QSTR_scl, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
156159
{ MP_QSTR_sda, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
157160
{ MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 400000} },
@@ -161,7 +164,9 @@ mp_obj_t machine_hw_i2c_make_new(const mp_obj_type_t *type, size_t n_args, size_
161164
mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
162165

163166
// Get I2C bus
164-
mp_int_t i2c_id = mp_obj_get_int(args[ARG_id].u_obj);
167+
mp_int_t i2c_id = args[ARG_id].u_int;
168+
169+
// Check if the I2C bus is valid
165170
if (!(I2C_NUM_0 <= i2c_id && i2c_id < I2C_NUM_MAX)) {
166171
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("I2C(%d) doesn't exist"), i2c_id);
167172
}

0 commit comments

Comments
 (0)