Same-day dispatch before 2 PM · Free delivery over ₹999 · GST invoices Get the appPrices incl. GST
Geekobot
Snap & SendNEWGeeko AIWhere's myOrder
Log in
Products
  • Projects
    • Component guidesHow parts work, with code you can run
    • Learning pathsFrom your first LED to your first robot
    • Workshops & eventsOnline sessions for makers and classes
    • ElectrolarkFree guided builds, simulator and certificates
    • Students & teachersStudent discount and classroom help
    • CommunityShare builds and ask other makers
    • CalculatorsOhm's law, LED resistor, 555 and 100+ more
    • Circuit builderWire parts and run the circuit, powered by Electrolark
    • Geeko AIAsk what to buy or how to wire it
    • Snap & SendPhotograph a part or list, we find it
    • Part finderAnswer a few questions, get the right part
    • Compatibility checkWill these two parts work together?
    • Compare partsSpecs side by side
    • Business & bulk ordersGST invoices, credit and volume prices
    • Request a quotationSend your list, get a quote
    • Classroom kitsPer-student kits and lab bundles
    • Gift cardsFor students, teams and events
  • Atal Tinkering Lab
BOM to cart
Geekobot

Components, kits and know-how for makers, students, engineers, labs and businesses across India.

Ask Geeko AIOrders, parts and projects, any timeEmail supportReply within 1 working dayGet the Geekobot appAdd it to your home screen, free

Follow us

Shop

  • Boards & SBCs
  • Sensors & Modules
  • IoT & Wireless
  • Drone & FPV
  • 3D Printing
  • Filaments & Resins
  • Motors & Drivers
  • Power & Batteries
  • Semiconductors
  • Passive
  • Displays & LEDs
  • Switches & Relays
  • Wires & Cables
  • Prototyping
  • Tools & Test
  • Robotics
  • STEM Kits
  • Atal Tinkering Lab
  • Mechanical Parts
  • Audio

Orders

  • Track your order
  • Help & support
  • Shipping and delivery
  • Refunds and cancellation
  • Contact us

Learn

  • Projects
  • Geeko AI project assistant
  • Learning paths
  • Guides
  • Calculators
  • Electrolark: free guided builds

Part tools

  • Part finder
  • Compare parts
  • Will it work with my board?

Institutions

  • Classroom kits
  • Atal Tinkering Lab
  • Students & teachers
  • Workshops & Events

Business

  • Business & education
  • Request a quotation
  • BOM bulk upload
  • Quick order by SKU

Company

  • About Geekobot
  • Community
  • Gift cards
  • Terms & conditions
  • Privacy policy
  • Product directory
  • Sitemap

© 2026 Geekobot, a trade name of OLatus Systems Private Limited. All rights reserved.

20, 1st Floor, Neeladri Complex, 10th Cross, Sampige Rd, 2nd Main, Malleshwaram, Bengaluru, Karnataka 560003 · GSTIN 29AACCO0462F1ZM

+91 91810 15607 · connect@geekobot.in · Monday to Saturday, 10 AM to 2 PM IST

UPI · CARDS · NETBANKING · GST INVOICES

ShopProjectsGeeko AIGuides
Compare 0 parts →
Log in

Shop by category

