Boundaries for a rotary encoder, and how to increment in only one direction
How do I set a minimum and maximum number that a rotary enconder can go to: Example volume control. How do I also increment only when I rotate right, and decrment when I rotate left.

2 Replies
/* Rotary Encoder Demo */
#include <Encoder.h>
// Original pins
// #define pinA 2
// #define pinB 3
// #define buttonPin 4
// Updated pins
#define pinA 6
#define pinB 7
#define buttonPin 8
Encoder myEnc(pinA, pinB);
long oldPosition = -999;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT_PULLUP);
}
void loop() {
long newPosition = myEnc.read();
if (newPosition != oldPosition) {
oldPosition = newPosition;
Serial.println(newPosition);
}
if (digitalRead(buttonPin) == LOW) {
Serial.println("Button pressed");
delay(200); // simple debounce
}
}
Here is an example that might help: https://wokwi.com/projects/304184909747978816
ky-040-counter.ino - Wokwi ESP32, STM32, Arduino Simulator
Run IoT and embedded projects in your browser: ESP32, STM32, Arduino, Pi Pico, and more. No installation required!