Absolute Multiturn Encoder IFM RM8001 (solved)

Hey guys!

I was looking for an absolute multiturn encoder. Usually it costs a lot. I have found RM8001 (25 bits ) from IFM which costs around 200 EUR. And does not need any external ic.

Wiring:
Encoder white wire - Arduino GND
Encoder brown wire - Arduino 5V or 5-30 VDC (external power)
Encoder green wire - Arduino PIN 5
Encoder gray wire - Arduino PIN 11
Encoder pink wire - Arduino PIN 12

Here is the code how you can work with it with arduino uno (please note that digitalread and digitalwrite are too slow for the sensor, thats why I had to use port manipulation).

#define ENCODER_OUT_PIN 5
#define ENCODER_IN_NORM 11
#define ENCODER_IN_INV 12

void setup() {
  Serial.begin(19200);
  setup_encoder();
}

void loop() {
  read_encoder();
  delay(1000);
}


void setup_encoder() {
  pinMode(ENCODER_OUT_PIN, OUTPUT);
  pinMode(ENCODER_IN_NORM, INPUT);
  pinMode(ENCODER_IN_INV, INPUT);
}

unsigned long read_encoder() {
  uint8_t readed[25];
  uint8_t readed_inv[25];
  uint32_t gray_value;
  unsigned long bin_value;
  uint8_t temp;
  int j=0;
  
  //digitalWrite(ENCODER_OUT_PIN, LOW);
  //delayMicroseconds(1);
  PORTD = PORTD & B11011111;
  
  for ( int i = 0; i < 25; i++) {  
    //digitalWrite(ENCODER_OUT_PIN, HIGH);
    PORTD = PORTD | B00100000;
    delayMicroseconds(1);

    temp[i] = PINB;
    readed[i] = ((temp>>3 & 0x01));
    readed_inv[i] = ((temp>>4 & 0x01));

    PORTD = PORTD & B11011111;
    //digitalWrite(ENCODER_OUT_PIN, LOW);
     
  }
  PORTD = PORTD | B00100000;
  //digitalWrite(ENCODER_OUT_PIN, HIGH);
  delay(1);

  gray_value = 0;
  for ( int i = 0; i < 25; i++ ) {

    if (( readed[i] + readed_inv[i] ) != 1 ){
      Serial.println("data and data inv dont match!");
    }
    gray_value = gray_value * 2 + readed[i];
  }
  bin_value = gray_decode(gray_value);
  
  Serial.print("Encoder: ");
  Serial.print(bin_value);
  Serial.println("  ");
  
  return bin_value;
}

uint32_t gray_decode(uint32_t n) {
    uint32_t p = n;
    while (n >>= 1) p ^= n;
    return p;
}