Mic-Triggered LED Firmware


I’ll correct the microphone clock rate and lower the trigger threshold, then rebuild a replacement UF2. The current software clock likely runs below the ICS-43434’s minimum because the 1 µs delay is applied on both clock edges.
Fixed and rebuilt the firmware. The replacement uses a faster microphone clock, a much lower adaptive trigger threshold, and flashes the LED three times at startup to confirm the image and LED path are working.
Download and flash: avocaudio_sound_led_v2
The corrected source is in Firmware Bring-Up. After flashing, verify the LED flashes three times, wait for calibration to finish, then snap near the microphone.
Still not working. Please read the components datasheet thoroughly and make sure to use appropriate libraries
I’ll rework this using the ICS-43434 timing requirements and a proven RP2040 PIO/DMA I²S implementation rather than software bit-banging. I’ll verify the datasheet timing, library pin constraints, rebuild, and provide a diagnostic UF2 that reports actual microphone levels.
Replaced the bit-banged receiver with hardware PWM clocks and a custom PIO I²S receiver using official Pico SDK libraries. V3 runs the ICS-43434 at 48 kHz, captures its full 24-bit left channel, detects short peaks, and reports live levels over USB CDC.
After flashing, the LED should blink three times. Open USB serial and look for changing avg, peak, and span values; if they remain zero or constant, the remaining fault is likely microphone power, soldering, acoustic-port blockage, or GPIO9/10/11 continuity.

Firmware Bring-Up
Milestone scope
This is a schematic-grounded Raspberry Pi Pico SDK C project for first-power firmware diagnostics on the bare RP2040. It does not modify or rely on PCB routing.
Downloadable source files
These links point to durable project assets and were verified by reading their stored contents back from the project. The combined bundle is the single-file fallback containing every source file in fenced sections.
Access verification: project asset metadata resolved all seven assets. Complete raw reads reached the final chunk for corrected main.c (10,402 characters), avocaudio_board.h (1,471), lora_uart.pio (1,637), README.md (2,052), and the combined bundle (17,110); the bundle contains all six intended paths.

Text


avocaudio-bringup/
├── CMakeLists.txt
├── pico_sdk_import.cmake
├── README.md
└── src/
    ├── main.c
    ├── avocaudio_board.h
    └── lora_uart.pio
Pin table

Table


FunctionRP2040 GPIOFirmware use / constraint
LoRa-E5 receive0PIO UART RX; connected to module PB6/UART1_TX
LoRa-E5 transmit1PIO UART TX; connected to module PB7/UART1_RX
LoRa reset12Configurable reset output; module RST is a reset-trigger input
Optional user input13Unconnected; disabled with AVO_USER_INPUT_GPIO=-1
DHT data16Bounded single-wire probe; external 5 kΩ pull-up exists
SD CLK17Low-speed bit-banged SPI clock
SD CMD18Bit-banged MOSI
SD DAT019Bit-banged MISO
SD DAT120Pulled-up input during diagnostic
SD DAT221Pulled-up input during diagnostic
SD DAT3/CS22Bit-banged chip select
User LED25Configurable active-high output
Native QSPIDedicated pinsBoot/XIP flash only; never reconfigured
USB D+/D−Native USBUSB CDC stdio
SW2 directly controls RUN and cannot be read by executing firmware. SW1 is BOOTSEL through the flash chip-select path and is deliberately not sampled while executing XIP.
Architecture and behavior
  • USB CDC starts immediately, waits only for the configurable grace period, then continues without a host.
  • Startup prints reset cause, immutable pin mapping, flash results, SD result, and LoRa configuration.
  • The main loop is timestamp-scheduled with a 1 ms cooperative sleep; no application-level operation waits indefinitely.
  • GPIO25 blinks continuously.
  • DHT is probed every 2.5 seconds with bounded edge timeouts, checksum validation, and DHT11/DHT22 interpretation.
  • SD uses safe low-speed GPIO bit-banged SPI on GPIO17/18/19/22. Startup initialization is bounded through CMD0, CMD8, CMD55/ACMD41, and CMD58; DAT1 and DAT2 remain pulled-up inputs. It reports card generation/capacity indication and OCR only. Periodic full re-initialization is disabled by default with AVO_SD_PERIODIC_RETRY=0; enabling it can introduce a bounded approximately 1 second worst-case cooperative pause due to ACMD41 retries.
  • Boot flash diagnostics issue read-only JEDEC opcode 0x9F through flash_do_cmd() with interrupts disabled around the RAM-resident transaction. Expected W25Q128JV bytes are EF 40 18. The SDK unique board ID is also reported; all operations are read-only.
  • LoRa uses separate PIO TX/RX state machines because RP2040 hardware UART0 has the wrong direction on GPIO0/1 for this schematic. TX uses one stop-bit period: the wrapped pull side 1 [7] supplies stop/idle before the next start bit. Reset, settle, AT\r\n, bounded receive, raw response, pass/fail, and retry are state-driven. Default 9600 8N1 is configurable.
  • Microphone GPIO/protocol assumptions are intentionally absent.
Build, flash, and test
  1. Install a current Raspberry Pi Pico SDK checkout with initialized submodules and an Arm GNU embedded toolchain.
  2. Set PICO_SDK_PATH to the SDK root.
  3. Build:

Sh


mkdir build
cd build
cmake -DPICO_BOARD=pico ..
cmake --build . -j
  1. Hold BOOTSEL while plugging in USB and copy build/avocaudio_bringup.uf2 to RPI-RP2.
  2. Open the USB CDC port. Terminal baud is ignored by USB CDC.
  3. Pass criteria: banner appears without an indefinite USB wait; LED continues blinking; flash JEDEC bytes are reported; SD gives a bounded pass/fail; DHT gives bounded reports; LoRa retries without blocking other tasks.
Example startup output

Text


AvocAudio v3 Rev 2 RP2040 bring-up
====================================
RESET     watchdog=no watchdog-enable=no
INPUTS    SW2=RUN unreadable; SW1=BOOTSEL/flash-CS not sampled; user GPIO=-1
LED       GPIO25 active-high
DHT       GPIO16 auto-interpret DHT11/DHT22
SD        CLK=17 CMD/MOSI=18 DAT0/MISO=19 DAT3/CS=22 bit-banged diagnostic
LORA      PIO UART RX=0 TX=1 NRST=12 9600 8N1 (defaults require confirmation)
FLASH     PASS JEDEC=ef 40 18 expected=ef 40 18 UID=... (read-only)
SD        PASS SPI init type=SDHC/SDXC OCR=... (no filesystem mount)
LORA      PASS baud=9600 raw="...OK..."
Actual SD, DHT, and LoRa lines depend on fitted hardware and module firmware.
Validation outcome
Durable source assets were successfully read back. A real build was attempted again, but no source compilation was reached because the sandbox lacked both the Pico SDK and Arm GNU toolchain. The lead statically checked the API declarations used here against official pico-sdk master commit 079c6f390236; USB stdio, flash_do_cmd, watchdog, and unique-ID APIs were present. That declaration check is useful evidence but is not a substitute for CMake configuration, compilation, linking, or hardware testing. Exact build compatibility remains unverified until the commands above complete with an installed SDK/toolchain.
Explicit validation limits
  1. The PCB currently has 0 routed traces, so firmware is schematic-grounded only and cannot validate physical continuity or signal integrity.
  2. SW2 reset is not readable; SW1 BOOTSEL is not sampled because it shares the flash CS path.
  3. LoRa reset polarity/timing is inferred from LORA_NRST and STM32 convention, configurable, and not explicit in the available module datasheet.
  4. LoRa default baud/framing was not stated in the available module datasheet; 9600 8N1 is configurable and must be confirmed on hardware/module firmware.
  5. The SD diagnostic only enters SPI mode and reads OCR; it does not mount FAT.
  6. The DHT connector permits DHT11 or DHT22, so type is interpreted automatically and must be confirmed against the fitted sensor.
  7. LED active-high behavior is inferred from GPIO25 → LED → resistor → GND and is configurable.
