KY-040 Rotary Encoder module with 20 steps per revolution.
|CLK||Rotary encoder pin A|
|DT||Rotary encoder pin B|
|SW||Push button pin. Normally open, shorted to GND on press|
The rotary encoder offers two ways of interaction:
- Rotation - You can rotate the knob by clicking on the arrows. The upper arrow rotates it one step clockwise, and the lower arrow rotates it one step counterclockwise. Rotating the knob will produce digital signals on the DT and CLK pins, as explained below.
- Button - Click on the knob to press the button. While pressed, the button connects the SW pin with the GND pin.
Every time the user rotates the knob, it produces a LOW signal on the DT and CLK pins:
- Rotating clockwise causes the CLK pin to go low first, and then the DT pin goes low too.
- Rotating counterclockwise causes the DT pin to go low first, and then the CLK pin go low.
Both pins will go back high within a few milliseconds. The following diagram illustrates this:
The KY-040 module includes two internal pull-up resistors that pull-up pins CLK and DT to VCC. The simulation always pulls these pins up, even if you left the VCC pin floating.
You can read the rotation by checking the status of the CLK pin. Whenever it goes LOW, read the value of the DT pin to determine the direction: HIGH means clockwise rotation, LOW means counterclockwise rotation. Code example:
You can also run this example on Wokwi.
Note: your code will need to read the state of the pins frequently in order to detect the rotations
loop() takes too long (e.g. you use
delay() in your code), we recommend using attachInterrupt() to listen for changes in the CLK pin. Assuming CLK is connected to pin 2, and DT to pin 3 (as before):
To read the state of the encoder's button, connect to to any Arduino IO pin and initialize this pin as
INPUT_PULLUP. Then read the state of the button using
It'll read LOW as long the the button is pressed.
The following code example will turn on Arduino's built-in LED (13) as long as the button is pressed. It assumes you connected the SW to Arduino pin 4. You also need to connect the GND pin to one of the Arduino's GND pins.
To control the rotary encoder with the keyboard, first on on it, then use the following keys:
|Right / Up||Rotate one step clockwise*|
|Left / Down||Rotate one step counterclockwise*|
|Spacebar||Press the button|
* Hold down the arrow keys to continuously rotate the encoder, generating a series of pulses on the CLK/DT pins.