Rotary Encoder
Principe
Er zijn twee verschillende typen van rotery encoders: absoluut en incremental (relative). De absolute encoders geven de huidige stand van de staaf aan, ze zijn hoek afhankelijk. De incremental encoders geven alleen informatie over de beweging van de staaf. Die beweging data is later vermoedelijk belangrijk voor snelheid van het bewegen etc. Een incremental voorbeeld:
An incremental encoder is a rotary sensor intended to turn rotational displacement into a series of digital pulse signals which are then used to control the angular displacement. It generates two-phase square waves whose phase difference is 90. Usually the two-phase square waves are called channel A and channel B as shown below:

sketch

//Rotary Encoder

/*You will see the angular displacement of the rotary encoder printed on Serial Monitor.
When you turn the rotary encoder clockwise, the angular displacement is increased;
when turn it counterclockwise, the displacement is decreased.
If you press the switch on the rotary encoder, the readings will return to zero.*/
//Email: support@sunfounder.com
//Website: www.sunfounder.com
//2015.5.7

const int clkPin= 2; //the clk attach to pin 2
const int dtPin= 3; //the dt pin attach to pin 3
const int swPin= 4 ;//the sw pin attach to pin 4

int encoderVal = 0;

void setup()
{
//set clkPin,dePin,swPin as INPUT
pinMode(clkPin, INPUT);
pinMode(dtPin, INPUT);
pinMode(swPin, INPUT);
digitalWrite(swPin, HIGH);
Serial.begin(9600); // initialize serial communications at 9600 bps

}

void loop()
{
int change = getEncoderTurn();//
encoderVal = encoderVal + change;
if(digitalRead(swPin) == LOW)//if button pull down
{
encoderVal = 0;
}
Serial.println(encoderVal);
}

int getEncoderTurn(void)
{
static int oldA = HIGH; //set the oldA as HIGH
static int oldB = HIGH; //set the oldB as HIGH
int result = 0;
int newA = digitalRead(clkPin);//read the value of clkPin to newA
int newB = digitalRead(dtPin);//read the value of dtPin to newB
if (newA != oldA || newB != oldB) //if the value of clkPin or the dtPin has changed
{
// something has changed
if (oldA == HIGH && newA == LOW)
{
result = (oldB * 2 - 1);
}
}
oldA = newA;
oldB = newB;
return result;
}

Bronnen:
sunfounder.com