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;
}
}
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.