2929
3030#include "py/runtime.h"
3131
32- // obj array to map pin -> self since nrfx hide the mapping
32+ #include <stdio.h>
33+
34+ // obj array to map pin number -> self since nrfx hide the mapping
3335static rotaryio_incrementalencoder_obj_t * _objs [NUMBER_OF_PINS ];
3436
3537static void _intr_handler (nrfx_gpiote_pin_t pin , nrf_gpiote_polarity_t action ) {
3638 rotaryio_incrementalencoder_obj_t * self = _objs [pin ];
3739 if (!self ) return ;
3840
39- self -> position ++ ;
41+ // reads a state 0 .. 3 *in order*.
42+ uint8_t new_state = nrf_gpio_pin_read (self -> pin_a );
43+ new_state = (new_state << 1 ) + (new_state ^ nrf_gpio_pin_read (self -> pin_b ));
44+
45+ uint8_t change = (new_state - self -> state ) & 0x03 ;
46+ if (change == 1 ) self -> position ++ ;
47+ else if (change == 3 ) self -> position -- ;
48+ // ignore other state transitions
49+
50+ self -> state = new_state ;
4051}
4152
4253void common_hal_rotaryio_incrementalencoder_construct (rotaryio_incrementalencoder_obj_t * self ,
@@ -75,9 +86,13 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o
7586 _objs [self -> pin_a ] = NULL ;
7687 _objs [self -> pin_b ] = NULL ;
7788
89+ nrfx_gpiote_in_event_disable (self -> pin_a );
90+ nrfx_gpiote_in_event_disable (self -> pin_b );
91+ nrfx_gpiote_in_uninit (self -> pin_a );
92+ nrfx_gpiote_in_uninit (self -> pin_b );
7893 reset_pin_number (self -> pin_a );
79- self -> pin_a = NO_PIN ;
8094 reset_pin_number (self -> pin_b );
95+ self -> pin_a = NO_PIN ;
8196 self -> pin_b = NO_PIN ;
8297}
8398
@@ -89,6 +104,3 @@ void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalenc
89104 mp_int_t new_position ) {
90105 self -> position = new_position ;
91106}
92-
93- void incrementalencoder_interrupt_handler (uint8_t channel ) {
94- }
0 commit comments