Pin names
Rotary encoder pin A
Rotary encoder pin B
Push button pin. Normally open, shorted to GND on press
Voltage supply
Ground
Operation
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.
- 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.
Schematics
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.Using the Rotary Encoder in Arduino
Reading the rotation
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:Your code will need to read the state of the pins frequently in order to detect the rotations correctly.
If your
loop() takes too long (e.g. you use delay() in your code), we recommend using attachInterrupt() to listen for changes in the CLK pin.Using the button
To read the state of the encoder’s button, connect to to any Arduino IO pin and initialize this pin asINPUT_PULLUP. Then read the state of the button using digitalRead().
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.
Keyboard control
To control the rotary encoder with the keyboard, first click on it, then use the following keys:| Key | Function |
|---|---|
| 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.