From fc86475de58581bd48d67ecc733377a5ed713367 Mon Sep 17 00:00:00 2001 From: Jeff Epler Date: Sun, 4 Apr 2021 13:48:47 -0500 Subject: [PATCH] IncrementalEncoder: support swapped pins Closes: #4422 --- .../common-hal/rotaryio/IncrementalEncoder.c | 15 +++++++++++---- .../common-hal/rotaryio/IncrementalEncoder.h | 1 + 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c index 5c61e0915c..faef077972 100644 --- a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c @@ -60,10 +60,17 @@ STATIC void incrementalencoder_interrupt_handler(void *self_in); void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t *self, const mcu_pin_obj_t *pin_a, const mcu_pin_obj_t *pin_b) { mp_obj_t pins[] = {MP_OBJ_FROM_PTR(pin_a), MP_OBJ_FROM_PTR(pin_b)}; + bool swap = false; if (!common_hal_rp2pio_pins_are_sequential(2, pins)) { - mp_raise_RuntimeError(translate("Pins must be sequential")); + pins[0] = MP_OBJ_FROM_PTR(pin_b); + pins[1] = MP_OBJ_FROM_PTR(pin_a); + swap = true; + if (!common_hal_rp2pio_pins_are_sequential(2, pins)) { + mp_raise_RuntimeError(translate("Pins must be sequential")); + } } + self->swap = swap; self->position = 0; self->quarter_count = 0; @@ -72,7 +79,7 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode 1000000, encoder_init, MP_ARRAY_SIZE(encoder_init), // init NULL, 0, 0, 0, // out pin - pin_a, 2, // in pins + pins[0], 2, // in pins 3, 0, // in pulls NULL, 0, 0, 0x1f, // set pins NULL, 0, 0, 0x1f, // sideset pins @@ -106,12 +113,12 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o } mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self) { - return self->position; + return self->swap ? -self->position : self->position; } void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, mp_int_t new_position) { - self->position = new_position; + self->position = self->swap ? -new_position : new_position; } STATIC void incrementalencoder_interrupt_handler(void *self_in) { diff --git a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h index 83fe97d316..d74c21035e 100644 --- a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h +++ b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h @@ -37,4 +37,5 @@ typedef struct { uint8_t last_state : 4; // int8_t quarter_count : 4; // count intermediate transitions between detents mp_int_t position; + bool swap; } rotaryio_incrementalencoder_obj_t;