ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Embedded / IoT > 하드웨어 펄스 카운터(PCNT)를 활용한 지터 없는 로터리 엔코더 읽기Jitter-Free Rotary Encoder Reading with ESP32 Hardware Pulse Counter (PCNT)
Embedded / IoT Advanced ESP-IDF / Arduino

하드웨어 펄스 카운터(PCNT)를 활용한 지터 없는 로터리 엔코더 읽기Jitter-Free Rotary Encoder Reading with ESP32 Hardware Pulse Counter (PCNT)

소프트웨어 인터럽트 채터링이나 CPU 부하 없이 ESP32 내장 PCNT 하드웨어 주변장치가 엔코더의 A/B 위상 구형파를 직접 계수하는 입력 드라이버 구현입니다.An input driver using the ESP32's built-in PCNT hardware peripheral to count quadrature A/B phase pulses directly in hardware without GPIO interrupt overhead.

#Embedded #ESP32 #Hardware #Encoder #Interrupt
핵심 개념로터리 엔코더를 일반 GPIO 외부 인터럽트(attachInterrupt)로 읽으면 고속 회전 시 인터럽트 지연이나 기계식 접점의 채터링(바운싱)으로 인해 카운트가 누락되거나 역방향으로 튀는 현상이 발생합니다. ESP32 내장 하드웨어 펄스 카운터(PCNT)와 글리치 필터를 활성화하면 CPU 개입 없이 정확한 구형파 펄스를 적산할 수 있습니다.
Key ConceptReading a rotary encoder via software GPIO interrupts (attachInterrupt) is prone to missed counts and false direction flips caused by interrupt latency and mechanical contact bounce during rapid rotation. Configuring the ESP32's dedicated Hardware Pulse Counter (PCNT) peripheral and its glitch filter accumulates quadrature pulses in hardware with 0% CPU intervention.

1. PCNT 하드웨어 엔코더 설정 C 코드1. PCNT Hardware Encoder Configuration in C

pcnt_encoder.c
#include "driver/pcnt.h"

#define PCNT_UNIT       PCNT_UNIT_0
#define ENCODER_PIN_A   18
#define ENCODER_PIN_B   19

void init_encoder(void)
{
    pcnt_config_t pcnt_config = {
        .pulse_gpio_num = ENCODER_PIN_A,
        .ctrl_gpio_num  = ENCODER_PIN_B,
        .channel        = PCNT_CHANNEL_0,
        .unit           = PCNT_UNIT,
        .pos_mode       = PCNT_COUNT_INC,   // 상승 에지에서 카운트 증가
        .neg_mode       = PCNT_COUNT_DEC,   // 하강 에지에서 카운트 감소
        .lctrl_mode     = PCNT_MODE_REVERSE,// 제어 핀(B)이 LOW일 때 증감 방향 반전
        .hctrl_mode     = PCNT_MODE_KEEP,   // 제어 핀(B)이 HIGH일 때 증감 방향 유지
        .counter_h_lim  = 30000,
        .counter_l_lim  = -30000,
    };
    pcnt_unit_config(&pcnt_config);

    // 하드웨어 글리치 필터 적용 (80MHz APB 클럭 기준 1023 사이클 ≈ 12.7us 미만 펄스 무시)
    pcnt_set_filter_value(PCNT_UNIT, 1023);
    pcnt_filter_enable(PCNT_UNIT);

    pcnt_counter_pause(PCNT_UNIT);
    pcnt_counter_clear(PCNT_UNIT);
    pcnt_counter_resume(PCNT_UNIT);
}

int16_t get_encoder_count(void)
{
    int16_t count = 0;
    pcnt_get_counter_value(PCNT_UNIT, &count);
    return count;
}
pcnt_encoder.c
#include "driver/pcnt.h"

#define PCNT_UNIT       PCNT_UNIT_0
#define ENCODER_PIN_A   18
#define ENCODER_PIN_B   19

