Skip to content

Instantly share code, notes, and snippets.

@buzztiaan
Created November 2, 2013 02:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buzztiaan/7274878 to your computer and use it in GitHub Desktop.
Save buzztiaan/7274878 to your computer and use it in GitHub Desktop.
volatile int state = HIGH;
volatile int flag = HIGH;
volatile int Aold = 0;
volatile int Anew = 0;
volatile int Bold = 0;
volatile int Bnew = 0;
static boolean rotating=false; // debounce management
boolean A_set = false;
boolean B_set = false;
volatile unsigned int encoderpos = 0;
unsigned int lastReportedPos = 1;
volatile long lastDebounceTime = 0;
volatile long debounceDelay = 1;
int count = 0;
#define encoderpinA PD_0
#define encoderpinB PD_1
#define encoderClick PD_2
void setup()
{
Serial.begin(9600);
pinMode(GREEN_LED, OUTPUT);
digitalWrite(GREEN_LED, state);
pinMode(encoderpinA, INPUT_PULLUP);
pinMode(encoderpinB, INPUT_PULLUP);
pinMode(encoderClick, INPUT_PULLUP);
attachInterrupt(encoderpinA, doencoderA, CHANGE);
attachInterrupt(encoderpinB, doencoderB, CHANGE);
attachInterrupt(encoderClick, blink, FALLING);
}
void loop()
{
rotating = true;
digitalWrite(GREEN_LED, state);
if((lastReportedPos != encoderpos)) {
Serial.println(encoderpos);
flag = LOW;
lastReportedPos = encoderpos;
}
}
void doencoderAold() {
Bnew^Aold ? encoderpos++:encoderpos--;
Aold = digitalRead(encoderpinA);
flag= HIGH;
}
void doencoderBold() {
Bnew= digitalRead(encoderpinB);
Bnew^Aold ? encoderpos++:encoderpos--;
flag= HIGH;
}
// Interrupt on A changing state
void doencoderA(){
// debounce
if ( rotating ) delay (debounceDelay); // wait a little until the bouncing is done
// Test transition, did things really change?
if( digitalRead(encoderpinA) != A_set ) { // debounce once more
A_set = !A_set;
// adjust counter + if A leads B
if ( A_set && !B_set )
encoderpos += 1;
rotating = false; // no more debouncing until loop() hits again
}
}
// Interrupt on B changing state, same as A above
void doencoderB(){
if ( rotating ) delay (debounceDelay);
if( digitalRead(encoderpinB) != B_set ) {
B_set = !B_set;
// adjust counter - 1 if B leads A
if( B_set && !A_set )
encoderpos -= 1;
rotating = false;
}
}
void blink()
{
state = !state;
flag = HIGH;
}
@spencercap
Copy link

thanks a ton buzztiaan!

@buzztiaan
Copy link
Author

superwelcome ;) (why didnt i spot this comment earlier?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment