Environment: Arduino ver. 1.8.19 - ESP32 WOROOM 38pin
I created this routine for the rotary encoder, but I have a problem.
I can't get the requested values.
If I use a min_val = 1 and a max_val = 10 I have no problems the values go from the minimum to the maximum allowed value, cycling from the minimum to the maximum and vice versa.
But if I use min_val = 0 and max_val = 10 when going below zero I get the maximum value allowed for an unsigned int.
I can't figure it out, is anyone able to fix this?
//
#define ENC_A 17 // Rotary encoder parameters
#define ENC_B 16 // Rotary encoder parameters
unsigned int counter = 0;
unsigned int lastCounter = 1;
unsigned int min_val = 1;
unsigned int max_val = 10;
void setup() {
Serial.begin(115200);
while(!Serial) {} // Wait for Serial port
delay(1000);
pinMode(ENC_A, INPUT_PULLUP); // Rotary encoder pins
pinMode(ENC_B, INPUT_PULLUP); // Rotary encoder pins
}
void loop() {
read_encoder();
if (counter != lastCounter) {
Serial.println(counter);
}
lastCounter = counter;
}
void read_encoder() {
static uint8_t old_AB = 3; // Lookup table index
static int8_t encval = 0; // Encoder value
static const int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0}; // Lookup table
old_AB <<= 2; // Remember previous state
if (digitalRead(ENC_A)) old_AB |= 0x02; // Add current state of pin A
if (digitalRead(ENC_B)) old_AB |= 0x01; // Add current state of pin B
encval += enc_states[( old_AB & 0x0f )];
// Update counter if encoder has rotated a full indent, that is at least 4 steps
if( encval >= 3 ) { // Four steps forward
counter++; // Increase counter
if (counter > max_val) {counter = min_val;}
encval = 0;
}
else if( encval <= -3 ) { // Four steps backwards
counter--; // Decrease counter
if (counter < min_val) {counter = max_val;}
encval = 0;
}
}