diff --git a/Encoder.h b/Encoder.h index 9ed35ee..5aa6cbb 100644 --- a/Encoder.h +++ b/Encoder.h @@ -151,6 +151,17 @@ class Encoder encoder.position = p; } #endif + inline int32_t getDirection() { + int32_t prevPos = encoder.position; + long currPos = read(); + int32_t direction = 0; + if (currPos > prevPos) { + direction = 1; + } else if (currPos < prevPos) { + direction = -1; + } + return direction; + } private: Encoder_internal_state_t encoder; #ifdef ENCODER_USE_INTERRUPTS diff --git a/examples/Direction/Direction.ino b/examples/Direction/Direction.ino new file mode 100644 index 0000000..e6abd86 --- /dev/null +++ b/examples/Direction/Direction.ino @@ -0,0 +1,29 @@ +/* Encoder Library - Basic Example + * http://www.pjrc.com/teensy/td_libs_Encoder.html + * + * This example code is in the public domain. + */ + +#include + +// Change these two numbers to the pins connected to your encoder. +// Best Performance: both pins have interrupt capability +// Good Performance: only the first pin has interrupt capability +// Low Performance: neither pin has interrupt capability +Encoder myEnc(5, 6); +// avoid using pins with LEDs attached + +void setup() { + Serial.begin(9600); + Serial.println("Encoder Direction Test:"); +} + +void loop() { + int direction = myEnc.getDirection(); + + if (direction > 0) { + Serial.println("Forward"); + } else if (direction < 0) { + Serial.println("Backward"); + } +}