Rotary encoder: Increment by 1 per 'click' while constraining values 0 - 127

Status
Not open for further replies.

Hitachii

Active member
Using the example in the PJRC encoder library, I'm trying to constrain my encoder values between 0 - 127. There's conflict between how the encoder wants to increment and how the counter acts. Using the "TwoKnobs Example", with only one encoder, My rotary encoder wants to count by 4 with each 'click' (each time both sensors are passed). I've tried several variations of bit-shifting "newLeft", as well as dividing it by four.

All of these result in things like:
- Increments by 1 per click (desired) but only counts to 64.
- Counts to 127 and starts over at zero (desired), but increments/decrements by 2.

How do I increment by one each time a 'click' is felt on my encoder (reading both sensors once), while at the same time having the values constrained to 0 - 127? You'll notice I tried to add another variable altogether in an attempt to constrain the value, which hasn't been successful either. Thanks.

Code:
#include <Encoder.h>

Encoder knobLeft(25, 26);

void setup() {
  Serial.begin(9600);
  Serial.println("TwoKnobs Encoder Test:");
}

byte positionLeft  = 0;

void loop() {

  byte newLeft;
  byte finalVal;

  newLeft = knobLeft.read();
  if ((newLeft >> 1) > 127) {
    newLeft = 0;
  }
  if ((newLeft >> 1) < 0) {
    newLeft = 127;
  }
  finalVal = (newLeft >> 1);
  if (newLeft != positionLeft) {
    positionLeft = newLeft;
    Serial.print("Left = ");
    Serial.print(finalVal);
    Serial.println();
  }
}
 
newleft = knobLeft.read() / 4;

and remove the shift here :
if ((newLeft >> 1) > 127) {

..and really.. don't use "byte" anymore.
use int or unsigned int.

byte (same as uint8_t) was maybe good when using those old 8-bit AVR-CPUs.
It does not help modern 32Bit CPUs in any way and can in some case be slower than 32bit.
Note, that "Int" can be 16 or 32 bit (..or even 64?)- whatever is better for the used cpu. On Teensy, or general ARM Cortex, it is 32 Bit wide.
 
Amazing, that did it! Thank you. Would you mind telling me why I should not use byte? I've been using it due to someone's suggestion that I should declare my hardware variables as a byte because I'm saving to EEPROM.
 
Well, you don't save your encoder position to eeprom?

But of course, Byte (better use uin8_t - "Byte" is a obscure Arduino invention) saves space on the eeprom. You can use uint8_t if you want to save space.
But don't use it, unless you need to.. esp. not for calculations.
 
Status
Not open for further replies.
Back
Top