Arduino Mega 2560 and Encoder Troubles at High Speeds

Hello fellow Arduino enthusiasts! :wave: 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--;
  }
}

Define "lower speed" and "cranked up speed".

Lower speed like when you tune the radio and fast speed more than 1m/s

giving a number with unit meter per second is useless in your case.

On a 2 m diamater wheel 1 m/s is less than 10 rotations per minute
On a 5 mm diameter wheel 1 m / s is as fast as 3822 rotations per minute

So simple post the number what is the biggest rpm rotation per minute that can occur

You have defined your variable for counting the encoder-pulses as

well an integer variable can hold only values +-32767
with an encoder with 3600 pulses per rotation this counts up to more than 36000 if you are rotating at 600 rpm = 10 rps within a second

You should define the variable as long which can count up to +-2147483647

best regards Stefan

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.