STM32 I2S Audio Codec (TLV320AIC3204): Audio DSP / Synth

In this tutorial, we’ll discuss how to use an STM32 I2S audio codec: the TLV320AIC3204 stereo codec from Texas Instruments, connected to an STM32H735 on my DeepSynth audio DSP board. You’ll learn how an audio codec talks to the STM32 over I2C (control) and I2S (audio samples), how to clock it, how to stream audio with DMA double buffering, and how to play, record, and process audio in real time.

Then, we’ll introduce our own TLV320AIC3204 driver (plain C, STM32 HAL), how it’s designed, and how we tested it on real hardware: codec bring-up over I2C, playback, recording, full-duplex processing with an FFT self-test, real-time effects with CMSIS-DSP, and a USB Audio Class headset, with the measured audio performance of each path. Without further ado, let’s get right into it!

How to Use an I2S Audio Codec With STM32 (HAL)

To use an audio codec with an STM32, you need three links: an I2C bus to configure the codec’s registers, an I2S (or SAI) interface to stream the audio samples, and a master clock (MCLK) that is a fixed multiple of the sample rate (usually 256 × fs). Start the I2S stream first (so MCLK runs), then configure the codec over I2C, then process the audio in the DMA half and complete callbacks.

STM32H735 PinPeripheralTLV320AIC3204 PinPurpose
PC7I2S3_MCKMCLKMaster clock, 256 × fs = 12.288MHz at 48kHz
PC10I2S3_CKBCLKBit clock, 32 × fs = 1.536MHz (16-bit stereo)
PA15I2S3_WSWCLKWord clock (left/right), = fs
PC12I2S3_SDODINPlayback samples (STM32 → codec DAC)
PC11I2S3_SDIDOUTRecorded samples (codec ADC → STM32)
PA8 / PC9I2C3_SCL / I2C3_SDASCL / SDACodec registers, 7-bit address 0x18
PD0GPIO outputRESETActive-low hardware reset
  1. Configure I2S as a full-duplex master with MCLK output, Philips standard, at your sample rate, and an I2C bus in fast mode (400kHz).
  2. Start the I2S stream with circular DMA, so MCLK, BCLK and WCLK are running.
  3. Reset the codec, then configure its clocks (PLL and dividers), power, routing and volume over I2C.
  4. Fill and read the audio buffers in the DMA half-complete and complete callbacks, one half at a time.

The rest of this tutorial explains how each part works, the CubeMX configuration, my TLV320AIC3204 driver, and how it performed in every test on a real custom hardware PCB design.

Note: The driver and every test in this tutorial are tested with DeepSynth v1.0 (an STM32H7-based Audio DSP/Synthesis Custom Hardware Design).


What is an Audio Codec?

An audio codec is a chip that holds a stereo ADC (to record), a stereo DAC (to play), and the analog circuitry around them: microphone preamps, input selectors, headphone and line drivers, and a digital processing engine. The MCU only exchanges digital samples with it over I2S. Compared to the STM32’s own 12-bit DAC and ADC, a codec gives you 16 to 32-bit audio, around 100dB of signal-to-noise ratio, real headphone drivers, and microphone inputs, all on one chip.

OptionWhat It Gives YouTypical Use
STM32 internal DAC / ADC12-bit, no audio filters, needs external amplifiersBeeps, simple tones, voice-grade audio
I2S DAC or I2S amplifier (e.g. PCM5102, MAX98357)Playback only, no configurationSpeakers and line out
I2S microphone (e.g. INMP441)Record only, one micVoice capture
Audio codec (e.g. TLV320AIC3204)Stereo ADC + DAC, mic preamps, HP and line drivers, configurable over I2CFull-duplex audio, effects, recorders, USB audio

TLV320AIC3204 Features

The TLV320AIC3204 is a low-power stereo codec in a 5×5mm QFN-32 package. These are the figures from its datasheet that matter for STM32 projects:

FeatureTLV320AIC3204
Stereo DAC100dB SNR, THD+N -83dB typical (line out)
Stereo ADC93dB SNR, THD+N -85dB typical
Sample rates8kHz to 96kHz in our driver (8, 11.025, 16, 22.05, 32, 44.1, 48, 88.2, 96kHz)
Analog inputs6 single-ended or 3 fully differential (IN1, IN2, IN3)
Mic preamp (MicPGA)0 to 47.5dB in 0.5dB steps, programmable MICBIAS
Digital microphonePDM input on the multifunction pins (MFP)
OutputsStereo headphone (HPL/HPR) and stereo line (LOL/LOR), -6 to +29dB driver gain
ClockingIntegrated PLL: runs from almost any MCLK
ProcessingSelectable filter blocks, AGC, DRC, beep generator
ControlI2C (address 0x18) or SPI, selected by the SPI_SELECT pin
SupplyAVDD and DVDD from internal LDOs (fed from LDOIN), IOVDD 1.1v to 3.6v
TLV320AIC3204 block diagram and internal architecture: stereo ADC, DAC, MicPGA, headphone and line drivers, PLL
Highlighted interfaces are the actively used ones by the DeepSynth hardware (almost all of them)

