+ 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);
+}
+
+static void
+ao_quadrature_isr(void)
+{
+#if AO_QUADRATURE_COUNT > 0
+ _ao_quadrature_set(0, _ao_quadrature_get(0));
+#endif
+#if AO_QUADRATURE_COUNT > 1
+ _ao_quadrature_set(1, _ao_quadrature_get(1));
+#endif
+}
+
+static void
+_ao_quadrature_start_one(uint8_t q, uint8_t new)
+{
+ ao_arch_block_interrupts();
+ ao_quadrature_state[q] = new;
+ ao_arch_release_interrupts();