Hi Lamikam,
When I tried your code, and rotated the encoder fast, I got the same issue.
But when I rotated the encoder very slowly [<1 click/sec], the output nicely counted up & down as expected.
Hooking up the oscilloscope showed a lot of spikes between the clicks of the encoder at fast rotating [sorry, no picture, should have hit the Print button then...].
That reminded me that the encoder, an ALPS EC11E1544505, is rather bouncy/noisy. Especially when it's been laying around for a few weeks. I guess some kind of corrosion builts up?
After a minute or 5 of fast rotating the encoder back & forth, the output became more stable [meaning counting reliably] at higher rotation speeds.
The number of spikes decreased and counting looked OK. Best visible in the yellow trace. I guess rotating the encoder for a longer time cleans the internal contacts?
Anyway, the Encoder library does not seem to like those bouncy/noisy encoders, so I coded my own encoder handler that seems to be more bounce/noise resistant:
Code:
#define EncoderPinA 2 // yellow wire
#define EncoderPinB 3 // purple wire
boolean StateA;
volatile boolean StateB;
volatile boolean RotationDetected = false;
int8_t EncoderClicks = 0;
void setup()
{
Serial.begin(9600);
pinMode(EncoderPinA, INPUT_PULLUP);
pinMode(EncoderPinB, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(EncoderPinA), EncoderRotated, CHANGE);
}
void loop()
{
if (RotationDetected) // Check whether encoder is rotated
{
delay(1); // Debounce the interrupt pin for 1ms before reading the state
StateA = digitalRead(EncoderPinA); // Read interrupt pinA
if (StateA != StateB) // Compare the states of both pins
{
++EncoderClicks; // CW, increment EncoderClicks by 1
}
else
{
--EncoderClicks; // CCW, decrement EncoderClicks by 1
}
RotationDetected = false; // Clear the flag
Serial.println(EncoderClicks);
}
}
void EncoderRotated() // ISR for encoder
{
StateB = digitalRead(EncoderPinB); // read PinB
RotationDetected = true; // exit the ISR, further processing by the main loop
}
By the way, this is the encoder switching diagram:
Here is the setup I used for testing:
The green wire from the encoder is the integrated push button [not used in this example].
Hope this helps.
Regards,
Paul