//by mircemk, September 2026 #include #include #include #include #include #include "driver/i2s.h" // Forward declarations for Arduino IDE 1.8.x auto-prototype compatibility. struct EncoderState; struct ButtonState; struct DCBlocker; struct OnePoleLP; // ===================================================== // ESP32 STEREO DIGITAL TUBE SOUND PROCESSOR // V1.2 - TRUE H2 TUBE TEST + 5 PRESETS + LAST STATE SAVE // ===================================================== // HARDWARE: 100% IDENTICAL to the completed 5-band Parametric EQ. // NO wiring / hardware modifications are required. // // ESP32 WROOM-32 DevKit // Waveshare WM8960 Audio Board (existing stereo LINE IN modification) // ILI9341 320x240 TFT via TFT_eSPI // 3 rotary encoders // // Proven audio configuration preserved: // 48 kHz / 16-bit stereo // ESP32 = I2S MASTER // WM8960 = SLAVE / PERIPHERAL // I2S_NUM_1 // BCLK GPIO14 // WS GPIO13 // GPIO17 -> WM8960 RXSDA (DAC data) // WM8960 TXSDA -> GPIO19 (ADC data) // SDA GPIO21 / SCL GPIO22 // // IMPORTANT STARTUP RULE PRESERVED: // 1) Configure WM8960 completely FIRST // 2) Start ESP32 I2S clocks LAST // // ----------------------------------------------------- // V1.1.2 PRESET SYSTEM + DELAYED LAST-STATE NVS SAVE // ----------------------------------------------------- // This is NOT a literal component-by-component guitar pedal emulation. // It translates the useful architecture into a stereo line-level Hi-Fi test: // // INPUT // -> DC block // -> mild MID/BAND emphasis before distortion // -> DRIVE // -> first gentle "diode" knee // -> second higher "LED / gain-reduction" knee // -> undo the LINEAR part of the pre-emphasis // -> MID CUT / BOOST stage // -> BASS/TREBLE TONE contour // -> OUTPUT level trim (Elektor P2 concept) // -> DC block // -> DAC // // BYPASS remains true sample-through bypass. // // 2x oversampling is intentionally NOT active in V1.0. // First we prove the architecture and sound at 48 kHz without overloading // the classic ESP32. Oversampling can be added later only around the clipper. // // CONTROLS: // ENC1 = DRIVE 0.0 ... +24.0 dB // ENC2 = TONE -100 ... +100 (WARM <-> BRIGHT) // ENC3 = OUTPUT -12.0 ... +18.0 dB // SW1 short = TRUE BYPASS // SW2 short = encoder speed 1x / 2x // SW2 long = factory defaults // SW3 short = MID BOOST / MID CUT // SW3 long = PRESET MODE // PRESET MODE: ENC3=P1..P5, SW3 short=LOAD, SW3 long=SAVE // Last DRIVE/TONE/OUTPUT/MID state auto-saves after 2 s inactivity // // V1.0 CHANGES FROM V0.9: // - TONE range from V0.9 is preserved unchanged // - left-panel visual order remains OUTPUT / TONE / DRIVE // - encoder GPIO/function mapping is UNCHANGED // - DRIVE range extended to +24 dB // - nonlinear clip core is deliberately stronger: // first knee 0.42, span 0.24 // second knee 0.62, span 0.11 // - drive calibration changed so DRIVE=0 stays essentially clean, // while upper settings reach the knees much more decisively // ===================================================== TFT_eSPI tft = TFT_eSPI(); TFT_eSprite graphSprite = TFT_eSprite(&tft); WM8960 codec; Preferences preferences; // ===================================================== // ENCODER PINS - IDENTICAL HARDWARE // ===================================================== #define ENC1_A 34 #define ENC1_B 35 #define ENC1_SW 32 #define ENC2_A 36 #define ENC2_B 39 #define ENC2_SW 33 #define ENC3_A 25 #define ENC3_B 26 #define ENC3_SW 27 #define ENC1_DIR -1 #define ENC2_DIR -1 #define ENC3_DIR -1 // ===================================================== // WM8960 / I2S - IDENTICAL PROVEN CONFIGURATION // ===================================================== #define WM_SDA 21 #define WM_SCL 22 #define I2S_BCLK 14 #define I2S_WS 13 #define I2S_DOUT 17 #define I2S_DIN 19 #define AUDIO_I2S I2S_NUM_1 const uint32_t AUDIO_SAMPLE_RATE = 48000; const int AUDIO_FRAMES = 240; int16_t audioBuffer[AUDIO_FRAMES * 2]; // Keep the same analog input sensitivity used in the proven EQ V1.4 // and in the recent real-hardware level tests (typically -2...-10 dBFS peaks). const float LINE_INPUT_PGA_DB = 0.0f; // ===================================================== // UI COLORS / LAYOUT // ===================================================== #define COL_BG 0x0000 #define COL_GRAPH_BG 0x0000 #define COL_GRID 0x8400 #define COL_BORDER 0x3D9F #define COL_CYAN 0x07FF #define COL_YELLOW 0xFFE0 #define COL_GREEN 0x07E0 #define COL_MAGENTA 0xF81F #define COL_RED 0xF800 #define COL_WHITE 0xFFFF #define COL_GREY 0x9E79 #define COL_ORANGE 0xFD20 const int TITLE_Y = 5; const int PANEL_X = 6; const int PANEL_Y = 30; const int PANEL_W = 78; const int PANEL_H = 145; const int GRAPH_X = 96; const int GRAPH_Y = 30; const int GRAPH_W = 216; const int GRAPH_H = 145; // ===================================================== // ENCODER READER // ===================================================== struct EncoderState { uint8_t pinA; uint8_t pinB; uint8_t pinSW; uint8_t lastAB; int8_t accumulator; }; EncoderState enc1 = { ENC1_A, ENC1_B, ENC1_SW, 0, 0 }; EncoderState enc2 = { ENC2_A, ENC2_B, ENC2_SW, 0, 0 }; EncoderState enc3 = { ENC3_A, ENC3_B, ENC3_SW, 0, 0 }; const int8_t encoderTable[16] = { 0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0 }; int readEncoder(EncoderState &enc) { uint8_t currentAB = (digitalRead(enc.pinA) << 1) | digitalRead(enc.pinB); uint8_t index = (enc.lastAB << 2) | currentAB; int8_t movement = encoderTable[index]; enc.lastAB = currentAB; enc.accumulator += movement; if (enc.accumulator >= 4) { enc.accumulator = 0; return +1; } if (enc.accumulator <= -4) { enc.accumulator = 0; return -1; } return 0; } // ===================================================== // BUTTON TRACKING // ===================================================== struct ButtonState { bool wasDown; bool longFired; unsigned long downAt; }; ButtonState sw1State = { false, false, 0 }; ButtonState sw2State = { false, false, 0 }; ButtonState sw3State = { false, false, 0 }; const unsigned long BUTTON_DEBOUNCE_MS = 30; const unsigned long LONG_PRESS_MS = 2000; // ===================================================== // USER PARAMETERS // ===================================================== float uiDriveDb = 6.0f; float uiTone = -20.0f; float uiOutputDb = 0.0f; const float DEFAULT_DRIVE_DB = 6.0f; const float DEFAULT_TONE = -20.0f; const float DEFAULT_OUTPUT_DB = 0.0f; bool bypassMode = false; bool speed2x = false; bool midBoostMode = true; // ===================================================== // 5 USER PRESETS - SAME OPERATING LOGIC AS EQ PROJECT // ===================================================== // NORMAL MODE: // ENC3 rotation = OUTPUT // SW3 short = MID BOOST / MID CUT // SW3 long = enter PRESET MODE // // PRESET MODE: // ENC3 rotation = select P1..P5 // SW3 short = LOAD selected preset // SW3 long = SAVE current sound to selected preset // // Presets store SOUND parameters only: // DRIVE, TONE, OUTPUT, MID BOOST/CUT // BYPASS and ENC 1x/2x are deliberately NOT preset data. const int PRESET_COUNT = 5; const unsigned long PRESET_MODE_TIMEOUT_MS = 8000; const unsigned long PRESET_STATUS_MS = 1000; bool presetMode = false; int presetSelectedSlot = 1; int lastPresetSlot = 1; unsigned long presetLastActivity = 0; String presetStatusText = ""; uint16_t presetStatusColor = COL_CYAN; unsigned long presetStatusUntil = 0; const uint32_t TUBE_PRESET_MAGIC = 0x54554231UL; // "TUB1" struct TubePresetStorage { uint32_t magic; float driveDb; float tone; float outputDb; uint8_t midBoost; }; // ===================================================== // LAST USED SOUND STATE - DELAYED NVS SAVE // ===================================================== // Only sound parameters are restored after restart: // DRIVE, TONE, OUTPUT, MID BOOST/CUT // BYPASS, ENC speed and preset-menu state are intentionally NOT saved. // Writes are delayed so encoder movement does not cause repeated flash writes. const uint32_t TUBE_CURRENT_MAGIC = 0x54554331UL; // "TUC1" const unsigned long CURRENT_SAVE_DELAY_MS = 2000; bool currentStateDirty = false; unsigned long currentStateChangedAt = 0; struct TubeCurrentStorage { uint32_t magic; float driveDb; float tone; float outputDb; uint8_t midBoost; }; // ===================================================== // UI -> AUDIO TASK HANDOFF // ===================================================== portMUX_TYPE dspSettingsMux = portMUX_INITIALIZER_UNLOCKED; float pendingDriveDb = DEFAULT_DRIVE_DB; float pendingTone = DEFAULT_TONE; float pendingOutputDb = DEFAULT_OUTPUT_DB; volatile bool pendingBypass = false; volatile bool pendingMidBoost = true; volatile bool dspResetRequested = true; float targetDriveDb = DEFAULT_DRIVE_DB; float targetTone = DEFAULT_TONE; float targetOutputDb = DEFAULT_OUTPUT_DB; float dspDriveDb = DEFAULT_DRIVE_DB; float dspTone = DEFAULT_TONE; float dspOutputDb = DEFAULT_OUTPUT_DB; bool dspBypassMode = false; bool dspMidBoostMode = true; TaskHandle_t audioTaskHandle = NULL; // ===================================================== // METERS / CLIP LATCHES // ===================================================== volatile float inputPeakAccumulator = 0.0f; volatile float dspDeltaPeakAccumulator = 0.0f; float uiInputPeakDbfs = -120.0f; float uiDspDeltaDbfs = -120.0f; volatile unsigned long inputClipUntil = 0; volatile unsigned long outputClipUntil = 0; // ===================================================== // DSP STATES // ===================================================== struct DCBlocker { float x1; float y1; }; struct OnePoleLP { float y; }; DCBlocker preDC_L = {0.0f, 0.0f}; DCBlocker preDC_R = {0.0f, 0.0f}; DCBlocker postDC_L = {0.0f, 0.0f}; DCBlocker postDC_R = {0.0f, 0.0f}; // Pre-emphasis band states: roughly 180 Hz ... 3.2 kHz. OnePoleLP preMidHi_L = {0.0f}; OnePoleLP preMidHi_R = {0.0f}; OnePoleLP preMidLo_L = {0.0f}; OnePoleLP preMidLo_R = {0.0f}; // Post-tone states. OnePoleLP toneLow_L = {0.0f}; OnePoleLP toneLow_R = {0.0f}; OnePoleLP toneHighLP_L = {0.0f}; OnePoleLP toneHighLP_R = {0.0f}; OnePoleLP postMidHi_L = {0.0f}; OnePoleLP postMidHi_R = {0.0f}; OnePoleLP postMidLo_L = {0.0f}; OnePoleLP postMidLo_R = {0.0f}; // 5 Hz DC blocker at 48 kHz. const float DC_R = 0.9993457f; // One-pole alphas: alpha = 1-exp(-2*pi*fc/fs) const float PRE_MID_HI_ALPHA = 0.3429532f; // ~3.2 kHz const float PRE_MID_LO_ALPHA = 0.0232857f; // ~180 Hz const float TONE_LOW_ALPHA = 0.0283820f; // ~220 Hz const float TONE_HIGH_ALPHA = 0.4802974f; // ~5.0 kHz const float POST_MID_HI_ALPHA = 0.2789540f; // ~2.5 kHz const float POST_MID_LO_ALPHA = 0.0447891f; // ~350 Hz // The Elektor circuit deliberately emphasizes an important band before // clipping. For Hi-Fi use we keep the emphasis moderate (~2.6 dB maximum // in the middle of the band) and remove its LINEAR component after clipping. const float PRE_EMPHASIS = 0.35f; inline float processDCBlock(float x, DCBlocker &s) { float y = x - s.x1 + DC_R * s.y1; s.x1 = x; s.y1 = y; return y; } inline float processOnePoleLP(float x, OnePoleLP &s, float alpha) { s.y += alpha * (x - s.y); return s.y; } // ===================================================== // V1.2 ASYMMETRIC H2-RICH TWO-KNEE TUBE CORE // ===================================================== // V1.1.x used the same transfer law on positive and negative half-cycles. // That produces mainly odd harmonics (H3/H5/...), especially as DRIVE rises. // // V1.2 deliberately makes the two half-cycles different. The positive side // reaches soft saturation earlier, while the negative side remains much more // open. This asymmetry creates a clearly measurable EVEN-harmonic component // (primarily H2) while retaining a smaller H3 component from the soft knees. // // The post-DSP DC blocker already present in the engine removes the small DC // term that naturally accompanies asymmetric transfer curves. inline float softKneeClip(float x, float knee, float span) { float a = fabsf(x); if (a <= knee) return x; float d = a - knee; float y = knee + (d * span) / (span + d); return (x < 0.0f) ? -y : y; } inline float dualKneeClip(float x) { float y = x; if (x >= 0.0f) { // Positive half-cycle: earlier / firmer compression. // This is the side that generates most of the H2 asymmetry. y = softKneeClip(y, 0.35f, 0.16f); y = softKneeClip(y, 0.56f, 0.11f); } else { // Negative half-cycle: deliberately later / softer saturation. // It remains much more linear than the positive side. y = softKneeClip(y, 0.95f, 0.80f); y = softKneeClip(y, 1.20f, 0.50f); } return y; } // DRIVE calibration is unchanged from V1.1.x. // DRIVE 0 dB -> model gain 0.35 (essentially clean) // DRIVE 6 dB -> model gain ~0.70 // DRIVE 12 dB -> model gain ~1.39 // DRIVE 18 dB -> model gain ~2.78 // DRIVE 24 dB -> model gain ~5.55 (extreme / diagnostic maximum) // With the real line input now restored to PGA = 0 dB, the exact amount of // generated H2/H3 also depends on source level. The useful Hi-Fi range is // expected to be roughly DRIVE 6...14 dB; 18...24 dB is intentionally strong. inline float driveModelGainFromDb(float driveDb) { return 0.35f * powf(10.0f, driveDb * 0.05f); } // Used only by the graph on Core 1. float visualClipTransfer(float x) { if (bypassMode) return x; float g = driveModelGainFromDb(uiDriveDb); float u = g * x; float y = dualKneeClip(u); return y / g; } // ===================================================== // DSP RESET / PARAMETER HANDOFF // ===================================================== void resetTubeDSPStates() { preDC_L = {0.0f, 0.0f}; preDC_R = {0.0f, 0.0f}; postDC_L = {0.0f, 0.0f}; postDC_R = {0.0f, 0.0f}; preMidHi_L = {0.0f}; preMidHi_R = {0.0f}; preMidLo_L = {0.0f}; preMidLo_R = {0.0f}; toneLow_L = {0.0f}; toneLow_R = {0.0f}; toneHighLP_L = {0.0f}; toneHighLP_R = {0.0f}; postMidHi_L = {0.0f}; postMidHi_R = {0.0f}; postMidLo_L = {0.0f}; postMidLo_R = {0.0f}; } void queueDSPSettings(bool requestReset = false) { portENTER_CRITICAL(&dspSettingsMux); pendingDriveDb = uiDriveDb; pendingTone = uiTone; pendingOutputDb = uiOutputDb; pendingBypass = bypassMode; pendingMidBoost = midBoostMode; if (requestReset) dspResetRequested = true; portEXIT_CRITICAL(&dspSettingsMux); } void applyPendingDSPSettings() { bool doReset = false; portENTER_CRITICAL(&dspSettingsMux); targetDriveDb = pendingDriveDb; targetTone = pendingTone; targetOutputDb = pendingOutputDb; dspBypassMode = pendingBypass; dspMidBoostMode = pendingMidBoost; if (dspResetRequested) { dspResetRequested = false; doReset = true; } portEXIT_CRITICAL(&dspSettingsMux); if (doReset) { dspDriveDb = targetDriveDb; dspTone = targetTone; dspOutputDb = targetOutputDb; resetTubeDSPStates(); } } inline int16_t floatToInt16(float x) { if (x >= 1.0f) return 32767; if (x <= -1.0f) return -32768; return (int16_t)(x * 32767.0f); } void processRealStereoTubeDSP(size_t bytes) { int sampleCount = bytes / sizeof(int16_t); bool inputClipped = false; bool outputClipped = false; float blockInputPeak = 0.0f; float blockDeltaPeak = 0.0f; // First measure the real input. This also works while in TRUE BYPASS. for (int i = 0; i + 1 < sampleCount; i += 2) { float xL = (float)audioBuffer[i] / 32768.0f; float xR = (float)audioBuffer[i + 1] / 32768.0f; float aL = fabsf(xL); float aR = fabsf(xR); float p = (aL > aR) ? aL : aR; if (p > blockInputPeak) blockInputPeak = p; if (aL >= 0.98f || aR >= 0.98f) inputClipped = true; } if (blockInputPeak > inputPeakAccumulator) inputPeakAccumulator = blockInputPeak; if (inputClipped) inputClipUntil = millis() + 500; // TRUE BYPASS = ADC samples written to DAC untouched. if (dspBypassMode) return; // --------------------------------------------------- // Parameter-derived math ONCE per 5 ms audio block. // No powf()/log/tanh inside the sample loop. // --------------------------------------------------- dspDriveDb = targetDriveDb; dspTone = targetTone; dspOutputDb = targetOutputDb; const float driveGain = driveModelGainFromDb(dspDriveDb); const float invDriveGain = 1.0f / driveGain; // TONE: -100 = warmer/darker, +100 = brighter/lighter. const float tone01 = constrain(dspTone * 0.01f, -1.0f, 1.0f); float lowDb = 0.0f; float highDb = 0.0f; if (tone01 < 0.0f) { float w = -tone01; // V0.9/V1.0: stronger WARM contour. // W100 = +4.0 dB low / -3.5 dB high. lowDb = +4.0f * w; highDb = -3.5f * w; } else { // V0.9/V1.0: stronger BRIGHT contour. // B100 = -2.5 dB low / +4.0 dB high. lowDb = -2.5f * tone01; highDb = +4.0f * tone01; } const float lowGain = powf(10.0f, lowDb * 0.05f); const float highGain = powf(10.0f, highDb * 0.05f); // Elektor S1-inspired MID CUT / BOOST. Kept moderate for Hi-Fi use. const float midDb = dspMidBoostMode ? +2.0f : -2.0f; const float midGain = powf(10.0f, midDb * 0.05f); // Elektor P2-inspired output trim. User can level-match processed/bypass. const float outputGain = powf(10.0f, dspOutputDb * 0.05f); for (int i = 0; i + 1 < sampleCount; i += 2) { float xL = (float)audioBuffer[i] / 32768.0f; float xR = (float)audioBuffer[i + 1] / 32768.0f; // Remove tiny ADC offset before nonlinear processing. float dcL = processDCBlock(xL, preDC_L); float dcR = processDCBlock(xR, preDC_R); // ------------------------------------------------- // 1) PRE-SHAPING BEFORE DISTORTION // ------------------------------------------------- // Create a broad ~180 Hz...3.2 kHz band and emphasize it before clipping, // analogous to Elektor's band-pass / pre-processing philosophy. float preHiL = processOnePoleLP(dcL, preMidHi_L, PRE_MID_HI_ALPHA); float preHiR = processOnePoleLP(dcR, preMidHi_R, PRE_MID_HI_ALPHA); float preLoL = processOnePoleLP(dcL, preMidLo_L, PRE_MID_LO_ALPHA); float preLoR = processOnePoleLP(dcR, preMidLo_R, PRE_MID_LO_ALPHA); float preBandL = preHiL - preLoL; float preBandR = preHiR - preLoR; float preL = dcL + PRE_EMPHASIS * preBandL; float preR = dcR + PRE_EMPHASIS * preBandR; // ------------------------------------------------- // 2) DRIVE + DIODE KNEE + LED KNEE // ------------------------------------------------- float uL = driveGain * preL; float uR = driveGain * preR; float clippedL = dualKneeClip(uL) * invDriveGain; float clippedR = dualKneeClip(uR) * invDriveGain; // Remove only the LINEAR pre-emphasis. If the clipper is inactive, // the path returns close to the original flat signal; when clipping is // active, the distortion still remains concentrated in the emphasized band. float coreL = clippedL - PRE_EMPHASIS * preBandL; float coreR = clippedR - PRE_EMPHASIS * preBandR; // ------------------------------------------------- // 3) POST TONE / MID CUT-BOOST // ------------------------------------------------- float lowL = processOnePoleLP(coreL, toneLow_L, TONE_LOW_ALPHA); float lowR = processOnePoleLP(coreR, toneLow_R, TONE_LOW_ALPHA); float hiBaseL = processOnePoleLP(coreL, toneHighLP_L, TONE_HIGH_ALPHA); float hiBaseR = processOnePoleLP(coreR, toneHighLP_R, TONE_HIGH_ALPHA); float highL = coreL - hiBaseL; float highR = coreR - hiBaseR; float midHiL = processOnePoleLP(coreL, postMidHi_L, POST_MID_HI_ALPHA); float midHiR = processOnePoleLP(coreR, postMidHi_R, POST_MID_HI_ALPHA); float midLoL = processOnePoleLP(coreL, postMidLo_L, POST_MID_LO_ALPHA); float midLoR = processOnePoleLP(coreR, postMidLo_R, POST_MID_LO_ALPHA); float midL = midHiL - midLoL; float midR = midHiR - midLoR; float yL = coreL + (lowGain - 1.0f) * lowL + (highGain - 1.0f) * highL + (midGain - 1.0f) * midL; float yR = coreR + (lowGain - 1.0f) * lowR + (highGain - 1.0f) * highR + (midGain - 1.0f) * midR; // ------------------------------------------------- // 4) OUTPUT LEVEL (Elektor P2 concept) // ------------------------------------------------- yL *= outputGain; yR *= outputGain; yL = processDCBlock(yL, postDC_L); yR = processDCBlock(yR, postDC_R); // Diagnostic DELTA = actual sample-domain difference from bypass. float dL = fabsf(yL - xL); float dR = fabsf(yR - xR); float d = (dL > dR) ? dL : dR; if (d > blockDeltaPeak) blockDeltaPeak = d; if (fabsf(yL) >= 1.0f || fabsf(yR) >= 1.0f) outputClipped = true; audioBuffer[i] = floatToInt16(yL); audioBuffer[i + 1] = floatToInt16(yR); } if (blockDeltaPeak > dspDeltaPeakAccumulator) dspDeltaPeakAccumulator = blockDeltaPeak; if (outputClipped) outputClipUntil = millis() + 500; } // ===================================================== // WM8960 CONFIGURATION // Copied from the proven EQ engine; codec is configured FIRST. // ===================================================== #define CODEC_CHECK(label, command) \ do \ { \ bool ok = false; \ int attempt = 0; \ \ for (attempt = 1; attempt <= 3; attempt++) \ { \ if (command) \ { \ ok = true; \ break; \ } \ delay(30); \ } \ \ Serial.print(label); \ Serial.print(" : "); \ \ if (ok) \ { \ Serial.print("OK"); \ if (attempt > 1) \ { \ Serial.print(" attempt "); \ Serial.print(attempt); \ } \ Serial.println(); \ } \ else \ { \ Serial.println("FAILED"); \ return false; \ } \ delay(10); \ } while (0) bool setupAudioCodec() { Serial.println(); Serial.println("======================================"); Serial.println("WM8960: CONFIGURE CODEC FIRST"); Serial.println("I2S CLOCKS ARE STILL STOPPED"); Serial.println("======================================"); Wire.begin(WM_SDA, WM_SCL); Wire.setClock(25000); delay(1000); bool found = false; for (int attempt = 1; attempt <= 10; attempt++) { Serial.print("codec.begin attempt "); Serial.print(attempt); Serial.print(" : "); if (codec.begin()) { Serial.println("OK"); found = true; break; } Serial.println("FAILED"); delay(100); } if (!found) return false; delay(200); CODEC_CHECK("VREF", codec.enableVREF()); CODEC_CHECK("VMID", codec.enableVMID()); delay(200); CODEC_CHECK("PLL prescale /2", codec.setPLLPRESCALE(WM8960_PLLPRESCALE_DIV_2)); CODEC_CHECK("PLL fractional", codec.setSMD(WM8960_PLL_MODE_FRACTIONAL)); CODEC_CHECK("PLL N=8", codec.setPLLN(8)); CODEC_CHECK("PLL K", codec.setPLLK(0x31, 0x26, 0xE8)); CODEC_CHECK("PLL ON", codec.enablePLL()); delay(100); CODEC_CHECK("Clock source PLL", codec.setCLKSEL(WM8960_CLKSEL_PLL)); CODEC_CHECK("SYSCLK /2", codec.setSYSCLKDIV(WM8960_SYSCLK_DIV_BY_2)); CODEC_CHECK("ADC divider 256fs", codec.setADCDIV(0)); CODEC_CHECK("DAC divider 256fs", codec.setDACDIV(0)); CODEC_CHECK("16-bit I2S", codec.setWL(WM8960_WL_16BIT)); CODEC_CHECK("WM8960 SLAVE", codec.enablePeripheralMode()); CODEC_CHECK("LR polarity normal", codec.setLRP(WM8960_LR_POLARITY_NORMAL)); CODEC_CHECK("ADC L/R swap OFF", codec.setALRSWAP(WM8960_ALRSWAP_NORMAL)); CODEC_CHECK("ADC/DAC common WS", codec.setALRCGPIO()); // LINE INPUT CODEC_CHECK("LEFT PGA ON", codec.enableLMIC()); CODEC_CHECK("RIGHT PGA ON", codec.enableRMIC()); CODEC_CHECK("LINPUT1 -> LEFT PGA", codec.connectLMN1()); CODEC_CHECK("RINPUT1 -> RIGHT PGA", codec.connectRMN1()); CODEC_CHECK("LEFT PGA UNMUTE", codec.disableLINMUTE()); CODEC_CHECK("RIGHT PGA UNMUTE", codec.disableRINMUTE()); CODEC_CHECK("LEFT PGA 0dB", codec.setLINVOLDB(LINE_INPUT_PGA_DB)); CODEC_CHECK("RIGHT PGA 0dB", codec.setRINVOLDB(LINE_INPUT_PGA_DB)); CODEC_CHECK("LEFT MIC BOOST 0dB", codec.setLMICBOOST(WM8960_MIC_BOOST_GAIN_0DB)); CODEC_CHECK("RIGHT MIC BOOST 0dB", codec.setRMICBOOST(WM8960_MIC_BOOST_GAIN_0DB)); CODEC_CHECK("LEFT PGA -> ADC mixer", codec.connectLMIC2B()); CODEC_CHECK("RIGHT PGA -> ADC mixer", codec.connectRMIC2B()); CODEC_CHECK("LEFT analog input ON", codec.enableAINL()); CODEC_CHECK("RIGHT analog input ON", codec.enableAINR()); // ADC CODEC_CHECK("LEFT ADC ON", codec.enableAdcLeft()); CODEC_CHECK("RIGHT ADC ON", codec.enableAdcRight()); CODEC_CHECK("LEFT ADC 0dB", codec.setAdcLeftDigitalVolumeDB(0.0)); CODEC_CHECK("RIGHT ADC 0dB", codec.setAdcRightDigitalVolumeDB(0.0)); // DAC CODEC_CHECK("DAC LEFT ON", codec.enableDacLeft()); CODEC_CHECK("DAC RIGHT ON", codec.enableDacRight()); CODEC_CHECK("DAC LEFT 0dB", codec.setDacLeftDigitalVolume(255)); CODEC_CHECK("DAC RIGHT 0dB", codec.setDacRightDigitalVolume(255)); CODEC_CHECK("Digital loopback OFF", codec.disableLoopBack()); CODEC_CHECK("LEFT DAC -> LEFT MIX", codec.enableLD2LO()); CODEC_CHECK("RIGHT DAC -> RIGHT MIX", codec.enableRD2RO()); CODEC_CHECK("LEFT OUTPUT MIX ON", codec.enableLOMIX()); CODEC_CHECK("RIGHT OUTPUT MIX ON", codec.enableROMIX()); CODEC_CHECK("LEFT analog bypass OFF", codec.disableLB2LO()); CODEC_CHECK("RIGHT analog bypass OFF", codec.disableRB2RO()); CODEC_CHECK("LEFT HEADPHONE ON", codec.enableLeftHeadphone()); CODEC_CHECK("RIGHT HEADPHONE ON", codec.enableRightHeadphone()); CODEC_CHECK("HEADPHONE 0dB", codec.setHeadphoneVolumeDB(0.0)); CODEC_CHECK("DAC UNMUTE", codec.disableDacMute()); delay(300); Serial.println("WM8960 CONFIG COMPLETE."); Serial.println(); return true; } bool setupAudioI2S() { Serial.println(); Serial.println("======================================"); Serial.println("START ESP32 FULL DUPLEX I2S LAST"); Serial.println("======================================"); i2s_config_t cfg = {}; cfg.mode = (i2s_mode_t)( I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_RX ); cfg.sample_rate = AUDIO_SAMPLE_RATE; cfg.bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT; cfg.channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT; cfg.communication_format = I2S_COMM_FORMAT_STAND_I2S; cfg.intr_alloc_flags = ESP_INTR_FLAG_LEVEL1; cfg.dma_buf_count = 8; cfg.dma_buf_len = AUDIO_FRAMES; cfg.use_apll = false; cfg.tx_desc_auto_clear = true; cfg.fixed_mclk = 0; esp_err_t err = i2s_driver_install(AUDIO_I2S, &cfg, 0, NULL); Serial.print("i2s_driver_install = "); Serial.println(err); if (err != ESP_OK) return false; i2s_pin_config_t pins = {}; pins.mck_io_num = I2S_PIN_NO_CHANGE; pins.bck_io_num = I2S_BCLK; pins.ws_io_num = I2S_WS; pins.data_out_num = I2S_DOUT; pins.data_in_num = I2S_DIN; err = i2s_set_pin(AUDIO_I2S, &pins); Serial.print("i2s_set_pin = "); Serial.println(err); if (err != ESP_OK) return false; i2s_zero_dma_buffer(AUDIO_I2S); delay(200); Serial.println("FULL DUPLEX I2S READY."); Serial.println(); return true; } // ===================================================== // DEDICATED AUDIO TASK - CORE 0 // ===================================================== void audioTask(void *parameter) { applyPendingDSPSettings(); for (;;) { applyPendingDSPSettings(); size_t bytesRead = 0; esp_err_t readErr = i2s_read( AUDIO_I2S, audioBuffer, sizeof(audioBuffer), &bytesRead, portMAX_DELAY ); if (readErr == ESP_OK && bytesRead > 0) { processRealStereoTubeDSP(bytesRead); size_t bytesWritten = 0; i2s_write( AUDIO_I2S, audioBuffer, bytesRead, &bytesWritten, portMAX_DELAY ); } } } // ===================================================== // UI HELPERS // ===================================================== String formatDrive(float db) { String s = "+"; s += String(db, 1); s += " dB"; return s; } String formatTone(float tone) { int v = (int)roundf(tone); if (v == 0) return "0"; if (v < 0) return String("W ") + String(-v); return String("B ") + String(v); } String formatOutput(float db) { String s; if (db >= 0.0f) s = "+"; s += String(db, 1); s += " dB"; return s; } bool inputClipActive() { unsigned long now = millis(); return ((long)(inputClipUntil - now) > 0); } bool outputClipActive() { if (bypassMode) return false; unsigned long now = millis(); return ((long)(outputClipUntil - now) > 0); } void drawHeader() { tft.setTextDatum(TC_DATUM); tft.setTextColor(COL_CYAN, COL_BG); tft.drawString("STEREO TUBE SOUND PROCESSOR", 160, TITLE_Y, 2); tft.drawFastHLine(7, TITLE_Y + 7, 32, COL_CYAN); tft.drawFastHLine(281, TITLE_Y + 7, 32, COL_CYAN); } void drawLeftPanel() { tft.fillRoundRect(PANEL_X, PANEL_Y, PANEL_W, PANEL_H, 6, COL_BG); tft.drawRoundRect(PANEL_X, PANEL_Y, PANEL_W, PANEL_H, 6, COL_BORDER); tft.setTextDatum(TC_DATUM); // Physical encoder mapping remains unchanged. // Labels now use the same larger font as their values. tft.setTextColor(COL_GREY, COL_BG); tft.drawString("OUTPUT", PANEL_X + PANEL_W / 2, PANEL_Y + 7, 2); tft.setTextColor(COL_CYAN, COL_BG); tft.drawString(formatOutput(uiOutputDb), PANEL_X + PANEL_W / 2, PANEL_Y + 29, 2); tft.setTextColor(COL_GREY, COL_BG); tft.drawString("TONE", PANEL_X + PANEL_W / 2, PANEL_Y + 55, 2); tft.setTextColor(COL_MAGENTA, COL_BG); tft.drawString(formatTone(uiTone), PANEL_X + PANEL_W / 2, PANEL_Y + 77, 2); tft.setTextColor(COL_GREY, COL_BG); tft.drawString("DRIVE", PANEL_X + PANEL_W / 2, PANEL_Y + 103, 2); tft.setTextColor(COL_YELLOW, COL_BG); tft.drawString(formatDrive(uiDriveDb), PANEL_X + PANEL_W / 2, PANEL_Y + 125, 2); } int transferX(float x) { x = constrain(x, -1.0f, 1.0f); return (int)roundf((x + 1.0f) * 0.5f * (GRAPH_W - 1)); } int transferY(float y) { y = constrain(y, -1.0f, 1.0f); return (int)roundf((1.0f - (y + 1.0f) * 0.5f) * (GRAPH_H - 1)); } void renderGraph() { bool clipActive = outputClipActive(); uint16_t curveColor = clipActive ? COL_RED : COL_CYAN; uint16_t borderColor = clipActive ? COL_RED : COL_BORDER; graphSprite.fillSprite(COL_GRAPH_BG); const int centerX = transferX(0.0f); const int centerY = transferY(0.0f); // =================================================== // TRANSFER CURVE GRADIENT TOWARD THE X AXIS // Same principle as the final Parametric EQ graph: // strongest color next to the curve, progressively // fading as it approaches the X axis (y = 0). // Works symmetrically on both sides of the Y axis. // =================================================== for (int p = 1; p < GRAPH_W - 1; p++) { float x = -1.0f + 2.0f * (float)p / (float)(GRAPH_W - 1); float y = visualClipTransfer(x); int py = transferY(y); int distance = abs(centerY - py); if (distance > 1) { int direction = (centerY > py) ? 1 : -1; for (int h = 1; h < distance; h++) { // Start at about 50% of the main curve intensity right beside // the curve, then fade more quickly toward the X axis. // Quadratic fade keeps the fill much softer, like the final EQ. float ratio = 1.0f - ((float)h / (float)distance); uint8_t val = (uint8_t)(ratio * ratio * 128.0f); uint16_t gradColor; if (clipActive) gradColor = tft.color565(val, 0, 0); else gradColor = tft.color565(0, val, val); graphSprite.drawPixel(p, py + direction * h, gradColor); } } } // =================================================== // DOTTED GRID - SAME STYLE AS FINAL PARAMETRIC EQ // =================================================== for (int i = 1; i <= 7; i++) { int y = (i * (GRAPH_H - 1)) / 8; for (int px = 1; px < GRAPH_W - 1; px += 3) graphSprite.drawPixel(px, y, COL_GRID); } for (int i = 1; i <= 10; i++) { int x = (i * (GRAPH_W - 1)) / 11; for (int py = 1; py < GRAPH_H - 1; py += 3) graphSprite.drawPixel(x, py, COL_GRID); } // =================================================== // X / Y AXES - restored as solid reference lines // =================================================== graphSprite.drawFastVLine(centerX, 1, GRAPH_H - 2, COL_GREY); graphSprite.drawFastHLine(1, centerY, GRAPH_W - 2, COL_GREY); // Linear y=x reference line. graphSprite.drawLine( transferX(-1.0f), transferY(-1.0f), transferX( 1.0f), transferY( 1.0f), COL_GREY ); // =================================================== // ACTUAL DUAL-KNEE TRANSFER CURVE // Single-pixel rendering, restored from V1.0.2. // This makes the bends/knees look softer and more rounded. // =================================================== int prevX = transferX(-1.0f); int prevY = transferY(visualClipTransfer(-1.0f)); for (int p = 1; p < GRAPH_W; p++) { float x = -1.0f + 2.0f * (float)p / (float)(GRAPH_W - 1); float y = visualClipTransfer(x); int px = transferX(x); int py = transferY(y); graphSprite.drawLine(prevX, prevY, px, py, curveColor); prevX = px; prevY = py; } // =================================================== // DRIVE / KNEE MARKERS // =================================================== // Display-only calibration. Orange second-knee markers // are already visible at DRIVE = 0 dB and both pairs // move progressively inward as DRIVE increases. if (!bypassMode) { float driveNorm = constrain(uiDriveDb / 24.0f, 0.0f, 1.0f); float k2Display = 0.985f - 0.75f * driveNorm; float k1Display = k2Display * (0.42f / 0.62f); int x1p = transferX( k1Display); int x1n = transferX(-k1Display); int x2p = transferX( k2Display); int x2n = transferX(-k2Display); graphSprite.drawFastVLine(x1p, 1, GRAPH_H - 2, COL_YELLOW); graphSprite.drawFastVLine(x1n, 1, GRAPH_H - 2, COL_YELLOW); graphSprite.drawFastVLine(x2p, 1, GRAPH_H - 2, COL_ORANGE); graphSprite.drawFastVLine(x2n, 1, GRAPH_H - 2, COL_ORANGE); } if (bypassMode) { graphSprite.setTextDatum(TC_DATUM); graphSprite.setTextColor(COL_YELLOW, COL_GRAPH_BG); graphSprite.drawString("BYPASS", GRAPH_W / 2, 6, 2); } // Border last so all inner graphics terminate cleanly. graphSprite.drawRoundRect(0, 0, GRAPH_W, GRAPH_H, 5, borderColor); graphSprite.pushSprite(GRAPH_X, GRAPH_Y); } void drawBottomStatus() { tft.fillRect(0, 184, 320, 56, COL_BG); tft.setTextDatum(TC_DATUM); bool inClip = inputClipActive(); bool outClip = outputClipActive(); uint16_t modeColor = bypassMode ? COL_YELLOW : COL_GREEN; uint16_t midColor = midBoostMode ? COL_MAGENTA : COL_ORANGE; // Compact status boxes. Their widths are based on the longest text, // so there is only a small horizontal margin around the label. const int boxY = 186; const int boxH = 21; const int leftCenterX = 62; const int rightCenterX = 258; const int padX = 10; int leftBoxW = tft.textWidth("TUBE ACTIVE", 2) + padX * 2; int rightBoxW = tft.textWidth("MID BOOST", 2) + padX * 2; int leftBoxX = leftCenterX - leftBoxW / 2; int rightBoxX = rightCenterX - rightBoxW / 2; // Fill, draw text, then draw the outline LAST. This prevents the text // background from erasing the lower part of the rounded rectangle. tft.fillRoundRect(leftBoxX, boxY, leftBoxW, boxH, 5, COL_BG); tft.setTextColor(modeColor, COL_BG); tft.drawString(bypassMode ? "BYPASS" : "TUBE ACTIVE", leftCenterX, boxY + 3, 2); tft.drawRoundRect(leftBoxX, boxY, leftBoxW, boxH, 5, modeColor); tft.fillRoundRect(rightBoxX, boxY, rightBoxW, boxH, 5, COL_BG); tft.setTextColor(midColor, COL_BG); tft.drawString(midBoostMode ? "MID BOOST" : "MID CUT", rightCenterX, boxY + 3, 2); tft.drawRoundRect(rightBoxX, boxY, rightBoxW, boxH, 5, midColor); // Encoder speed centered horizontally between the two status boxes. tft.setTextColor(COL_WHITE, COL_BG); tft.drawString(speed2x ? "ENC 2x" : "ENC 1x", 160, boxY + 3, 2); // Bottom status labels. The center space is now used by PRESET status. tft.setTextColor(inClip ? COL_RED : COL_GREY, COL_BG); tft.drawString(inClip ? "INPUT CLIP" : "INPUT OK", 67, 214, 2); String centerText; if (presetStatusActive()) { centerText = presetStatusText; } else if (presetMode) { centerText = String("PRESET P") + String(presetSelectedSlot); } else { centerText = "CURRENT"; } // Center status: same baseline/font size as INPUT/OUTPUT and always yellow. tft.setTextColor(COL_YELLOW, COL_BG); tft.drawString(centerText, 160, 214, 2); tft.setTextColor(outClip ? COL_RED : COL_GREY, COL_BG); tft.drawString(outClip ? "OUTPUT CLIP" : "OUTPUT OK", 253, 214, 2); } void drawWholeUI() { tft.fillScreen(COL_BG); drawHeader(); drawLeftPanel(); renderGraph(); drawBottomStatus(); } // ===================================================== // PRESET STATUS / NVS HELPERS // ===================================================== bool presetStatusActive() { if (presetStatusText.length() == 0) return false; return ((long)(presetStatusUntil - millis()) > 0); } void setPresetStatus(const String &text, uint16_t color) { presetStatusText = text; presetStatusColor = color; presetStatusUntil = millis() + PRESET_STATUS_MS; } void clearPresetStatus() { presetStatusText = ""; presetStatusUntil = 0; } void makeTubePresetKey(int slot, char *key, size_t keySize) { snprintf(key, keySize, "p%d", slot); } bool savePresetSlot(int slot) { if (slot < 1 || slot > PRESET_COUNT) return false; TubePresetStorage data; data.magic = TUBE_PRESET_MAGIC; data.driveDb = uiDriveDb; data.tone = uiTone; data.outputDb = uiOutputDb; data.midBoost = midBoostMode ? 1 : 0; char key[8]; makeTubePresetKey(slot, key, sizeof(key)); preferences.begin("tubepres", false); size_t written = preferences.putBytes(key, &data, sizeof(data)); preferences.end(); return (written == sizeof(data)); } bool loadPresetSlot(int slot) { if (slot < 1 || slot > PRESET_COUNT) return false; char key[8]; makeTubePresetKey(slot, key, sizeof(key)); TubePresetStorage data; preferences.begin("tubepres", true); size_t storedLength = preferences.getBytesLength(key); if (storedLength != sizeof(data)) { preferences.end(); return false; } size_t readLength = preferences.getBytes(key, &data, sizeof(data)); preferences.end(); if (readLength != sizeof(data) || data.magic != TUBE_PRESET_MAGIC) return false; // Defensive validation against old/corrupt NVS data. uiDriveDb = constrain(data.driveDb, 0.0f, 24.0f); uiTone = constrain(data.tone, -100.0f, 100.0f); uiOutputDb = constrain(data.outputDb, -12.0f, 18.0f); midBoostMode = (data.midBoost != 0); return true; } void markCurrentStateDirty() { currentStateDirty = true; currentStateChangedAt = millis(); } bool saveCurrentState() { TubeCurrentStorage data; data.magic = TUBE_CURRENT_MAGIC; data.driveDb = uiDriveDb; data.tone = uiTone; data.outputDb = uiOutputDb; data.midBoost = midBoostMode ? 1 : 0; preferences.begin("tube", false); size_t written = preferences.putBytes("current", &data, sizeof(data)); preferences.end(); return (written == sizeof(data)); } bool loadCurrentState() { TubeCurrentStorage data; preferences.begin("tube", true); size_t storedLength = preferences.getBytesLength("current"); if (storedLength != sizeof(data)) { preferences.end(); return false; } size_t readLength = preferences.getBytes("current", &data, sizeof(data)); preferences.end(); if (readLength != sizeof(data) || data.magic != TUBE_CURRENT_MAGIC) return false; // Defensive validation against corrupt/obsolete NVS data. if (!isfinite(data.driveDb) || !isfinite(data.tone) || !isfinite(data.outputDb)) return false; uiDriveDb = constrain(data.driveDb, 0.0f, 24.0f); uiTone = constrain(data.tone, -100.0f, 100.0f); uiOutputDb = constrain(data.outputDb, -12.0f, 18.0f); midBoostMode = (data.midBoost != 0); // These are deliberately always reset on power-up. bypassMode = false; speed2x = false; presetMode = false; return true; } void updateCurrentStateSave() { if (!currentStateDirty) return; unsigned long now = millis(); if (now - currentStateChangedAt < CURRENT_SAVE_DELAY_MS) return; if (saveCurrentState()) { currentStateDirty = false; } else { // Retry later instead of writing continuously on a failure. currentStateChangedAt = now; } } void updatePresetTimers(bool &presetVisualChanged) { unsigned long now = millis(); if (presetMode && (now - presetLastActivity >= PRESET_MODE_TIMEOUT_MS)) { presetMode = false; setPresetStatus("PRESET CANCEL", COL_GREY); presetVisualChanged = true; } if (presetStatusText.length() > 0 && !presetStatusActive()) { clearPresetStatus(); presetVisualChanged = true; } } // ===================================================== // UI PARAMETER CHANGES // ===================================================== int speedMultiplier() { return speed2x ? 2 : 1; } void changeDrive(int direction) { uiDriveDb += direction * 0.5f * speedMultiplier(); uiDriveDb = constrain(uiDriveDb, 0.0f, 24.0f); } void changeTone(int direction) { uiTone += direction * 2.0f * speedMultiplier(); uiTone = constrain(uiTone, -100.0f, 100.0f); } void changeOutput(int direction) { uiOutputDb += direction * 0.5f * speedMultiplier(); uiOutputDb = constrain(uiOutputDb, -12.0f, 18.0f); } void factoryDefaults() { uiDriveDb = DEFAULT_DRIVE_DB; uiTone = DEFAULT_TONE; uiOutputDb = DEFAULT_OUTPUT_DB; bypassMode = false; speed2x = false; midBoostMode = true; queueDSPSettings(true); markCurrentStateDirty(); } // Returns: 0=nothing, 1=short press, 2=long press. int updateButton(uint8_t pin, ButtonState &b, bool allowLong) { bool down = (digitalRead(pin) == LOW); unsigned long now = millis(); if (down && !b.wasDown) { b.wasDown = true; b.longFired = false; b.downAt = now; return 0; } if (down && b.wasDown && allowLong && !b.longFired) { if (now - b.downAt >= LONG_PRESS_MS) { b.longFired = true; return 2; } } if (!down && b.wasDown) { unsigned long held = now - b.downAt; bool wasLong = b.longFired; b.wasDown = false; b.longFired = false; if (!wasLong && held >= BUTTON_DEBOUNCE_MS) return 1; } return 0; } // ===================================================== // SETUP // ===================================================== void setup() { Serial.begin(115200); delay(500); Serial.println(); Serial.println("===================================================="); Serial.println("ESP32 STEREO TUBE PROCESSOR V1.2 - TRUE H2 TUBE TEST"); Serial.println("IDENTICAL HARDWARE TO 5-BAND PARAMETRIC EQ"); Serial.println("48 kHz / 16-bit stereo / WM8960 slave / ESP32 master"); Serial.println("===================================================="); pinMode(ENC1_A, INPUT); pinMode(ENC1_B, INPUT); pinMode(ENC2_A, INPUT); pinMode(ENC2_B, INPUT); pinMode(ENC3_A, INPUT); pinMode(ENC3_B, INPUT); pinMode(ENC1_SW, INPUT_PULLUP); pinMode(ENC2_SW, INPUT_PULLUP); pinMode(ENC3_SW, INPUT_PULLUP); enc1.lastAB = (digitalRead(ENC1_A) << 1) | digitalRead(ENC1_B); enc2.lastAB = (digitalRead(ENC2_A) << 1) | digitalRead(ENC2_B); enc3.lastAB = (digitalRead(ENC3_A) << 1) | digitalRead(ENC3_B); tft.init(); tft.setRotation(1); graphSprite.setColorDepth(16); graphSprite.createSprite(GRAPH_W, GRAPH_H); // Restore the last used SOUND settings before the first UI draw and // before DSP startup. If NVS is empty/invalid, factory defaults remain. bool restoredCurrentState = loadCurrentState(); Serial.println(restoredCurrentState ? "Last sound state restored from NVS." : "No saved last state - using defaults."); drawWholeUI(); // Initial DSP targets before audio starts. queueDSPSettings(true); // --------------------------------------------------- // AUDIO STARTUP: WM8960 FIRST, ESP32 I2S LAST // --------------------------------------------------- if (!setupAudioCodec()) { Serial.println("AUDIO CODEC SETUP FAILED"); while (1) delay(1000); } if (!setupAudioI2S()) { Serial.println("AUDIO I2S SETUP FAILED"); while (1) delay(1000); } BaseType_t taskResult = xTaskCreatePinnedToCore( audioTask, "TubeDSP", 8192, NULL, 3, &audioTaskHandle, 0 ); if (taskResult != pdPASS) { Serial.println("AUDIO TASK CREATE FAILED"); while (1) delay(1000); } Serial.println("V1.2 TRUE H2 TUBE TEST RUNNING."); Serial.println("LINE INPUT PGA = +18.0 dB (same real-hardware test sensitivity)"); Serial.println("ENC1 DRIVE 0..24 dB"); Serial.println("ENC2 TONE: WARM -100 .. 0 .. BRIGHT +100"); Serial.println("ENC3 OUTPUT -12..+18 dB (level-match to BYPASS)"); Serial.println("SW3 LONG = PRESET MODE"); Serial.println("PRESET: ENC3=P1..P5, SW3 short=LOAD, SW3 long=SAVE"); Serial.println("SW1 short = TRUE BYPASS"); Serial.println("SW2 short = 1x/2x, long = FACTORY DEFAULT"); Serial.println("SW3 short = MID BOOST / MID CUT"); Serial.println("V1.2 nonlinear core: asymmetric H2-rich dual-knee"); Serial.println("Last sound state: delayed NVS save after 2 s of inactivity."); Serial.println(); } // ===================================================== // LOOP // ===================================================== void loop() { bool redrawParameters = false; bool redrawAll = false; bool presetVisualChanged = false; int e1 = readEncoder(enc1); int e2 = readEncoder(enc2); int e3 = readEncoder(enc3); if (e1 != 0 && !bypassMode) { changeDrive(e1 * ENC1_DIR); redrawParameters = true; } if (e2 != 0 && !bypassMode) { changeTone(e2 * ENC2_DIR); redrawParameters = true; } if (e3 != 0) { if (presetMode) { int direction = e3 * ENC3_DIR; presetSelectedSlot += direction; if (presetSelectedSlot > PRESET_COUNT) presetSelectedSlot = 1; if (presetSelectedSlot < 1) presetSelectedSlot = PRESET_COUNT; presetLastActivity = millis(); clearPresetStatus(); presetVisualChanged = true; } else if (!bypassMode) { changeOutput(e3 * ENC3_DIR); redrawParameters = true; } } if (redrawParameters) { queueDSPSettings(false); markCurrentStateDirty(); drawLeftPanel(); renderGraph(); } // SW1: short = TRUE BYPASS. int sw1Event = updateButton(ENC1_SW, sw1State, false); if (sw1Event == 1) { bypassMode = !bypassMode; queueDSPSettings(true); redrawAll = true; } // SW2: short = speed, long = defaults. int sw2Event = updateButton(ENC2_SW, sw2State, true); if (sw2Event == 1) { speed2x = !speed2x; redrawAll = true; } else if (sw2Event == 2) { factoryDefaults(); redrawAll = true; } // SW3 NORMAL: short = MID BOOST/CUT, long = enter PRESET MODE. // SW3 PRESET: short = LOAD, long = SAVE. int sw3Event = updateButton(ENC3_SW, sw3State, true); if (sw3Event == 1) { if (presetMode) { // PRESET MODE SHORT = LOAD selected slot. if (loadPresetSlot(presetSelectedSlot)) { lastPresetSlot = presetSelectedSlot; presetMode = false; setPresetStatus(String("P") + String(presetSelectedSlot) + " LOADED", COL_GREEN); queueDSPSettings(true); markCurrentStateDirty(); drawLeftPanel(); renderGraph(); presetVisualChanged = true; } else { // Empty slot: remain in PRESET MODE so another slot can be selected. setPresetStatus(String("P") + String(presetSelectedSlot) + " EMPTY", COL_YELLOW); presetLastActivity = millis(); presetVisualChanged = true; } } else { // NORMAL MODE SHORT = MID BOOST / MID CUT. midBoostMode = !midBoostMode; queueDSPSettings(false); markCurrentStateDirty(); redrawAll = true; } } else if (sw3Event == 2) { if (presetMode) { // PRESET MODE LONG = SAVE current sound into selected slot. if (savePresetSlot(presetSelectedSlot)) { lastPresetSlot = presetSelectedSlot; presetMode = false; setPresetStatus(String("P") + String(presetSelectedSlot) + " SAVED", COL_GREEN); } else { presetMode = false; setPresetStatus("SAVE ERROR", COL_RED); } presetVisualChanged = true; } else { // NORMAL MODE LONG = ENTER PRESET MODE. presetMode = true; presetSelectedSlot = lastPresetSlot; presetLastActivity = millis(); clearPresetStatus(); presetVisualChanged = true; } } updatePresetTimers(presetVisualChanged); updateCurrentStateSave(); if (redrawAll) { drawLeftPanel(); renderGraph(); drawBottomStatus(); } if (presetVisualChanged && !redrawAll) { drawBottomStatus(); } // Redraw clip status on transitions. static bool lastInputClip = false; static bool lastOutputClip = false; bool nowInputClip = inputClipActive(); bool nowOutputClip = outputClipActive(); if (nowInputClip != lastInputClip || nowOutputClip != lastOutputClip) { lastInputClip = nowInputClip; lastOutputClip = nowOutputClip; renderGraph(); drawBottomStatus(); } // Update meters 4x / second. Log math stays on Core 1. static unsigned long lastPeakUiAt = 0; unsigned long nowMs = millis(); if (nowMs - lastPeakUiAt >= 250) { lastPeakUiAt = nowMs; float peak = inputPeakAccumulator; float deltaPeak = dspDeltaPeakAccumulator; inputPeakAccumulator = 0.0f; dspDeltaPeakAccumulator = 0.0f; if (peak > 0.000001f) uiInputPeakDbfs = 20.0f * log10f(peak); else uiInputPeakDbfs = -120.0f; if (!bypassMode && deltaPeak > 0.000001f) uiDspDeltaDbfs = 20.0f * log10f(deltaPeak); else uiDspDeltaDbfs = -120.0f; } // Serial diagnostics once per second. static unsigned long lastSerialAt = 0; if (nowMs - lastSerialAt >= 1000) { lastSerialAt = nowMs; Serial.print("MODE="); Serial.print(bypassMode ? "BYPASS" : "TUBE"); Serial.print(" DRIVE="); Serial.print(dspDriveDb, 1); Serial.print("dB TONE="); Serial.print(dspTone, 0); Serial.print(" OUTPUT="); Serial.print(dspOutputDb, 1); Serial.print("dB MID="); Serial.print(dspMidBoostMode ? "BOOST" : "CUT"); Serial.print(" PK="); Serial.print(uiInputPeakDbfs, 1); Serial.print("dBFS DELTA="); if (uiDspDeltaDbfs <= -119.0f) Serial.println("--"); else { Serial.print(uiDspDeltaDbfs, 1); Serial.println("dBFS"); } } }