A codec turns a microphone’s tiny voltage into numbers, and numbers back into sound. Set its gain, its power-up order or its control bytes wrong, and you get hiss, clipping or a pop.
Learn what sits inside an audio codec, how its converters work, how to set gain so the quiet parts and the loud parts both survive, how firmware talks to it over I2C, and how to wake it up without a thump in the headphones.
Pick a mic gain, then slide the voice from a whisper to a shout. Watch where the wave hits the red walls. Then we build, piece by piece, everything inside the chip and the firmware around it.
You need a little C and a feel for a voltage (an electrical push, measured in volts). We build the rest from zero. The code and numbers come from the SGTL5000 codec datasheet and its programming note.
Part of Firmware from Zero to Expertise, audio track. Built from primary sources: the SGTL5000 datasheet (Rev. 6.0), NXP application note AN3663, the Linux sgtl5000 driver and the NXP UM10204 I2C specification.
Illustrative voice: a mic output from 0.5 mV to 200 mV peak. The converter limits are the SGTL5000’s at VDDA = 1.8 V: a 1.60 V peak to peak maximum input, so 0.80 V peak is 0 dBFS. The noise floor of about 85 dB below full scale reads the datasheet’s 85 dB SNR figure.
Chapter 0
Hear the three classic failures of an audio board, and see which part of the firmware causes each one
You have a new audio board on your desk. A microcontroller sits on it, and next to it sits a small chip with a dozen tiny pins. You plug in headphones and press the reset button. The headphones go thump.
You fix that, and you speak into the microphone. Your voice is there, but under it runs a steady hiss, like a distant waterfall. You turn the gain up to beat the hiss. Now when you laugh, the sound cracks and buzzes.
These are the three classic failures of audio firmware: a pop (a sudden step in the output voltage that the speaker turns into a thump), hiss (a quiet voice sitting too close to the electrical noise), and clipping (a loud voice that does not fit, so its peaks are sliced flat). None of them is a bug in your C. All of them are caused by how you set up the chip beside the microcontroller.
Put a toy number on each one. Say a voice peaks at 1 mV when the converter wants 800 mV. That is 58 dB below the ceiling, and the converter’s own noise sits about 85 dB below it. The voice stands only 27 dB above the hiss.
Now add 40 dB of gain, a factor of 100. The voice peaks at 100 mV, which fits. A shout 30 times louder would peak at 3 V, nearly four times the ceiling, and it clips. Both numbers are illustrative. The same gain knob caused both failures, so the fix is to choose it with care, as Chapter 4 does.
A microcontroller thinks in numbers. A microphone makes a smooth, wiggling voltage. A speaker wants a smooth, wiggling voltage too. Something must stand between the two worlds.
That something is a codec (short for coder and decoder). It holds an ADC (analog to digital converter), which measures the microphone voltage again and again and writes the results as numbers. It also holds a DAC (digital to analog converter), which does the reverse and turns numbers into a voltage that drives the headphones. Around them sit amplifiers, volume controls and a small control port, a few wires that firmware uses to change the chip’s settings.
The numbers flow over a separate digital audio bus, the I2S wires that the previous lesson on digital audio takes apart. This lesson is about the chip at the other end of those wires, and about the control port that configures it.
We use one real part as our guide: the SGTL5000, a stereo codec with a headphone amplifier. It is a good teacher because its datasheet is open, its register map is clean, and NXP publishes a full programming note (AN3663) for it. Everything with a number in this lesson comes from those documents, or is marked as a toy.
Choose a failure below. The canvas draws the output voltage over time and shows what the speaker would be asked to do. The read-out gives the number that matters.
Each trace is a toy of one failure. Press a button, then read what the numbers say about it and where in this lesson it is fixed.
Toy traces. The 0.90 V reference is the SGTL5000 example for a 1.8 V supply (AN3663). The hiss and clip levels are chosen to show the shape of each failure, not measured on a board.
A pop is a problem of order and time: what you switch on, and when. Hiss and clipping are problems of gain: how loud the signal is when it reaches the converter. Both depend on registers, and registers depend on the control port. That gives us the road for this lesson.
Chapter 1
Follow a signal through the blocks of the SGTL5000 and see which registers choose its path
Imagine a small city with three roads. On the first road, a voice travels from a microphone to your microcontroller. On the second, music travels from your microcontroller to a pair of headphones. On the third, a signal from a line cable crosses the city without ever becoming a number. A codec is that city, and the registers are the road signs.
A microphone makes a very small voltage, often a few millivolts (a millivolt is a thousandth of a volt). The converter wants a voltage near one volt. So the first block is a microphone amplifier, which multiplies the voltage. On the SGTL5000 the field CHIP_MIC_CTRL GAIN picks 0 dB, +20 dB, +30 dB or +40 dB.
A decibel (dB) is a way to say “how many times bigger” using small numbers. Every +20 dB multiplies a voltage by 10. So +20 dB is 10 times, +40 dB is 100 times, and +6 dB is about 2 times. We use decibels all through this lesson.
Next comes the ADC with its own small amplifier, a programmable gain amplifier (PGA: an amplifier whose gain a register sets). The datasheet gives it 0 to +22.5 dB in steps of 1.5 dB. The ADC output then goes to the I2S output port, the digital wires toward your microcontroller.
Samples arrive from the microcontroller on the I2S input. They pass a digital audio processor (volume, equalizer, bass), then the DAC, then the headphone amplifier, a stage that can push enough current to move a small speaker. A volume control sits at the end, in 0.5 dB steps.
The line input can go straight to the headphone amplifier. The datasheet says this route bypasses the ADC and the audio switch, and that only the headphone volume and mute then affect the output. It saves power because both converters can sleep.
The device below draws the three roads. Choose one. The read-out names the registers that AN3663 writes to select it.
Dots show the signal moving along the chosen road. The other roads stay dark, which means those blocks do no work on this route.
Block names and register fields are from the SGTL5000 datasheet and AN3663 section 2.2.3. The picture is simplified: the chip also has a line output, a mixer and a PLL that are not drawn.
Notice how little changes between the roads. Each route is a few bit fields: one picks the ADC input, one picks the data source for I2S, one picks what feeds the headphone amplifier. In firmware you set them once at start-up. The harder part is the work around them: power, clocks and mute.
First, the control port. It is a two-wire I2C bus. Your firmware is the master and the codec is a slave. Every setting in this lesson travels over it. Chapter 6 shows the bytes.
Second, the master clock (MCLK). The codec needs a steady clock to run its converters. The datasheet says a clock synchronous with the sample rate works best, and that any clock from 8.0 to 27 MHz can be used with the internal PLL. AN3663 sets 48 kHz with an MCLK of 256 times the sample rate, which is 12.288 MHz.
Third, the reference voltage, called VAG. It is the analog middle of the chip. Both converters measure from it. Chapter 3 explains why it matters so much for pops.
Numbers make the road real. Let a microphone give a 10 mV peak while someone speaks. Set the mic amplifier to +20 dB. That multiplies the voltage by 10, so the peak is now 100 mV.
Set the ADC amplifier to two steps. Two steps of 1.5 dB add 3 dB, a factor of 1.4125. The peak at the ADC is 100 mV × 1.4125 = 141.25 mV.
Divide by the 0.80 V full scale: 0.14125 / 0.80 = 0.1766. In decibels, 20 log10(0.1766) = −15.06 dBFS. The ADC reports this peak as a signed number. In a 24-bit word the largest value is 223 = 8,388,608, so the peak sample is about 0.1766 × 8,388,608 = 1,481,153, which is 0x1699C0. That is the number your firmware finds in its buffer.
Symptom. The board boots, the I2C writes all return OK, and the headphones are silent.
Measurement. Read back CHIP_ANA_CTRL (0x0024). At reset its mute bits are set, so the headphones, the line out and the ADC are all muted. If bit 4 (MUTE_HP) still reads 1, you never unmuted. Then put a logic analyzer on the I2S wires. If BCLK and LRCK are running, the data path is alive.
Fix. Clear the mute bit as the last step of start-up, as Chapter 7 shows. Check the routing fields the same way: a route that was never selected also gives silence.
Chapter 2
Round a smooth voltage onto a ladder of levels, and measure what the rounding costs you in decibels
You are standing on a staircase with a stopwatch and a tape measure. Your friend walks up a smooth ramp. Every 20 microseconds you shout the height, but you may only say a whole number of steps. Your friend is at 41.3 steps. You say “41”. That small lie, repeated 48,000 times a second, is what an ADC does.
Two things happen. First, sampling: the ADC looks at the voltage at fixed instants. A sample rate of 48 kHz means 48,000 looks each second. The previous lesson shows how those samples travel on the wire. Second, quantization: each look is rounded to the nearest level on a ladder. This chapter is about the ladder.
An ADC with N bits has 2N levels. A 16-bit ADC has 65,536 levels. A 24-bit ADC has 16,777,216. The levels are spread evenly across the full scale, the biggest voltage swing the converter accepts. The gap between two levels is one LSB (least significant bit), the step size of the ladder.
The SGTL5000 datasheet gives the largest input as 1.60 V peak to peak when the analog supply (VDDA) is 1.8 V. Take that full scale. A 16-bit ladder has an LSB of 1.60 V divided by 65,536, which is 24.4 microvolts. A 24-bit ladder has an LSB of 95 nanovolts. Those are tiny steps, and a real circuit cannot hold them still, as we see below.
Rounding is always off by a bit. The error can be anywhere from minus half an LSB to plus half an LSB, and every value in that range is about equally likely. Mathematicians call this a uniform spread. Its average power is a known quantity: the rms (root mean square, a kind of average size) of the error is the LSB divided by the square root of 12.
Now compare that error with a signal. Take a sine wave that fills the whole ladder. Its peak is 2N LSB divided by 2, so its rms is that divided by the square root of 2. The ratio of signal to error comes out as:
N = 16: 6.02 × 16 + 1.76 = 98.08 dB N = 24: 6.02 × 24 + 1.76 = 146.24 dB
This formula is textbook material. Analog Devices tutorial MT-001 explains it. It holds for a sine wave that fills the full scale, with the error spread evenly. It is the best any N-bit ADC can do.
Now the catch. The formula assumes a full-scale signal. If your voice is 40 dB below full scale, the signal shrinks and the error does not. The SNR then falls by 40 dB. Quiet signals use only a few levels of the ladder.
The blue line is the smooth voltage. The warm stairs are what the ADC reports. The purple strip below shows the error, drawn in units of one LSB. Lower the bits first, then lower the level.
Computed live from 600 samples of a sine wave with an ideal rounding ADC and a 1.60 V peak to peak full scale (the SGTL5000 limit at VDDA = 1.8 V). “Measured” is the rms of the signal over the rms of the real rounding error. At very few bits and low levels it drifts from the formula, because the error stops being evenly spread.
Here is a trap that catches many firmware writers. The I2S port of a codec may send 24-bit words. That does not mean the ADC has 24 good bits. Real circuits add their own electrical noise, called thermal noise, and it is far bigger than a 24-bit LSB.
The SGTL5000 datasheet lists the line input to ADC path at 85 dB SNR, measured with a −60 dB input, at VDDA = 1.8 V. Invert the formula: (85 − 1.76) / 6.02 = 13.8. That is the effective number of bits: the ideal bit count whose rounding noise equals the real noise. The chip sends 24-bit words, and only about 14 of them carry information. The rest is noise, faithfully measured.
This changes how you work. Buying a bigger word length does not clean a signal. Lowering the noise at the analog stage does. That is the story of the next four chapters.
Take the 16-bit ladder on a 1.60 V swing: one LSB is 24.4 µV. A voice that peaks at 1.25 mV at the ADC is 1.25 mV / 0.80 V = 0.00156 of full scale, which is −56.1 dBFS. Its peak spans 1.25 mV / 24.4 µV = about 51 levels above the middle. The picture is a sine wave drawn on a staircase with only 51 steps up and 51 down.
The ideal SNR is 98.08 − 56.1 = 42.0 dB. That is fine for a phone call and poor for a studio. The cure is not a bigger word. It is more signal at the converter, which is the subject of Chapter 4.
Symptom. A recording sounds smooth when loud and rough and gritty when quiet. The tail of a note sounds like it is crumbling.
Measurement. Dump a few hundred samples from a quiet passage and list them. If only a handful of different values appear (say −3 to +3), the signal uses very few steps of the ladder. Compute the peak in LSB, and then the SNR as above.
Fix. Raise the signal before the converter so it uses more levels. If the file is already recorded, nothing can restore the lost detail. If your firmware lowers the volume in the digital domain, do the maths in a wider word than the output word, and round once at the end.
Chapter 3
See why a silent output still sits at a voltage, and why switching that voltage on makes a thump
Hold a skipping rope still, then lift your hand an inch and put it back. A wave runs down the rope. Now picture a speaker cone. It is a light, stiff disc that moves when the voltage across it changes. It does not care whether the change is music or an accident.
That is the whole story of a pop. The speaker follows any change in voltage. A wanted change is sound. An unwanted change is a thump.
The DAC does the ADC’s job in reverse. It receives a sample, say the 16-bit number 12,000, and puts out a voltage in proportion. A signed 16-bit sample runs from −32,768 to +32,767. The DAC maps zero to the middle of its output range and the extremes to the two ends.
So a silent signal, all zeros, is not 0 V at the pin. It is the middle voltage. The chip calls it VAG (analog ground). The datasheet says VAG is the internal voltage reference for both the ADC and the DAC. Set it to half the supply for the biggest swing: the datasheet says “VDDA/2 or lower for best performance.” With VDDA = 1.8 V that is 0.9 V.
Register CHIP_REF_CTRL (0x0028) holds the field VAG_VAL. It runs in 25 mV steps from 0.800 V (code 0) to 1.575 V (code 31). To get 0.9 V, the code is (0.900 − 0.800) / 0.025 = 4. AN3663 writes 0x004E: the 4 sits in bits 8:4, and the bias current field in bits 3:1 is set to 7 (50% of nominal, the same note as the AN says).
When power arrives, VAG starts at 0 V. It must climb to 0.9 V. A capacitor on the VAG pin makes that climb take time. The datasheet says that setting the bit SMALL_POP (bit 0 of CHIP_REF_CTRL) “slows down the VAG ramp from ~200 to ~400 ms to reduce the startup pop, but increases the turn on/off time.” AN3663 uses exactly this: it writes 0x004E first, then 0x004F.
Why does a slower ramp help? Between the reference and the speaker there is usually some AC coupling: a capacitor, or an amplifier that passes changes and blocks steady levels. A steady level is invisible to it. A change is not. The faster the climb, the bigger the push through the coupling.
We can compute that push. Think of the coupling as a first-order high-pass filter with corner frequency fc. Its time constant is RC = 1 / (2π fc). For a long steady ramp of slope s, the output rises to about s × RC and then holds. With fc = 20 Hz, RC = 7.96 ms. The fast ramp has slope 0.9 V / 0.2 s = 4.5 V/s, so the thump is about 4.5 × 0.00796 = 36 mV. The slow ramp has 2.25 V/s and about 18 mV. Half the slope gives half the thump, which is 6 dB less.
The warm line is VAG climbing from 0 V to 0.90 V. The red line is what the speaker feels after the coupling. Choose the ramp, move the corner, and try the mute.
Toy model: the coupling is one first-order high-pass filter, solved in 1 ms steps. The 0.90 V target and the 200 ms and 400 ms ramp times are the SGTL5000 datasheet’s. Real parts differ: the SGTL5000 and the CS43L22 both have capless headphone outputs, and the true thump depends on the board.
Read the device. Switch to the slow ramp and the red peak halves. Raise the corner frequency and it shrinks, because a stiffer coupling follows the ramp less. Disconnect the output, and the speaker feels nothing at all. That last case is the cheapest trick in this lesson. A muted output cannot pop.
The reference is not the only trouble. A volume change is a change in voltage too. The SGTL5000 gives you a zero-cross detector (ZCD) for the headphone amplifier: the datasheet says it “prevents any volume change until a zero-volt crossing of the audio signal is detected”. A step in gain at a zero crossing moves the signal by almost nothing, so nothing audible happens. AN3663 enables it with CHIP_ANA_CTRL. The DAC volume ramps by itself: AN3663 notes that the DAC volume ramp is handled by the chip.
The Cirrus Logic CS43L22, a stereo DAC with a headphone amplifier, lists “Pop and Click Suppression” as a feature of its design. The same ideas return in every codec: slow the reference, mute while you change things, and move gain at zero crossings.
Suppose, as a toy, that the DAC swings 0.80 V above and below VAG for full-scale samples. The sample 0 gives 0.90 V. The sample 12,000 is 12,000 / 32,768 = 0.366 of the positive range, so it gives 0.90 + 0.366 × 0.80 = 1.193 V. The sample −32,768 gives 0.90 − 0.80 = 0.10 V.
Look at what this means for the first sample of a song. If the stream stops at digital zero and then jumps to 12,000, the output jumps 0.293 V between two samples, in 20 µs at 48 kHz. That is a step the speaker will hear even though the reference is perfectly settled.
Symptom. The power-up is clean, but each time a song begins or ends there is a small click.
Measurement. Put a scope on the output and trigger on the first non-zero sample. You will see a single-sample step. Print the first four samples your firmware sends: if the first is far from zero, the stream begins mid-wave.
Fix. Fade the samples in and out in firmware over a few milliseconds, starting and ending at zero. At 48 kHz, 5 ms is 240 samples. Do the same for pause and resume. The chip’s own volume ramp and zero-cross detector help with gain changes; they do not shape the start of your stream.
Chapter 4
Slide the loudness of a real voice up and down between the noise floor and the ceiling, and learn where to park it
Picture a room with a floor that is noisy and a ceiling that is hard. A tall person standing in the room hits the ceiling. A short person is lost in the rumble of the floor. You cannot change the room. You can only choose the height of the platform they stand on.
An ADC is that room. The hard ceiling is full scale, 0 dBFS. The decibels relative to full scale (dBFS) scale says how far a level sits below that ceiling: −6 dBFS is half the ceiling voltage. The noisy floor is the converter’s noise, near −85 dBFS for our chip. Your gain settings are the platform.
A talker is not one level. A whisper is quiet. A shout is a hundred times larger in voltage. Take two toy peak voltages at the microphone output: a whisper at 0.25 mV and a shout at 25 mV. Their ratio is 100, so the span is 40 dB.
The SGTL5000 full-scale peak is 0.80 V. With no gain at all, the whisper sits at 20 log10(0.00025 / 0.80) = −70.1 dBFS and the shout sits at −30.1 dBFS. The whisper is only 15 dB above the noise. That is the hiss from Chapter 0.
Add the mic amplifier at +20 dB. All voltages grow 10 times. The whisper is 2.5 mV, at −50.1 dBFS. The shout is 250 mV, at −10.1 dBFS. Both fit. The whisper is now 35 dB above the floor. The shout still has 10 dB of space to the ceiling.
Now try +40 dB. The shout becomes 2.5 V, far over the 0.80 V ceiling. The top of the shout is sliced flat. You fixed the hiss and made a new problem.
Headroom is the distance, in dB, from your loudest expected peak to the ceiling. It is your safety margin. Too little and a surprise (a laugh, a clap, a dropped cup) clips. Too much and you throw away resolution, because the quiet parts sink toward the floor. A common rule of thumb is to place the loudest expected peak near −6 dBFS, about half the ceiling. Choose your own margin from what your product records.
Gain staging is the habit of setting the gain at each stage, from the microphone to the output, so that no stage clips and no stage buries the signal in its own noise. Each amplifier and the ADC has a ceiling of its own. If an early stage clips, turning down a later gain does not bring the peaks back.
In the SGTL5000 the stages you control on the record road are the mic amplifier (0, +20, +30, +40 dB in CHIP_MIC_CTRL) and the ADC amplifier (0 to +22.5 dB in 1.5 dB steps in CHIP_ANA_ADC_CTRL). The total gain is their sum.
The bar spans a whisper (bottom) to a shout (top). The red zone is above full scale. The purple zone is the converter noise. Change the gains until the whole bar sits in the clear band between them.
Illustrative sources: a 0.25 mV peak whisper and a 25 mV peak shout at the mic output. The 0.80 V peak full scale is the SGTL5000 limit at VDDA = 1.8 V; the −85 dBFS floor reads the datasheet’s 85 dB ADC SNR. The gain steps (0, 20, 30, 40 dB and 1.5 dB) are the chip’s.
Press the button. It looks for the largest total gain that keeps the shout at or below −6 dBFS. The answer is +20 dB at the mic and two ADC steps, +23 dB in all. The shout lands at −7.1 dBFS and the whisper at −47.1 dBFS, 38 dB above the floor. A setting of 0 dB at the mic and the full 22.5 dB in the ADC gives almost the same total. In this toy they match. In a real chip they do not, and Chapter 5 shows why.
Your product may meet a quiet voice in a quiet room, then a loud voice in a loud one. A fixed gain cannot serve both. The usual answers are: pick the gain for the loudest case and accept more hiss in quiet cases; change the gain at run time with an automatic gain control; or add the chip’s own AVC block (automatic volume control), which has a programmable threshold, attack rate and decay rate. We do not need those details yet. The point is that gain staging is a decision, with the ceiling on one side and the floor on the other.
Do not guess a peak. Measure it. A short loop over a buffer finds the largest absolute sample, and one line turns it into dBFS.
c/* peak meter for 24-bit samples held in int32_t (value range -8388608 .. 8388607) */ float peak_dbfs(const int32_t *x, int n) { int32_t peak = 0; for (int i = 0; i < n; i++) { int32_t a = x[i] < 0 ? -x[i] : x[i]; if (a > peak) peak = a; } return 20.0f * log10f((float)peak / 8388608.0f); /* 0 dBFS at full scale */ }
Run it on every block of samples and keep the highest value. A reading near 0 dBFS means you are about to clip. A reading below −40 dBFS means you are wasting the ladder.
Symptom. Speech is clean, but a laugh, a clap or a shout crackles.
Measurement. Record the loud event and count how many samples sit at the largest code, 8,388,607, or the smallest, −8,388,608. A run of three or more in a row is clipping, since a real wave does not stay at its peak for three samples at 48 kHz. Check also the stage before the ADC: if the mic amplifier is at +40 dB it may clip first, and the ADC will see a flat top that is already damaged.
Fix. Lower the gain by 6 dB (halve the voltage), record the same event again, and re-measure. Repeat until the peak sits near −6 dBFS. If the quiet parts then hiss, you need a better microphone or an automatic gain stage, not a hotter converter.
Chapter 5
Compare a gain applied before the ADC with the same gain applied after it, and measure why the first one wins
You photograph a faint star with a phone. The picture is dark and grainy. You open an editor and drag the brightness slider to the right. The star gets brighter. The grain gets brighter too. Nothing new appears.
Now imagine you could instead hold a lens in front of the camera, so that more light reaches the sensor before the picture is taken. The star is brighter, and the grain from the sensor stays the same size. That is the difference between gain before the converter and gain after it.
On the record road you can add gain in two places. The analog gain stage (the mic amplifier and the ADC’s PGA) acts on the voltage before it is measured. The digital gain acts on the numbers after the ADC: your firmware, or a digital volume control, multiplies each sample.
Two noises matter. The first is the noise that arrives with the signal and in the first amplifier. Call it the analog noise. The second is the converter’s own noise, from the rounding and its circuits. We use the −85 dBFS floor from Chapter 2. Both are fixed by the hardware. The question is what each gain does to them.
Work in dBFS at the ADC pin, with no gain. Let the voice be S = −60 dBFS. Let the analog noise be na = −96 dBFS. Let the ADC noise be nq = −85 dBFS. These two noise values are toys, chosen to look like a real chip. Noise powers add, so we add them in linear units.
No gain. The total noise is 10 log10(10−9.6 + 10−8.5) = −84.7 dBFS. So SNR = −60 − (−84.7) = 24.7 dB.
+30 dB of digital gain. The numbers are multiplied after the ADC, so the signal and both noises rise 30 dB. The gap stays 24.7 dB. The voice is louder, and no cleaner.
+30 dB of analog gain. The signal and the analog noise rise 30 dB, to −30 and −66 dBFS. The ADC adds its noise after the amplifier, so it stays at −85. The total noise is 10 log10(10−6.6 + 10−8.5) = −65.95 dBFS. SNR = −30 − (−65.95) = 35.9 dB. That is 11 dB better than digital gain, for the same loudness.
There is a limit. With very large analog gain the ADC noise stops mattering and the analog noise rules. Then SNR approaches S − na = −60 + 96 = 36 dB. No gain can beat the noise that came in with the signal. The analog amplifier’s job is only to lift the signal above the ADC’s noise.
The curves show SNR as the gain grows from 0 to 40 dB. Blue is gain before the ADC. Warm is gain after it. The red line marks the gain where the signal reaches the ceiling and clips. Move the voice level and the gain.
Toy model: analog noise −96 dBFS and ADC noise −85 dBFS, both referred to the ADC pin at 0 dB gain. The −85 reads the datasheet’s 85 dB SNR; the −96 is invented to show the shape. SNR = signal minus the power sum of the noises, computed in linear units.
Set the voice to −60 and the gain to 30. You will see 35.9 dB for analog and 24.7 dB for digital. Slide the voice louder and the gap shrinks, because the ADC noise matters less once the signal is far above it. Slide the gain up until the red line and the analog curve is cut off by clipping: the best gain is just below that line.
Digital gain is not wrong. It is exact, repeatable, and free of added analog noise. It is the right tool for a user volume knob, for matching two microphones, and for a last small trim after the signal is already healthy. The rule of thumb: fix the level with analog gain, then trim with digital gain.
When you do apply digital gain in C, guard against overflow. Multiplying a 16-bit sample by a gain wider than one can leave the 16-bit range. The fix is to saturate (pin to the limits) and not wrap. On Cortex-M the CMSIS intrinsic __SSAT does this in one instruction.
c/* gain_q12: 4096 = 1.0 (0 dB), 8192 = about +6 dB, 16384 = about +12 dB */ static inline int16_t apply_gain(int16_t x, int32_t gain_q12) { int32_t y = ((int32_t)x * gain_q12) >> 12; /* 32-bit product, no overflow */ return (int16_t)__SSAT(y, 16); /* pin to -32768..32767 */ }
Without the saturation, a sample of 30,000 times 1.5 would wrap around to a large negative number and make a loud crack. A crack from wrapping is far uglier than clipping. Fixed-point arithmetic is the subject of the later lesson on DSP on a Cortex-M.
The datasheet adds a practical note. On the mic path, the 0 dB setting has a THD (total harmonic distortion) that is typically around 65 dB, and other gain settings do better. A real chip is not a perfect amplifier, so test your gain settings on the real board.
Move the voice louder, to S = −40 dBFS. Add 20 dB. Digital gain leaves the SNR at S minus the noise sum with no gain: −40 + 84.67 = 44.7 dB. Analog gain raises the signal to −20 and the analog noise to −76 dBFS. The total noise is 10 log10(10−7.6 + 10−8.5) = −75.48 dBFS, so the SNR is −20 + 75.48 = 55.5 dB. The analog route is still 10.8 dB better. The louder voice moves the starting SNR up, and analog gain keeps its lead.
Symptom. With the microphone far from the speaker, the hiss grows every time the user turns the volume up.
Measurement. Record two seconds of room silence. Measure its rms in dBFS. Apply 6 dB of digital gain and measure again. If the hiss rose by exactly 6 dB, all the noise was already in the numbers. Now raise the analog gain by 6 dB and measure a third time. If the hiss rose by less than 6 dB, part of it came from the ADC and the analog gain beat it.
Fix. Move gain into the analog stages up to the headroom limit from Chapter 4. Past that, only a quieter microphone and amplifier input, shorter wires or better grounding can help. No register fixes noise that arrived with the voice.
Chapter 6
Read every byte on the two control wires, and see what a missing acknowledge looks like
You knock on a door in a long corridor of doors. You call out a name. If the person behind the door is home, they say “yes”. Then you pass a note through the slot, one word at a time, and after every word they say “got it”. If no one says “yes”, you stop, because there is nobody to hear the rest.
That is I2C (inter-integrated circuit, said “I squared C”). It is how your microcontroller changes every codec setting in this lesson. The corridor has two wires: SCL, the clock, which the master (your microcontroller) drives, and SDA, the data, which master and slave share.
Both wires use open-drain outputs: a chip can pull a wire to ground, and it can let go. It cannot push it high. A pull-up resistor on each wire pulls it high when nobody holds it low. This is why many devices can share the wires without a fight, and why a missing pull-up gives a bus that is stuck.
One bit travels per clock pulse. The data wire may change only while the clock is low. It is read while the clock is high. Two special moments break this rule on purpose. A START is SDA falling while SCL is high. A STOP is SDA rising while SCL is high. Masters make both; slaves never do.
Every byte is eight bits, most significant bit first, followed by a ninth clock pulse for the acknowledge. During that ninth pulse the receiver pulls SDA low. That is an ACK (“got it”). If SDA stays high, that is a NACK (“no one answered, or I cannot take more”). UM10204, the I2C specification, defines both. So each byte costs nine clocks, not eight.
Every I2C chip has a 7-bit address. The SGTL5000 datasheet says the address is 0n01010, where n comes from the pin CTRL_ADR0_CS. With the pin low it is 0001010, which is 0x0A. With the pin high it is 0101010, which is 0x2A. (The 20-pin package is always 0x0A.)
On the wire, the address takes the top seven bits of the first byte and the last bit says read (1) or write (0). So 0x0A write becomes 0x0A × 2 = 0x14, and 0x0A read becomes 0x15. Mixing up the 7-bit address and this 8-bit byte is the most common I2C bug there is.
The SGTL5000 has more registers than one byte can name, so each register has a 16-bit address, and each register holds 16 bits of data. Here is the datasheet’s write recipe, in order: START, the device address with write, two bytes of register address (most significant first), two bytes of data (most significant first), STOP. A read sends the register address, then a repeated START and the device address with read, then the chip returns two bytes.
Take headphone volume. Register CHIP_ANA_HP_CTRL is at 0x0022. Writing 0x7F7F sets both channels to the quietest step, −51.5 dB. The five bytes are 14 00 22 7F 7F.
Pick a transaction, an address and a bus speed. Pink bits come from the master. Blue bits come from the codec. Try the wrong address and watch the first acknowledge fail.
A model of the bus drawn from the datasheet recipe: the codec on the bus has its CTRL_ADR0_CS pin low, so only 0x0A answers. The CHIP_ID low byte (revision) is shown as rr. The datasheet allows an I2C clock up to 400 kHz. Times count nine clocks per byte and ignore the START and STOP.
Count the time. A five-byte write is 45 clocks. At 400 kHz each clock is 2.5 µs, so the write takes 112.5 µs. At 100 kHz it takes 450 µs. A start-up sequence of ten such writes costs about 1.1 ms at 400 kHz. That is nothing, until you try to change a volume 48,000 times a second. Control is slow and for settings. Samples go over I2S.
A NACK on the very first byte means nobody owns that address. Check four things in order: the 7-bit versus 8-bit address, the address pin, the power and MCLK (the datasheet gives a minimum time between supplies and clock being present and the first communication), and the pull-ups. A NACK on a later byte means the chip heard its name but refused the data.
The device also has an auto-increment feature: you may keep sending data pairs without a new register address. That halves the cost of loading a block of consecutive registers.
A read has two halves. The master first writes the register address, then repeats START and asks for data. To read CHIP_ID (0x0000) the bytes are: 0x14 (address, write), 0x00, 0x00 (the register), a repeated START, 0x15 (address, read). The codec then drives SDA with two bytes, 0xA0 for the part ID and the revision byte. The master pulls SDA low after the first byte (ACK, “send more”) and leaves it high after the second (NACK, “enough”). Six bytes, 54 clocks, 135 µs at 400 kHz.
Symptom. HAL_I2C_Mem_Write returns HAL_ERROR or HAL_TIMEOUT.
Measurement. Look at the wires with a logic analyzer, and sort what you see into three cases. One: clock pulses with a NACK on byte one. Nobody answered; check the address, the pin, the power and the MCLK. Two: no clock pulses at all. The peripheral or its pins are not configured, or a pin is in the wrong alternate function. Three: SDA stuck low. A slave is holding the bus, often after a reset in the middle of a transfer.
Fix. For case one, fix the cause and retry once. For case three, many drivers pulse SCL up to nine times until the slave releases SDA, then send STOP; check your MCU’s reference manual for the recipe. Always log the error with the register that failed, so a field report says where.
Chapter 7
Put nine start-up steps in the right order, and watch the scope show you every mistake as a pop
A theatre crew raises the curtain only after the actors stand in place and the lights are on. If the curtain goes up first, the audience sees the crew running about. A codec start-up is the same. The pop is what the audience sees when you raise the curtain too early.
In Chapter 3 we found the cause: the output must never see a change in voltage that the music did not ask for. In Chapter 6 we found the tool: register writes over I2C. This chapter joins the two. The job is to write the registers in an order that keeps a muted output muted until everything behind it is calm.
NXP’s programming note AN3663 gives the SGTL5000 start-up as code. Read it as a story with four acts.
Why does the order matter? Each step answers one cause of a pop.
Nine steps wait below. Tap them into the order you choose. When all nine are placed, the scope shows what the headphones would hear. Tap a placed step to remove it. Find an order with zero pops.
Tap a step to add it. Tap a placed step to take it out. The scope draws time from left to right; the long gap is the wait for the reference.
A model. The register values (0x004E, 0x004F, 0x6AFF, 0x0073, 0x7F7F) and the rule that outputs stay muted during configuration are from AN3663; the 500 ms wait is the Linux driver’s VAG delay. Step durations other than the wait, and the size and shape of each pop, are illustrative: the model shows which cause makes which kind of pop, not millivolts measured on a board.
Powering off can pop too. The safe order mirrors start-up: ramp the volume down in steps, mute, power down the amplifier and converters, and let VAG ramp down before you remove supplies. The Linux driver defines SGTL5000_VAG_POWERDOWN_DELAY as 500 ms for this wait, and it carries a comment that the longer it waits, the smaller the pop. Never cut MCLK or power while the output is live and unmuted.
One more trap sits outside the chip. A reset of the microcontroller does not reset the codec, because the codec has its own power. After a warm reset, the codec may be playing at full volume, unmuted, with your old routing. The first thing a reset-time driver must do is mute. The Linux driver carries a warning for this: a VAG left powered from before “may create a loud pop even with all outputs muted”.
A safe start-up is not free. Add it up: the 500 ms wait for the reference, about 10 ms for the register writes, and about 115 ms for the unmute ramp from Chapter 8. The user waits about 0.6 seconds from power-on to sound. The datasheet says the normal ramp takes about 200 ms against about 400 ms with SMALL_POP, so the faster ramp saves time and, in our toy model, doubles the pop.
That is a product decision, not a coding one. A voice assistant may accept 0.6 s. A camera shutter click may not. Whatever you pick, write the number in the code comment beside the delay, and say why.
Symptom. A cold power-up is clean. After a watchdog or button reset of the microcontroller, the board pops.
Measurement. Trigger a scope on the first I2C byte after the reset. The codec was still powered, with its outputs unmuted and its old volume. Your fresh start-up then rewrites the reference and routing under a live output.
Fix. Make mute the first write after every boot, before any other configuration. Ramp the volume down if the old volume is high. Then run the full start-up. If your board lets the microcontroller control the codec’s supply or reset, cycling that is cleaner still.
Chapter 8
Turn bit fields into hex values, then turn the start-up recipe into small C functions you can test
A recipe card says “add a pinch of salt”. A firmware driver must say exactly which register, which bits, which value, and in what order. The work of this chapter is the translation from the datasheet’s tables to C that a machine can run, and that a person can check.
Each SGTL5000 register is 16 bits wide. Bits are grouped into fields: a group of neighbouring bits that carries one number. The datasheet names the bits as high:low, so “7:4” means bits 7, 6, 5 and 4. To read a field, shift the register right by the low bit number and mask to the field width.
Three registers from this lesson show the idea. CHIP_ANA_ADC_CTRL (0x0020) holds the ADC amplifier: bits 3:0 are the left gain, bits 7:4 are the right gain, and bit 8 shifts both ranges down by 6.0 dB. CHIP_MIC_CTRL (0x002A) holds the mic amplifier in bits 1:0, the bias voltage in 6:4 and the bias resistor in 9:8. CHIP_ANA_HP_CTRL (0x0022) holds the left headphone volume in bits 6:0 and the right in bits 14:8; its reset value is 0x18 in each, which is 0 dB.
The device below shows these three registers as sixteen switches. Click a bit to flip it. Greyed bits are reserved and read only. The read-out decodes every field and prints the five I2C bytes that write the value.
Choose a register. Click bits, or press a preset. Coloured underlines mark fields. Watch the hex value, the decoded gain, and the bytes.
Field positions, reset values and decodes are from the SGTL5000 datasheet (Rev. 6.0), tables 24, 25 and 29. The bytes assume the codec at 0x0A and a 16-bit register address sent most significant byte first, as in Chapter 6.
Keep the driver in four layers, from the wire up. Each layer knows about the one below it only. The names below are the ones we use; any consistent names work.
Here is the bus layer and the modify helper, written for an STM32 with the HAL library. The function HAL_I2C_Mem_Write sends the device address, then the register address (here two bytes, most significant first), then the data bytes, which is exactly the frame from Chapter 6. Pass it the 7-bit address shifted left.
c#define SGTL_ADDR (0x0A << 1) /* 7-bit 0x0A, shifted: HAL wants the 8-bit form */ extern I2C_HandleTypeDef hi2c1; static int sgtl_write(uint16_t reg, uint16_t val) { uint8_t d[2] = { (uint8_t)(val >> 8), (uint8_t)val }; /* most significant byte first */ return HAL_I2C_Mem_Write(&hi2c1, SGTL_ADDR, reg, I2C_MEMADD_SIZE_16BIT, d, 2, 20) == HAL_OK ? 0 : -1; } static int sgtl_read(uint16_t reg, uint16_t *val) { uint8_t d[2]; if (HAL_I2C_Mem_Read(&hi2c1, SGTL_ADDR, reg, I2C_MEMADD_SIZE_16BIT, d, 2, 20) != HAL_OK) return -1; *val = (uint16_t)(d[0] << 8 | d[1]); return 0; } static int sgtl_modify(uint16_t reg, uint16_t mask, uint16_t bits) /* mask = bits we own */ { uint16_t v; if (sgtl_read(reg, &v)) return -1; return sgtl_write(reg, (v & ~mask) | (bits & mask)); }
A note on naming. AN3663’s own Modify takes a mask of the bits to keep (it ANDs with it), the opposite of the mask above. Pick one meaning, write it in a comment, and keep to it.
The 20 ms timeout is a choice. A single write takes 112.5 µs at 400 kHz. A timeout is not a delay: it only says how long to wait before giving up. When it expires, return an error. Never ignore the result, because a lost write is the silent half of a bug (Chapter 7).
The start-up of Chapter 7 is a list of writes. Hold it as data in a table, not as thirty lines of code. A table is easy to compare with the datasheet, easy to print, and easy to test. These rows follow AN3663 for VDDIO = 3.3 V, VDDA = 1.8 V and an externally driven VDDD; other supplies change some rows, so check the note for yours.
ctypedef struct { uint16_t reg, val; uint16_t wait_ms; } step_t; static const step_t init_tbl[] = { { 0x0030, 0x4260, 0 }, /* CHIP_ANA_POWER: startup supplies off (VDDD external) */ { 0x0028, 0x004E, 0 }, /* CHIP_REF_CTRL: VAG = 0.9 V, bias -50% */ { 0x002C, 0x0322, 0 }, /* CHIP_LINE_OUT_CTRL */ { 0x0028, 0x004F, 500 }, /* slow VAG ramp (SMALL_POP), then wait for it */ { 0x0024, 0x0133, 0 }, /* CHIP_ANA_CTRL: zero-cross on; outputs stay muted */ { 0x0030, 0x6AFF, 0 }, /* CHIP_ANA_POWER: LINEOUT, HP, ADC, DAC on */ { 0x0002, 0x0073, 0 }, /* CHIP_DIG_POWER: I2S in/out, DAP, DAC, ADC */ }; int codec_start(void) { uint16_t id; if (sgtl_read(0x0000, &id) || (id >> 8) != 0xA0) return -1; /* CHIP_ID: is anyone home? */ for (unsigned i = 0; i < sizeof init_tbl / sizeof init_tbl[0]; i++) { if (sgtl_write(init_tbl[i].reg, init_tbl[i].val)) return -2; if (init_tbl[i].wait_ms) HAL_Delay(init_tbl[i].wait_ms); } /* clocks (SYS_FS 48 kHz, MCLK 256*Fs) and routing go here, still muted */ return hp_unmute_ramp(0x18); /* last: unmute, then raise the volume */ } int hp_unmute_ramp(uint8_t target) /* 0x7F = -51.5 dB ... 0x18 = 0 dB ... 0x00 = +12 dB */ { if (sgtl_write(0x0022, 0x7F7F)) return -3; /* quietest step first */ if (sgtl_modify(0x0024, 1u << 4, 0)) return -3; /* MUTE_HP = 0 */ for (uint8_t v = 0x7F; v > target; ) { v--; if (sgtl_write(0x0022, (uint16_t)(v << 8 | v))) return -3; HAL_Delay(1); /* about 1 ms per half-dB step */ } return 0; }
Count the ramp. From 0x7F (−51.5 dB) to 0x18 (0 dB) is 103 steps of 0.5 dB. At 112.5 µs per write that is 11.6 ms of bus time, and with a 1 ms delay per step, about 115 ms of wall clock. Sounds quick. A listener hears a smooth fade-in, not a jump.
A last good habit: test the driver without hardware. Replace HAL_I2C_Mem_Write with a fake that records each (register, value) pair. Run codec_start() on your laptop and compare the list with the AN3663 order. The lesson on drivers and HALs and the lesson on testing firmware show how.
Symptom. The driver works when you step through it in the debugger. Free running, the first writes fail or the volume is wrong.
Measurement. The debugger adds delays that hide a timing bug. Log the return value of every write with a timestamp, and look at the gap between the supply coming on, MCLK starting, and the first write. A first write that arrives too early gets no ACK.
Fix. Put the waits in the table, as data, with a comment naming the datasheet or driver line that sets them. Retry the ID read a few times with a short delay before you report the codec missing. Never rely on a delay that exists only because the debugger was attached.
The driver calls two HAL functions. On a laptop, replace them with fakes that record what they were asked to do. Then the whole start-up becomes an ordinary test.
c/* host test: record every register write instead of using I2C */ static struct { uint16_t reg, val; } wlog[64]; static int nlog; HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *h, uint16_t dev, uint16_t reg, uint16_t sz, uint8_t *d, uint16_t n, uint32_t to) { wlog[nlog].reg = reg; wlog[nlog].val = (uint16_t)(d[0] << 8 | d[1]); nlog++; return HAL_OK; } /* test: after codec_start(), the unmute (CHIP_ANA_CTRL write) must come after every power write */
Now you can assert the order. The last write to CHIP_ANA_POWER must come before the first write that clears MUTE_HP. A test like this is the cheapest pop detector you will ever own.
Chapter 9
Review the numbers, the checklist and the core code, then see where to go next in the audio track
You can now follow a codec from the pin to the register. A microphone voltage rises through a mic amplifier and a PGA to meet an ADC that rounds it onto a ladder. The numbers cross I2S to your microcontroller and come back to a DAC that rests at a middle voltage. Firmware steers all of it over I2C, and the order of the writes decides whether the headphones thump.
A codec holds an ADC, a DAC, amplifiers, a reference voltage (VAG) and an I2C control port. Pops come from voltage steps the music did not ask for, so start the chip in a fixed order and keep its outputs muted while you configure it. Hiss comes from a signal too close to the noise floor, and clipping from a signal that hits the ceiling, so stage the gain: aim the loudest peak near −6 dBFS, and add gain before the ADC, not after it. Every setting is a field in a 16-bit register, so build the driver in layers and test it without hardware.
| What | Number | Source |
|---|---|---|
| I2C address | 0x0A (pin low), 0x2A (pin high); bytes 0x14 write, 0x15 read | SGTL5000 datasheet |
| Register and data width | 16-bit address, 16-bit data, most significant byte first | SGTL5000 datasheet, AN3663 |
| Part ID | CHIP_ID (0x0000) high byte 0xA0 | SGTL5000 datasheet, Table 16 |
| I2C clock, maximum | 400 kHz; a 5-byte write is 45 clocks, 112.5 µs | Datasheet timing; arithmetic |
| ADC full scale | 1.60 V peak to peak at VDDA = 1.8 V (0.80 V peak) | SGTL5000 datasheet, Table 4 |
| ADC SNR, line in | 85 dB at −60 dB input, about 13.8 effective bits | Datasheet, Table 5; arithmetic |
| Ideal N-bit ADC | SNR = 6.02 N + 1.76 dB (98.08 dB at 16 bits) | Analog Devices MT-001 |
| Mic amplifier gain | 0, +20, +30, +40 dB | SGTL5000 datasheet, Table 29 |
| ADC amplifier gain | 0 to +22.5 dB in 1.5 dB steps, or −6 to +16.5 dB | SGTL5000 datasheet, Table 24 |
| Headphone volume | +12 dB (0x00) to −51.5 dB (0x7F), 0.5 dB steps; reset 0x18 = 0 dB | SGTL5000 datasheet, Table 25 |
| VAG | 0.800 V to 1.575 V in 25 mV steps; 0.9 V is code 4 (0x004E) | SGTL5000 datasheet; AN3663 |
| VAG ramp | about 200 ms; about 400 ms with SMALL_POP | SGTL5000 datasheet, Table 28 |
| Driver waits | 500 ms after VAG up and after VAG down | Linux sgtl5000 driver |
| Unmute ramp | 103 half-dB steps from 0x7F to 0x18, 11.6 ms of bus time | Arithmetic from the table above |
c/* the whole lesson in eleven lines */ power_on_supplies(); start_mclk(); HAL_Delay(2); /* Ch 7: chip ready */ if (sgtl_read(0x0000, &id) || (id >> 8) != 0xA0) return ERR_NO_CODEC; /* Ch 6: ACK and ID */ sgtl_write(CHIP_REF_CTRL, 0x004E); /* Ch 3: VAG = 0.9 V */ sgtl_write(CHIP_REF_CTRL, 0x004F); HAL_Delay(500); /* slow ramp, then wait */ sgtl_write(CHIP_ANA_POWER, 0x6AFF); /* Ch 1: power the road */ sgtl_write(CHIP_DIG_POWER, 0x0073); set_routing_and_clocks(); /* still muted (default) */ sgtl_modify(CHIP_MIC_CTRL, 0x3, 1); /* Ch 4: mic +20 dB */ sgtl_modify(CHIP_ANA_ADC_CTRL, 0xFF, 0x22); /* Ch 5: +3 dB each side */ hp_unmute_ramp(0x18); /* Ch 7: unmute last */
Every codec has this shape: converters, amplifiers, a reference, a control port, a mute. Other parts differ in register names and ramp times. The first pages of the Cirrus Logic CS43L22 datasheet, a stereo DAC with headphone amplifier, list the same families of tools: pop and click suppression, a charge pump, a negative voltage regulator and soft-ramp volume. Learn one chip deeply with its programming note, and the next one takes an afternoon.
Part of the Firmware from Zero to Expertise series, audio track. This lesson uses no course slides. Every number comes from a primary source or is labelled a toy.
Now press Present or Teach and explain, from memory, how a muted codec wakes without a pop and why gain belongs before the ADC. Then go back to the first device and park the voice again.