ai-esp32-rotary-encoder icon indicating copy to clipboard operation
ai-esp32-rotary-encoder copied to clipboard

rotaryEncoder.setEncoderValue() offset by one when value is negative

Open jasontaubman opened this issue 1 year ago • 2 comments

Hello,

When using rotaryEncoder.setEncoderValue() to set a negative value, and then reading the resulting encoder value with rotaryEncoder.readEncoder() the result is always off by one towards zero. For example:

void setup() {
  Serial.begin(115200);
  rotaryEncoder.begin();
  rotaryEncoder.setup(readEncoderISR);
  bool circleValues = false;
  rotaryEncoder.setBoundaries(-1000, 1000, circleValues); 
  rotaryEncoder.setAcceleration(250);  
  
 test = -10;
  
  rotaryEncoder.setEncoderValue(test);

}

void loop() {

  Serial.println(rotaryEncoder.readEncoder());

}

This code results in printing the value -9 when -10 would be expected.

Setting the encoder to a value >= 0 works as expected.

ETA: using library version 1.6 and Arduino IDE 2.3.2 on an ESP32 WROVER

jasontaubman avatar Apr 03 '24 17:04 jasontaubman

setEncoderValue calls the reset() function, inside AiEsp32RotaryEncoder.cpp

void AiEsp32RotaryEncoder::setEncoderValue(long newValue)
{
	reset(newValue);
}

and inside the reset() function there is a "correction" parameter that sets the offset to 1 to our set value (in this case it is 1, but it depends on the set number of steps).

void AiEsp32RotaryEncoder::reset(long newValue_)
{
	newValue_ = newValue_ * this->encoderSteps;
	this->encoder0Pos = newValue_ + this->correctionOffset;
	this->lastReadEncoder0Pos = this->encoder0Pos;
	if (this->encoder0Pos > this->_maxEncoderValue)
		this->encoder0Pos = this->_circleValues ? this->_minEncoderValue : this->_maxEncoderValue;
	if (this->encoder0Pos < this->_minEncoderValue)
		this->encoder0Pos = this->_circleValues ? this->_maxEncoderValue : this->_minEncoderValue;

	this->lastReadEncoder0Pos = this->readEncoder();
}

If you eliminate that value correction, it would be showing you the real value

- this->encoder0Pos = newValue_ + this->correctionOffset;
+ this->encoder0Pos = newValue_; //+ this->correctionOffset;

correctionOffset is defined within AiEsp32RotaryEncoder.h with value 2. I don't know very well the reason for this correction, the author will know how to tell us better.

int correctionOffset = 2;

kr4fty avatar Apr 12 '24 14:04 kr4fty