Skip to content

Instantly share code, notes, and snippets.

@tegila
Created May 6, 2015 04:12
Show Gist options
  • Save tegila/9fc3cc35df50089f7189 to your computer and use it in GitHub Desktop.
Save tegila/9fc3cc35df50089f7189 to your computer and use it in GitHub Desktop.
Rotary Encoder KY-040 from China - Sample Code
long virtualPosition=0;
#define PinCLK 2 // Used for generating interrupts using CLK signal
#define PinDT 3 // Used for reading DT signal
#define PinSW 4 // Used for the push button switc
void isr () {
noInterrupts();
if (digitalRead(PinCLK) == digitalRead(PinDT))
virtualPosition++;
else
virtualPosition--;
Serial.print ("Count = ");
Serial.println (virtualPosition);
interrupts();
}
void setup () {
pinMode(PinCLK,INPUT);
pinMode(PinDT,INPUT);
pinMode(PinSW,INPUT);
attachInterrupt (0,isr,CHANGE); // interrupt 0 is always connected to pin 2 on Arduino UNO
Serial.begin (9600);
Serial.println("Start");
}
void loop () {
}
@tegila
Copy link
Author

tegila commented May 6, 2015

TERMINAL OUTPUT:
Start
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
Count = 6
Count = 5
Count = 6
Count = 7
Count = 8
Count = 9
Count = 10

@bratoff
Copy link

bratoff commented Apr 9, 2018

This code will double-count each detent. You should only use one edge of CLK, not both.

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