Make encoder setup easier to change

This commit is contained in:
Lynn Ochs 2021-07-16 21:21:54 +02:00
parent 2f78a78ed8
commit e121ecd896

View File

@ -10,23 +10,25 @@ static volatile int pos;
static void check(void); static void check(void);
#define PIN1 GPIO4 #define PIN_OPEN GPIO1
#define PIN1_IRQ NVIC_EXTI4_IRQ #define PIN_OPEN_IRQ NVIC_EXTI1_IRQ
#define PIN2 GPIO5 #define PIN_CLOSE GPIO2
#define PIN2_IRQ NVIC_EXTI9_5_IRQ #define PIN_CLOSE_IRQ NVIC_EXTI2_IRQ
#define PIN_PORT GPIOC
#define PIN_RCC RCC_GPIOC
void encoder_setup(void) { void encoder_setup(void) {
rcc_periph_clock_enable(RCC_GPIOA); rcc_periph_clock_enable(PIN_RCC);
gpio_mode_setup(GPIOA, GPIO_MODE_INPUT, GPIO_PUPD_NONE, PIN1 | PIN2); gpio_mode_setup(PIN_PORT, GPIO_MODE_INPUT, GPIO_PUPD_NONE, PIN_OPEN | PIN_CLOSE);
/* Set up exti on A0 & A1 */ exti_select_source(PIN_OPEN | PIN_CLOSE, PIN_PORT);
exti_select_source(PIN1 | PIN2, GPIOA); exti_set_trigger(PIN_OPEN | PIN_CLOSE, EXTI_TRIGGER_BOTH);
exti_set_trigger(PIN1 | PIN2, EXTI_TRIGGER_BOTH); exti_enable_request(PIN_OPEN | PIN_CLOSE);
exti_enable_request(PIN1 | PIN2);
nvic_enable_irq(PIN1_IRQ); nvic_enable_irq(PIN_OPEN_IRQ);
nvic_enable_irq(PIN2_IRQ); nvic_enable_irq(PIN_CLOSE_IRQ);
} }
int encoder_get() { int encoder_get() {
@ -36,27 +38,39 @@ int encoder_get() {
static int prev = 0; static int prev = 0;
void check(void) { void check(void) {
int pp = pos; int pp = pos;
int now = GPIO_IDR(GPIOA); int now = GPIO_IDR(PIN_PORT);
now = (!!(now & PIN1))<<0 | (!!(now & PIN2)) << 1; now = (!!(now & PIN_OPEN))<<0 | (!!(now & PIN_CLOSE)) << 1;
switch (prev << 2 | now) { #define NEITHER 0
case 0 * 4 + 2: #define JUST_OPEN 1
case 1 * 4 + 0: #define JUST_CLOSE 2
case 2 * 4 + 3: #define BOTH 3
case 3 * 4 + 1: #define WAS(x) ((x)<<2)
pos++; #define IS(x) (x)
break;
case 0 * 4 + 1: switch (WAS(prev) + IS(now)) {
case 1 * 4 + 3: case WAS(NEITHER) + IS(JUST_CLOSE):
case 2 * 4 + 0: case WAS(JUST_OPEN) + IS(NEITHER):
case 3 * 4 + 2: case WAS(JUST_CLOSE) + IS(BOTH):
case WAS(BOTH) + IS(JUST_OPEN):
pos--; pos--;
break; break;
case WAS(NEITHER) + IS(JUST_OPEN):
case WAS(JUST_OPEN) + IS(BOTH):
case WAS(BOTH) + IS(JUST_CLOSE):
case WAS(JUST_CLOSE) + IS(NEITHER):
pos++;
break;
default: default:
prev = now; prev = now;
return; return;
} }
#undef NEITHER
#undef JUST_OPEN
#undef JUST_CLOSE
#undef BOTH
#undef WAS
#undef IS
prev = now; prev = now;
if (pos < MIN_POS) if (pos < MIN_POS)
pos = MIN_POS; pos = MIN_POS;
@ -64,11 +78,11 @@ void check(void) {
pos = MAX_POS; pos = MAX_POS;
} }
void exti4_isr(void) { void exti1_isr(void) {
exti_reset_request(EXTI4); exti_reset_request(EXTI1);
check(); check();
} }
void exti9_5_isr(void) { void exti2_isr(void) {
exti_reset_request(EXTI5); exti_reset_request(EXTI2);
check(); check();
} }