simple encoder question

Status
Not open for further replies.
Hello again!

I´m implementing an encoder to my project and decided to use the encoder lib that comes with Teensyduino. As I want it to change a value from 0 to 4 in a loop I had to modify it a bit. Also ist worked more stable after I've added a millis() debounce. So that's what it looks like right now:

#include <Encoder.h>

Encoder myEnc(18, 17);
byte value = 255;
unsigned long debounce = 0;

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

long oldPosition = -999;

void loop() {
long newPosition = myEnc.read() / 4;
if (newPosition > oldPosition && (millis() - debounce > 10)) {
value++;
value %= 5;
oldPosition = newPosition;
Serial.println(value);
debounce = millis();
}
if (newPosition < oldPosition && (millis() - debounce > 10)) {
if(value == 0)
value = 4;
else
value--;
oldPosition = newPosition;
Serial.println(value);
debounce = millis();
}
}

this works quite reliable, but I thought this could be made in a more sophisticated way. This is lets say beginner level. I know that there are commands like "falling" and "rising" but I've never used them, as I saw in tutorials here and there this is mostly used in interrupt routines. In my code I don't have use for the number in "myEnc.read()", I just use it to know if the encoder has been turned left or right. couldn't I say "if the number is rising increase the value" or "if its falling decrease it"? I know, thats what my code does, but could I do it shorter? would like to have some input here.

Thanks in advance, greetings from Bremen, Germany!

Phil.
 
Your code works and it's short and simple (if a bit messy). There is no point changing something like this. Focus your attention on something more important, as I expect you have after one month.
 
This is probably as short as you can get it--one could probably hack some lines out, but without knowing the context, this is probably has short as you can get.


You mention RISING / FALLING, however these are not commands, they are constants used when creating an interrupt (where the MCU will be triggered to perform an activity on a rising edge of a signal, or a falling edge of a signal). something like this.

// in setup
attachInterrupt(2, CALL_THIS_FUNCTION, RISING);

// special function
void CALL_THIS_FUNCTION(){


}
 
Status
Not open for further replies.
Back
Top