misan / dcservo

Position control of DC motors
312 stars 113 forks source link

Cant understand code #75

Open kotopuz opened 3 years ago

kotopuz commented 3 years ago

I cant understand how you read encoder inputs. There is some array then some weird calcs. There is A and B channels. Generally when A comes you count pulse. Then inside A interrupt you may compare to B state to determine direction. Can you direct me to explanation of this code please

const int QEM [16] = {0,-1,1,2,1,0,2,-1,-1,2,0,1,2,1,-1,0}; // Quadrature Encoder Matrix static unsigned char New, Old;

void encoderInt() { // handle pin change interrupt for D2 Old = New; //New = PIND & 3; //(PINB & 1 )+ ((PIND & 4) >> 1); // Mauro Manco New = digitalRead(encoder0PinA)2 + digitalRead(encoder0PinB); encoder0Pos+= QEM [Old 4 + New]; }

Thanks !

misan commented 3 years ago

The encoder part I borrowed from Let's make robots blog, but they revamped their site and I cannot find it anymore. But evidence is there: https://www.robotshop.com/community/forum/t/dagu-5rover-arduino-code/10875

It is a state machine, where +1 or -1 corresponds to valid encoder count updates and 2 represents invalid transitions in the finite automaton that should never happen.

Hold on, I have found a document that explains it all: https://cdn.sparkfun.com/datasheets/Robotics/How%20to%20use%20a%20quadrature%20encoder.pdf