Generate Graycode from reed switches

Hi all,

First post... trying to simulate graycode with 2 reed switches, so I can determine the direction last few cycles hopefully?
There's another thread on the subject, but no joy with the answers there for me :zipper_mouth_face:

My sketch so far...

 * @see
 * Dec Gray   Binary
 * 0   000    000
 * 1   001    001
 * 2   011    010
 * 3   010    011

#define LEFT 2
#define RIGHT 3

const long graycodes[4]={
  0b01, //0b00 -> 0b01
  0b11, //0b01 -> 0b11
  0b00, //0b10 -> 0b00
  0b10  //0b11 -> 0b10

volatile long state;
long previous = 0b00;

void interrupt2(void){
  state |= 0b01; // bin 1
void interrupt1(void){
  state |= 0b10; // bin 2 
void setup(void){
  pinMode(LEFT, INPUT);
  pinMode(RIGHT, INPUT);

  attachInterrupt(LEFT  -2, interrupt1, FALLING);
  attachInterrupt(RIGHT -2, interrupt2, FALLING);

  state = (digitalRead(LEFT) ? 0b10 : 0b00) | (digitalRead(RIGHT) ? 0b01 : 0b00);
void loop(void){
  if(previous != state){

    Serial.print(" - ");

    previous = state; //store
    state = 0b00; //reset

Any help appreciated

I don't know what your question is, but to convert a binary code to Gray code (and vice versa) just takes a couple of lines of C.
Scroll down this page for examples: Gray code - Wikipedia

I'll elaborate a bit more.

Have wheel with magnets that runs over 2 reed switches.
I would like to determine the direction of the last few rotations basically.
Which is what you'd do with a rotary encoder using 2bit graycode I think.
So trying to emulate this behaviour.

Hope my quest is a bit more clear now?

Thanks for looking :wink:

OK, I now understand that you are making your own quadrature encoder. If the switches and magnets are arranged and offset properly then you can determine the direction of rotation (after any transition) from the current and last states of the switches.
The mechanical design details are important.

Google "DIY quadrature encoder" for lots of information on design, construction and decoding operations. There is an Arduino site dedicated to the topic as well.

Ton of info indeed, cheers, let me see if I can figure it out and post back.

Thanks so far :slight_smile: