Created
May 6, 2015 04:12
-
-
Save tegila/9fc3cc35df50089f7189 to your computer and use it in GitHub Desktop.
Rotary Encoder KY-040 from China - Sample Code
This file contains 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
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 () { | |
} |
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
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