/* This sketch shows an interface between a KY-040 or EC-11 mechanical rotary
encoder and an Arduino nano.
The interpreted data is a counter value displayed on the serial monitor
A counter update is triggered at each encoder rotation step.
The CLK pin(A) is pulled up in the circuit and pin C is connected to GND.
The CLK pin(A) goes LOW (or connects to C), then goes back HIGH during each
encoder step, in either direction. The CLK pin also connects to the DT pin(B)
during each encoder step.
CONDITION CHECK CONDITION CHECK
: :
________. : ___.____//____.___ : ._________ 1
.|: | . . |: |.
D3 : CK : A .|:_____| . . |:_____|. 0
. :[CK=0] . . :[CK=0].
________._:[DT=1] ._____//___. : ____._________ 1
. | |. .| : | .
D4 : DT : B . |______|. .|___:[DT=0]. 0
|<--------->| |<--------->|
one step CW one step CCW
If CLK goes to ground before connecting to pin DT(B), the encoder is rotating
clockwise. IF CLK goes to ground after connecting to pin DT(B), the encoder
is rotating counterclockwise.
In the code, the rotary encoder is deemed to rotate whenever CLK pin(A) goes
LOW (connects to C). While CLK pin is stilLOW, the status of pin DT(B) is read:
-If DT != CLK (or 0), then the rotation is CW & the counter is incremented
-If DT == CLK (or 0), then the rotation is CCW & the counter is decremented
The counter is reset if SW goes low. */
#include <LibPrintf.h>
#define CLK 3
#define DT 4
#define SW 5
int counter1;
int counter2;
int CLK_State;
int DT_State;
int SW_State;
void setup()
{
pinMode(CLK, INPUT_PULLUP); // Digital pin 3
pinMode(DT, INPUT_PULLUP); // Digital pin 4
pinMode(SW, INPUT_PULLUP); // Digital pin 5
Serial.begin(9600);
}
void loop()
{
int last_CLK = 1;counter1 = 0;counter2 = 0;
while (last_CLK)
{
for (int i = 0; i < 2000; i++)
{
if (digitalRead(CLK) == 0) // Detects CLK cycle (During cycle, CLK goes down then back up)
{
last_CLK = 0;
if (digitalRead(DT) != 0)
{
counter1++; // if DT != 0 : Rotation is CW : Increase counter by 1
}
else
{
counter2--; // if DT == 0 : Rotation is CCW : Decrease counter by 1
}
if (digitalRead(SW) == 0) // If switch is pressed : Reset counter
{
counter1 = 0;
printf("Switch pressed. Counter reset to 0\n");
delay(1000);
}
}
}
}
printf("CW steps : %i | CCW steps : %i\n", counter1, counter2);
last_CLK = 1;
delay(200);
//exit(0);
}