Note: The TLV320AIC3204 has no chip ID register. To detect it, read a few registers right after a reset and compare them to their documented default values. Our driver does this with 18 registers (see Test 1).


STM32 I2S Audio Interface Explained

I2S (Inter-IC Sound) is a 3-wire serial bus for audio samples: BCLK clocks every bit, WCLK (also called LRCLK or WS) selects the left or the right channel, and a data line carries the samples, MSB first. A full-duplex link has two data lines: DIN for playback and DOUT for recording. Most codecs also need MCLK, a fast clock that runs their internal converters and PLL.

STM32 I2S timing diagram: MCLK, BCLK, WCLK, DIN and DOUT for a 16-bit stereo Philips I2S frame at 48kHz

In the Philips I2S standard, WCLK is low for the left sample and high for the right sample, and the MSB of each sample starts one BCLK after the WCLK edge. With 16-bit samples in a 16-bit frame, one stereo frame is 32 bits, so the clocks at a 48kHz sample rate are:

ClockFormulaAt fs = 48kHzAt fs = 44.1kHz
WCLKfs48kHz44.1kHz
BCLK2 channels × 16 bits × fs1.536MHz1.4112MHz
MCLK256 × fs12.288MHz11.2896MHz

STM32 I2S vs SAI

STM32 microcontrollers have two audio peripherals. The I2S is a mode of the SPI peripheral (SPI1/2/3 on the H7): it supports the I2S, MSB, LSB and PCM formats, full duplex, and an MCLK output. The SAI (Serial Audio Interface) is a dedicated audio block with two sub-blocks, TDM with up to 16 slots, and a PDM interface for digital microphones. For one stereo codec, both work. The DeepSynth board uses I2S3 for the codec, and SAI1 in PDM mode for the second MEMS microphone.


TLV320AIC3204 STM32 Hardware Connections

For this tutorial, I’m using my DeepSynth v1.0 board: an STM32H735IGT6 (Cortex-M7 at 550MHz) with a TLV320AIC3204 codec, a 0.96″ display, four audio jacks, analog and digital microphones, a microSD card slot, and USB. The board’s hardware design is explained in detail in the STM32 DSP Audio Processing & Synth PCB article.

STM32 audio codec interface diagram: STM32H735 connected to the TLV320AIC3204 over I2C, I2S and MCLK, with line in, microphones, headset and line out

TLV320AIC3204 audio codec schematic diagram on the DeepSynth STM32 board

The codec’s analog side is routed to the board’s jacks and microphones as follows:

Codec PinsConnected ToNotes
IN1_L / IN1_RLINE IN jack (J6)AC-coupled, 20kΩ input resistance in our examples
IN2_L / IN2_RElectret microphone (MK2)Differential, biased from MICBIAS
IN3_RHeadset microphone (J8 ring)MICBIAS 2.5v, also used for headset detection (MFP3)
MFP4 / MFP5PDM MEMS microphone (IC6)Codec supplies the PDM clock and reads the data
HPL / HPRHEADSET jack (J8)Headphone drivers
LOL / LORLINE OUT jack (J7)LOR also feeds the LM4871 speaker amplifier when DIP switch SW3 selects it
SPI_SELECTGNDI2C control mode
LDO_SELECT3.3vInternal LDOs supply AVDD and DVDD

If you’re building your own board or module, the codec needs the same five I2S/MCLK lines, the two I2C lines with 2.2 to 4.7kΩ pull-ups, and a reset line (or a pull-up on RESET). Here is the full DeepSynth pinout for reference:

DeepSynth v1.0 STM32H735 board pinout diagram with the TLV320AIC3204 codec, IO headers and on-board peripherals


STM32 I2S Clock Configuration For Audio (48kHz & 44.1kHz)

The STM32 is the I2S master in all our tests: it generates MCLK, BCLK and WCLK, and the codec follows. The I2S kernel clock must divide down to exactly 256 × fs, otherwise the sample rate is off. On the STM32H735, I use PLL3 (fractional) as the I2S3 kernel clock, with one setting per sample-rate family, from the 25MHz crystal:

Sample-Rate FamilyPLL3 (M, N, FRACN, P)PLL3P (I2S3 Kernel Clock)Exact Rates
48kHz5, 98, 2490, 1049.152MHz8, 16, 32, 48, 96kHz
44.1kHz5, 90, 2596, 1045.1584MHz11.025, 22.05, 44.1, 88.2kHz

