Skip to content

Instantly share code, notes, and snippets.

@mumrah
Created November 6, 2017 02: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 mumrah/ccd82aa13e784e77b788810dbaa8f4a3 to your computer and use it in GitHub Desktop.
Save mumrah/ccd82aa13e784e77b788810dbaa8f4a3 to your computer and use it in GitHub Desktop.
Sketch for a KY-040 rotary encoder
/**
* Sketch for KY-040 Encoders
*
* SW pin _must_ have a pull up resistor on it.
*
* CLK and DT _should_ have a ~0.1uF for hardware debounce.
*/
int pinSW = 2;
int pinCLK = 3; // Connected to CLK on KY-040
int pinDT = 4; // Connected to DT on KY-040
int encoderPosCount = 0;
int pinClkLast;
int clkVal;
boolean bCW;
void setup() {
pinMode (pinSW, INPUT);
pinMode (pinCLK, INPUT);
pinMode (pinDT, INPUT);
/* Read Pin A
Whatever state it's in will reflect the last position
*/
pinClkLast = digitalRead(pinCLK);
Serial.begin (9600);
}
volatile uint8_t sw_buffer = 0xFF;
void loop() {
clkVal = digitalRead(pinCLK);
if (clkVal != pinClkLast){ // Means the knob is rotating
// if the knob is rotating, we need to determine direction
// We do that by reading pin B.
if (digitalRead(pinDT) != clkVal) { // Means pin A Changed first - We're Rotating Clockwise
encoderPosCount ++;
bCW = true;
} else {// Otherwise B changed first and we're moving CCW
bCW = false;
encoderPosCount--;
}
Serial.print ("Rotated: ");
if (bCW){
Serial.println ("clockwise");
}else{
Serial.println("counterclockwise");
}
Serial.print("Encoder Position: ");
Serial.println(encoderPosCount);
sw_buffer = 0xFF;
} else {
// check for click, use software debounce
int new_state = digitalRead(pinSW);
sw_buffer = (sw_buffer << 1) & 0xff;
sw_buffer |= (new_state & 0x1);
// if last 4 reads were 0, we detect a click
if(sw_buffer == 0xF0) {
Serial.println("CLICK");
}
}
pinClkLast = clkVal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment