#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/signal.h>

volatile int8_t   enc_delta=0;      // -128 ... 127

int main( void )
{
  // rotary switch connection  
  DDRE &= ~(_BV(PE3) | _BV(PE4)); // set to input
  PORTE |=(_BV(PE3) | _BV(PE4));  // enable pull up

  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 uint8_t last_state = 0,last_cnt = 0;
  uint8_t new_state;

  new_state=PINE & (_BV(PINE4) | _BV(PINE3));
  if ((new_state^last_cnt)==(_BV(PINE4) | _BV(PINE3)) )
  {
    if ((new_state ^ last_state)==_BV(PINE4))
      enc_delta+=1;
    else
      enc_delta-=1;
    last_cnt=new_state;
  }
  last_state=new_state;
}
