From f557ff05324a0d786e06c06079f1eab5d0bf04f7 Mon Sep 17 00:00:00 2001 From: IhorNehrutsa Date: Fri, 18 Aug 2023 19:38:42 +0300 Subject: [PATCH] Update machine_encoder.c --- ports/esp32/machine_encoder.c | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/ports/esp32/machine_encoder.c b/ports/esp32/machine_encoder.c index 235dbea145fa0..29ca5973abdd0 100755 --- a/ports/esp32/machine_encoder.c +++ b/ports/esp32/machine_encoder.c @@ -449,7 +449,7 @@ STATIC void mp_machine_Counter_init_helper(mp_pcnt_obj_t *self, size_t n_args, c } else { self->x124 = 0; if (direction != MP_OBJ_NULL) { - if (mp_obj_is_type(direction, &machine_pin_type)) { + if (mp_obj_is_type(direction, &machine_pin_type) || mp_obj_is_small_int(direction)) { self->bPinNumber = pin_or_int(direction); } else { self->bPinNumber = mp_obj_get_int(direction); @@ -545,6 +545,15 @@ STATIC void mp_machine_Counter_init_helper(mp_pcnt_obj_t *self, size_t n_args, c check_esp_err(pcnt_counter_resume(self->unit)); } +STATIC int find_free_unit() { + for (int id = 0; id < PCNT_UNIT_MAX; ++id) { + if (!pcnts[id]) { + return id; + } + } + return -1; +} + STATIC void pcnt_init_new(mp_pcnt_obj_t *self, size_t n_args, const mp_obj_t *args) { self->aPinNumber = PCNT_PIN_NOT_USED; self->bPinNumber = PCNT_PIN_NOT_USED; @@ -560,11 +569,17 @@ STATIC void pcnt_init_new(mp_pcnt_obj_t *self, size_t n_args, const mp_obj_t *ar self->handler_zero = MP_OBJ_NULL; self->unit = mp_obj_get_int(args[0]); + if (self->unit == -1) { + self->unit = find_free_unit(); + if (self->unit < 0) { + mp_raise_msg_varg(&mp_type_RuntimeError, MP_ERROR_TEXT("out of PCNT units:%d"), PCNT_UNIT_MAX - 1); + } + } if ((self->unit < 0) || (self->unit >= PCNT_UNIT_MAX)) { mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("id must be from 0 to %d"), PCNT_UNIT_MAX - 1); } if (pcnts[self->unit] != MP_OBJ_NULL) { - mp_raise_msg(&mp_type_Exception, MP_ERROR_TEXT("already used")); + mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("already used")); } if (n_args >= 2) {