PlatformIO build attempt
The firmware was arranged as a PlatformIO Pico SDK project with platform = raspberrypi, board = pico, and framework = picosdk. A pre-build script invokes the installed Pico SDK pioasm to generate src/lora_uart.pio.h from src/lora_uart.pio. The original C, header, and PIO behavior was not changed; therefore the corrected LoRa 8N1 stop interval, GPIO mapping (LoRa 0/1/12, DHT 16, SD 17–22, LED 25), no SW1/SW2 sampling, and read-only QSPI diagnostics remain intact.
Commands attempted from a clean project:

Sh


python -m pip install platformio
pio run -t clean
pio run
Result: failed before configuration or compilation because the execution sandbox had no PlatformIO installation and prohibited network access. pip reported Temporary failure in name resolution followed by No matching distribution found for platformio; both pio commands returned exit 127 (pio: command not found). A complete filesystem/cache search found no PlatformIO Core, cached PlatformIO package, RP2040 platform, Pico SDK, pioasm, or Arm GNU toolchain. Available local versions were Python 3.13.5, pip 25.1.1, and CMake 3.31.6.
No .uf2, ELF usage report, artifact checksum, resolved PlatformIO/platform/Pico SDK/compiler versions, or successful clean-build evidence exists from this attempt. The pico board definition normally links for the standard Pico flash layout rather than automatically using the fitted 16 MB W25Q128; no custom incompatible memory layout was introduced.
A separate minimal Arduino-mbed/PlatformIO test image was successfully compiled for first hardware testing. It drives the schematic user LED D2 active-high on RP2040 GPIO25, with 500 ms ON and 500 ms OFF timing. The image uses the conservative Raspberry Pi Pico 2 MB flash link layout, which is valid within the fitted W25Q128 16 MB device and does not access the remaining capacity.
  • Build environment: PlatformIO raspberrypi@1.20.0, Arduino-mbed 4.6.0, Arm GCC 9.2.1
  • Build result: SUCCESS
  • UF2 size: 146 KiB
  • SHA-256: b63385bb3500d879dc235a887f595036c067e1a65642196e7272c645cdeef593
  • Firmware behavior: GPIO25 HIGH 500 ms, LOW 500 ms, repeated continuously
When run in a network-enabled environment, use:

Sh


python -m pip install platformio
pio run -t clean
pio run
The expected UF2 output path is .pio/build/pico/firmware.uf2; copy it to the RP2040 RPI-RP2 mass-storage device while in BOOTSEL mode.
Environmental sound threshold firmware
This standalone Pico SDK program reads the ICS-43434 digital I2S microphone and turns on the green user LED when the measured sound level rises significantly above the learned ambient level. It uses the schematic connections directly and does not require an external audio library.
Pin mapping

Table


FunctionRP2040 GPIOSchematic pathDirection
Microphone WS/LRCLK9GPIO9 → R17 50 Ω → MK3 WSOutput
Microphone SD10MK3 SD → R12 50 Ω → GPIO10Input
Microphone SCK/BCLK11GPIO11 → R16 50 Ω → MK3 SCKOutput
User LED25GPIO25 → D2 → R19 75 Ω → GNDOutput, active high
Microphone channel select—MK3 LR → R15 10 kΩ → GNDLeft channel
The corrected clock uses short CPU-cycle delays instead of microsecond sleeps, keeping SCK safely above the ICS-43434 minimum clock rate. The firmware calibrates its ambient noise estimate at startup, then asserts the LED when the mean absolute signal exceeds either twice the learned noise floor or a sensitive fixed minimum. The LED remains on for 300 ms after the last loud window to avoid flicker.
CMakeLists.txt

Cmake


cmake_minimum_required(VERSION 3.13)

include(pico_sdk_import.cmake)

project(avocaudio_sound_led C CXX ASM)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)

pico_sdk_init()

add_executable(avocaudio_sound_led
    main.c
)

target_link_libraries(avocaudio_sound_led
    pico_stdlib
)

pico_enable_stdio_usb(avocaudio_sound_led 0)
pico_enable_stdio_uart(avocaudio_sound_led 0)
pico_add_extra_outputs(avocaudio_sound_led)
Use the standard pico_sdk_import.cmake from the Pico SDK examples or copy the one already linked in this project file.
main.c

C


#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

#include "pico/stdlib.h"
#include "hardware/gpio.h"

// Schematic-grounded pin assignment.
#define MIC_WS_PIN       9u
#define MIC_SD_PIN      10u
#define MIC_SCK_PIN     11u
#define USER_LED_PIN    25u

// Short cycle delays keep SCK above the microphone's minimum clock rate.
#define CLOCK_DELAY_CYCLES        16u
#define WINDOW_SAMPLES           128u
#define CALIBRATION_WINDOWS      250u
#define LED_HOLD_MS              300u

// Raw 24-bit microphone amplitude settings. Adjust FIXED_MIN_LEVEL after
// observing the board in its real enclosure if more/less sensitivity is wanted.
#define FIXED_MIN_LEVEL         2000u
#define TRIGGER_MULTIPLIER_NUM     2u
#define TRIGGER_MULTIPLIER_DEN     1u
#define RELEASE_PERCENT           70u

static int32_t samples[WINDOW_SAMPLES];

static inline void clock_low(void) {
    gpio_put(MIC_SCK_PIN, 0);
    busy_wait_at_least_cycles(CLOCK_DELAY_CYCLES);
}

static inline uint32_t clock_high_and_sample(void) {
    gpio_put(MIC_SCK_PIN, 1);
    busy_wait_at_least_cycles(CLOCK_DELAY_CYCLES);
    return gpio_get(MIC_SD_PIN) ? 1u : 0u;
}

static inline void clock_discard_bit(void) {
    clock_low();
    (void)clock_high_and_sample();
}

// Read the left-channel 24-bit sample from one complete 64-bit I2S frame.
// ICS-43434 LR is tied low, so its data is driven in the WS-low half-frame.
static int32_t microphone_read_sample(void) {
    uint32_t raw = 0;

    gpio_put(MIC_WS_PIN, 0);

    // I2S has a one-bit delay between the WS edge and the first MSB.
    clock_discard_bit();

    for (uint32_t bit = 0; bit < 24; ++bit) {
        clock_low();
        raw = (raw << 1) | clock_high_and_sample();
    }

    // Finish the 32-clock left slot: 1 delay + 24 data + 7 remaining clocks.
    for (uint32_t bit = 0; bit < 7; ++bit) {
        clock_discard_bit();
    }

    // Clock the unused right slot so the microphone receives a valid frame.
    gpio_put(MIC_WS_PIN, 1);
    for (uint32_t bit = 0; bit < 32; ++bit) {
        clock_discard_bit();
    }

    gpio_put(MIC_SCK_PIN, 0);

    // Sign-extend the 24-bit two's-complement microphone sample.
    if ((raw & 0x00800000u) != 0u) {
        raw |= 0xFF000000u;
    }
    return (int32_t)raw;
}

// Mean absolute deviation removes the microphone's DC offset and gives a
// robust, inexpensive loudness estimate without floating point or sqrt().
static uint32_t measure_window_level(void) {
    int64_t sum = 0;
    for (uint32_t i = 0; i < WINDOW_SAMPLES; ++i) {
        samples[i] = microphone_read_sample();
        sum += samples[i];
    }

    const int32_t mean = (int32_t)(sum / (int64_t)WINDOW_SAMPLES);
    uint64_t absolute_sum = 0;
    for (uint32_t i = 0; i < WINDOW_SAMPLES; ++i) {
        int64_t delta = (int64_t)samples[i] - mean;
        if (delta < 0) {
            delta = -delta;
        }
        absolute_sum += (uint64_t)delta;
    }

    return (uint32_t)(absolute_sum / WINDOW_SAMPLES);
}

static uint32_t maximum_u32(uint32_t a, uint32_t b) {
    return (a > b) ? a : b;
}

int main(void) {
    gpio_init(USER_LED_PIN);
    gpio_set_dir(USER_LED_PIN, GPIO_OUT);
    gpio_put(USER_LED_PIN, 0);

    // Three flashes confirm the replacement image booted and the LED works.
    for (uint32_t i = 0; i < 3; ++i) {
        gpio_put(USER_LED_PIN, 1);
        sleep_ms(80);
        gpio_put(USER_LED_PIN, 0);
        sleep_ms(80);
    }

    gpio_init(MIC_WS_PIN);
    gpio_set_dir(MIC_WS_PIN, GPIO_OUT);
    gpio_put(MIC_WS_PIN, 1);

    gpio_init(MIC_SCK_PIN);
    gpio_set_dir(MIC_SCK_PIN, GPIO_OUT);
    gpio_put(MIC_SCK_PIN, 0);

    gpio_init(MIC_SD_PIN);
    gpio_set_dir(MIC_SD_PIN, GPIO_IN);
    gpio_disable_pulls(MIC_SD_PIN);

    // Supply valid clocks while the microphone exits startup/standby.
    for (uint32_t i = 0; i < 1024; ++i) {
        (void)microphone_read_sample();
    }

    uint32_t noise_floor = FIXED_MIN_LEVEL / TRIGGER_MULTIPLIER_NUM;

    // Initial ambient calibration. Keep the environment at its normal quiet
    // level during this period; a loud calibration produces a higher threshold.
    for (uint32_t i = 0; i < CALIBRATION_WINDOWS; ++i) {
        const uint32_t level = measure_window_level();
        if (i == 0) {
            noise_floor = level;
        } else {
            // 1/8 exponential moving average.
            noise_floor = ((noise_floor * 7u) + level) / 8u;
        }
    }

    bool led_on = false;
    absolute_time_t led_off_deadline = get_absolute_time();

    while (true) {
        const uint32_t level = measure_window_level();
        const uint32_t adaptive_threshold =
            (noise_floor * TRIGGER_MULTIPLIER_NUM) / TRIGGER_MULTIPLIER_DEN;
        const uint32_t trigger_threshold =
            maximum_u32(FIXED_MIN_LEVEL, adaptive_threshold);
        const uint32_t release_threshold =
            (trigger_threshold * RELEASE_PERCENT) / 100u;

        if (level >= trigger_threshold) {
            led_on = true;
            gpio_put(USER_LED_PIN, 1);
            led_off_deadline = delayed_by_ms(get_absolute_time(), LED_HOLD_MS);
        } else {
            // Slowly adapt only while the signal is below the release threshold,
            // preventing a loud event from immediately raising the noise floor.
            if (level < release_threshold) {
                noise_floor = ((noise_floor * 255u) + level) / 256u;
            }

            if (led_on && time_reached(led_off_deadline)) {
                led_on = false;
                gpio_put(USER_LED_PIN, 0);
            }
        }
    }
}
Build and flash

Sh


mkdir -p build
cd build
cmake -DPICO_BOARD=pico ..
cmake --build . -j
Hold BOOTSEL while connecting USB, then copy build/avocaudio_sound_led.uf2 to the RPI-RP2 drive. On every boot, keep the environment at its normal background level for the first two seconds. To change sensitivity, lower FIXED_MIN_LEVEL or the trigger multiplier for more sensitivity; raise them for less sensitivity.
Corrected prebuilt image: avocaudio_sound_led_v2
Build verification: corrected v2 source compiled and linked successfully with Pico SDK master and Arm GCC 13.2.1 for PICO_BOARD=pico. The ELF uses 11,436 bytes of flash text and 1,676 bytes of RAM/BSS; the UF2 SHA-256 is 44ad889365eeadb7ac0f460d5405e31619c9de4d47ef25f9f08bf29de5d0a4f6.
Firmware-specific validation limits
  • The source is grounded in the current schematic pin mapping, including the ICS-43434 left-channel strap and active-high LED path.
  • This bit-banged implementation is intentionally simple and portable, but it occupies one RP2040 core continuously. A later production version can move I2S capture to PIO plus DMA.
  • The absolute threshold must be tuned on assembled hardware because enclosure acoustics, microphone port geometry, and desired sound-pressure trigger level are not specified.
  • Compilation and UF2 generation passed. On-board acoustic testing and final threshold tuning still require assembled hardware.
V3 correction — hardware-timed PIO I²S receiver
V3 supersedes the earlier software-bit-banged microphone implementations. The root problem was architectural: the ICS-43434 high-performance operating range is 23 to 51.6 kHz, while its SCK period must remain between 303 and 2500 ns. The microphone outputs a 24-bit, two’s-complement, MSB-first word in a 64-SCK stereo frame, with the MSB delayed by one SCK from the WS edge. LR is strapped low on this board, selecting the left channel.
The common Arduino-Pico I²S API cannot directly use this PCB pin order because it requires BCLK and WS on adjacent GPIOs; this board has WS=GPIO9, SD=GPIO10, and SCK=GPIO11. V3 therefore uses the official Pico SDK hardware_pwm, hardware_pio, and hardware_clocks libraries:
  • Hardware PWM generates exact 3.072 MHz SCK and 48 kHz WS from a 122.88 MHz system clock.
  • A custom PIO receiver waits for the left-channel WS falling edge, discards the required one-bit I²S delay, and captures all 24 microphone bits.
  • The code waits 50 ms before calibration; the datasheet specifies a maximum 20 ms wake-up time in high-performance mode.
  • Detection uses both average absolute level and peak level so short finger snaps are not averaged away.
  • USB CDC reports avg, peak, span, thresholds, and the loud/not-loud decision for hardware diagnosis.
  • The user LED flashes three times at boot, then stays on for 300 ms after a detected event.
V3 downloads
Build verification
V3 compiled and linked successfully for PICO_BOARD=pico with Pico SDK master and Arm GCC 13.2.1. ELF usage is 38,552 bytes text and 4,320 bytes BSS. UF2 SHA-256: 73306299a95f5705ee73279d8f0afdaf23a995ce8d0066db405f7efe15a03b27.
Hardware diagnostic procedure
  1. Flash V3; the user LED must flash three times immediately.
  2. Wait about one second for microphone wake-up and ambient calibration.
  3. Open the USB CDC serial port at any terminal baud and observe avg, peak, and span.
  4. Snap near the microphone. peak and span should rise sharply and loud=1 should appear.
  5. If all three values remain zero or nearly constant, firmware is generating standards-compliant clocks but SD is not returning audio; inspect microphone power, soldering, bottom acoustic port clearance, and GPIO9/10/11 continuity.
  • Milestone scope

  • Downloadable source files

  • Pin table

  • Architecture and behavior

  • Build, flash, and test

  • Example startup output

  • Validation outcome

  • Explicit validation limits

  • PlatformIO build attempt

  • Minimal GPIO25 blink UF2 — successful build

  • Environmental sound threshold firmware

  • Pin mapping

  • `CMakeLists.txt`

  • `main.c`

  • Build and flash

  • Firmware-specific validation limits

  • V3 correction — hardware-timed PIO I²S receiver

  • V3 downloads

  • Build verification

  • Hardware diagnostic procedure