limit on encoder?

Status
Not open for further replies.

heliboy

Active member
I am using encoder from the Teensyduino library on a Teensy 3.2. It works ok but I cannot figure out a way to limit the encoder limits. In other words, I want to count up to say 5 and then further positive movement of the encoder should not generate any number greater then 5. I can constrain or do similar tricks but the encoder keeps counting on internally. So I get 1,2,3,4,5,5,5,5,5, .. if I keep going. Now I if go in the reverse direction it takes a number of clicks before I finally get below 5 and then 4,3,2,1 etc..
I have using the encoder to select options off a menu and this is driving a crazy. Any ideas appreciated.
 
Encoder has a write method to set its value. So you can set it to your constrained value.
 
????

if (x>5) x =5;
else
if (x<1) x=1;

This obvious method does not work. The encoder code keeps incrementing the internal value. So you get 1,2,3,4,5,5,5,5,5,5,5 if you keep turning. Then 5,5,5,5,5,4,3,2,1 on way back. This is no good.
 
Encoder has a write method to set its value. So you can set it to your constrained value.

This does not work either. You can write(0) or whatever but the encoder continues to count for it's last value. Maybe there is reset method but I cannot find it.
 
Calling the following function with the current encoder value should do the trick...

Code:
int limit(int current)
{
	static int last = 0;
	static int val = 0;

	int delta =  current - last;
	last = current;

	val = min(val + delta, 5) ;
	return val;
}
 
This does not work either. You can write(0) or whatever but the encoder continues to count for it's last value. Maybe there is reset method but I cannot find it.
It works. You are probably doing it wrong.

Code:
#include <Encoder.h>

Encoder enc(6, 7);
const int32_t enc_min = 0;
const int32_t enc_max = 5;

void setup() {
    Serial.begin(9600);
    delay(2000);
}

int32_t old_enc_val = 0;

void loop() {
    int32_t enc_val = enc.read();
    if(enc_val < enc_min) {
        enc_val = enc_min;
        enc.write(enc_min);
    } else if(enc_val > enc_max) {
        enc_val = enc_max;
        enc.write(enc_max);
    }
    if(enc_val != old_enc_val) {
        Serial.println(enc_val);
        old_enc_val = enc_val;
    }
}
 
It sounds like the OP is using an interrupt-driven encoder reader... more info is needed.
If that's the case, the file "encoder.h", which contains the code, could be modified.
Best would be to make the limit(s) a function parameter, but they could be hard-coded.
 
Status
Not open for further replies.
Back
Top