Hello fellow Arduino enthusiasts! I'm currently grappling with a peculiar issue involving an Arduino Mega 2560 and a rotary incremental encoder. The encoder, a CHBGA - ZSP3806 Driver Output Model, with 3600 p/r operates on a 5V power supply and works flawlessly at lower speeds. However, I'm losing pulses when the speed is cranked up.
At low speeds, everything functions smoothly. Yet, when I increase the speed, the Arduino seems to miss pulses from the encoder. It's leaving me scratching my head and seeking the collective wisdom of this community.
I'm reaching out to the community for advice. If you've encountered similar issues or have expertise in troubleshooting high-speed encoder problems, your insights would be invaluable.
This is the code used:
const int encoderPinA = 2;
const int encoderPinB = 3;
const float shaftDiameter = 6.0; // in millimeters
volatile int encoderPos = 0;
volatile int lastEncoderPos = 0;
volatile float distanceTravelled = 0.0;
void setup() {
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB), updateEncoder, CHANGE);
}
void loop() {
if (encoderPos != lastEncoderPos) {
float circumference = PI * shaftDiameter; // Calculate the circumference of the shaft
float distanceChange = (float)(encoderPos - lastEncoderPos) * circumference / 3600.0;
distanceTravelled += distanceChange;
Serial.print("Current Position: ");
Serial.print(encoderPos);
Serial.print(" Distance Travelled: ");
Serial.print(distanceTravelled);
Serial.println(" mm");
lastEncoderPos = encoderPos;
}
}
void updateEncoder() {
if (digitalRead(encoderPinA) == digitalRead(encoderPinB)) {
encoderPos++;
} else {
encoderPos--;
}
}