Skip to content

Instantly share code, notes, and snippets.

@antimodular
Last active April 13, 2022 03:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antimodular/b1fdf1389ba0bdb30d67 to your computer and use it in GitHub Desktop.
Save antimodular/b1fdf1389ba0bdb30d67 to your computer and use it in GitHub Desktop.
#include "rotaryencoder.h"
int rotaryencoder::counterValue;
bool rotaryencoder::A_set;
bool rotaryencoder::B_set;
rotaryencoder::rotaryencoder(int _a, int _b) {
encoderPinA = _a;
encoderPinB = _b;
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
pullUpDnControl(encoderPinA, PUD_UP);
pullUpDnControl(encoderPinB, PUD_UP);
if ( wiringPiISR (encoderPinA,INT_EDGE_BOTH, &handleInterrupt) < 0 ) {
// ofLog()<<"Unable to setup encoderPinA ISR";
}
if ( wiringPiISR (encoderPinB,INT_EDGE_BOTH, &handleInterrupt) < 0 ) {
// ofLog()<<"Unable to setup encoderPinB ISR";
}
}
void rotaryencoder::update(){
wrappedCounter = 0;
if(counterValue < 0 ) wrappedCounter = linesPerRevolution + counterValue;
else wrappedCounter = counterValue;
encoderPosition = (int)ofMap(wrappedCounter,0,linesPerRevolution,0,2400); //1200 = (60 frames per sec) * (20 sec per 360 degrees)
}
void rotaryencoder::handleInterrupt() {
rotaryencoder::A_set = digitalRead(0) == HIGH;
rotaryencoder::counterValue += (rotaryencoder::A_set == rotaryencoder::B_set) ? +1 : -1;
rotaryencoder::B_set = digitalRead(7) == HIGH;
rotaryencoder::counterValue += (rotaryencoder::A_set != rotaryencoder::B_set) ? +1 : -1;
rotaryencoder::counterValue = rotaryencoder::counterValue % linesPerRevolution; //keeps the counter between -9600 and 9600
}
//http://www.disk91.com/2013/technology/hardware/oregon-scientific-sensors-with-raspberry-pi/
#pragma once
#include "ofMain.h"
#include "wiringPi.h"
#define linesPerRevolution 9600 //500 lines * 4 edges * gear ratio (48:10);
class rotaryencoder
{
public:
rotaryencoder(int _a, int _b);
void update();
//encoder
int encoderPinA = 0; //A2
int encoderPinB = 7; //A3
int dir = 1;
int encoderPosition = 0;
unsigned int wrappedCounter = 1;
private:
static void handleInterrupt();
static int counterValue;
static bool A_set;
static bool B_set;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment