Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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