0
votes

Background:

I am writing a driver for a Gray-code rotary encoder using a state machine after reading this arduino example. My device is coded with c# using the .net micro framework. Since it's not quite a real-time embedded os, I can only capture the state of ONE of the encoder's two pins during an interrupt. Upon interrupt, the event is queued to run in a high priority thread. The state of the pin which generated the interrupt is passed as an argument into the "ISR" aka the NativeEventHandler delegate. Reading the second pin's state while the handler runs is not accurate because it's several milliseconds after the actual event was queued.(I've tried it)

In my case, the base state is with both Pins A and B pulled high (value=1)

So, I have only 4 measurable states, but the actual states are based on the previous state.

  1. Pin A High 1
  2. Pin B High 1
  3. Pin A Low 0
  4. Pin B Low 0

I'm having trouble making a state transition table where the table won't get confused. I am trying to come up with some speedy logic to or maybe some bitwise operations to complete this.

Here's the states table(not the transition table) I've come up with:

Pin State   Assigned Value  State Name
PinB-High   4               CW Rot
PinA-High   3               CW3
PinB-Low    2               CW2
PinA-Low    1               CW1
Start       0               Start
PinB-Low    5               CCW1
PinA-Low    6               CCW2
PinB-High   7               CCW3
PinA-High   8               CCW Rot

How do I get the right transitions only 4 states?

2

2 Answers

0
votes

In Gray code only one bit changes at a time, I suggest that instead of looking at it as 4 states try to think about it in a bit-wise representation. Lets say PinA is bit 0 and PinB is bit 1.

Since you said both pins are high in the base state then the transitions could be:

CW: b11 -> b01 -> b00 -> b10

CCW: b11 -> b10 -> b00 -> b01

The logic might be flipped depending on how your encoder works.

You should then be able to handle it with a switch case easily.

0
votes

Even if you think about bit pairs for each of the encoder states, contact bouncing is so noisy that decoding these excitations using a state machine, the results can be inaccurate. A mix of states plus some kind of capacitor debouncing and some delay matching the contact bouncing time spec introduced in the interrupt function, can help. Bouncing can change a lot from one encoder brand and model to another. Software latencies in operating systems can make things even worse. It takes time and some testing.