Three wires carry sound between two chips. Move the data one clock tick, flip a channel, or pick the wrong slot width, and one ear turns to noise. Fix each fault on a virtual logic analyzer.
Learn how a microphone, a codec and a microcontroller agree on every bit of a sound: the clocks, the frame, the first bit, and the one-bit microphone that needs a filter before it makes sense.
The receiver below starts with one setting wrong. Press the settings until both ear traces turn green. Then press Break it to meet the other two faults. After that, we build the wire piece by piece, from one sample to a working PDM microphone.
You need to know what a pin and a clock are (First Light) and how a bus carries bits (Buses on the Wire). We build the rest from zero.
Built from primary sources: the NXP I2S bus specification, UM11732 Rev. 3.0 (17 February 2022, from the Philips 1986 specification revised in 1996), the ST MP34DT01-M datasheet (DocID026514 Rev 3), and the public STM32 CMSIS and HAL source. All devices here are models, not real silicon.
Toy numbers: 6-bit samples in 8-clock slots, the same 3 to 4 ratio as real 24-bit audio in 32-bit slots. The sender is correct standard I2S: LRCK low is left, and the first data bit comes one clock after LRCK changes (UM11732 sections 3.1 and 3.2). Only the receiver can be wrong. The tone is made up.
Chapter 0
See why moving sound between two chips needs an agreement on every single bit, and watch a receiver build one number from eight clock ticks
You wire a digital microphone board to a development board. You flash the example code. Sound comes out of the speaker, but it is wrong. The voice is there, yet it is buzzy and far too quiet, and it plays in one ear only.
You check the power. You check the pins. The scope shows a clean clock. Nothing looks broken, and still the sound is. The fault is not in any wire. It is in an agreement between two chips that nobody wrote down on your board.
This lesson is about that agreement. It is short to state and easy to get wrong by one tick.
A microphone turns air pressure into a voltage. A chip then measures that voltage again and again, many thousand times each second. Each measurement is one sample: a single whole number that says how strong the sound was at that instant.
CD audio takes 44,100 samples each second. Most phones and computers use 48,000. So a second of sound is a long list of 48,000 numbers, and stereo sound is two such lists, one for each ear.
A list of numbers is easy to hold in memory. The hard part is moving it from the chip that measured it to the chip that will use it, fast and without a single mistake.
A pin is either high or low. That is one bit: a 0 or a 1. A 16-bit sample needs 16 of them. If we use only one wire for data, we must send the bits one after another. We call that serial transfer.
Serial transfer raises four questions at once. When does the receiver look at the wire? Which bit of the number comes first? Where does one number end and the next begin? And in stereo, which number belongs to which ear?
A wire cannot answer any of these by itself. So we add helper wires and agree on rules. A clock wire answers the first question: the receiver looks at the data wire exactly when the clock rises. The rest of the lesson answers the other three.
Try the first answer now. The receiver below holds a shift register: a row of one-bit cells where each clock tick pushes every bit one cell to the left and lets the new bit in on the right. After eight ticks the row holds one whole number.
The data line SD carries the number. Each time BCLK rises, the receiver copies the bit it sees on SD into its register. Press Next tick eight times and watch the register fill from the right.
A model, not silicon. The number is 8 bits, sent most significant bit first, and read as a two’s complement whole number: the top bit has weight −128, the others +64 down to +1. Real audio words are 16, 24 or 32 bits long.
Look at what the register holds half way through. After four ticks it holds only the top four bits of the number. The receiver does not know the full number yet, and it must not use it yet. That tiny fact explains most audio bugs: if the receiver starts one tick early or late, every bit lands in the wrong cell.
You may know I2C and SPI from Buses on the Wire. They send a message when the processor asks, then they go quiet. Audio never goes quiet. A new sample is due every 20.8 microseconds at 48 kHz, whether the processor is ready or not.
The bus built for this is I2S, short for Inter-IC Sound. Philips wrote the specification in 1986 and revised it in 1996. NXP now publishes it as UM11732. The spec says the bus handles audio data only, and sends control and other signals separately. It uses a 3-line serial bus: a line for two time-multiplexed data channels, a word select line and a clock line.
The other half of the lesson is the PDM microphone. It does not send samples at all. It sends one bit per clock tick, millions of times each second, and a filter in your firmware turns that stream into samples. You will build that filter in Chapter 7.
Chapter 1
Work out how fast the bit clock must run, from three choices you make about the sound
A teammate asks you for a clock that carries stereo audio at 48 kHz with 32-bit slots. You have a scope and a calculator. How fast must the bit clock run? You can answer in one line, once you know what a frame is.
The sample rate, written fs, is how many samples one channel delivers each second. At 48 kHz that is 48,000. Nothing else on the wire is allowed to drift from it: if the sender thinks 48,000 and the receiver thinks 47,900, one of them runs out of data.
The bit depth is how many bits make one sample. Phone calls use 8 or 16. Music uses 16 or 24. A higher depth lets the sound be softer or louder before the steps between numbers become audible. Chapter 4 looks at depth in detail.
The channel count is how many separate lists run side by side: one for mono, two for stereo, four or eight for a microphone array.
Take one instant in time. Measure the left ear and the right ear at that instant. Put the two numbers side by side. That bundle is a frame (some data sheets say PCM frame, from pulse code modulation, the plain name for a list of samples). The wire sends one frame every 1 / fs seconds. At 48 kHz that is every 20.83 microseconds.
Inside a frame, each channel owns a slot: a fixed block of clock ticks reserved for that channel’s number. The slot can be wider than the sample. A 24-bit sample often rides in a 32-bit slot, with the spare 8 bits sent as zeros. So there are two widths: the data width (bits that carry the sample) and the slot width (clock ticks the channel owns).
The data wire sends one bit per tick of the bit clock, called BCLK (the I2S specification calls it SCK, the serial clock). So the number of ticks in one frame is the number of slots times the slot width. Divide the frame time by that, and you have the clock period. Said the other way round:
48,000 × 2 × 32 = 3,072,000 Hz (3.072 MHz, so one bit lasts 325.5 ns)
That is your teammate’s answer: 3.072 MHz. Check it the other way. One frame lasts 20.83 µs and holds 2 × 32 = 64 ticks, so each tick lasts 20.83 / 64 = 0.3255 µs. The two calculations agree.
Now play with the numbers. The device draws one frame to scale, the slots in it, and the cost in clock rate and in bytes.
Pick the three choices. The bar is one frame, drawn to scale; each box is a slot. The read-out gives the clock you must generate and the bytes the memory must absorb.
Arithmetic from fBCLK = fs × N × W; the byte counts assume each slot sits in a memory word as wide as the slot. The TDM frame sync pulse is drawn one tick wide, as the “short frame” style; real chips also offer a long pulse (Chapter 3).
Stereo needs two slots. A four-microphone array needs four. TDM, time-division multiplexing, simply gives each channel its own slot in a longer frame. The data wire stays one wire. The word-select wire changes job: with only two slots it flips half way through, but with eight slots it makes one short pulse at the start of each frame, called a frame sync. Count ticks from the pulse and you know which slot you are in.
Try 8 slots at 96 kHz with 32-bit slots. The clock reaches 24.576 MHz. That is far above the 3.25 MHz limit of a PDM microphone in Chapter 6, and it explains why array boards often use TDM for the digital side but PDM for the microphones.
Many codec chips want a faster clock named MCLK, the master clock. A common rule is MCLK = 256 × fs. The STM32 HAL source does exactly that when you enable its MCLK output: it picks the divider so that MCLK = 256 fs. At 48 kHz this is 12.288 MHz. BCLK and the frame rate are then made from MCLK by dividing: 12.288 MHz / 4 = 3.072 MHz = BCLK for 32-bit slots, and 3.072 MHz / 64 = 48 kHz = the frame rate.
On real hardware. Board: an STM32 Nucleo with an I2S peripheral (a Nucleo-F411RE works). Set 48 kHz, 16-bit data. In the HAL source a 16-bit format counts as a 32-tick frame, so measure BCLK with a scope or a logic analyzer and expect about 1.536 MHz. Then switch to the 32-bit format and expect about 3.072 MHz. If the numbers differ by a few percent, Chapter 4 explains why.
Chapter 2
Read one stereo frame by hand, tick by tick, and learn the timing rule that keeps the receiver from guessing
You clip three scope probes onto a codec board. Channel 1 shows a fast square wave. Channel 2 shows a slower one that flips every so often. Channel 3 looks like random noise. Which is which, and where does a number start?
The I2S specification answers in one sentence: the bus has three lines, and the device that generates the clock and the word select is the controller. Rev. 3.0 of the document, published by NXP on 17 February 2022, uses the words controller and target. Older chips and data sheets say master and slave. They mean the same thing.
SCK, the continuous serial clock, is the fast square wave. Audio chips usually call it BCLK, the bit clock, and the spec says it is continuous: it keeps running between words. One tick moves one bit.
WS, the word select, is the slower wave. Audio chips usually call it LRCK, left-right clock, or FS. The spec gives it a plain job: WS = 0 means channel 1, the left channel; WS = 1 means channel 2, the right channel. It flips once per slot, so it runs at exactly the sample rate, with half its period for each ear.
SD is the serial data line, the one that looks like noise. It carries both channels, one after the other, in two’s complement, most significant bit first. The spec explains why MSB first: the sender and the receiver may use different word lengths, so the top of the number must always sit in the same place. Chapter 4 uses that.
One chip makes BCLK and LRCK. The sender makes SD. These can be the same chip or two chips. In a simple system the sender is the controller: it drives all three wires. In a larger system one “system controller” drives the clocks, and the sender, now a target, puts SD on the wire under that external clock. Every codec data sheet has a pin setting for this choice.
Here is the sentence that causes most I2S bugs. The spec says: the transmitter always sends the MSB of the next word one clock period after the WS changes. LRCK changes first. One BCLK tick later, the top bit of the new word appears on SD.
The reason is practical. A target sender needs a moment to react to the LRCK edge and line up its data. The receiver also gains a tick to save the word it just finished and clear its register. The cost is that the last bit of one word and the LRCK flip for the next word land on the same tick, which surprises most readers.
The other half of the rule says when each wire changes and when it is read. The sender may change SD on the falling or the rising edge of BCLK. The receiver must latch (copy) SD on the rising edge. LRCK is also latched on the rising edge. So the usual picture has all three lines change after a falling edge and get read at the next rising edge.
Try this on a real frame. Slide the cursor along the ticks. The device tells you which bit of which word is on SD at that tick.
The left sample is +83 and the right sample is −41, both 8 bits long. Drag the cursor, or use the jump buttons. Watch the word select flip one tick before each top bit.
A model of UM11732 Figure 1: standard I2S, 8-bit words, one frame of 16 ticks, numbered from the frame start (tick 0 is where LRCK falls). Tick 16 belongs to the next frame but carries the last bit of the right word, exactly as the spec’s one-clock delay requires.
Take the left word, +83. In 8-bit two’s complement that is 0101 0011. The right word, −41, is 1101 0111 (256 − 41 = 215). The frame starts when LRCK falls at tick 0.
Notice the pattern. LRCK always changes before the top bit, and the final bit of one word shares a tick with the LRCK change that announces the next word. A receiver that follows LRCK edges handles this without counting.
The spec states every timing in terms of the clock period T, so it still holds at higher rates. The clock must be high at least 0.35T and low at least 0.35T. The sender must put new data on the wire within 0.8T of the clock edge. The receiver must accept data that arrives as late as that, because it needs only 0.2T of setup. At 3.072 MHz, T = 325.5 ns and 0.8T = 260.4 ns. At 12.288 MHz, T = 81.4 ns and 0.8T = 65.1 ns. Faster clocks leave much less room for a long wire.
The bar is one clock period T. Choose a clock rate, then slide the delay between the clock edge and valid data. The purple line is the 0.8T limit.
The 0.8T transmitter delay and the 0.2T receiver set-up come from UM11732 Table 3 and Figure 2. The delay you set is illustrative: in a real board it is the chip’s output delay plus the trace and any cable.
The spec also fixes the voltage levels for its TTL-era origin: outputs must be below 0.4 V for low and above 2.4 V for high, and inputs treat anything below 0.8 V as low and above 2.0 V as high. Today’s 1.8 V and 3.3 V parts follow their own data sheets, but the idea stays: leave a gap between what a sender drives and what a receiver needs.
When BCLK is fast and the wire is long, the failure looks like crackling that gets worse with heat or with a longer cable. The measurement is to put two probes on BCLK and SD at the receiver pin and check how far SD changes from the clock edge. The fix is a shorter wire, a lower rate, or a series resistor near the sender to calm the ringing. That last step is common practice, not part of the spec.
On real hardware. Board: an STM32 Nucleo or an nRF52840 DK with a codec or an I2S microphone breakout. Probe BCLK, LRCK and SD at the receiver pin with a logic analyzer set to at least 4 times BCLK. Measure the number of BCLK ticks between two LRCK falls. It must equal the slot count times the slot width from Chapter 1.
Chapter 3
Learn the three places a word can start inside its slot, and find a one-bit offset with a single test value
You open a codec data sheet and find a setting called audio interface format. The choices read “I2S”, “left-justified”, “right-justified” and “DSP mode”. They all use the same three wires. Your driver picks one. If it picks the wrong one, nothing crashes. The sound just gets quieter, rougher or louder than it should be.
A slot has room for more bits than a sample needs, or exactly as many. So the sample can sit in different places. Justification means where the sample sits inside the slot, measured from the LRCK edge.
Why do three exist? I2S is the original standard. Left-justified is what you get if you remove the one-tick delay. Right-justified lines the last bit up with the end of the slot. Data sheets offer all three because chips in the field use all three. Only I2S and left-justified keep the top bit in a known place when the word length changes. That is the point of MSB first. A right-justified receiver must know the word length in advance.
The PCM and DSP modes are a fourth family. There, the word select line is not a left-right switch but a short frame sync pulse, and the slots follow one after the other. This is the shape TDM uses (Chapter 1). The STM32 HAL names the two flavours I2S_STANDARD_PCM_SHORT and I2S_STANDARD_PCM_LONG, a one-tick pulse and a longer one.
Now a table of names. They differ between vendors, which causes confusion.
| What it means | Other names | STM32 HAL macro (I2SSTD field) | Top bit appears |
|---|---|---|---|
| I2S | Philips, standard | I2S_STANDARD_PHILIPS (00) | 1 tick after the LRCK edge |
| Left-justified | MSB-justified, MSB format | I2S_STANDARD_MSB (01) | On the LRCK edge tick |
| Right-justified | LSB-justified, LSB format | I2S_STANDARD_LSB (10) | Slot width minus word length ticks after the edge |
| PCM / DSP | short or long frame sync | I2S_STANDARD_PCM_SHORT, _LONG (11) | After a frame sync pulse |
The register fields are real: I2SSTD[1:0] sits at bits 5:4 of SPI_I2SCFGR in the STM32F411 header, and the HAL defines the four macros above from those two bits. The names in the third column come straight from that source.
Suppose the sender is standard I2S and the receiver is set to left-justified. Take the toy words from the hero: 6-bit samples in 8-tick slots. The left sample is +28, which is 011100. On the wire the I2S sender puts these six bits on ticks 1 to 6, and zeros on ticks 0 and 7.
In the toy, the stray bit on tick 0 is a padding zero. In a real 16-bit sample in a 16-tick slot, the stray bit is the last bit of the other channel’s word. It is random, so the sign bit flips at random. That is the sound of crackle on top of a quiet signal.
The reverse mistake is also real. An I2S receiver on left-justified data starts one tick late. It drops the top bit and takes in the first bit of the padding or the next word. The sample is twice as large, and any value above half scale wraps to a negative number.
Choose the sender’s format and the receiver’s format. Brackets show what the receiver captured. Press Send test value to swap the tone for a single 1 bit and see the shift directly.
Toy model: 6-bit words in 8-tick slots, left +28 and right −20 (test value +16 on both). Padding bits are zeros, as the spec says for a short word. Real 16-bit words in 16-tick slots have no padding, so the stray bit is the other channel’s last bit.
Do not guess from a scope picture. Send a number with only one bit set, and read back what arrives. In 16 bits, send 0x4000: a 1 followed by fifteen zeros after the sign bit. If the receiver returns 0x4000, the formats match. If it returns 0x2000, the receiver read one tick early, which is a left-justified receiver on I2S data. If it returns 0x8000, which is −32768, the receiver read one tick late.
We checked these two cases in the model used for this lesson: I2S data into a left-justified receiver gives 0x2000, and left-justified data into an I2S receiver gives −32768. The method is general. A shifted result tells you which way and how far.
The fix is one field: set the receiver’s format to match the sender’s data sheet, not to match another board that happened to work. On an STM32 that is the I2SSTD field, or the Standard member of I2S_InitTypeDef in the HAL.
On real hardware. Board: an STM32 Nucleo-F411RE or a nRF52840 DK. Configure the board as I2S transmitter, 16-bit, and send the constant 0x4000 on both channels. Probe SD and LRCK with a logic analyzer. Count the ticks from the LRCK edge to the one 1 bit: it must be 2 in I2S (tick 1 is the sign bit) and 1 in left-justified.
Chapter 4
Find out why a 24-bit sample fits in a 16-bit receiver, and why your 48 kHz is really 47,619 Hz
Two things go wrong on a new audio board, and they look alike. The first: the codec sends 24-bit samples, but you configured a 16-bit port. The second: the sound is fine, but it is a little flat, and an hour-long recording drifts away from the video. In the first case the question is about widths. In the second it is about the divider. Both need one idea from the specification, so we take them together.
Recall that I2S sends the most significant bit first. The spec gives the reason in one sentence: the transmitter and receiver may have different word lengths, and neither needs to know the other’s. It then gives three rules.
The top bit has a fixed position and the last bit moves. That is the whole trick. So a 24-bit value 0x123456 arrives at a 16-bit receiver as 0x1234. The low byte, 0x56, is gone. The sound is the same loudness with 8 fewer bits of detail. A 16-bit sender with 0x1234 arriving at a 24-bit receiver gives 0x123400, which is the same fraction of full scale. No gain error appears.
Why does that matter? Each bit adds about 6.02 dB of dynamic range, so 16 bits give about 96 dB and 24 bits about 144 dB. (Quantization noise shows where the 6.02 comes from.) Dropping 8 bits costs about 48 dB of range. For a speech microphone that is fine. For a mastering chain it is a loss.
The sample is 0x123456 at full 24-bit precision. Choose how many bits the sender transmits and how many the receiver stores. The slot is 32 ticks in all cases.
The rules are those of UM11732 section 3.1. A 32-bit sender is modelled as the 24-bit sample followed by 8 zero bits (the common case of a 24-bit converter in a 32-bit word). Fractions are the value divided by half the receiver’s range.
If widths are so forgiving, where do width bugs come from? From the container that your software uses to read the data. That is Chapter 5. And from a receiver that counts ticks instead of watching LRCK, like the third setting in the hero: a receiver set to 24 ticks per word, fed by a 32-tick slot, slips 8 ticks every word.
The second symptom is a numbers problem. A microcontroller makes BCLK by dividing a faster clock. On the STM32F4 family, the I2S block divides the I2S input clock by 2 × I2SDIV + ODD. I2SDIV is an 8-bit field. ODD is one extra bit that adds half a step. Together they allow a divider such as 63, which is 31 × 2 + 1.
The HAL function HAL_I2S_Init works out these two fields from the rate you ask for. Its rule, when MCLK is off, is:
c/* From stm32f4xx_hal_i2s.c, simplified. packetlength is 32 for a 16-bit format (16 ticks times 2 channels) and 64 for 24-bit or 32-bit formats. */ tmp = (((i2sclk / packetlength) * 10 / AudioFreq) + 5) / 10; /* round to nearest */ odd = tmp & 1; i2sdiv = (tmp - odd) / 2; if (i2sdiv < 2 || i2sdiv > 0xFF) return HAL_ERROR; /* prescaler error */
With MCLK on, the HAL divides by 256 × fs instead, so MCLK = 256 fs (Chapter 1). Now a worked example. Say the I2S input clock is 96 MHz, you want 48 kHz, and the data format is 16-bit (packet length 32).
The error is −380.95 Hz, which is −0.794%, or −7,937 parts per million (ppm). It is a pitch error of about 13.8 cents, and it also means the board’s audio clock disagrees with any other 48 kHz clock by that amount. The next lesson, DMA, ping-pong and clock drift, shows what a disagreement of even 50 ppm does to a buffer.
Now change the input clock to 98.304 MHz. That number is 2,048 × 48,000. The divider is 98,304,000 / (32 × 48,000) = 64, with no rounding. The rate is exactly 48,000 Hz. This is why audio designs carry a special PLL, or a crystal at 12.288 MHz or 24.576 MHz: the family of rates is made of multiples of 48,000 or 44,100 that divide down without a remainder.
Pick the I2S input clock, the sample rate and the format. The device runs the HAL’s own integer arithmetic. Try 96 MHz, then 98.304 MHz.
The arithmetic is copied from the integer expressions in stm32f4xx_hal_i2s.c (I2SDIV must be 2 to 255). The input clock slider is illustrative: on a real board you set it with the PLL, and not every value is reachable. The cent value is 1200 × log2(real / wanted).
A divider is a whole number (or a whole number plus a half). When the ratio between the input clock and the wanted BCLK is not whole, the nearest divider gives a rate that is slightly off. The fix is not in the divider. It is in the clock: choose an input clock that is a whole multiple of the audio rate.
On real hardware. Board: an STM32 Nucleo-F411RE. Configure 48 kHz, 16-bit, MCLK off. Measure BCLK with a frequency counter or a scope, and LRCK as well. Divide BCLK by 32 to get the frame rate. Compare with 48,000 and compute the ppm error. Then change the I2S PLL so that the input clock is 98.304 MHz and repeat. (Use the clock tree from First Light to see which PLL feeds I2S on your part.)
Chapter 5
Follow one 24-bit sample from SD into a DMA buffer, and learn the two lines of C that turn four halfwords into two clean numbers
Your logic analyzer shows a perfect I2S stream. You print the first samples from the buffer, and the numbers make no sense. The left channel holds 4660. The right channel holds 22016. A test tone would sound like static. The wire is fine. The array is where it went wrong.
The I2S peripheral has a shift register, like the one in Chapter 0. When it has collected a word, it copies it into a data register and raises a flag. In the STM32F4 family that register is 16 bits wide. A DMA engine (a small hardware copier, covered in Interrupts, DMA and the 12 Cycles) then moves each value from the data register into a RAM buffer, with no processor work.
Two facts from the STM32 HAL source matter here. The buffer pointer type is uint16_t *: the peripheral moves halfwords. And the comment on the size argument says: for a 16-bit format, the size counts 16-bit values; for a 24-bit or 32-bit format, the size counts 24-bit or 32-bit samples. Inside, the code doubles the size (Size << 1), so each sample takes two halfwords.
The order in memory follows the order on the wire. For one stereo frame of 24-bit audio in 32-bit slots, memory holds four halfwords: left high, left low, right high, right low. Then the next frame follows. Samples are interleaved: left, right, left, right.
Take the left sample 0x123456 (1,193,046). Its 24 bits ride the top of a 32-bit slot, followed by 8 zero bits: 0x12345600. The DMA writes it as two halfwords: first 0x1234, then 0x5600. The low byte of the second halfword is padding. Now the right sample, −2,000,000. In 24-bit two’s complement that is 16,777,216 − 2,000,000 = 14,777,216 = 0xE17B80, so the slot holds 0xE17B8000: halfwords 0xE17B and 0x8000.
To get the sample back, glue the two halfwords into one 32-bit word, then shift the padding away. The shift must be arithmetic: it copies the top bit in as it moves, which is sign extension. That keeps a negative number negative. Check with the right sample: (0xE17B << 16 | 0x8000) is 0xE17B8000; as a signed 32-bit number it is negative; an arithmetic shift right by 8 gives 0xFFE17B80, which is −2,000,000. A logical shift would give 0x00E17B80, a large positive number: a loud click of the wrong sign.
c/* 24-bit stereo in 32-bit slots. buf holds 4 halfwords per frame. */ static inline int32_t unpack24(const uint16_t *h) { uint32_t w = ((uint32_t)h[0] << 16) | h[1]; /* high half first: it arrived first */ return (int32_t)w >> 8; /* arithmetic shift on Arm GCC: sign extends */ } void process(const uint16_t *buf, int frames, int32_t *l, int32_t *r) { for (int i = 0; i < frames; i++) { l[i] = unpack24(&buf[4 * i + 0]); r[i] = unpack24(&buf[4 * i + 2]); } }
In ISO C, shifting a negative signed number right is implementation-defined. The Arm GCC compiler does an arithmetic shift, which is what we want. If you port the code, check that on the new compiler.
In circular mode the DMA fills the buffer and then starts over at the top. The HAL tells you twice per lap. It calls HAL_I2S_RxHalfCpltCallback when the first half is full and HAL_I2S_RxCpltCallback when the second half is full. In each callback you unpack the half that just filled, while DMA writes the other half.
Do the sums for a buffer of 240 frames at 48 kHz. The buffer lasts 5 ms, so each half lasts 2.5 ms. At 96 MHz that is 240,000 cycles for 120 frames, or 2,000 cycles per frame. The unpack code needs a few dozen. If a callback runs late, DMA reaches your half before you finish with it, and the sound has a click. The next lesson studies exactly that.
Now the bugs. Each one reads the correct buffer in a wrong way. The device below holds the two frames of halfwords from the worked example. Pick how your code reads them and where the capture started.
The boxes are the DMA buffer, in memory order. The true samples are +1,193,046 (left) and −2,000,000 (right). Choose a reading method, then slide the start of the capture.
A model of the memory layout in this chapter, computed with the same shifts as the C code. Little-endian halfwords, as on Arm Cortex-M. The 48.2 dB figure is 20 log10(256).
Method B is the classic trap. Cast the uint16_t buffer to uint32_t *, and a little-endian Cortex-M puts the first halfword in the low 16 bits. You get 0x56001234 for the left sample, so the two halves swap. Method D forgets to shift: every sample is 256 times too large, 48.2 dB louder, and clips at once. Method A treats the four halfwords as two stereo pairs. A start that is one slot late, which the status register can reveal through its channel-side flag (CHSIDE in SPI_SR), gives a perfect signal in the wrong ears.
The measurement is simple. Send known constants, stop the program, and dump the first eight halfwords in the debugger. If you see 1234 5600 E17B 8000, the wire and DMA are right, and the bug is in your reading code. If the values are rotated by two, the capture started on the wrong slot.
On real hardware. Board: an STM32 Nucleo-F411RE with a 24-bit codec or a loopback to a second I2S port. Fill the transmit buffer with the constants above, run in circular mode, and halt the debugger. Read the first eight halfwords of the receive buffer from the memory window and compare with 1234 5600 E17B 8000.
Chapter 6
See how a microphone with no word select and no sample words can still say how loud the room is, one bit at a time
A small digital MEMS microphone has five pads: power, ground, a clock input, a data output and a pin marked L/R. There is no word select. There are no 16-bit words. You feed it a clock between 1 and 3.25 MHz, and the data pin answers with a stream of zeros and ones at that same rate. Plot a thousand of them and they look like noise. Yet your voice is in there.
Picture a garden sprinkler that can only be on or off, but flips thousands of times a second. If it is on 50% of the time, the garden gets a medium amount of water. If it is on 90% of the time, a lot. You never see the amount. You see the on-off pattern, and the amount is the share of time on.
A PDM microphone (pulse density modulation) works like this. A loud positive sound makes a stream with many ones. A loud negative sound makes mostly zeros. Silence makes about half ones and half zeros. The sound is the density of ones over a short stretch.
The chip inside is a one-bit converter running at full speed. It is called a sigma-delta modulator. Its loop is small enough to write in two lines. Keep a running total of the error between the input and the last output bit. If the total is above zero, send a 1. If not, send a 0. Each bit pushes the error back toward zero, so the average of the bits follows the input.
c/* A first-order sigma-delta modulator, as a model of the converter inside the microphone. x is the input in [-1, 1]. The return value is the next output bit. */ int pdm_bit(float x, float *acc, int *prev) { *acc += x - (*prev ? 1.0f : -1.0f); /* integrate the error */ *prev = (*acc >= 0.0f); /* 1 bit out */ return *prev; }
The modulator runs much faster than the sound needs. Audio at 48 kHz is made from a clock of 2.4 MHz or 3.072 MHz. The ratio is the oversampling ratio, OSR = fclock / fs. For 2.4 MHz and 48 kHz that is 50. For 3.072 MHz it is 64. Each PCM sample you want comes from 50 or 64 bits.
Why spend so many bits? A one-bit converter makes a lot of rounding error. The modulator pushes that error toward high frequencies, far above the voice band. A filter later removes it. So the trade is: simple converter, fast clock, and a filter in firmware. Chapter 7 builds that filter.
The grey curve is the sound. The strips are the microphone’s bits (a stripe is a 1). The teal curve is the average of the last W bits. Make the sound louder, then change the window.
A model, not the real chip: a second-order sigma-delta loop makes the bits. The tone is drawn one cycle per 120 bits so you can see it. A real 1 kHz tone at 2.4 MHz takes 2,400 bits per cycle. The clock choices are within the 1 to 3.25 MHz range of the MP34DT01-M data sheet.
Drag the window. A short window leaves the bit noise in the answer. A long one smooths the noise away, but it also flattens the tone, because the window starts to cover a whole cycle. The best window sits in between. In the next chapter the same trade-off gets a proper name and a proper filter.
The ST MP34DT01-M is a real part of this kind. Its data sheet (DocID026514 Rev 3) lists these numbers:
| Quantity | Value | Where |
|---|---|---|
| Clock frequency | 1 MHz min, 2.4 MHz typical, 3.25 MHz max; duty cycle 40% to 60% | Table 3, note 3 |
| Signal to noise | 61 dB, A-weighted, 1 kHz, 1 Pa | Table 3 |
| Acoustic overload point | 120 dB SPL | Table 3 |
| Sensitivity | −26 dBFS typical (−29 to −23) | Table 3 |
| Supply and current | 1.64 to 3.6 V; 0.6 mA typical in normal mode | Table 3 |
| Turn-on time | 10 ms max, from the first clock edge to valid data | Table 3, note 4 |
| Power-down | clock at or below 0.23 MHz; 20 µA typical with the clock held static | Tables 3 and 5 |
One number deserves a calculation. A sensitivity of −26 dBFS means a 1 Pa tone gives a signal of 10−26/20 = 0.0501 of full scale. The density of ones is (1 + 0.0501 sin) / 2, so it swings only between 47.5% and 52.5%. A normal voice makes a stream that looks almost half ones. Read that again: the whole voice lives in a 5-point wobble of the density, which is why the filter must be good. Try the loudness slider at 5% to see it.
If the microphone gets no clock, it gives no data. The data sheet also lists a power-down clock of 0.23 MHz or less, and a typical 20 µA when the clock is held static. So firmware can save power by stopping or slowing the clock, with no extra pin.
On real hardware. Board: an STM32 Nucleo with a PDM microphone breakout, or an RP2040 board with a PDM breakout. Probe the clock and data pins with a logic analyzer at 8 times the clock rate or more. Count the ones in 1,000 bits in a quiet room. Expect about 500. Clap near the board and watch the count swing.
Chapter 7
Build the filter that turns 3,072,000 bits a second into 48,000 numbers a second, using only adds and subtracts
You have the microphone bits arriving at 3.072 MHz. The sound needs a 48 kHz stream of numbers. In Chapter 6 you averaged a window of bits and got the tone back. That worked on a slow screen. Now do it in firmware, for real, with a processor that has to finish before the next bit arrives.
Decimation means lowering the sample rate by an integer factor R. You keep one value in every R and throw away the others. At 3.072 MHz with R = 64, that leaves 48 kHz.
You cannot just drop bits. Sound above half the new rate, 24 kHz, would fold back into the audible band and sound like a whistle that was never in the room. This folding is aliasing. The microphone makes it worse: its quantization noise sits mostly above 20 kHz, and aliasing would fold all of that noise down on top of the voice. So you must filter first, drop second.
The simplest filter is the one from Chapter 6: the average of R bits. Its response has a handy shape. It falls to zero at 48 kHz, 96 kHz, 144 kHz and so on: every multiple of the new rate. Those are exactly the frequencies that would alias onto zero hertz. One average also leaves gaps: just beside each zero it still lets a lot through, and the noise there folds into the band. The cure is to average the average. Stack N of them in a row, and the dips get deeper and wider. This is the sinc filter of order N. Its response is:
A plain average of R bits costs R adds per output. A stack of N costs more. In 1981 Eugene Hogenauer found a way to do it with almost no work, and the result is the CIC filter: cascaded integrator-comb. It has two parts.
An integrator is a running total: i += x. A comb is a difference between now and R steps ago: y = i − i_old. A running total minus an older running total is exactly the sum of the values in between. So integrator then comb equals a sum over R values with no inner loop. Check it on small numbers, R = 4:
For order N, put N integrators at the fast bit rate, decimate, then N combs at the slow sample rate. The integrators do one add per bit each, and the combs run 64 times less often. No multiplies anywhere. This is why a CIC filter is the first stage in almost every PDM chain.
Each stack multiplies the gain. A DC level of 1 comes out as RN. For R = 64 and N = 4 that is 644 = 224 = 16,777,216. So the output needs N × log2(R) = 4 × 6 = 24 more bits than the input. The input is 1 bit, so 25 bits hold it all. A 32-bit integer is enough.
The integrators will overflow, because a running total never stops growing. This is fine. In two’s complement arithmetic, a wrap-around adds or removes a whole multiple of 232, and the comb subtracts it again. The final result is exact if the register is at least as wide as the final output. This is the key property Hogenauer proved, and it is why plain uint32_t variables work.
The microphone clock is 3.072 MHz. Choose the ratio R and the order N. The top plot is the filter’s gain; the green band is the sound you want; the red bands fold onto it. The bottom plot is the recovered 1 kHz tone.
The gain curves are the sinc formula above. The SNR is measured live in your browser on a model: a generic second-order sigma-delta loop with a 1 kHz tone at half scale, a CIC in exact arithmetic, and a 512-point Hann-windowed transform over the wanted band (5/12 of the output rate, 20 kHz at 48 kHz). The numbers depend on the model and move a few decibels with its settings.
Play with the order. Order 1 leaves the noise: the signal is only about 30 dB above it. Order 2 brings a big jump. Orders 3 and 4 give a little more, and then the gain stops, because the modulator’s own noise limits the result. Meanwhile the droop keeps growing: at 20 kHz each extra order costs another 2.64 dB at R = 64. High notes get duller as the filter gets better at rejecting aliases.
The sinc shape is not flat inside the band. At N = 4, R = 64 and 3.072 MHz, a 20 kHz tone comes out about 10.5 dB quieter than a 1 kHz tone. That loss is called droop. The standard fix is a short second stage after the CIC, running at the low rate, whose response is the inverse of the droop. Many PDM chains also add a high-pass filter after it, to remove the DC offset of the bit stream.
The symptom of an undersized filter is a hiss and a few faint whistles at odd pitches. The measurement is to play a sweep from 1 kHz to 20 kHz into the microphone and record the level at each pitch. The fix is a higher order, a larger R, or a better second stage.
Hardware can do this for you. The STM32F412, F413, F423 and L4 families have DFSDM, a block that filters sigma-delta bit streams in hardware. The reference manuals describe a sinc filter of order 1 to 5 (the FORD[2:0] field) and an oversampling ratio up to 1024 (the FOSR[9:0] field), with tighter limits at higher orders. Check the table for your part.
c/* A fourth-order CIC, R = 64, for one microphone. b[] holds 64 bits as 0 or 1. The result is a signed 16-bit sample. All registers are uint32_t and wrap on purpose. */ typedef struct { uint32_t integ[4]; uint32_t comb[4]; } cic_t; int16_t cic4_r64(cic_t *s, const uint8_t b[64]) { for (int k = 0; k < 64; k++) { /* fast rate: 4 adds per bit */ s->integ[0] += b[k]; s->integ[1] += s->integ[0]; s->integ[2] += s->integ[1]; s->integ[3] += s->integ[2]; } uint32_t y = s->integ[3]; /* decimate: keep one value */ for (int j = 0; j < 4; j++) { /* slow rate: 4 subtractions */ uint32_t t = y; y -= s->comb[j]; s->comb[j] = t; } /* y is 0 .. 2^24 (gain 64^4). Centre it and keep the top 16 bits. */ int32_t v = ((int32_t)y - (1 << 23)) >> 8; return (int16_t)(v > 32767 ? 32767 : v); }
We checked this arithmetic, with 32-bit wrap-around, against a direct fourth-order convolution on 10 consecutive output samples of a modelled microphone. All 10 matched exactly. The model is not a real microphone, so treat that as proof of the arithmetic only.
On real hardware. Board: an STM32 Nucleo with a PDM microphone, or an RP2040 board with a PDM breakout. Capture a few seconds of the 1 kHz tone from a phone speaker. Compute a spectrum of your PCM output with any audio tool. Repeat with N = 2, 3 and 4. Compare the height of the 1 kHz peak with the noise floor, and note the level of a 15 kHz test tone against 1 kHz.
Chapter 8
Wire a stereo pair to a single data pin, then decide whether the processor or a hardware block runs the CIC
A stereo recording board has two microphones, but the chip has only one data pin free. The designer ties both microphones to the same clock and the same data line. Left and right both speak on one wire, and nothing is lost. How is that possible, and what happens if one strap is wrong?
The MP34DT01-M has a pin called L/R (Table 2 of its data sheet). You must tie it to Vdd or to ground. Table 7 gives the rule, and it is short:
| L/R pin tied to | While CLK is low | While CLK is high |
|---|---|---|
| GND | Data valid | High impedance |
| Vdd | High impedance | Data valid |
High impedance (Hi-Z) means the output lets go of the wire, as if it were unplugged. So a microphone tied to ground drives the line only when the clock is low, and one tied to Vdd drives it only when the clock is high. They take turns, twice per clock period. The receiver reads the data line near the end of each half period: at the rising clock edge for the first microphone, and at the falling edge for the second.
The data sheet gives the hand-over times in Table 5 and Figure 3: the output is enabled at least 16 to 18 ns after the clock edge (the exact value depends on the strap) and disabled within 16 ns. The sister MP34DT01 sheet, Doc ID 022331 Rev 4, lists the same pair of times. At 3.072 MHz one half period lasts 162.8 ns, so the hand-over takes up about a tenth of the half period. At 3.25 MHz, the top clock rate, a half period is 153.8 ns.
Count the bits. Each microphone makes one bit per clock period. The shared wire carries two bits per period, one from each. The line changes twice as fast as the clock. Each microphone still has the full oversampling ratio of Chapter 6, and each gets its own CIC filter in Chapter 7.
Each microphone has a strap to ground or to Vdd. The shaded band shows when each one drives DOUT. Red means two outputs fight. A dotted line means nobody drives. Try both straps the same.
A model of Table 7 of the MP34DT01-M data sheet. The bits are made up. The receiver is modelled as reading each half period at its end. Real contention depends on the output drivers: this model only marks where two outputs would drive at once.
The failure shows up in the hardware first. If both straps point the same way, both microphones drive in the same half and nobody drives in the other half. In the shared half the bits collide whenever they differ. In the empty half the line floats and the receiver reads noise. The symptom is one silent or hissing channel, plus a channel that sounds like a mix. The measurement is to look at DOUT with a scope while the clock is high, then while it is low. You must see data in both halves. The fix is a strap on the board, not a line of code.
Now the receiver. The raw bit stream is big. Two microphones at 3.072 MHz make 6.144 million bits a second, which is 768,000 bytes a second. A 10 ms block holds 7,680 bytes. Before any filtering, the processor must even have somewhere to put them. Then there is the arithmetic.
Take the fourth-order CIC of Chapter 7. Every bit goes through four integrators. For two microphones that is 6.144 million × 4 = 24.6 million adds each second. At one add per cycle and 96 MHz, this uses 25.6% of the core. Real loops cost more, because each add also loads and stores. You have three options.
Choose the processor clock, the number of microphones, the filter order and the method. The bar is the share of the core the integrators use.
Illustrative cycle counts, not measurements. The bit loop is assumed to cost 1 cycle per integrator add (real code costs more). The byte lookup is assumed to cost 2 cycles per integrator per 8 bits. The microphone clock is 3.072 MHz; each microphone makes one bit per clock period. Measure your own code with the cycle counter.
The lesson for planning: the filter is cheap per bit, but the bits never stop. A bit loop on a slow core can eat most of the processor before your application does anything. Count the integrator adds per second before you pick a part.
On real hardware. Board: an STM32 Nucleo or a Nordic development kit with a stereo PDM pair, or one microphone on each strap. Probe CLK and DOUT. Capture at least 4 times the clock rate. Check that the data line has transitions in both halves, then run your CIC and use the processor’s cycle counter (the DWT cycle count register on Cortex-M) to measure cycles per output sample.
Chapter 9
Go from a bad sound to its cause in a fixed order, and learn why your own analyzer can say “clean” when it is not
A board plays audio, and it sounds wrong. You have a logic analyzer, a debugger and one hour. Where do you start? Do not start by listening harder. Start with measurements, in an order that rules out the cheap causes first.
The order matters because each step needs the one before it. A divider error makes the format test meaningless, and a wrong format makes the memory dump misleading.
The table puts the common faults in one place. Each row is a story you now have the tools to tell.
| Symptom | Measurement | Likely cause and fix |
|---|---|---|
| 6 dB too quiet with crackle, or too loud and wrapping | Send 0x4000. Read back 0x2000 or 0x8000. | One-tick offset. Set the receiver format to the sender’s (Chapter 3). |
| Left and right swapped | Send left only. It arrives in the right. | LRCK polarity or a capture that began one slot late (Chapters 2 and 5). |
| Pitch a little flat, clicks every few minutes | Count LRCK. Compute the error in ppm. | Divider rounding or two unrelated clocks. Choose a multiple clock (Chapter 4). |
| Roughly 48 dB too loud, clipped | Dump halfwords. They look right. | Missing shift after unpacking 24-bit data (Chapter 5). |
| Hiss, dull highs, faint whistles from a PDM microphone | Sweep a tone and plot level against pitch. | CIC order or ratio too small, or no droop fix (Chapter 7). |
| One microphone silent, one hissing | Scope DOUT while CLK is high, then low. | L/R straps equal or floating (Chapter 8). |
| The analyzer shows a clean capture, the sound is wrong | Raise the analyzer rate to 4 times BCLK or more. | The analyzer under-sampled the clock. Read the next section. |
A board plays a voice about 6 dB too quiet, with crackle. Step 1: the counter reads 48.000 kHz on LRCK and 3.072 MHz on BCLK, so the clock is fine. Step 2: the analyzer counts 64 ticks between falling LRCK edges, so the slots are right. Step 3: you send 0x4000 and read back 0x2000. That is a one-tick offset, and the receiver is set to left-justified while the codec sends I2S. One field in the driver fixes it, and you never touched the cable.
Write down each measurement as you go: the number, the tool and the setting. When a fix fails, you can see which step you skipped. A log of four lines is worth more than an hour of listening.
The device below breaks a receiver in a way you have met. You see the capture and the samples the receiver produced. Read the evidence, then choose the cause.
The sender is correct I2S and sends the same two numbers every frame. The brackets show what the receiver captured. Choose what is wrong, then press New capture.
Toy model: 6-bit words in 8-tick slots; the sender is correct I2S with left +26 and right −11. Each capture hides one fault, or none.
A logic analyzer does not see the wire. It sees samples of the wire, taken at its own rate. To read BCLK edges correctly it must sample fast enough to see every edge. A common bench rule is at least 4 times the bit clock. Below 2 times the clock, it can miss whole clock periods, and the decoder then reads bits from the wrong places. The picture looks tidy because the analyzer shows what it decoded, not what happened.
Dots are the analyzer’s samples. It decodes a bit at each rising edge it sees on its sampled copy of BCLK. Lower the rate and compare its bits with the true bits.
A model of an analyzer that samples BCLK and SD at a fixed rate and a fixed phase, and takes a bit whenever its sampled BCLK goes from low to high. Real analyzers add their own edge detection, but they cannot see an edge that falls between two samples.
This ties to the lesson on bench work, Bench and Root Cause. The rule there is the same: know what your instrument can and cannot see, before you believe it.
On real hardware. Board: any of the boards above plus a cheap logic analyzer. Capture BCLK and SD at 4 times BCLK, then at 1.3 times BCLK. Decode both with an I2S decoder. Compare the two decoded streams with the bits you sent from a known test pattern, and note where they part.
Chapter 10
Keep the numbers, the checklist and the core code in one place, and see where to go next
Digital audio crosses a wire as a stream of frames. Three lines carry it: a bit clock, a word select and a data line. The bit clock is the sample rate times the slot count times the slot width. The data word starts one tick after the word select changes, unless the format says otherwise. Bits come most significant first, so word lengths may differ. A PDM microphone skips the words: it sends one bit per clock tick, and a CIC filter turns 50 to 64 of them into one sample.
| Item | Value or meaning | Source |
|---|---|---|
| I2S lines | SCK (BCLK), WS (LRCK), SD. The device that drives SCK and WS is the controller. | UM11732 section 3 |
| Word select | WS = 0 left, WS = 1 right. Changes one clock before the top bit. | UM11732 section 3.2 |
| Data | Two’s complement, MSB first. Short sender word: low bits zero. Long sender word: receiver ignores the rest. | UM11732 section 3.1 |
| Latch edge | Receiver latches SD and WS on the rising edge of SCK. | UM11732 sections 3.1, 3.2 |
| Timing | Clock high and low each at least 0.35T. Transmitter delay at most 0.8T. Receiver set-up 0.2T. Hold times 0 for both. | UM11732 Table 3 |
| Levels (spec) | Output low below 0.4 V, high above 2.4 V. Input low 0.8 V, high 2.0 V. | UM11732 section 5 |
| Bit clock | fBCLK = fs × N × W. Example: 48 kHz × 2 × 32 = 3.072 MHz. | Chapter 1 |
| STM32F4 divider | BCLK = I2S clock / (2 I2SDIV + ODD), I2SDIV from 2 to 255. Packet length 32 for 16-bit, 64 for 24 or 32-bit. MCLK on gives 256 fs. | stm32f4xx_hal_i2s.c |
| STM32 formats | I2SSTD: 00 Philips, 01 MSB, 10 LSB, 11 PCM short or long. | stm32f4xx_hal_i2s.h |
| 24-bit DMA | uint16_t buffer, two halfwords per sample, high halfword first. Unpack, then shift right by 8. | HAL source; Chapter 5 |
| MP34DT01-M | Clock 1 to 3.25 MHz (typical 2.4), duty 40 to 60%. SNR 61 dB. AOP 120 dB SPL. Sensitivity −26 dBFS. 1.64 to 3.6 V. | DocID026514 Rev 3, Table 3 |
| L/R pin | GND: data valid while CLK low. Vdd: valid while CLK high. Otherwise Hi-Z. Output enable at least 16 to 18 ns, disable at most 16 ns. | Tables 5 and 7 |
| Oversampling | OSR = fclock / fs: 50 at 2.4 MHz and 48 kHz, 64 at 3.072 MHz. | Chapter 6 |
| CIC filter | Gain RN. Extra register bits N log2 R. N = 4, R = 64: 24 extra bits. Droop at 20 kHz: about 10.5 dB. | Hogenauer 1981; Chapter 7 |
| Hardware filter | DFSDM sinc filter, order set in FORD[2:0], ratio in FOSR[9:0]. | RM0430, RM0351 |
c/* 1. Receive 24-bit stereo I2S on an STM32F4 with the HAL. buf holds 4 halfwords per frame. Size counts 24-bit samples (2 per frame), as the HAL comment says. */ static uint16_t buf[4 * FRAMES]; I2S_HandleTypeDef hi2s2 = { .Instance = SPI2 }; hi2s2.Init.Mode = I2S_MODE_MASTER_RX; hi2s2.Init.Standard = I2S_STANDARD_PHILIPS; /* match the sender's format (Chapter 3) */ hi2s2.Init.DataFormat = I2S_DATAFORMAT_24B; /* 24 data bits in a 32-tick slot */ hi2s2.Init.MCLKOutput = I2S_MCLKOUTPUT_DISABLE; hi2s2.Init.AudioFreq = I2S_AUDIOFREQ_48K; /* check the real rate in ppm (Chapter 4) */ hi2s2.Init.CPOL = I2S_CPOL_LOW; if (HAL_I2S_Init(&hi2s2) != HAL_OK) Error_Handler(); HAL_I2S_Receive_DMA(&hi2s2, buf, 2 * FRAMES); /* 2. Unpack (Chapter 5). */ static inline int32_t unpack24(const uint16_t *h) { return (int32_t)(((uint32_t)h[0] << 16) | h[1]) >> 8; } /* 3. Bit rate and PDM decimation (Chapters 1, 6, 7). */ #define BCLK_HZ(fs, slots, width) ((fs) * (slots) * (width)) #define OSR(fclk, fs) ((fclk) / (fs)) /* cic4_r64(): four integrators per bit, four combs per 64 bits, centre and shift by 8. */
The code above is a sketch built from the HAL names we read in the source. Compile it against your own project and part, because field names differ between families.
stm32f4xx_hal_i2s.c, stm32f4xx_hal_i2s.h) and CMSIS device header stm32f411xe.h, on GitHub.Now press Present or Teach and explain one stereo frame from memory: what the three lines do, why the top bit comes one tick after LRCK, and what a 24-bit sample looks like in RAM. Then go back to the receiver at the top, break it, and fix each fault using a single measurement.