Skip to content

Commit a14b0af

Browse files
committed
fix(ameba-rtos-m): accept string pin names in machine.I2CTarget(scl=, sda=)
I2CTarget(scl=, sda=) only accepted integer PinName, unlike every other pin-accepting constructor in this port. Add the same string-pin-parsing helper machine_spi.c/machine_i2c.c already use. Verified on both boards: string and integer pins both work; an invalid string raises ValueError instead of crashing.
1 parent 21873ab commit a14b0af

1 file changed

Lines changed: 37 additions & 2 deletions

File tree

ports/ameba-rtos-m/src/machine_i2c_target.c

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,41 @@ static const PinName i2c_target_default_sda[MICROPY_PY_MACHINE_I2C_TARGET_MAX] =
4040
MICROPY_HW_I2C0_SDA, MICROPY_HW_I2C1_SDA,
4141
};
4242

43+
// ---- Pin parse: int PinName, or string "PAx"/"PA_x"/"PBx"/"PB_x" --
44+
// (same helper as machine_spi.c's machine_spi_get_pin() / machine_i2c.c's
45+
// machine_i2c_get_pin() -- each pin-accepting constructor in this port
46+
// keeps its own static copy rather than sharing one across files).
47+
static PinName machine_i2c_target_get_pin(mp_obj_t obj) {
48+
if (mp_obj_is_int(obj)) {
49+
return (PinName)mp_obj_get_int(obj);
50+
}
51+
if (mp_obj_is_str(obj)) {
52+
size_t len;
53+
const char *s = mp_obj_str_get_data(obj, &len);
54+
if (len >= 3 && s[0] == 'P' && (s[1] == 'A' || s[1] == 'B')) {
55+
size_t i = 2;
56+
if (s[i] == '_') {
57+
i++;
58+
}
59+
int num = 0;
60+
bool has_digit = false;
61+
for (; i < len; i++) {
62+
if (s[i] < '0' || s[i] > '9') {
63+
has_digit = false;
64+
break;
65+
}
66+
num = num * 10 + (s[i] - '0');
67+
has_digit = true;
68+
}
69+
if (has_digit && num >= 0 && num <= 31) {
70+
int base = (s[1] == 'B') ? (int)PB_0 : (int)PA_0;
71+
return (PinName)(base + num);
72+
}
73+
}
74+
}
75+
mp_raise_ValueError(MP_ERROR_TEXT("invalid I2C pin"));
76+
}
77+
4378
// ---------------------------------------------------------------------------
4479
// Port object struct
4580
// ---------------------------------------------------------------------------
@@ -330,10 +365,10 @@ static mp_obj_t mp_machine_i2c_target_make_new(const mp_obj_type_t *type,
330365

331366
// Resolve SCL/SDA — fall back to board defaults if not given.
332367
PinName scl = (args[ARG_scl].u_obj != mp_const_none)
333-
? (PinName)mp_obj_get_int(args[ARG_scl].u_obj)
368+
? machine_i2c_target_get_pin(args[ARG_scl].u_obj)
334369
: i2c_target_default_scl[i2c_id];
335370
PinName sda = (args[ARG_sda].u_obj != mp_const_none)
336-
? (PinName)mp_obj_get_int(args[ARG_sda].u_obj)
371+
? machine_i2c_target_get_pin(args[ARG_sda].u_obj)
337372
: i2c_target_default_sda[i2c_id];
338373
self->scl = scl;
339374
self->sda = sda;

0 commit comments

Comments
 (0)