Skip to content

Instantly share code, notes, and snippets.

@sivar2311
Created January 12, 2024 16:29
Show Gist options
  • Save sivar2311/741613a5c8879e1cae567797c57d1445 to your computer and use it in GitHub Desktop.
Save sivar2311/741613a5c8879e1cae567797c57d1445 to your computer and use it in GitHub Desktop.
RotaryEncoder
#include <Arduino.h>
#include "RotaryEncoder.h"
RotaryEncoder encoder(34, 35);
void setup() {
Serial.begin(115200);
}
void loop() {
if (encoder.available()) {
Serial.print(encoder.getPosition());
}
}
#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;
}
}
#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