Shop all components
  • Boards & SBCs1,910 products
    • Alternative Single Board Computers
    • Arduino Ecosystem
    • FPGA & Logic Boards
    • Microcontroller & Wireless Boards
    View all
  • Sensors & Modules4,701 products
    • Biomedical & Heart Rate
    • Current, Voltage & Power
    • Force, Weight & Pressure
    • Gas, Weather & Environmental
    View all
  • IoT & Wireless2,314 products
    • RF Modules
    • RFID & NFC
    • Antennas & RF Accessories
    • Cameras & Smart Vision
    View all
  • Drone & FPV3,558 products
    • Flight Control & Navigation
    • FPV Video & Optics
    • Frames & Structural Parts
    • Motors & Propulsion
    View all
  • 3D Printing2,204 products
    • 3D Printers
    • 3D Scanners & Digitizers
    • Laser Engravers & Cutters
    • Material Management & Upgrades
    View all
  • Filaments & Resins1,472 products
    • Filaments
    • Photopolymer Resins
    View all
  • Motors & Drivers463 products
    • BLDC Motor Drivers
    • DC & Geared Motors
    • DC Motor Drivers
    • Linear Actuators & Solenoids
    View all
  • Power & Batteries557 products
    • Battery Holders & Connectors
    • Breadboard Power
    • Chargers & BMS
    • DC-DC Converters
    View all
  • Semiconductors295 products
    • Diodes & Rectifiers
    • Interface & RF Encoder ICs
    • Logic ICs (74xx)
    • Logic ICs (CD4000)
    View all
  • Passive67 products
    • Capacitors
    • Circuit Protection
    • Crystals & Oscillators
    • Inductors
    View all
  • Displays & LEDs572 products
    • 7-Segment & Dot Matrix
    • Addressable LEDs
    • Character LCDs
    • Graphic LCDs
    View all
  • Switches & Relays184 products
    • Keypads & Touch
    • Push Buttons & Tactile
    • Relay Modules
    • Relays
    View all
  • Wires & Cables233 products
    • Board-to-Wire Connectors
    • Crimp & Splice
    • Headers & Dupont
    • Heat Shrink & Sleeving
    View all
  • Prototyping101 products
    • Breadboards
    • Interface Modules
    • PCBs & Perfboards
    View all
  • Tools & Test717 products
    • Bench Power Supplies
    • Hand Tools
    • Measuring Tools
    • Meters & Testers
    View all
  • Robotics180 products
    • Humanoid & Legged Robots
    • Robot Chassis & Platforms
    • Robotic Arms & Grippers
    • Wheels & Casters
    View all
  • STEM Kits268 products
    • Arduino Learning Kits
    • Coding & IoT Kits
    • Early Coding (Ages 3-8)
    • Invention Kits
    View all
  • Atal Tinkering Lab196 products
    • Package 1: Electronics, Robotics, IoT and Sensors
    • Package 2: Rapid Prototyping Tools
    • Package 3: Mechanical, Electrical and Measurement Tools
    • Package 4: Power Supply, Accessories and Safety Equipment
    View all
  • Mechanical Parts212 products
    • Bearings
    • Brackets & Mounts
    • Couplers
    • Fasteners & Standoffs
    View all
  • Audio109 products
    • Amplifier Modules
    • Buzzers & Sirens
    • Speakers
    View all
  1. Home
  2. ›Guides
  3. ›Switches, Relays & Input
  4. ›Rotary Encoders

How-to · Beginner · 3 min read

Rotary Encoders

KY-040 Wiring, Code and Debouncing

By Geekobot Learning Team · Updated 24 Oct 2026

On this page
Short answerHow quadrature worksWiring and codeBounce and missed stepsTry itStep by stepCommon mistakesFAQsParts and next steps
Short answer

A rotary encoder is a knob that turns endlessly and outputs two square-wave signals, A and B, a quarter step apart. Which one changes first tells the direction, and counting the changes gives how far it turned. The common KY-040 module has about 20 clicks per turn plus a push button. Unlike a potentiometer, it has no end stops, which makes it ideal for menus and volume controls.

Key specs at a glance

Type
Incremental, mechanical, quadrature (A and B)
Steps
Usually 20 detents and 20 pulses per turn (some 15 or 30)
Pins (KY-040)
CLK (A), DT (B), SW (button), + and GND
Supply
3.3 to 5 V; module has 10 kΩ pull-ups
Push switch
Built-in, active LOW
High resolution
Optical encoders, hundreds to thousands of pulses per turn
01

How quadrature works

Inside are two contacts that open and close as the shaft turns, offset by a quarter of a step. Turning clockwise, A changes before B; anticlockwise, B changes before A. Reading B at the moment A falls tells the direction: if B is HIGH, it turned one way; if LOW, the other. Each click (detent) usually corresponds to one full cycle on the KY-040.

02

Wiring and code

Connect CLK and DT to two interrupt-capable pins (D2 and D3 on an Uno), SW to another pin with INPUT_PULLUP, + to 5 V or 3.3 V and GND to GND.

The easiest reliable option is the Encoder library by Paul Stoffregen: Encoder knob(2,3); long pos = knob.read()/4; (divide by 4 because it counts every edge). On ESP32, the ESP32Encoder library uses the hardware pulse counter, so no counts are missed even at high speed.

03

Bounce and missed steps

Mechanical contacts bounce, which shows up as counts jumping back and forth. Fixes, from simplest: 1. Use a library with a state-table decoder, which ignores invalid transitions. 2. Add 10 nF to 100 nF capacitors from CLK and DT to ground, which forms an RC filter with the 10 kΩ pull-ups. 3. Avoid delay() in the main loop if you poll rather than use interrupts.

For a menu, change one item per detent and use the push switch to select. For motor shaft speed and position, see motor encoders.

04

Try it: RC filter calculator

Change the values and the diagram and results update as you type.

05

Read a KY-040 rotary encoder with Arduino

You need: Arduino Uno, KY-040 rotary encoder module, 5 jumper wires · Tools: Computer with Arduino IDE

