Skip to content

Instantly share code, notes, and snippets.

@delta-G
Last active January 4, 2018 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save delta-G/3ca70a737234fd2d615a0298e2d62306 to your computer and use it in GitHub Desktop.
Save delta-G/3ca70a737234fd2d615a0298e2d62306 to your computer and use it in GitHub Desktop.
// Code compiles but is untested
// In reality it would be too slow
// But it is easier to understand the
// concept here with digitalRead than
// it is with diret port reads
// I have used the same code written
// with port reads many times to read
// encoders. It works.
// If your encoder gives four increments per "click"
// and you only want one, then remove one interrupt
// entirely and set the other to RISING or FALLING
// instead of CHANGE.
// The two pins from the encoder
const byte epinA = 2;
const byte epinB = 3;
int printInterval = 500;
volatile int encoderCount = 0;
void setup(){
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(epinA), eintA, CHANGE);
attachInterrupt(digitalPinToInterrupt(epinB), eintB, CHANGE);
}
void loop(){
static unsigned long pt = millis();
unsigned long ct = millis();
int encoderRead = 0;
if(ct - pt >= printInterval){
cli();
encoderRead = encoderCount;
sei();
Serial.println(encoderRead);
}
}
/*
This is actually too slow for fast encoders.
Should use direct port reads instead of
digitalRead. But this illustrates the point.
if your encoder ends up going backwards
just switch the ++ and -- in both ISR's.
*/
void eintA(){
// if the pins read the same we're going one direction
// else we're going the other direction.
if(digitalRead(epinA) == digitalRead(epinB)){
encoderCount++;
}
else {
encoderCount--;
}
}
void eintB(){
// Same as above, except the directions are switched for
// the other pin.
if(digitalRead(epinB) == digitalRead(epinA)){
encoderCount--;
}
else {
encoderCount++;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment