← Back admin@posix.lt: ~/projects/ESP32 MIDI Lrc
admin@posix.lt:~/projects$

ESP32 MIDI valdiklis rotoriams darbui su Lightroom

2026-10-29 · baigtas

„Adobe Lightroom“ MIDI valdiklis naudojant ESP32-S3 ir „Rotary“ enkoderius#

Dažnai dirbant su „Adobe Lightroom“ ir redaguojant didelius kiekius nuotraukų, slankiklių (sliders) tampymas pele tampa lėtu ir varginančiu procesu. Profesionaliems retušuotojams įprasta naudoti specializuotas fizines konsoles (pvz., „Loupedeck“), tačiau jos yra labai brangios.

Siekdamas optimizuoti savo darbo eigą, sukūriau alternatyvą – nuosavą MIDI valdiklį (MIDI Controller). Šis projektas paremtas ESP32-S3 mikrokontroleriu ir leidžia prijungti iki 9 sukamųjų enkoderių (KY-040), kurie valdo „Lightroom“ funkcijas pasitelkiant populiarųjį „MIDI2LR“ įskiepį (pluginą).

Kaip veikia šis valdiklis?#

  1. Native USB MIDI: Skirtingai nei senesni mikrovaldikliai (pvz., „Arduino Uno“), kuriems reikia papildomų programų (kaip „Hairless MIDI“), ESP32-S3 turi tiesioginį USB OTG palaikymą. Prijungus jį prie kompiuterio, jis iškart atpažįstamas kaip standartinis „Plug & Play“ MIDI įrenginys.
  2. Sukamieji enkoderiai (Rotary Encoders): Naudojami enkoderiai sukasi be galo (neturi ribų kaip paprasti potenciometrai). Programa siunčia Relative (Binary Offset) tipo MIDI komandas (Control Change). Tai reiškia, kad kompiuteris gauna informaciją tik apie tai, ar rankenėlė pasukta į kairę, ar į dešinę. Tai tobula „Lightroom“ slankikliams.
  3. Mygtukai: Kiekvienas enkoderis turi paspaudžiamą mygtuką. Mygtukai taip pat siunčia MIDI signalus (pvz., galima nustatyti, kad paspaudus mygtuką, slankiklis grįžtų į pradinę 0 padėtį). Programa turi „debounce“ logiką, apsaugančią nuo netyčinių dvigubų paspaudimų.

Techninė Įranga (Hardware) ir Priklausomybės#

  • Mikrovaldiklis: ESP32-S3 (pvz., N16R8 modelis).
  • Komponentai: Iki 9x KY-040 sukamųjų enkoderių.
  • Sujungimas: Programa naudoja saugius ESP32-S3 kontaktus (pins), vengiant tų, kurie rezervuoti Flash/PSRAM atminčiai (26-37) ar TX/RX linijoms.
  • Programinės bibliotekos (Libraries):
    • RotaryEncoder by Matthias Hertel (greitam ir tiksliam kontaktų skaitymui / software polling).
    • Standartinės ESP32 USB.h ir USBMIDI.h bibliotekos.

Kodas (Arduino IDE)#

Šis C++ kodas skirtas įkelti per Arduino IDE. Prieš įkeliant įsitikinkite, kad Arduino IDE nustatymuose (Tools -> USB Mode) pasirinktas „Hardware CDC and JTAG“ arba atitinkamas USB OTG režimas, leidžiantis USB klasei veikti.

cpp
/**
 * @file      Lightroom_MIDI_Controller.ino
 * @brief     ESP32-S3 MIDI controller using Rotary Encoders.
 * @author    Mindaugas Nefas <minde@posix.lt>
 * @version   1.0
 * @description
 * This program configures the ESP32-S3 microcontroller to act as a native
 * USB MIDI device. It polls up to 9 rotary encoders with push buttons and
 * sends "Relative" (Binary Offset) Control Change (CC) MIDI messages.
 * It is perfectly optimized for controlling Adobe Lightroom via the MIDI2LR plugin.
 * @hardware
 * - Board: ESP32-S3 N16R8
 * - Components: Up to 9x KY-040 (or similar) rotary encoders.
 * - USB Connection: UART port for programming, USB/OTG port for MIDI operation.
 * @dependencies
 * - "RotaryEncoder" by Matthias Hertel (for fast software polling)
 * - Built-in ESP32 "USB" and "USBMIDI" libraries
 */

#include <RotaryEncoder.h>
#include "USB.h"
#include "USBMIDI.h"

/* ========================================================================= *
 * CONFIGURATION                                                             *
 * ========================================================================= */

/// @brief The MIDI channel used for all outgoing messages (1-16)
const uint8_t MIDI_CHANNEL = 1;

/** * @brief The number of active rotary encoders.
 * @warning Change this number to match the exact amount of PHYSICALLY connected
 * modules. Leaving unused pins active will cause floating pin noise and crash the controller.
 */
const int NUM_ENCODERS = 9;

/* ========================================================================= *
 * PIN ASSIGNMENTS                                                           *
 * ========================================================================= */
// Safe ESP32-S3 pins, avoiding Flash/PSRAM (26-37) and dedicated USB/TX/RX pins.

/// @brief Array of CLK (Phase A) pins for the encoders
const int clkPins[] = {1, 4, 6, 8, 10, 12, 14, 16, 18};

/// @brief Array of DT (Phase B) pins for the encoders
const int dtPins[]  = {2, 5, 7, 9, 11, 13, 15, 17, 21};

/// @brief Array of SW (Push Button) pins for the encoders
const int swPins[]  = {38, 39, 40, 41, 42, 47, 48, 0, 3};

/* ========================================================================= *
 * MIDI CC ADDRESSES                                                         *
 * ========================================================================= */

/// @brief MIDI Control Change (CC) addresses for rotation (CC 10 - 18)
const int encCCs[] = {10, 11, 12, 13, 14, 15, 16, 17, 18};

/// @brief MIDI Control Change (CC) addresses for push buttons (CC 20 - 28)
const int btnCCs[] = {20, 21, 22, 23, 24, 25, 26, 27, 28};

/* ========================================================================= *
 * OBJECTS & STATE VARIABLES                                                 *
 * ========================================================================= */

USBMIDI MIDI; ///< USB MIDI instance

/// @brief Array of pointers to store RotaryEncoder objects
RotaryEncoder *encoders[9];

int32_t lastPositions[9];        ///< Stores the previous encoder position
bool lastBtnStates[9];           ///< Stores the previous button state
unsigned long lastBtnPresses[9]; ///< Timestamp for button debounce logic

/* ========================================================================= *
 * MAIN CODE                                                                 *
 * ========================================================================= */

/**
 * @brief Initial microcontroller setup.
 * Executed once upon power-up or reset.
 */
void setup()
{
    // Initialize the MIDI system.
    // NOTE: MIDI must be initialized before USB.begin() so the board
    // properly identifies itself to the host computer as a MIDI device.
    MIDI.begin();
    USB.begin();

    // Allow the host OS (Windows/Mac) time to enumerate the new USB device
    delay(1000);

    // Initialize only the number of encoders specified by NUM_ENCODERS
    for (int i = 0; i < NUM_ENCODERS; i++)
    {
        // Set the button pin to use the internal pull-up resistor
        pinMode(swPins[i], INPUT_PULLUP);

        // Initialize the RotaryEncoder object.
        // LatchMode::FOUR3 is optimal for standard mechanical encoders like KY-040.
        encoders[i] = new RotaryEncoder(dtPins[i], clkPins[i], RotaryEncoder::LatchMode::FOUR3);

        // Set initial state values
        lastPositions[i] = 0;
        lastBtnStates[i] = HIGH;
        lastBtnPresses[i] = 0;
    }
}

/**
 * @brief Main execution loop.
 * Runs continuously at maximum processor speed.
 */
void loop()
{
    for (int i = 0; i < NUM_ENCODERS; i++)
    {
        // 1. UPDATE ENCODER STATE
        // The processor manually checks the pin states (software polling).
        encoders[i]->tick();

        // 2. CHECK FOR ROTATION
        int32_t newPos = encoders[i]->getPosition();
        int32_t diff = newPos - lastPositions[i]; // Calculate the step difference

        // If the encoder has been turned, send a MIDI message
        if (diff != 0)
        {
            // Safeguard: Clamp the maximum delta per loop (-60 to +60)
            // to prevent exceeding the 7-bit MIDI value range (0-127) during fast spins.
            if (diff > 60)
                diff = 60;
            if (diff < -60)
                diff = -60;

            // Send a "Relative" (Binary Offset) MIDI message.
            // 64 is center (no movement). >64 means turn right, <64 means turn left.
            MIDI.controlChange(encCCs[i], 64 + diff, MIDI_CHANNEL);

            lastPositions[i] = newPos;
        }

        // 3. CHECK PUSH BUTTON (With Software Debounce)
        bool currentBtnState = digitalRead(swPins[i]);

        // If the button was just pressed (transitioned from HIGH to LOW)
        if (currentBtnState == LOW && lastBtnStates[i] == HIGH)
        {
            if (millis() - lastBtnPresses[i] > 50)
            {                                                   // 50ms debounce window
                MIDI.controlChange(btnCCs[i], 127, MIDI_CHANNEL); // 127 = Pressed
                lastBtnPresses[i] = millis();
            }
        }
        // If the button was just released (transitioned from LOW to HIGH)
        else if (currentBtnState == HIGH && lastBtnStates[i] == LOW)
        {
            if (millis() - lastBtnPresses[i] > 50)
            {
                MIDI.controlChange(btnCCs[i], 0, MIDI_CHANNEL); // 0 = Released
                lastBtnPresses[i] = millis();
            }
        }

        // Save the current button state for the next loop iteration
        lastBtnStates[i] = currentBtnState;
    }
}

← all projects

terminal