+ a = ao_debounce(a, &debounce_state[0]);
+ b = ao_debounce(b, &debounce_state[1]);
+
+ return 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);
+}