diff --git a/docs/api.md b/docs/api.md index 7c463c0..225181b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -90,6 +90,12 @@ Represents a Modulino Knob module. - **`bool isPressed()`** Returns `true` if the button on the knob is pressed, `false` otherwise. +- **`int8_t getDirection()`** + Returns the direction of the knob rotation. + - `1` for clockwise + - `-1` for counter-clockwise + - `0` if no movement is detected + - **`void set(int16_t value)`** Sets the knob value. diff --git a/examples/Modulino_Knob/Knob_Basic/Knob_Basic.ino b/examples/Modulino_Knob/Knob_Basic/Knob_Basic.ino index b933002..60dc248 100644 --- a/examples/Modulino_Knob/Knob_Basic/Knob_Basic.ino +++ b/examples/Modulino_Knob/Knob_Basic/Knob_Basic.ino @@ -24,6 +24,8 @@ void loop(){ int position = knob.get(); // Check if the knob has been pressed (clicked) bool click = knob.isPressed(); + // Get the rotation direction + int8_t direction = knob.getDirection(); Serial.print("Current position is: "); Serial.println(position); @@ -32,4 +34,11 @@ void loop(){ Serial.println("Clicked!"); } -} \ No newline at end of file + if (direction == 1) { + Serial.println("Rotated clockwise"); + } else if (direction == -1) { + Serial.println("Rotated counter-clockwise"); + } + + delay(10); // optional small delay to reduce serial spam +} \ No newline at end of file diff --git a/src/Modulino.h b/src/Modulino.h index 6f62aaf..365d3c1 100644 --- a/src/Modulino.h +++ b/src/Modulino.h @@ -243,8 +243,9 @@ class ModulinoKnob : public Module { bool begin() { auto ret = Module::begin(); if (ret) { - // check for set() bug auto _val = get(); + _lastPosition = _val; + _lastDebounceTime = millis(); set(100); if (get() != 100) { _bug_on_set = true; @@ -277,6 +278,24 @@ class ModulinoKnob : public Module { get(); return _pressed; } + int8_t getDirection() { + unsigned long now = millis(); + if (now - _lastDebounceTime < DEBOUNCE_DELAY) { + return 0; + } + int16_t current = get(); + int8_t direction = 0; + if (current > _lastPosition) { + direction = 1; + } else if (current < _lastPosition) { + direction = -1; + } + if (direction != 0) { + _lastDebounceTime = now; + _lastPosition = current; + } + return direction; + } virtual uint8_t discover() { for (unsigned int i = 0; i < sizeof(match)/sizeof(match[0]); i++) { if (scan(match[i])) { @@ -288,6 +307,9 @@ class ModulinoKnob : public Module { private: bool _pressed = false; bool _bug_on_set = false; + int16_t _lastPosition = 0; + unsigned long _lastDebounceTime = 0; + static constexpr unsigned long DEBOUNCE_DELAY = 30; protected: uint8_t match[2] = { 0x74, 0x76 }; };