Inside the codec, its own PLL multiplies MCLK up to about 86 to 106MHz, and dividers (NDAC, MDAC, DOSR for the DAC; NADC, MADC, AOSR for the ADC) produce the converter clocks. The driver’s clock solver computes all of them for any MCLK and sample rate, and checks every datasheet limit. These are the values it uses with MCLK = 256 × fs:

fsPLL P, R, J.DCODEC_CLKINNDAC, MDAC, DOSRNADC, MADC, AOSR
8kHz1, 1, 52106.496MHz2, 8, 8322, 52, 128
16kHz1, 1, 2186.016MHz2, 7, 3842, 21, 128
44.1kHz1, 1, 890.3168MHz2, 8, 1282, 8, 128
48kHz1, 1, 786.016MHz2, 7, 1282, 7, 128
96kHz2, 1, 786.016MHz2, 7, 642, 7, 64

The 44.1kHz result matches TI’s own configuration script in SLAA404C. For the details of the STM32 clock tree, check the STM32 RCC clock configuration guide.

Note: Start the I2S stream (MCLK) before configuring the codec. The codec’s PLL, its power-up status flags, and its power-down sequence all need MCLK running. Without it, the init stalls or the codec stays silent.


STM32 I2S DMA Double Buffering

Audio is a continuous stream, so it’s moved by DMA in circular mode. One call to HAL_I2SEx_TransmitReceive_DMA() starts both directions with two buffers (TX and RX) of the same size. The DMA raises an interrupt when it reaches the middle (half complete) and the end (complete) of the buffers, and wraps around. While the DMA streams one half, the CPU processes the other half.

STM32 I2S DMA double buffering: circular RX and TX buffers with half complete and complete callbacks

The CPU has exactly one half-buffer time to finish its work. With 1024 frames per half at 48kHz, that is 21.3ms; with 256 frames, 5.33ms. A bigger buffer gives the CPU more time but adds latency. For the basics of DMA on STM32, see the STM32 DMA tutorial.

STM32H7 D-Cache and DMA Buffers

On the STM32H7, the D-cache sits between the CPU and the RAM, while the DMA reads and writes the RAM directly. If an audio buffer is cacheable, the CPU and the DMA see different data, and you hear old samples or noise. The simplest robust solution, which all our test projects use: put the audio buffers in SRAM1 (0x30000000) and make that region non-cacheable with the MPU. Then no cache clean or invalidate calls are needed anywhere.

In practice, that’s two small changes: a section in the linker script that places a named section (for example .audio_dma) in RAM_D2 (SRAM1), and an MPU region over that 32KB of SRAM1 set as normal, non-cacheable, shareable memory (TEX = 1, C = 0, B = 0), configured before the caches are enabled. The audio buffers are then declared with that section attribute. Also note that the DTCM RAM (0x20000000) is not reachable by DMA1/DMA2 at all, so audio buffers must never be placed there.


STM32 I2S Codec CubeMX Configuration

These are the STM32CubeMX settings used by every test project in this tutorial (STM32H735IGT6 on the DeepSynth board):

CubeMX SettingValueWhy
SYS › DebugSerial WireFrees PA15 (JTDI) for I2S3_WS
RCC › HSECrystal/Ceramic Resonator (25MHz)Accurate audio clocks
PWR › Power Supply SourcePWR_LDO_SUPPLYThe DeepSynth runs the H735 from its LDO (see the note below)
I2S3 › ModeFull-Duplex Master, Master Clock Output enabledSTM32 drives MCLK, BCLK and WCLK
I2S3 › Communication StandardI2S PhilipsMatches the codec’s default I2S format
I2S3 › Data and Frame Format16 Bits Data on 16 Bits FrameBCLK = 32 × fs
I2S3 › Selected Audio Frequency48kHzReal frequency 47.999kHz with PLL3P = 49.152MHz
I2S3 › Master Keep IO StateEnabledClocks stay defined between transfers
Clock Configuration › SPI1,2,3 Clock MuxPLL3P (49.152MHz)Exact 256 × fs MCLK
DMA1 › SPI3_RX / SPI3_TXStream 0 / Stream 1, Circular, Half WordContinuous full-duplex stream
I2C3 (PA8 / PC9)Fast Mode 400kHzCodec control
PD0GPIO Output, initial level HighCodec RESET (active low)
Cortex-M7ICache and DCache enabled, MPU region for SRAM1 (code above)Speed without cache problems on the DMA buffers

STM32 TLV320AIC3204 Driver (HAL)

