Rotary encoder interrupt and setting limits to position

I'm trying to program a rotary encoder on a interrupt to go from 1 to 100 and when they turn it further past those number it just sets the position to either one respectively. When i code it and turn the encoder past those number and then go to turn it back it does start immediately counting up or down from 1 or 100 but doesnt change until you turn it back the amount you over turned it.
I'm using a arduino nano and the rotary is connected to pins 2 and 3.

// -----
// InterruptRotator.ino - Example for the RotaryEncoder library.
// This class is implemented for use with the Arduino environment.
//
// Copyright (c) by Matthias Hertel, http://www.mathertel.de
// This work is licensed under a BSD 3-Clause License. See http://www.mathertel.de/License.aspx
// More information on: http://www.mathertel.de/Arduino

// This example checks the state of the rotary encoder using interrupts and in the loop() function.
// The current position and direction is printed on output when changed.

#include <Arduino.h>
#include <RotaryEncoder.h>

#define PIN_IN1 2
#define PIN_IN2 3

// A pointer to the dynamic created rotary encoder instance.
// This will be done in setup()
RotaryEncoder *encoder = nullptr;

void checkPosition(){encoder->tick();} // just call tick() to check the state.

void setup()
{
  Serial.begin(9600);
  while (!Serial)
    ;
  Serial.println("InterruptRotator example for the RotaryEncoder library.");

  // setup the rotary encoder functionality

  // use TWO03 mode when PIN_IN1, PIN_IN2 signals are both LOW or HIGH in latch position.
  encoder = new RotaryEncoder(2, 3, RotaryEncoder::LatchMode::TWO03);

  // register interrupt routine
  attachInterrupt(digitalPinToInterrupt(2), checkPosition, CHANGE);
  attachInterrupt(digitalPinToInterrupt(3), checkPosition, CHANGE);
} // setup()


// Read the current position of the encoder and print out when changed.
void loop()
{
  static int pos = 0;

  encoder->tick(); // just call tick() to check the state.

  int newPos = encoder->getPosition();
  if(newPos <0){newPos=1;}
  if(newPos >100){newPos=100;}
  if (pos != newPos) {
    Serial.print("pos:");
    Serial.print(newPos);
    Serial.print(" dir:");
    Serial.println((int)(encoder->getDirection()));

    pos = newPos;
  } // if
} // loop ()

You are constraining the 'newPos' variable but aren't telling the encoder object about it. Try this:

  int newPos = constrain(encoder->getPosition(), 1, 100);
  encoder->setPosition(newPos);

See This Example that comes as part of This Encoder Library.

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