Encoder maximum value

Hello,

I've been searching around on the forum, but I couldn't find the right answer.
I am working on a midi controller, but for now I have just a single encoder connected.
The code works fine for the most part, There is just one thing I need to work around.
I'm using Encoder.h.

when I read the encoder value, it reads 4 steps in one click. to fix that, I just did "read /4" (See code below).
how ever, I added a line to limit the max value to 127. the problem with this is, when the value reaches 127, it automatically gets divided by 4 and jumps to 31.
If I don't do "wh1.write", the value will keep printing in the serial monitor continuously.

Please help me fix this!

EDIT:
I found a work around: in stead of write 127, I do write 508.
That works, but there must be a more elegant way?

#include <Encoder.h>

Encoder Wh1 (2, 3);  //Wheel1

long oldPos1 = 64;

void setup() {

Serial.begin(9600);

pinMode (2, INPUT_PULLUP);
pinMode (3, INPUT_PULLUP);

}

void loop() {
 
long newPos1 = Wh1.read() /4; //Read value and divide by 4

  if (newPos1 != oldPos1) {

    if (newPos1 > 127){
      newPos1 = 127;
      Wh1.write(127);
    }
    if (newPos1 < 1){
      newPos1 = 0;
      Wh1.write(0);
    }
    Serial.print("newPos1: ");
    Serial.println(newPos1);
  
    oldPos1 = newPos1;
  }
}

Consequently write like

      newPos1 = newpos1 * 4; //write value multiplied by 4

Post a link for the encoder's datasheet. How many complete quadrature cycles does it complete per "click". The most common types are one cycle per click and one cycle every two clicks. Here's an example of each:
https://www.adafruit.com/product/377
https://www.mouser.com/ProductDetail/Alps-Alpine/EC11E15244G1?qs=YMSFtX0bdJDiV4LBO61anw%3D%3D&countrycode=US&currencycode=USD

Thus, the most common "mis-count" scenarios (when the code assumes the wrong type) are getting two counts per click or only getting one count for every two clicks.

Getting 4 counts per click is not common, so I'm interested in what type of encoder you have.

you have a real quadrature encoder and the encoder library does give you all the ticks so you get "4 ticks for one click"

Dividing by 4 when reading and multiplying by 4 when writing a value is thus needed.

Also if you want to reset the encoder, don't write 0 as you might be having a few ticks engaged, so write the current value modulo 4 - this way if you had 7 ticks engaged and you were showing '1' (7 / 4) and you want to reset the count, you need to write 3 and not 0.

This may be useful: Control Surface: AbsoluteRotaryEncoder.ino

Thanks for all the help.
in the end, just multiplying by 4 was the simplest solution.

if (newPos1 > 127){
      newPos1 = 127;
      Wh1.write(newPos1 *4) ;

This is the encoder i use:

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