For this tutorial, I’ve made a custom STM32 TLV320AIC3204 driver (library): one .c and one .h file, built on top of the STM32 HAL directly. Every option is set in the header or in the configuration structure; there’s no dynamic memory, and several codecs can run with one handle each. It works on any STM32 with an I2C bus and an I2S or SAI interface; only the HAL include at the top of the header changes between families.

Driver Features

  • Bring-up: hardware and software reset, identity check (reset-default signature), internal LDO or external supply power-up, de-init, standby.
  • Clocks: a divider and PLL solver for any MCLK and any rate from 8 to 96kHz, and sample-rate change at runtime without a reset.
  • Playback: DAC volume -63.5 to +24dB (0.5dB steps, soft-stepped inside the codec), soft mute, headphone and line outputs with a pop-free switching order, driver gains -6 to +29dB, the built-in beep generator.
  • Record: every analog input with 10k/20k/40kΩ input resistance, MicPGA 0 to 47.5dB, ADC volume -12 to +20dB, MICBIAS, AGC, PDM digital microphone.
  • Loopbacks and detection: digital, interface and analog loopback, headset detection.
  • Error codes on every call: TLV320_ERR_NACK (codec absent), TLV320_ERR_TIMEOUT (bus stuck), TLV320_ERR_PARAM, TLV320_ERR_CLOCK, TLV320_ERR_ID, and more.

Adding The Driver To A CubeIDE Project

  1. Copy the TLV320AIC3204 folder into your project, for example, to Drivers/TLV320AIC3204.
  2. In Project › Properties › C/C++ General › Paths and Symbols, add the folder to the Includes and to the Source Location.
  3. If your MCU isn’t an STM32H7, change the HAL include at the top of TLV320AIC3204.h (for example stm32f4xx_hal.h).
  4. In CubeMX, enable an I2C in fast mode, an I2S in master mode with MCLK output, and a GPIO output for RESET (initial level high).
  5. Start the I2S stream, then call TLV320_Init().

Driver Configuration Options

TLV320_Config FieldDefaultAllowed Values
hi2cnone (required)any I2C_HandleTypeDef*
i2c_addr0x187-bit address (the part only answers 0x18)
reset_portreset_pinNULL, 0 (software reset only), or the RESET GPIO
mclk_hz00 = 256 × sample_rate, or the real MCLK in Hz
sample_rate480008000 to 96000
word_lengthTLV320_WORD_1616, 20, 24 or 32 bits (must match the I2S frame)
formatTLV320_FMT_I2SI2S, DSP, right-justified, left-justified
roleTLV320_ROLE_SLAVESlave (MCU drives the clocks) or master
pllTLV320_PLL_AUTOAuto (only if needed), always, never
supplyTLV320_SUPPLY_LDOInternal LDO (LDO_SELECT high) or external
output_swingTLV320_SWING_NORMALNormal (0.5Vrms full scale) or high (about 1Vrms)
dmic01 = keep the ADC clock in the PDM microphone window

Driver API Functions

FunctionWhat It Does
TLV320_Init(h, cfg)Reset, identity check, clocks, supplies, DACs on (muted); outputs and ADCs off
TLV320_DeInit(h)Orderly power-down and reset
TLV320_CheckSignature(h, &n)Compares 18 reset defaults (the chip has no ID register)
TLV320_SetSampleRate(h, fs, mclk)New sample rate without a reset
TLV320_SetOutputs(h, outs)Headphone and/or line out, pop-free order
TLV320_SetDacVolume(h, l_db, r_db)-63.5 to +24dB
TLV320_SetDacMute(h, m)Soft mute
TLV320_SetOutputGain(h, outs, db)Analog driver gain -6 to +29dB
TLV320_SetInput(h, ch, in, res)Selects IN1/IN2/IN3 and powers the ADC
TLV320_SetPgaGain(h, ch, db)MicPGA 0 to 47.5dB
TLV320_SetAdcVolume(h, ch, db)-12 to +20dB
TLV320_SetMicBias(h, bias)Off, 1.25, 1.7, 2.5v or LDOIN
TLV320_SetAgc(h, ch, &agc)Automatic gain control on/off
TLV320_SetDigitalMic(h, ch)PDM microphone on MFP4/MFP5
TLV320_SetLoopback(h, mode, db)Digital, interface or analog loopback
TLV320_Beep(h, hz, ms, atten)Built-in sine generator
TLV320_ReadReg / WriteReg / UpdateBitsPage-cached register access

Driver Design Decisions

  • The STM32 masters the clocks. The STM32 generates MCLK = 256 × fs, BCLK and WCLK, and the codec is the I2S slave running its PLL from MCLK. This keeps the audio clock under the MCU’s control, which the USB audio test needs (its clock is trimmed to follow the PC). Codec-master mode is still supported for other boards.
  • A clock solver instead of a fixed table. For any MCLK and sample rate, the driver searches for PLL and divider values in a fixed preference order (no PLL, then integer PLL, then fractional PLL; the largest valid oversampling ratio first) and checks every limit from TI’s application reference guide. It has no I2C access, so it can also be called on its own.
  • No blind delays. Init follows TI’s documented order: reset, clocks and PLL, audio interface, processing blocks, supplies, ADC, DAC. Converter and headphone power-up and power-down poll the codec’s status flags with a timeout; only the 1ms reset lockout and the 10ms PLL lock (which has no flag) are fixed waits.
  • Pop-free volume and routing. The DAC volume is soft-stepped inside the codec, and routing changes follow the order soft mute, change, slow headphone ramp, unmute.
  • Runtime sample-rate change. Standby while the old MCLK runs, new MCLK, new dividers, power back up. No reset, and the routing and gain settings are kept.
  • Identity by signature. 18 reset-default registers are compared right after reset, because the chip has no ID register.

Two documentation-related bugs turned up while writing/testing the driver: TI’s headset-detection description names the wrong bit for the enable (page 0, register 67: the enable is D7, not D1), and the input power-up value for 3.1ms in SLAA404C is 0x31, not 0x32. The driver uses the correct values.

The driver files are available in the download box at the end of this tutorial.


Testing The TLV320AIC3204 Driver On The DeepSynth Board

I tested the driver on the DeepSynth v1.0 board in seven test groups, from the I2C control interface up to a USB Audio Class headset. Each test group is a separate CubeIDE project that prints a [PASS] or [FAIL] line for every check on the console (UART9 through the board’s USB-UART connector, 115200 baud). The audio paths were measured with a Focusrite Solo audio interface and REW. This section explains what each test does, how it was done, and what the result was.

Test GroupWhat It VerifiesResult
1. I2C controlIdentity, registers, init/deinit loop, error paths20 of 20 checks passed
2. PlaybackSine, channel identity, sweep, WAV, rate switching, volume, routingAll passed; 8 to 96kHz without a reset
3. RecordFour inputs, gain steps, MICBIAS, AGC, WAV recording, noise floorAll passed; LINE IN dynamic range 92.1dB
4. Full duplexPassthrough, latency, loopbacks, FFT self-testTHD -83.4dB in loopback, 0.875ms analog round trip
5. WAV playerPlayback from SD with buttons, wheel and displayPassed
6. Audio effectsEcho and 4th-order low-pass (CMSIS-DSP) in real time-6.0dB at the 1.5kHz cutoff, -50dB at 6kHz
7. USB Audio ClassUSB speaker + mic, clock locked to the PC5 minutes, 0 underruns, 0 overruns

Test 1: I2C Control Interface & Codec Identification

The first test proves that the STM32 controls the codec reliably before any audio is involved. The steps:

  1. Identity: the TLV320AIC3204 has no chip ID register, so the driver resets it and compares 18 registers on pages 0 and 1 with their documented reset values (PLL, oversampling, DAC/ADC mute, beep generator, driver gains, MicPGA).
  2. Register access: dump pages 0 and 1 after reset, then write test patterns to 66 registers on both pages and read them back, including page switching.
  3. Init → deinit → re-init: 100 cycles in a row, to prove that no state is left stuck after a deinit.
  4. Error paths: a wrong I2C address (0x19), the codec held in reset, a 0ms bus timeout, and out-of-range arguments (DAC volume +30dB, PGA 50dB, a 7kHz sample rate, an MCLK with no valid divider). Each must return its own error code instead of hanging.
CheckResult
Reset-default signature18 of 18 registers match
Write / read-back66 registers, 0 errors
Init / deinit loop100 of 100 cycles OK, TLV320_Init() takes 26ms
Codec absent / held in resetTLV320_ERR_NACK
Bus timeout (0ms budget)TLV320_ERR_TIMEOUT, and the bus works again afterwards
Invalid argumentsTLV320_ERR_PARAM, TLV320_ERR_CLOCK and TLV320_ERR_STATE as expected
Clocks at 48kHzMCLK 12.288MHz, PLL J = 7, CODEC_CLKIN 86.016MHz, NDAC 2 / MDAC 7 / DOSR 128

Since there’s no ID register, the identity check must run right after a reset: once the codec is configured, those registers hold other values. The driver’s init does it automatically and refuses to continue (TLV320_ERR_ID) if the part doesn’t match, so a wrong part or a broken bus is caught before anything is powered.

Test 2: Audio Playback (Sine, Channels, Sweep, WAV)

