Skip to content

Add getDirection() support to ModulinoKnob and example ⚑ #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

6 changes: 6 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
11 changes: 10 additions & 1 deletion examples/Modulino_Knob/Knob_Basic/Knob_Basic.ino
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -32,4 +34,11 @@ void loop(){
Serial.println("Clicked!");
}

}
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
}
24 changes: 23 additions & 1 deletion src/Modulino.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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])) {
Expand All @@ -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 };
};
Expand Down