Skip to content

Commit fc86475

Browse files
committed
IncrementalEncoder: support swapped pins
Closes: #4422
1 parent 93d6cee commit fc86475

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,17 @@ STATIC void incrementalencoder_interrupt_handler(void *self_in);
6060
void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t *self,
6161
const mcu_pin_obj_t *pin_a, const mcu_pin_obj_t *pin_b) {
6262
mp_obj_t pins[] = {MP_OBJ_FROM_PTR(pin_a), MP_OBJ_FROM_PTR(pin_b)};
63+
bool swap = false;
6364
if (!common_hal_rp2pio_pins_are_sequential(2, pins)) {
64-
mp_raise_RuntimeError(translate("Pins must be sequential"));
65+
pins[0] = MP_OBJ_FROM_PTR(pin_b);
66+
pins[1] = MP_OBJ_FROM_PTR(pin_a);
67+
swap = true;
68+
if (!common_hal_rp2pio_pins_are_sequential(2, pins)) {
69+
mp_raise_RuntimeError(translate("Pins must be sequential"));
70+
}
6571
}
6672

73+
self->swap = swap;
6774
self->position = 0;
6875
self->quarter_count = 0;
6976

@@ -72,7 +79,7 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode
7279
1000000,
7380
encoder_init, MP_ARRAY_SIZE(encoder_init), // init
7481
NULL, 0, 0, 0, // out pin
75-
pin_a, 2, // in pins
82+
pins[0], 2, // in pins
7683
3, 0, // in pulls
7784
NULL, 0, 0, 0x1f, // set pins
7885
NULL, 0, 0, 0x1f, // sideset pins
@@ -106,12 +113,12 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o
106113
}
107114

108115
mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self) {
109-
return self->position;
116+
return self->swap ? -self->position : self->position;
110117
}
111118

112119
void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self,
113120
mp_int_t new_position) {
114-
self->position = new_position;
121+
self->position = self->swap ? -new_position : new_position;
115122
}
116123

117124
STATIC void incrementalencoder_interrupt_handler(void *self_in) {

ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,5 @@ typedef struct {
3737
uint8_t last_state : 4; // <old A><old B><new A><new B>
3838
int8_t quarter_count : 4; // count intermediate transitions between detents
3939
mp_int_t position;
40+
bool swap;
4041
} rotaryio_incrementalencoder_obj_t;

0 commit comments

Comments
 (0)