The playback test exercises the DAC path and every playback function of the driver:

  1. The codec’s built-in beep generator (no I2S data needed), then a 1kHz sine from a lookup table, refilled in the DMA callbacks.
  2. Channel identity: left only, right only, then 440Hz on the left and 880Hz on the right, to catch swapped channels.
  3. A logarithmic sweep from 20Hz to 20kHz in 10 seconds.
  4. WAV file playback from the microSD card, with the DMA half and complete callbacks refilling the buffer from the file.
  5. Sample-rate switching through 8, 16, 22.05, 32, 44.1, 48 and 96kHz while playing, without a reset.
  6. Volume steps and ramps, mute toggling, output routing (headphone, line out, both), and headset detection.

I recorded the whole sequence with a USB microphone in front of the speaker (fed from LOR, the right channel). The spectrogram shows each test in order: the beep, the 1kHz tone, the left-only test (silent, as expected on the right channel), the right-only test, 880Hz on the right channel, the sweep, the sample-rate switching, the volume steps, and the mute toggles:

STM32 I2S codec playback test spectrogram: beep, 1kHz sine, channel identity, sweep and sample-rate switching

Every sample-rate switch worked without a reset, in 79 to 133ms. A rate change takes three steps, because on the STM32 MCLK changes with the rate: put the codec in standby while the old MCLK still runs, reprogram PLL3 and the I2S divider and restart the stream, then give the codec its new dividers and power it back up. The routing, gains and AGC settings are kept.

The line output’s frequency response, measured with the Focusrite, is flat within ±0.05dB from 100Hz to 3kHz and -1.35dB at 20kHz:

TLV320AIC3204 DAC line out frequency response measured on the STM32 DeepSynth board

The DAC volume control moves the output by exactly 6.0dB per 6dB step, and the headphone driver gain from 0 to 27dB moves it by 27.4dB. The codec soft-steps every volume change by 0.5dB per sample, so there’s no zipper noise, and the driver changes outputs in a pop-free order (soft mute, change the routing, slow headphone power-up ramp, unmute). A 4-pole headset was detected 114ms after headset detection was enabled.

TLV320AIC3204 headphone output volume and driver gain steps measured on STM32

Test 3: Audio Recording (Microphones & Line In)

The record test covers all four inputs on the board: LINE IN (IN1), the electret microphone (IN2, differential), the headset microphone (IN3_R), and the PDM MEMS microphone on the codec’s digital-mic pins. For each one:

  1. Route the input to the ADC with the driver, and set the MicPGA gain and MICBIAS.
  2. Step the MicPGA from 0 to 42dB, the ADC volume from -12 to +20dB, and the MICBIAS voltages, and toggle the AGC, measuring the level at every step.
  3. Record 5 seconds to the microSD card as a WAV file (and 1 second to RAM, dumped over the UART), and inspect the files in Audacity.
  4. With the input open, record digital silence to measure the noise floor and the DC offset.

Recording to the SD card while the audio streams needs care: the DMA callback copies each half-buffer into a FIFO of slots, and the main loop writes them to the card in bursts of 12KB or more. With small writes, the card’s latency drops blocks; with large bursts, a 60-second recording lost none. Both microphones capture correctly:

TLV320AIC3204 electret microphone vs PDM MEMS microphone spectrum recorded with STM32

The MicPGA gain steps track the setting, and the ADC volume stays within 0.6dB of the ideal value over its full range:

TLV320AIC3204 MicPGA gain steps with the electret microphone on STM32

For the line input, the board ran from a power bank, the Focusrite fed a 1kHz tone at -6dBFS into LINE IN, and the board recorded 60 seconds to the SD card. The analysis of that WAV file: THD -80.6dB (0.009%), a noise floor of -93.5dBFS, and a dynamic range of 92.1dB (unweighted). The datasheet specifies 92dB A-weighted, so the ADC performs as specified on this board.

TLV320AIC3204 ADC line in spectrum: 1kHz tone recorded by STM32 to SD card, THD -80dB

Test 4: Full Duplex, Latency & FFT Self-Test

The full-duplex test runs both directions at once, with a 3.5mm cable from LINE OUT (J7) to LINE IN (J6) so the board can test itself:

  1. Passthrough: every received half-buffer is copied to the transmit half-buffer that the DMA sends next (ADC → MCU → DAC).
  2. Latency: play a single impulse and find it in the recorded samples.
  3. Loopbacks: the codec’s digital loopback (ADC to DAC inside the codec), interface loopback (DIN to DOUT, checked sample by sample), and analog bypass.
  4. FFT self-test: play a tone, record 4096 samples, and analyze them with the CMSIS-DSP real FFT to measure the frequency, level, SNR, and THD.

The test tone is 996.09Hz, not 1kHz: at 48kHz with a 4096-point FFT, 996.09Hz falls exactly on bin 85. The tone and all its harmonics then sit on exact bins and don’t leak into their neighbors, so no window function is needed and the THD reading is clean.

