// 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)