Created
November 2, 2013 02:43
-
-
Save buzztiaan/7274878 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
thanks a ton buzztiaan!