MeasurementResult
Frequency (left / right)996.09Hz / 996.09Hz (exact)
Level (tone played at -20dBFS)-17.45dBFS / -17.24dBFS
THD (left / right)-83.4dB (0.0067%) / -81.8dB (0.0082%)
SNR (left / right)68.9dB / 67.9dB
Interface loopback DIN → DOUT512 of 512 samples bit-exact
Analog round trip (DAC → cable → ADC)42 samples = 0.875ms
Passthrough latency (2 × 256-frame DMA buffering)11.5ms

The SNR here is the tone level (-17.5dBFS) over the noise, not the codec’s dynamic range. The 0.875ms round trip is the codec’s own filters; everything above it in the passthrough is DMA buffering, so a smaller buffer reduces the latency at the cost of more interrupts.

Test 5: WAV Player With Buttons & Display

This test combines the playback path with the board’s user interface: a WAV player for the files on the microSD card, with S1 for play/pause, S2 for the next file, and the thumb wheel for volume and mute. The 0.96″ display shows the file name, the playing time and a level meter. The point of the test is concurrency: the display is drawn by SPI4 with its own DMA stream (DMA2), the audio uses DMA1, and the playback continued without a dropout while the screen updated.

Test 6: Real-Time Audio Effects (Echo & Low-Pass Filter)

The effects test passes the line input or the microphone through two effects in the DMA callback, in floating point:

  • A 4th-order low-pass filter: two cascaded biquads (Q = 0.707) computed with the standard audio-EQ formulas and run by the CMSIS-DSP biquad function, with an adjustable cutoff.
  • An echo: a delay line whose output is fed back into the input, with adjustable delay and feedback.

A built-in self-test feeds a known sine and an impulse through the effects and measures the output. The low-pass filter measured -6.0dB at the 1.5kHz cutoff and -50dB at 6kHz, and the echo taps decayed as set (0.500, 0.225, 0.101):

STM32 CMSIS-DSP biquad low-pass filter response measured in real time

STM32 real-time audio echo effect impulse response

Test 7: USB Audio Class Headset (Speaker + Mic)

The last test turns the board into a USB Audio Class 2 headset: the PC sees a USB speaker and a USB microphone, at 44.1 or 48kHz, 16 or 24-bit, using the TinyUSB stack (ST’s USB device library only supports playback for the audio class). It’s the most demanding test, because it runs both directions continuously and has to match two clocks.

The PC sends 48 samples per 1ms USB frame, timed by the PC’s clock, while the I2S runs from the board’s crystal. The two drift apart by up to a few hundred ppm, which would empty or overflow the buffer within minutes. The solution: the speaker endpoint is declared adaptive, and every 100ms a PI controller on the buffer fill level fine-tunes PLL3’s fractional divider (about 1.24ppm per step). MCLK, BCLK and WCLK follow the PC’s clock, and the codec simply runs a tiny bit faster or slower.

STM32 USB audio class FIFO level and PLL3 clock trim following the host clock

In a 5-minute run, there were 0 underruns and 0 overruns, and the clock trim settled between +30 and +70ppm. Two details for USB on the STM32H735: the USB OTG_HS core runs with its internal full-speed PHY on PA11/PA12, and the USB regulator must be enabled with HAL_PWREx_EnableUSBReg(). Also, Windows sends the USB volume control per channel, not on the master control, so the firmware applies both.


TLV320AIC3204 Measured Audio Performance

I measured the codec on the DeepSynth board with a Focusrite Solo audio interface and REW (Room EQ Wizard), with the board running from a power bank. These are the results next to the datasheet values:

MeasurementMeasured (DeepSynth)Datasheet (Typical)
LINE OUT THD, 1kHz -1dBFS-79.2dB (0.011%), REW: -79.9dBTHD+N -83dB
LINE OUT noise (20Hz–20kHz)-88.9dB below the tone100dB SNR (A-weighted)
LINE OUT frequency response±0.05dB 100Hz–3kHz, -1.35dB at 20kHz–
LINE IN THD, 1kHz -6dBFS-80.6dB (0.009%)THD+N -85dB
LINE IN dynamic range92.1dB (unweighted)92dB (A-weighted)
LINE IN frequency response±0.05dB 100Hz–10kHz, -0.27dB at 20kHz–
Loopback THD (DAC → ADC), -20dBFS-83.4dB–
Analog round-trip latency0.875ms–
TLV320AIC3204 line out 1kHz spectrum measured on STM32: THD -80dB, noise floor -90dB

Note: The measured THD includes the audio interface’s own distortion, so the codec is at least this good.


