diff --git a/libraries/RotaryEncoder/SwRotaryEncoder.cpp b/libraries/RotaryEncoder/SwRotaryEncoder.cpp index 10644d62..b528d4d7 100644 --- a/libraries/RotaryEncoder/SwRotaryEncoder.cpp +++ b/libraries/RotaryEncoder/SwRotaryEncoder.cpp @@ -86,6 +86,11 @@ bool SwRotaryEncoder::begin(uint8_t pina, uint8_t pinb) return true; } +void SwRotaryEncoder::setCallback(callback_t fp) +{ + _cb = fp; +} + void SwRotaryEncoder::stop(void) { detachInterrupt(_pina); @@ -122,9 +127,11 @@ void SwRotaryEncoder::_irq_handler(void) if ( val != digitalRead(_pinb) ) { _abs++; + if (_cb) _cb(1); }else { _abs--; + if (_cb) _cb(-1); } _a_last = val; diff --git a/libraries/RotaryEncoder/SwRotaryEncoder.h b/libraries/RotaryEncoder/SwRotaryEncoder.h index 2455aea4..6ade67fd 100644 --- a/libraries/RotaryEncoder/SwRotaryEncoder.h +++ b/libraries/RotaryEncoder/SwRotaryEncoder.h @@ -43,15 +43,20 @@ class SwRotaryEncoder { public: + typedef void (*callback_t) (int step); + SwRotaryEncoder(void) { _pina = _pinb = 0; _a_last = 0; _last_read = _abs = 0; + + _cb = NULL; } bool begin(uint8_t pina, uint8_t pinb); + void setCallback(callback_t fp); void stop(void); int32_t read(void); @@ -69,6 +74,8 @@ class SwRotaryEncoder int32_t _abs; int32_t _last_read; + + callback_t _cb; }; diff --git a/libraries/RotaryEncoder/examples/SwEncoderCallback/SwEncoderCallback.ino b/libraries/RotaryEncoder/examples/SwEncoderCallback/SwEncoderCallback.ino index 0fc1d7dd..556fe0eb 100644 --- a/libraries/RotaryEncoder/examples/SwEncoderCallback/SwEncoderCallback.ino +++ b/libraries/RotaryEncoder/examples/SwEncoderCallback/SwEncoderCallback.ino @@ -28,20 +28,21 @@ void setup() // Initialize Encoder swEncoder.begin(PIN_A, PIN_B); + swEncoder.setCallback(encoder_callback); } void loop() { - int value = swEncoder.read(); + // do nothing +} - if (value) +void encoder_callback(int step) +{ + if ( step > 0 ) { - if ( value > 0 ) - { - Serial.println("Right"); - }else - { - Serial.println("Left"); - } + Serial.println("Right"); + }else + { + Serial.println("Left"); } }