Hi there !
I am currently doing experiments with a salvaged mouse rotary encoder.
the problem i’m facing isn’t from the code itself, ‘cos i tried a bunch of ‘em i’ve found on internet
the problem is, this encoder is quite old, it come from a mouse i’ve been using for a while now, so of course it is used, and the contacts A and B aren’t tight anymore.
here’s an example of code i used to make it work (not my code !) :
#define encoder0PinA 2
#define encoder0PinB 3
#define encoder0Btn 4
int encoder0Pos = 0;
void setup() {
Serial.begin(9600);
pinMode(encoder0PinA, INPUT_PULLUP);
pinMode(encoder0PinB, INPUT_PULLUP);
pinMode(encoder0Btn, INPUT_PULLUP);
attachInterrupt(0, doEncoder, CHANGE);
}
int valRotary,lastValRotary;
void loop() {
int btn = digitalRead(encoder0Btn);
Serial.print(btn);
Serial.print(" ");
Serial.print(valRotary);
if(valRotary>lastValRotary)
{
Serial.print(" CW");
}
if(valRotary {
Serial.print(" CCW");
}
lastValRotary = valRotary;
Serial.println(" ");
delay(250);
}
void doEncoder()
{
if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB))
{
encoder0Pos++;
}
else
{
encoder0Pos--;
}
valRotary = encoder0Pos/2.5;
}
and using it with a new rotary encoder (not from a mouse), it works very well.
But with the old mouse encoder here’s what happens (on the serial monitor) :
rotating in one way, i get “rotating clockwise”. Good, it works.
now the other way, i get “rotating counter-clockwise” then “clockwise” the “counter..” etc.
does anyone knows if i can compensate in a way or an other the fact the this component is used ? i already tried using a delay, it doesn’t change anything.