Eliminating overshoot when using a rotary encoder

The code below is just a simplified problem that illustrates the problem I am having. If the user turns the rotary encoder clockwise, after it has already reached zero, it continues to go deeper into the 0s' however many times it was turned after reaching zero, that will need to turn it a equal number of times (+1) to start sending a signal to the LED.

I want it to start counting once a person turns the encoder, not to remain buried somewhere in a stack of 0s'

The same at the top, I want the counter to stop accumulating once it reaches 250.

Yes, I realize this is best done with a potentiometer and map(), but I am trying to get a better understanding of rotary encoders

#include <Arduino.h>
#include <BasicEncoder.h>

const int8_t pinCLK = 2;
const int8_t pinDT = 3;

BasicEncoder encoder(pinCLK, pinDT);

const byte yellowPin = 5;

void setup() {
  Serial.begin(9600);
  pinMode(yellowPin, OUTPUT);
}

void loop() {
  encoder.service();
  int encoder_change = encoder.get_change();
  if (encoder_change) {
    int countX10 = constrain((encoder.get_count()*10), 0, 250); 

    Serial.println(countX10); 
    analogWrite(yellowPin, countX10);                   
  } 
} 

Please provide a link to documentation to your specific rotary encoder so the rest of us can see what you are using.

Constrain the encoder count, not count*10, as your program does now.

The library is limited. What you needs sounds like a set_count(…) function and it doesn’t have one. It does have a reset() which would work for the 0 end.

 if(encoder.get_count()<0) encoder.reset();

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