STM32 Audio Codec Troubleshooting

The codec doesn’t respond on I2C (NACK)

Check the address first: the TLV320AIC3204 answers at 0x18 (0x30 as the 8-bit write address in HAL calls). Then check that RESET is high, that SPI_SELECT is tied low (I2C mode), and that SDA/SCL have pull-ups. An I2C scanner (see the STM32 I2C tutorial) confirms the codec is on the bus.

I2C works, but there is no sound

The usual cause is a missing MCLK: start the I2S DMA stream before configuring the codec. Then check that the DAC is unmuted, the outputs are enabled, the output drivers aren’t muted, and the volume isn’t at its minimum.

The audio plays at the wrong speed or pitch

The I2S kernel clock doesn’t divide to exactly 256 × fs. Check the “Real Audio Frequency” in CubeMX: with PLL3 at 49.152MHz it’s 47.999kHz. A 48kHz project on a 44.1kHz-family clock (or the other way round) plays about 9% off.

The I2S DMA callbacks are called, but the audio is noise or old data (STM32H7)

The buffers are in cacheable RAM or in DTCM. Put them in SRAM1/SRAM2 and make that region non-cacheable with the MPU, or clean and invalidate the D-cache around every DMA transfer.

The left and right channels are swapped

Check the I2S standard on both sides (Philips I2S, not MSB/LSB justified) and the data format (16-bit data in a 16-bit frame on both). A one-bit shift between the two sides also swaps or corrupts the channels.

Clicks and pops when starting, stopping or changing outputs

Soft-mute the DAC, wait for the ramp, then change the routing or power, and unmute last. The driver does this in this order, and uses the codec’s slow headphone power-up ramp.

Hum or a buzz in every measurement

A ground loop through USB. Power the board from a battery or an isolated supply when the audio interface is on the same PC.


FAQ

Which STM32 can drive an I2S audio codec?

Any STM32 with an I2S-capable SPI or a SAI peripheral, plus an I2C bus. For most codecs, the I2S also needs an MCLK output pin, which not every I2S instance has on every package. Check the pinout in CubeMX before you design the board.

Does the codec need MCLK for I2C?

The TLV320AIC3204 answers on I2C without MCLK, but its PLL, its power-up flags, and its power-down sequence need MCLK running. Some other codecs (such as the SGTL5000) don’t respond on I2C at all without it.

Can the STM32 do 24-bit or 96kHz audio?

Yes. The STM32 I2S supports 16, 24 and 32-bit data. Our tests ran from 8 to 96kHz with 16-bit samples, and the USB audio test also ran 24-bit.

Can I use this driver with another STM32 or another board?

Yes. Change the HAL include in the header, pass your I2C handle and reset pin in the configuration, and start your I2S with MCLK = 256 × fs. Nothing in the driver is specific to the DeepSynth.


Download STM32 TLV320AIC3204 Driver

Download all attachment files for this Article/Tutorial (project files, schematics, code, etc.) using the link below. Everything is tested and verified to work on real hardware, as you’ve seen in the demo videos & screenshots. Please consider supporting my work if it helped you.


Wrap Up

To conclude this tutorial, we’ve connected the TLV320AIC3204 audio codec to the STM32 over I2C and I2S, clocked it with PLL3 at exactly 256 × fs, and streamed audio with circular DMA and double buffering. Then we introduced our TLV320AIC3204 driver and tested it from codec bring-up to playback, recording, full-duplex processing with CMSIS-DSP, and a USB audio headset, all measured on real hardware.

The same driver and the same structure work with any STM32 that has an I2S or SAI interface. To learn more about the board itself, check the STM32 DSP Audio Processing & Synth PCB article, and for more STM32 tutorials, check the STM32 tutorials series.

I did a hardware design walkthrough as well as some hardware/firmware bring-up testing for this STM32 Audio DSP/Synth system on my YouTube channel (video’s link below), but I can make a follow-up showing the Codec part since it wasn’t included in the previous video. Just let me know if you’re interested in that.

Share This Page With Your Network!
Join Our +25,000 Newsletter Subscribers!

Stay Updated With All New Content Releases. You Also Get Occasional FREE Coupon Codes For Courses & Other Stuff!

Photo of author
Author
Embedded systems engineer with several years of experience in embedded software and hardware design. I work as an embedded SW engineer in the Automotive & e-Mobility industry. However, I still do Hardware design and SW development for DSP, Control Systems, Robotics, AI/ML, and other fields I'm passionate about.
I love reading, writing, creating projects, and teaching. A reader by day and a writer by night, it's my lifestyle. I believe that the combination of brilliant minds, bold ideas, and a complete disregard for what is possible, can and will change the world! I will be there when it happens, will you?

Leave a Comment