uint8_t       encoder_1or2, encoders_conf;
int32_t       encoder_val[2];

int 
process_encoders(void)
{
  return 0;
}

int
read_encoders(int *clicks, int encoder_nr)
{
  int result = encoder_val[encoder_nr];
  encoder_val[encoder_nr] = 0;
  return result;
}

// the encoders function is called from EXTI_Int 0 and 2 only
 
int
encoders( int bit_enc )
{
  int           direction;

  switch ( encoder_1or2 )
  {
    case 0:
      direction = GPIOC->IDR >> 1;
      direction ^= encoders_conf;
      direction &= 1;
      if( direction )
	encoder_val[0]++;
      else
	encoder_val[0]--;
      return encoder_val[0];
    case 1:
      direction = GPIOC->IDR >> 3;
      direction ^= encoders_conf >> 1;
      direction &= 1;
      if( direction )
	encoder_val[1]++;
      else
	encoder_val[1]--;
      return encoder_val[1];
    default:
      return 0;
  }
}

static void
init_encoders( void )
{
  GPIOC->MODER &= 0xFFFFFF00;	// GPIOC inputs 0-3
  GPIOC->PUPDR |= 0x55;		// GPIOC pull-ups 0-3
  RCC->APB4ENR |= 1 << 1;	// SYSCFGEN bit
  __asm volatile ( "dsb 0xF":::"memory" );
  SYSCFG->EXTICR[0] |= 0x202;	// EXTI 0/2 from GPIOC pins
  EXTI->RTSR1 &= ~0xf;		// clear rising edge EXTI0-3
  EXTI->FTSR1 = ( EXTI->FTSR1 & ~0xf ) | 0x5;	// enable falling edge 0/2
  EXTI->D1IMR1 = ( EXTI->D1IMR1 & ~0xf ) | 0x5;	// enable interrupt events 0/2
  NVIC->IP[6] = 0;		// priority 0
  NVIC->ISER[0] = 1 << 6;	// enable EXTI0 (irq 6)
  NVIC->IP[8] = 0;		// priority 0
  NVIC->ISER[0] = 1 << 8;	// enable EXTI2 (irq 8)
  GPIOD->MODER &= 0xFFFFFFF;	// GPIOD inputs 14-15
  GPIOD->PUPDR |= 0x50000000;   // GPIOD pull-ups 14-15
  encoder_val[0] = encoder_val[1] = 0;
}
