กลับไปหน้ารวมไฟล์
how-to-use-incremental-encoders-338566-en.md

Digital Control: Incremental Rotary Encoders

A standard potentiometer can only turn 270 degrees before it hits a physical wall. This makes it terrible for scrolling long lists or adjusting endless variables. The KY-040 Incremental Rotary Encoder spins infinitely in either direction, outputting digital "clicks" instead of an analog voltage.

button_led_basic_interaction_1772681969235.png

The Physics of Quadrature Output

How does the Arduino know if the knob is turning Left or Right? An encoder has two switches inside (Pin A and Pin B). They are slightly offset.

  • When you turn the knob Right (Clockwise), switch A clicks HIGH slightly before switch B clicks HIGH.
  • When you turn Left (Counter-Clockwise), switch B clicks HIGH slightly before switch A.
  • The Arduino code constantly monitors the state of these two pins. By comparing them, it knows exactly which direction the shaft moved!

Hardware Interrupts (The True Solution)

If you use digitalRead() inside the loop(), you might miss a click if the Arduino was busy doing something else (like printing to an LCD).

  • You must use Hardware Interrupts: attachInterrupt(digitalPinToInterrupt(2), updateEncoder, CHANGE);.
  • Now, no matter what the Arduino is doing, the instant the knob turns a microscopic amount, the processor literally pauses its current task, updates the counting variable instantly, and resumes. Flawless tracking!

Hardware Requirements

  • Arduino Uno/Nano.
  • KY-040 Rotary Encoder Module (The module includes necessary pull-up resistors on the board).
  • An LED or LCD Screen to display the counting numbers.

Mastering rotaries is essential for building 3D Printer interfaces or digital synthesizers.

ข้อมูล Frontmatter ดั้งเดิม

title: "How to Use Incremental Encoders"
description: "Spin to infinity! Replace frustrating analog potentiometers with digital rotary encoders to build endlessly scrolling menus and precision volume knobs."
category: "Basic Electronics"
difficulty: "Intermediate"