void init_encoder(void)
{
    pcnt_config_t pcnt_config = {
        .pulse_gpio_num = ENCODER_PIN_A,
        .ctrl_gpio_num  = ENCODER_PIN_B,
        .channel        = PCNT_CHANNEL_0,
        .unit           = PCNT_UNIT,
        .pos_mode       = PCNT_COUNT_INC,   // Increment on rising edge
        .neg_mode       = PCNT_COUNT_DEC,   // Decrement on falling edge
        .lctrl_mode     = PCNT_MODE_REVERSE,// Reverse count direction when control pin (B) is LOW
        .hctrl_mode     = PCNT_MODE_KEEP,   // Keep count direction when control pin (B) is HIGH
        .counter_h_lim  = 30000,
        .counter_l_lim  = -30000,
    };
    pcnt_unit_config(&pcnt_config);

    // Enable hardware glitch filter (ignores pulses shorter than 1023 APB clock cycles ≈ 12.7us at 80MHz)
    pcnt_set_filter_value(PCNT_UNIT, 1023);
    pcnt_filter_enable(PCNT_UNIT);

    pcnt_counter_pause(PCNT_UNIT);
    pcnt_counter_clear(PCNT_UNIT);
    pcnt_counter_resume(PCNT_UNIT);
}

int16_t get_encoder_count(void)
{
    int16_t count = 0;
    pcnt_get_counter_value(PCNT_UNIT, &count);
    return count;
}

2. 실무 적용 및 주의사항2. Practical Considerations and Caveats

  • 4체배(Full-Quadrature X4) 정밀도 확장: 단일 채널(PCNT_CHANNEL_0)만 설정하면 A상의 상승·하강 에지만 검사하는 2체배 모드로 동작합니다. 동일한 유닛(PCNT_UNIT_0)의 PCNT_CHANNEL_1에 A핀과 B핀 역할을 서로 교차하여 등록하면 A상과 B상의 모든 에지를 계수하는 4체배 해상도를 얻을 수 있습니다.
  • 16비트 부호 있는 카운터 레지스터 범위 제한: ESP32의 PCNT 하드웨어 카운터는 16비트(int16_t, -32768 ~ 32767) 크기를 가집니다. 모터 엔코더처럼 한 방향으로 계속 회전하는 환경에서는 counter_h_lim과 counter_l_lim 도달 인터럽트를 활성화하여 상위 32비트/64비트 소프트웨어 누적 변수에 더해주어야 오버플로우를 막을 수 있습니다.
  • 기계식 엔코더의 외부 RC 디바운스 병행: PCNT 하드웨어 글리치 필터의 최대 설정값(1023)은 80MHz APB 클럭 기준 약 12.78us 폭의 노이즈까지만 걸러냅니다. 수 밀리초(ms) 단위의 긴 바운싱이 발생하는 저가형 기계식 노브 엔코더에서는 핀과 GND 사이에 10nF~100nF 세라믹 커패시터를 함께 달아주는 것이 안정적입니다.
  • Full X4 Quadrature Decoding via Both Channels: Configuring only PCNT_CHANNEL_0 counts rising and falling edges on phase A (X2 mode). Configuring PCNT_CHANNEL_1 on the same PCNT_UNIT_0 with swapped pulse/control pins counts edges on both phases A and B for full X4 quadrature resolution.
  • Handling 16-Bit Signed Counter Rollover: Because the hardware PCNT register is a 16-bit signed integer (int16_t, -32768 to 32767), continuous high-RPM motor encoders should enable counter_h_lim and counter_l_lim threshold interrupts to accumulate rollovers into a 32-bit or 64-bit variable.
  • Pair Hardware Filter with External RC Capacitors on Mechanical Knobs: The maximum 10-bit hardware filter value (1023 cycles at 80MHz) filters glitches up to ~12.78us. For mechanical detent encoders with millisecond-scale contact bounce, add 10nF–100nF decoupling capacitors between the A/B pins and GND.

ESP32의 PCNT 주변장치를 활용하면 고주파 모터 제어 루프나 Wi-Fi 인터럽트가 집중되는 구간에서도 CPU 인터럽트 오버헤드 없이 로터리 엔코더의 회전량을 정확하게 추적할 수 있습니다.

Offloading quadrature decoding to the ESP32 PCNT peripheral guarantees accurate position tracking without interrupt storms, even when Wi-Fi traffic or motor control loops are active.

참고자료 & 관련 링크