#ifndef F_CPU #define F_CPU 16000000UL #endif #include #include #include static uint8_t encoder_read(void) { return PINC & 0x03U; /* bit 0 = A, bit 1 = B */ } int main(void) { static const int8_t transitions[16] = { 0, 1, -1, 0, -1, 0, 0, 1, 1, 0, 0, -1, 0, -1, 1, 0 }; UCSR0B = 0; DDRD = 0xFF; PORTD = 0; DDRC &= (uint8_t)~0x03U; PORTC |= 0x03U; _delay_ms(10); uint8_t previous = encoder_read(); uint8_t count = 0; int8_t partial = 0; while (1) { uint8_t current = encoder_read(); if ((current ^ previous) == 3U) { partial = 0; /* Both bits changed: resynchronize. */ } else { partial += transitions[(previous << 2) | current]; if (partial >= 4) { ++count; partial = 0; } else if (partial <= -4) { --count; partial = 0; } } previous = current; PORTD = count; _delay_us(100); } }