diff --git a/src/main.cpp b/src/main.cpp index 1ba6448..5e69d1e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -38,6 +38,7 @@ #include #include "595n.h" #include "165.h" +#include "rotaryEncoder.h" #include // NOTES - 595N @@ -145,6 +146,8 @@ Joystick_ Joystick( false ); +RotaryEncoder re1 = NewRotaryEncoder(14, 16); + #define PULSE_DURATION 100 // ms const int pulseButtons[] = { @@ -173,10 +176,12 @@ void setup() { } SR595N_write(&input, 0b00000100); + RotaryEncoder_init(&re1); } // TODO - comment this debugging thing at the end // unsigned long lastPrint = 0; +int lastRE = 0; void loop(void) { unsigned long currentMillis = millis(); diff --git a/src/rotaryEncoder.cpp b/src/rotaryEncoder.cpp new file mode 100644 index 0000000..21311d0 --- /dev/null +++ b/src/rotaryEncoder.cpp @@ -0,0 +1,32 @@ +#include "rotaryEncoder.h" +#include "Arduino.h" + +RotaryEncoder NewRotaryEncoder(int clk, int dt) { + return RotaryEncoder{ + .clkPin = clk, + .dtPin = dt, + }; +} + +void RotaryEncoder_init(RotaryEncoder *enc) { + pinMode(enc->clkPin, INPUT_PULLUP); + pinMode(enc->dtPin, INPUT_PULLUP); + enc->lastStateCLK = digitalRead(enc->clkPin); +} + +int RotaryEncoder_read(RotaryEncoder *enc) { + int curStateClk = digitalRead(enc->clkPin); + int direction = RE_NOCHANGE; + + if (curStateClk != enc->lastStateCLK && curStateClk == 1) { + if (digitalRead(enc->dtPin) != curStateClk) { + direction = RE_CCW; + } else { + direction = RE_CW; + } + } + + enc->lastStateCLK = curStateClk; + + return direction; +} diff --git a/src/rotaryEncoder.h b/src/rotaryEncoder.h new file mode 100644 index 0000000..e941850 --- /dev/null +++ b/src/rotaryEncoder.h @@ -0,0 +1,19 @@ +#ifndef __ROTARY_ENC__ +#define __ROTARY_ENC__ + +const int RE_NOCHANGE = 0; +const int RE_CCW = -1; +const int RE_CW = 1; + +typedef struct { + int clkPin; + int dtPin; + + int lastStateCLK; +} RotaryEncoder; + +RotaryEncoder NewRotaryEncoder(int clk, int dt); +void RotaryEncoder_init(RotaryEncoder *enc); +int RotaryEncoder_read(RotaryEncoder *enc); + +#endif