#include <io.h>
#include <interrupt.h>
#include <signal.h>


#define PHASE_A  (PINC & 1<<PINC0)  // PINC.0
#define PHASE_B (PINC & 1<<PINC1)  // PINC.1


volatile char  enc_delta;    // -128 ... 127


int main( void )
{
  TCCR0 = 1<<CS01;      //divide by 8 * 256
  TIMSK = 1<<TOIE0;      //enable timer interrupt

  DDRB = 0xFF;
  sei();
  for(;;)        // main loop
    PORTB = enc_delta;
}


SIGNAL (SIG_OVERFLOW0)
{
  static char enc_last = 0x01;
  char i = 0;

  if( PHASE_A )
    i = 1;

  if( PHASE_B )
    i ^= 3;        // convert gray to binary

  i -= enc_last;      // difference new - last

  if( i & 1 ){        // bit 0 = value (1)
    enc_last += i;      // store new as next last

    enc_delta += (i & 2) - 1;    // bit 1 = direction (+/-)
  }
}