Get the parts3 of 3 found in our store · ₹676

  • Arduino UnoArduino Uno R3 Development Board with USB Cable₹385
  • KY-040 rotary encoder moduleM274 KY-040 Incremental Rotary Encoder Brick Module – 20 CPR, 5V DC₹46
  • 5 jumper wiresDupont Jumper Wires (40 pcs)₹49
  1. 1
    Wire powerConnect + to 5V and GND to GND.
  2. 2
    Wire the signalsConnect CLK to D2, DT to D3 and SW to D4.
  3. 3
    Install the libraryInstall the Encoder library by Paul Stoffregen.
  4. 4
    UploadCreate Encoder knob(2,3) and print knob.read()/4 when it changes.
  5. 5
    TestTurn the knob both ways and press it; swap CLK and DT if the direction is reversed.
06

Common mistakes to avoid

  • !Using pins without interrupts and missing fast turns.
  • !Forgetting to divide the count by 4 (or 2) per detent.
  • !Long delay() calls in the loop when polling.
  • !No pull-up on the bare encoder's switch pin.
  • !Expecting an absolute position after power loss.
07

Frequently asked questions

What is the difference between a rotary encoder and a potentiometer?

A potentiometer gives an absolute position over a limited turn. An encoder turns endlessly and reports steps and direction.

Why does my encoder count go up and down randomly?

Contact bounce. Use a state-table library, add small capacitors to ground, or both.

Why does my encoder count 4 per click?

The library counts every edge of both signals. Divide by 4, or by 2 on some encoders.

Does the KY-040 work at 3.3 V?

Yes. Power it from 3.3 V so the pull-ups match ESP32 or Pico logic.

Does a rotary encoder remember its position?

No. Incremental encoders only report changes. Save the value in memory or use an absolute encoder.

Parts for this guide

  • 16mm Rotary Potentiometer (Linear)
    ₹14View
  • 0.96" OLED Display 128x64
    ₹139View
Shop Push Buttons & Tactile

Calculators

RC filter calculatorRC time constant calculator

Terms in this guide

DebounceFiltering the rapid on-off bouncing of a mechanical switch so one press counts once.InterruptA hardware signal that makes the microcontroller pause its program and run a short function immediately, for example when a button pin changes.Pull-up resistorA resistor from a signal line to the supply that keeps the line high when nothing pulls it low.RC filterA resistor and capacitor in series that smooths a signal, turning PWM into a steady voltage or removing high-frequency noise.

Projects that use it

Put this into practice: 5 step-by-step builds in our project library use parts from this guide.

Intermediate · 1–2 hoursPrecision servo positionerView projectBeginner · 1 hourKitchen countdown timer with a rotary knobView projectIntermediate · 2 hoursRoom thermostat with a rotary knobView project
Browse all 5 projects

Keep learning

Component guideBeginnerPotentiometers and TrimmersA potentiometer is a three-terminal variable resistor: the outer pins connect across the full resistance and the middle pin (wiper) taps a point you set with the knob.3 min read · Passive ComponentsHow-toBeginnerPush Buttons with ArduinoWire a push button between a digital pin and ground, set the pin to INPUT_PULLUP, and the pin reads LOW while pressed.3 min read · Switches, Relays & InputConcept explainerIntermediateMotor Encoders and Speed FeedbackA motor encoder reports how far and how fast a shaft has turned.3 min read · Motors & MotionHow-toBeginnerSSD1306 OLED DisplayThe SSD1306 is the driver chip in most small monochrome OLED displays, such as the popular 0.96 inch 128x64 module.3 min read · Displays & LEDsConcept explainerBeginnerPull-Up and Pull-Down ResistorsA pull-up resistor connects an input pin to the supply so it reads HIGH when nothing drives it; a pull-down connects it to ground so it reads LOW.3 min read · Electronics Fundamentals

Sources

  • Bourns and Alps EC11-series encoder datasheets
  • Encoder library documentation (PJRC)

Written by the Geekobot team from manufacturer datasheets. Always check the datasheet for the exact part and variant you buy.

On this page
Short answerHow quadrature worksWiring and codeBounce and missed stepsTry itStep by stepCommon mistakesFAQsParts and next steps
Need a hand?Ask Geeko AI which part fits your project, or talk to the Geekobot team.Ask Geeko AIHelp & support

Parts for this guide3 items · ₹480

Arduino Uno R3 Development Board with USB Cable · M274 KY-040 Incremental Rotary Encoder Brick Module – 20 CPR, 5V DC · Dupont Jumper Wires (40 pcs)

Ask the Community

Ask a question