KY-040 Rotary Encoder |
KY-040 Rotary Encoder PinOut |
Keyes Rotary Encoder Schematic |
KY-040 Evaluation Circuit |
KY-04 Connection to the Arduino |
Arduino Sketch
int pinA = 3; // Connected to CLK on KY-040
int pinB = 4; // Connected to DT on KY-040
int encoderPosCount = 0;
int pinALast;
int aVal;
boolean bCW;
void setup()
int encoderPosCount = 0;
int pinALast;
int aVal;
boolean bCW;
void setup()
{
pinMode (pinA,INPUT);
pinMode (pinB,INPUT);
/* Read Pin A
Whatever state it's in will reflect the last position
*/
pinALast = digitalRead(pinA);
Serial.begin (9600);
}
void loop()
pinMode (pinA,INPUT);
pinMode (pinB,INPUT);
/* Read Pin A
Whatever state it's in will reflect the last position
*/
pinALast = digitalRead(pinA);
Serial.begin (9600);
}
void loop()
{
aVal = digitalRead(pinA);
if (aVal != pinALast)
aVal = digitalRead(pinA);
if (aVal != pinALast)
{
// Means the knob is rotating
// if the knob is rotating, we need to determine direction
// We do that by reading pin B.
if (digitalRead(pinB) != aVal)
// if the knob is rotating, we need to determine direction
// We do that by reading pin B.
if (digitalRead(pinB) != aVal)
{
// Means pin A Changed first - We're Rotating Clockwise
encoderPosCount ++;
bCW = true;
}
encoderPosCount ++;
bCW = true;
}
else
{
// Otherwise B changed first and we're moving CCW
bCW = false;
encoderPosCount--;
}
Serial.print ("Rotated: ");
if (bCW)
bCW = false;
encoderPosCount--;
}
Serial.print ("Rotated: ");
if (bCW)
{
Serial.println ("clockwise");
}
Serial.println ("clockwise");
}
else
{
Serial.println("counterclockwise");
}
Serial.print("Encoder Position: ");
Serial.println(encoderPosCount);
}
pinALast = aVal;
Serial.println("counterclockwise");
}
Serial.print("Encoder Position: ");
Serial.println(encoderPosCount);
}
pinALast = aVal;
}
Sumber
Keyes KY-040 Arduino Rotary Encoder User Manual
Where to buy
KY-040 Rotary Encoder Module
Tidak ada komentar:
Posting Komentar