When the rotary switch is moved, the direction of movement and the current position of the rotary switch are coded and output via the outputs.

coding

With a rotary switch, the state of the two outputs changes per step. The direction of rotation can be determined by checking which of the two states changed first.

pin assignment

Code example Arduino

Pin assignment Arduino

Arduino Sensor
5 V + V
Ground GND
Pin 3 CLK
Pin 4 DT
Pin 5 Button

The sample program checks for the change of the pin states and determines the direction of rotation as soon as a rotation has been detected. After the direction has been determined, the steps from the start position are counted and output. Pressing the button resets the count.

// Initialization of the required variables
int counter = 0;
boolean direction;
int Pin_clk_Last;
int Pin_clk_Aktuell;
 
// Definition of the input pins
int pin_clk = 3;
int pin_dt = 4;
int button_pin = 5;
  
  
void setup ()
{
   // input pins are initialized ...
   pinMode (pin_clk, INPUT);
   pinMode (pin_dt, INPUT);
   pinMode (button_pin, INPUT);
    
   // ... and their pull-up resistors activated
   digitalWrite (pin_clk, true);
   digitalWrite (pin_dt, true);
   digitalWrite (button_pin, true);
    
   // Initial reading of the Pin_CLK
   Pin_clk_last = digitalRead (pin_clk);
   Serial.begin (115200);
 }
 
// If the pin status has changed, the program checks which of the two
// Pins changed first, which indicates the direction of rotation.
// This information is obtained by taking one of the two pin values from a previous
// Compare pass with the value of the current pass.
// After the direction has been determined, the steps are counted and output from the start position.
// Pressing the rotary encoder button resets the current position.
 
void loop ()
{
   // Read out the current status
   Pin_clk_Aktuell = digitalRead (pin_clk);
    
   // Check for change
   if (Pin_clk_Aktuell! = Pin_clk_Lieter)
   {
          
        if (digitalRead (pin_dt)! = Pin_clk_Aktuell)
        {
            // Pin_CLK changed first
            Counter ++;
            Direction = true;
        }
          
        else
        {// Otherwise, Pin_DT changed first
            Direction = false;
            Counter--;
        }
        Serial.println ("Rotation detected:");
        Serial.print ("Direction of rotation:");
         
        if (direction)
        {
           Serial.println ("clockwise");
        }
        else
        {
           Serial.println ("counterclockwise");
        }
         
        Serial.print ("Current position:");
        Serial.println (Counter);
        Serial.println ("------------------------------");
          
   }
    
   // Preparation for the next run:
   // The value of the current run is the previous value for the next run
   Pin_clk_Lieter = Pin_clk_Aktuell;
    
   // Reset function to save the current position
   if (! digitalRead (button_pin) && Counter! = 0)
     {
       Counter = 0;
       Serial.println ("position reset");
     }
      
 }

Sample program download

KY040-Arduino.zip

Code example Raspberry Pi

Pin assignment Raspberry Pi

Raspberry Pi Sensor
GPIO 14 [pin 8] Button
3.3 V [pin 1] + V
Ground [pin 6] GND
GPIO 16 [pin 36] CLK
GPIO 15 [pin 10] DT

The sample program checks for the change of the pin states and determines the direction of rotation as soon as a rotation has been detected. After the direction has been determined, the steps from the start position are counted and output. Pressing the button resets the count.

# coding=utf-8
# required modules are imported and set up
import RPi.GPIO as GPIO
import time
 
GPIO.setmode(GPIO.BCM)
 
# Here the input pins are declared, to which the sensor is connected.
PIN_CLK = 16
PIN_DT = 15
BUTTON_PIN = 14
 
GPIO.setup(PIN_CLK, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(PIN_DT, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP)
 
# Required variables are initialized
Counter = 0
direction = True
PIN_CLK_LAST = 0
PIN_CLK_CURRENT = 0
delayTime = 0.01
 
# Initial readout of the pin_CLK
PIN_CLK_LETZTER = GPIO.input(PIN_CLK)
 
# This output function is executed on signal detection
def outputFunction(null):
    global Counter
 
    PIN_CLK_CURRENT = GPIO.input(PIN_CLK)
 
    if PIN_CLK_ACTUAL != PIN_CLK_LETZTER:
 
        if GPIO.input(PIN_DT) != PIN_CLK_ACTUAL:
            Counter += 1
            Direction = True;
        else:
            Direction = False
            Counter = Counter - 1
 
        print ("Rotation detected: ")
 
        if Direction:
            print ("Direction of rotation: Clockwise")
        else:
            print ("Direction of rotation: Counterclockwise")
 
        print ("Current position: ", Counter)
        print ("------------------------------")
 
def CounterReset(null):
    global Counter
 
    print ("Position reset!")
    print ("------------------------------")
    Counter = 0
 
# To integrate a debounce directly, the functions for output are initialized using the
# CallBack option initialized by the GPIO Python module
GPIO.add_event_detect(PIN_CLK, GPIO.BOTH, callback=output_function, bouncetime=50)
GPIO.add_event_detect(BUTTON_PIN, GPIO.FALLING, callback=CounterReset, bouncetime=50)
 
 
print ("Sensor test [press CTRL+C to end test]")
 
# main program loop
try:
        while True:
            time.sleep(delayTime)
 
# clean up after the program is finished
except KeyboardInterrupt:
        GPIO.cleanup()

Sample program download

KY040-RPi.zip

To start with the command:

sudo python3 KY040-RPi.py

Code example Micro:Bit

Pinout Micro:Bit:

Micro:Bit Sensor
3 V +V
Ground GND
Pin 1 CLK
Pin 2 DT
Pin 0 Button

Sample program download

microbit-KY-040.zip