Read a KY-040 rotary encoder with an Arduino
FunduinoPublished on
Drehrichtung und Schritte auslesen – mit Interrupt für den Taster
You need this
KY-040 Rotary Encoder - Incremental Encoder with Push Button, 5 V
1,84 € *Item no. FUN-1010566About the product — KY-040 Rotary Encoder - Incremental Encoder with Push Button, 5 V
Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino
11,12 € *Item no. F23107480About the product — Funduino UNO R3 Microcontroller - ATmega328P, 16 MHz, for Arduino
830-point Breadboard - solderless breadboard for Arduino
2,90 € *Item no. FUN-1010553About the product — 830-point Breadboard - solderless breadboard for Arduino
All 3 parts together 15,86 € *Ready to ship immediately · Delivery time: 1-3 business days
* All prices include statutory VAT, plus shipping costs.
How does the encoder work?
1 / 2
Pinout
Example sketch
Read the step position and key press
#include <Encoder.h> // Using the library
const int CLK = 6; // Pin definitions. CLK to D6, DT to D5.
const int DT = 5;
const int SW = 2; // The switch is connected to pin D2. IMPORTANT: Use an interrupt pin!
long altePosition = -999; // Definition of the "old" position (This fictitious old position is needed so that the current position is displayed in the serial monitor later only when we move the rotary encoder)
Encoder meinEncoder(DT,CLK); // A new encoder project is created here. The connection is made using the previously defined variables (DT and CLK).
void setup() // Beginning of setup
{
Serial.begin(9600);
pinMode(SW, INPUT); // The interrupt is installed here.
attachInterrupt(digitalPinToInterrupt(SW), Interrupt, CHANGE); // As soon as the status (CHANGE) of the interrupt pin (SW = D2) changes, the interrupt command is executed.
}
void loop()
{
long neuePosition = meinEncoder.read(); // The encoder's "new" position is defined. The encoder's current position is read using the Variable.Command().
if (neuePosition != altePosition) // If the new position is not equal to the old one (-999) (and only then!)…
{
altePosition = neuePosition;
Serial.println(neuePosition); // …the current position is displayed in the serial monitor.
}
}
void Interrupt() // Beginning of the interrupt. When the rotary knob is pressed, the program automatically jumps to this point. After…
{
Serial.println("Switch pressed"); //…after the signal is output, the program continues.
}Rate the instructions