I been playing with a US Digital Optical Encoders (S2-2500-250-I-N-D - superceeded bvy http://www.usdigital.com/assets/general … heet_3.pdf
I’ve done some testing with a 5V mini-pro and am currently using a Mega.
The encoder has an index line which helps get an absolute position.
By sensing a change of state each of the A and B lines I can get 10k positions out of the encoder. At a fast hand turn speed the accuracy drops off (some missed steps) but for slow fine control it’s great.
/*
- Basic Rotary Encoder reader.
*/
const int Channel_a = 2;
const int Channel_b = 3;
const int IndexPin = 21;
int StepCount = 0;
int Ch_a_state;
int Ch_b_state;
int Index_state;
int LastCount = 0;
void StateChange0() {
Ch_a_state = digitalRead(Channel_a);
Ch_b_state = digitalRead(Channel_b);
Index_state = digitalRead(IndexPin);
if ( Ch_a_state == Ch_b_state ) ++StepCount;
else --StepCount;
}
void StateChange1() {
Ch_a_state = digitalRead(Channel_a);
Ch_b_state = digitalRead(Channel_b);
Index_state = digitalRead(IndexPin);
if ( Ch_a_state != Ch_b_state ) ++StepCount;
else --StepCount;
}
void StateChange2() {
Index_state = digitalRead(IndexPin);
// if ( Index_state != LOW )
Serial.println(“Index pin state change”);
Serial.print("StepCount is ");
Serial.println(StepCount);
StepCount = 0;
}
void setup()
{
pinMode(Channel_a, INPUT);
pinMode(Channel_a, INPUT);
pinMode(IndexPin, INPUT);
attachInterrupt(0, StateChange0, CHANGE);
attachInterrupt(1, StateChange1, CHANGE);
attachInterrupt(2, StateChange2, RISING);
Serial.begin(9600);
}
void loop()
{
if ( StepCount != LastCount )
{
Serial.print("Changing Position to ");
Serial.println(StepCount);
LastCount = StepCount;
}
delay(100);
}