-
-
Save sivar2311/741613a5c8879e1cae567797c57d1445 to your computer and use it in GitHub Desktop.
RotaryEncoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Arduino.h> | |
#include "RotaryEncoder.h" | |
RotaryEncoder encoder(34, 35); | |
void setup() { | |
Serial.begin(115200); | |
} | |
void loop() { | |
if (encoder.available()) { | |
Serial.print(encoder.getPosition()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "RotaryEncoder.h" | |
#include <Arduino.h> | |
#include <FunctionalInterrupt.h> | |
RotaryEncoder::RotaryEncoder(int gpio_clk, int gpio_dt) | |
: gpio_clk(gpio_clk) | |
, gpio_dt(gpio_dt) { | |
pinMode(gpio_clk, INPUT); | |
pinMode(gpio_dt, INPUT); | |
} | |
RotaryEncoder::~RotaryEncoder() { | |
detachInterrupt(gpio_clk); | |
detachInterrupt(gpio_dt); | |
} | |
void RotaryEncoder::begin() { | |
attachInterrupt(gpio_clk, std::bind(&RotaryEncoder::ISR, this), CHANGE); | |
attachInterrupt(gpio_dt, std::bind(&RotaryEncoder::ISR, this), CHANGE); | |
} | |
bool RotaryEncoder::available() { | |
return changed; | |
} | |
int RotaryEncoder::getPosition() { | |
changed = false; | |
return position; | |
} | |
void RotaryEncoder::setPosition(int newPosition) { | |
position = newPosition; | |
} | |
void RotaryEncoder::ISR() { | |
int clk = digitalRead(gpio_clk); | |
int dt = digitalRead(gpio_dt); | |
switch (state) { | |
case 0: | |
if (!clk) state = 1; | |
else if (!dt) state = 4; | |
break; | |
case 1: | |
if (!dt) state++; | |
break; | |
case 2: | |
if (clk) state++; | |
break; | |
case 3: | |
if (clk && dt) { | |
position++; | |
changed = true; | |
state = 0; | |
} | |
break; | |
case 4: | |
if (!clk) state++; | |
break; | |
case 5: | |
if (dt) state++; | |
break; | |
case 6: | |
if (clk && dt) { | |
position--; | |
changed = true; | |
state = 0; | |
} | |
break; | |
default: | |
break; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
class RotaryEncoder { | |
public: | |
RotaryEncoder(int gpio_clk, int gpio_dt); | |
~RotaryEncoder(); | |
void begin(); | |
bool available(); | |
int getPosition(); | |
void setPosition(int newPosition); | |
protected: | |
void ISR(); | |
protected: | |
int gpio_clk, gpio_dt; | |
int position = 0; | |
int state = 0; | |
bool changed = false; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment