+#ifndef AO_QUADRATURE_DEBOUNCE
+#error must define AO_QUADRATURE_DEBOUNCE
+#endif
+
+static uint8_t
+ao_debounce(uint8_t cur, struct ao_debounce *debounce)
+{
+#if AO_QUADRATURE_DEBOUNCE > 0
+ if (debounce->count > 0) {
+ debounce->count--;
+ } else if (cur != debounce->state) {
+ debounce->state = cur;
+ debounce->count = AO_QUADRATURE_DEBOUNCE;
+ }
+ return debounce->state;
+#else
+ (void) debounce;
+ return cur;
+#endif
+}
+
+static uint16_t
+ao_quadrature_read(struct stm_gpio *gpio, uint8_t pin_a, uint8_t pin_b, struct ao_debounce debounce_state[2]) {
+ uint16_t v = ~stm_gpio_get_all(gpio);
+ uint8_t a = (v >> pin_a) & 1;
+ uint8_t b = (v >> pin_b) & 1;
+
+ a = ao_debounce(a, &debounce_state[0]);
+ b = ao_debounce(b, &debounce_state[1]);
+
+ return (uint16_t) (a | (b << 1));
+}
+
+#define _ao_quadrature_get(q) ao_quadrature_read(port(q), bita(q), bitb(q), ao_debounce_state[q])
+
+static void
+_ao_quadrature_step(uint8_t q, int8_t step)
+{
+#ifndef AO_QUADRATURE_SINGLE_CODE
+ ao_quadrature_step[q] += step;
+ if (ao_quadrature_state[q] != 0)
+ return;
+ if (ao_quadrature_step[q] >= 4) {
+ ao_quadrature_step[q] = 0;
+ step = 1;
+ } else if (ao_quadrature_step[q] <= -4) {
+ ao_quadrature_step[q] = 0;
+ step = -1;
+ } else
+ return;
+#endif
+ ao_quadrature_count[q] += step;
+#if AO_EVENT
+ ao_event_put_isr(AO_EVENT_QUADRATURE, q, step);
+#endif
+ ao_wakeup(&ao_quadrature_count[q]);
+}
+
+static const struct {
+ uint8_t prev, next;
+} ao_quadrature_steps[4] = {
+ [0] { .prev = 2, .next = 1 },
+ [1] { .prev = 0, .next = 3 },
+ [3] { .prev = 1, .next = 2 },
+ [2] { .prev = 3, .next = 0 },
+};
+
+static void
+_ao_quadrature_set(uint8_t q, uint8_t new)
+{
+ uint8_t old;
+
+ ao_arch_block_interrupts();
+ old = ao_quadrature_state[q];
+ ao_quadrature_state[q] = new;
+ ao_arch_release_interrupts();
+
+ if (new == ao_quadrature_steps[old].next)
+ _ao_quadrature_step(q, 1);
+ else if (new == ao_quadrature_steps[old].prev)
+ _ao_quadrature_step(q, -1);
+}