Instructions

KY-040 Rotary encoder
Serial.println ("Rotation detected: ");
Serial.print ("Rotational direction: ");
if (Richtung)
{
Serial.println ("Clockwise");
}
else
{
Serial.println("Counterclockwise");
}
Serial.print("Current position: ");
Serial.println(Counter);
Serial.println("------------------------------");
}
// Preparation for the next run:
// The current value will be the last value for the next run.
Pin_clk_Letzter = Pin_clk_Aktuell;
// Reset funciton to save the current position
if (!digitalRead(button_pin) && Counter!=0)
{
Counter = 0;
Serial.println("Position resetted");
}
}
Connections Arduino:
CLK = [Pin 3]
DT = [Pin 4]
Button = [Pin 5]
+ = [Pin 5V]
GND = [Pin GND]
Code example download
KY-40_rotary-encoder_ARD
Code example Raspberry Pi
The program checks which pin has changed first, to get the rotational direction, after detecting a change at
the pin status. You will get the rotational direction after you compare the current status of the pins with the
last status. After detecting the rotational direction, the steps from the start will be counted and outputted.
Pushing the button of the rotary encoder will reset the current position.
# coding=utf-8
# Needed modules will be imported and configured
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# Declaration and initialisation of the input pins which are connected with the sensor.
PIN_CLK = 16
PIN_DT = 15
Export: 16.06.2017 Copyright by Joy-IT - Published under CC BY-NC-SA 3.0 Page 193 of 214