mathertel / RotaryEncoder

RotaryEncoder Arduino Library
Other
342 stars 107 forks source link

Constraining encoder to range of values #5

Closed jwhendy closed 7 years ago

jwhendy commented 7 years ago

First off, awesome library. After feeling like I've scoured the earth, this one seems really reliable, elegant, and simple. I kept getting "microsteps" with other libraries, quick jitters between values (like printing 4, 5, 4, 5, 4, 5 sometimes when changing direction), stepping 4 at a time, etc.

I'm trying to use two encoders to create a sort of Etch-a-Sketch on a 16x16 LED matrix. Thus, I'd like my encoders to only range between 0-15 for my rows/columns. I also think I'll scale the detents so perhaps 3-4 is one "step" as my detents are pretty closely spaced.

My approach was as follows, based on your SimplePollRotator example:

  encoder.tick();

  int newPos = constrain(encoder.getPosition(), 0, 15);
  encoder.setPosition(newPos);

  if (pos != newPos) {
    Serial.print(newPos);
    Serial.println();
    pos = newPos;

  } // if

I'm using both constrain() and setPosition because constrain() by itself will only control newPos, not the cumulative encoder value that's getting picked up by getPosition. So, as I turn it past 15, I'll only see 15's printed out on the screen, but getPosition might be much higher. Thus, I have to turn back until getPosition is between 0-15 and then the value changes.

What I thought I could do was make sure that the position of the encoder would be fixed to 0 or 15 if it tried to go outside those ranges and that encoder.tick() would still pick up changes to get it out of that endpoint. What I'm finding is nothing happens, so I'm guessing pos != newPos is somehow never met?

Any suggestion on how I can sort of ignore the encoder if it's trying to go above/below my limits but still register changes that put it back in those limits? I'm not a hardcore C guy so I'm unable to follow your bit shifting code at the moment, but also feel like I may not understand what setPosition is doing.

Thanks for any tips!

mathertel commented 7 years ago

I just added the LimitedRotator sample. Have a look. https://github.com/mathertel/RotaryEncoder/tree/master/examples/LimitedRotator