Jul 4, 2015

convert gray-code to binary (in arduino's Wiring/C++ language)

This routine accepts an integer of n bits in gray code and converts it back to binary. I needed this to read the value of an absolute rotary encoder that outputted in gray code format. One of the gotchas in getting this to work was realizing that the bits were active-low from the encoder. An error in the description and in some sample code further compounded the troubleshooting. This code was used to read the 10-bit gray code encoder TRD series from automationdirect. It was implemented on the Teensyduino 3.1.


// read a gray-coded value and convert back to a binary value
int graytobin(int grayVal, int nbits ) {
  // Bn-1 = Bn XOR Gn-1   source of method:  http://stackoverflow.com/questions/5131476/gray-code-to-binary-conversion but include correction 
  int binVal = 0;
  bitWrite(binVal, nbits - 1, bitRead(grayVal, nbits - 1)); // MSB stays the same
  for (int b = nbits - 1; b > 0; b-- ) {
    // XOR bits
    if (bitRead(binVal, b) == bitRead(grayVal, b - 1)) { // binary bit and gray bit-1 the same
      bitWrite(binVal, b - 1, 0);
    }
    else {
      bitWrite(binVal, b - 1, 1);
    }
  }
  return binVal;
}

A loop reads the bits one at a time, inverts and shifts to bit position. Plenty fast (11 us) for my application.


for (i = 0; i < numberofBits; i++) {
    v =  !digitalReadFast(encPins[i]);  // invert bit as encoder is active-low
    enc_val_g |= v << i;
  } 

and then is called with:


    enc_val = graytobin(enc_val_g, numberofBits);




(The code is formatted using hilite.me)