TactivergeOffline

Level 4 Engineering Complex Systems · Term 3: Signals and Computing Hardware

Signals in time and frequency, and the digital hardware that processes them: sampling, quantisation and aliasing; spectra, Fourier series and the DFT; moving-average and IIR filters; then down to doped silicon and CMOS gates, and back up through state machines, instruction sets and register-transfer design to a processor you program and speed up. All browser-based simulation.

In this file: 28 lessons across weeks 19–27, with 145 practice questions (questions only, no answers).

Model, control, optimise and benchmark dynamic engineering systems using calculus, control theory, signal processing and computer architecture, with explicit assumptions and reproducible evidence. Levels describe what you can do, not your age. About About 3–4 hours a week: 1.5–2 hours of lessons and worked problems, 1–1.5 hours of simulation and 30 minutes of write-up..

Week 19: Continuous and discrete signals

This week you will

From a wave to a list of numbers

Your phone's microphone hears a smooth, endless pressure wave. Your phone stores a list of whole numbers. What happened in between?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Every sensor reading a robot uses, every sound you stream and every heartbeat a smartwatch logs is a signal that was sampled. Before you can filter, compress or analyse a signal you have to know exactly what the numbers in the list mean: which instant each one belongs to, and what is lost between them.

Goals

Predict

A temperature sensor is read at fs = 4 Hz, starting at t = 0. At what time is sample x[10] taken?

  1. 10 s
  2. 2.5 s
  3. 0.4 s
  4. 40 s

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, define x(t) = 2·cos(2π·3·t), pick fs = 24 Hz and build the list x[n] = x(n/fs) for n = 0…23. Print t and x[n] side by side, then repeat with fs = 6 Hz. How many samples land in each cycle of the wave?

What the interactive shows, in words

Without the Code Lab: for x(t) = 2cos(2π·3t) at fs = 24 Hz there are 8 samples per cycle, giving values 2, 1.41, 0, −1.41, −2, −1.41, 0, 1.41 repeating. At fs = 6 Hz there are only 2 samples per cycle, alternating 2 and −2: the shape between them is lost.

Understand

Two independent choices: time and value

A continuous-time signal x(t) has a value at every instant. A discrete-time signal x[n] exists only at the sample instants. Separately, a value can be analog (any real number) or quantised (one of a fixed set of levels). A digital signal is both discrete in time and quantised in value. The two steps are done by one chip, an ADC, but they cause different errors: sampling can cause aliasing, quantising adds rounding noise.

x[n] = x(nT)

Uniform sampling takes one value every T seconds; the sample rate is fs = 1/T. Sample n is the value at t = nT. The list x[0], x[1], x[2], … is all a processor ever sees. Square brackets mean an integer index; round brackets mean real time. Mixing them up is the commonest source of off-by-a-factor bugs in signal code.

Energy and power

For a sequence, energy E = Σ x[n]², the sum of squared samples (for a voltage across 1 Ω this is proportional to the energy delivered). Signals that go on for ever, like a sine wave, have infinite energy, so we use average power P = mean of x². A sinusoid of amplitude A has P = A²/2, and its RMS value √P = A/√2 is the steady voltage that would deliver the same power.

Explain it another way: intuitive

Sampling is like a strobe light in a dark room: you only see the dancer at each flash. Between flashes you have to guess, and if the flashes are too slow your guesses will be wrong.

Explain it another way: technical

An ideal sampler multiplies x(t) by a train of impulses spaced T apart, keeping x(nT). A real ADC holds the input on a small capacitor (sample-and-hold) for a short aperture, then converts the held voltage to a code.

Explain it another way: mathematical

x[n] = x(nT), n ∈ ℤ, T = 1/fs. For x(t) = A·cos(2πft + φ), x[n] = A·cos(2π(f/fs)n + φ): only the ratio f/fs matters to the samples. Energy E = Σₙ |x[n]|²; average power P = lim (1/N)·Σ_{n=0}^{N−1} |x[n]|².

Explain it another way: applied

A heart-rate chest strap samples its ECG electrodes at a few hundred hertz. Its firmware stores samples with time stamps n/fs, and its software computes the power in a window to detect whether the strap is touching skin at all.

Try these examples

Example 1

x(t) = 3·cos(2π·2·t) is sampled at fs = 8 Hz. List x[0] to x[3].

The worked solution is in the online lesson.

Example 2

What is the energy of x = [1, 2, −1, 0]?

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Which signal is discrete in time but NOT quantised?

  • A microphone voltage on a wire
  • A list of exact real-number samples held in a spreadsheet
  • The 12-bit codes from an ADC
  • A thermometer's mercury height

2. A signal is sampled at fs = 1 kHz from t = 0. At what time, in seconds, is sample x[250] taken?

Answer: s

3. x(t) = 3·cos(2π·2·t) is sampled at fs = 12 Hz, so x[n] = x(n/12). Find x[5] (to 2 decimal places).

Answer:

4. What is the energy E = Σ x[n]² of the sequence x = [2, −3, 1, 0, 1]?

Answer:

5. Code computes x[n] = sin(2π·5·n) for n = 0, 1, 2… and every value is (almost) zero. What went wrong?

  • sin is broken for whole numbers
  • It used n where it needed t = n/fs, so it sampled once per second, exactly on whole cycles of a 5 Hz wave
  • The amplitude is too small
  • It needs more samples

6. A voltage is v(t) = 3 + 5·sin(2π·100·t) volts. What is its RMS value, in volts (to 2 decimal places)?

Answer: V

Apply it

Pick any periodic quantity you can describe as a formula (a 50 Hz mains waveform, a 1 Hz breathing rhythm). Choose a sample rate, generate ten samples by hand or in code, and plot them as dots over the true curve. Explain in two sentences whether your sample rate shows the shape well.

Reflect

What information about a signal does a list of samples lose, and what extra number do you always need to keep alongside it?

Amplitude, frequency, phase

Two notes with exactly the same pitch and loudness can look completely different on an oscilloscope. Which one number changed?

About 30 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Sinusoids are the alphabet of signals. Mains electricity, radio carriers, motor vibrations and musical notes are all sinusoids or sums of them. Three numbers describe each one completely, and once you can read them you can read almost any oscilloscope trace.

Goals

Predict

You shift a sinusoid's phase by 90° without changing its amplitude or frequency. What happens to its average power?

  1. It doubles
  2. It halves
  3. It stays the same
  4. It drops to zero

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Start from 'Pure tone'. Change the amplitude, then the frequency, then the phase of component 1, and watch both views. Which slider changes the spectrum bar's height, which moves it, and which changes neither?

What the interactive shows, in words

The synthesiser adds three sinusoids. Amplitude changes the height of a component's spectrum bar, frequency moves the bar left or right, and phase changes the shape of the summed wave in time but leaves the bars and the power readout (sum of A²/2) unchanged.

Understand

Three numbers

x(t) = A·sin(2πft + φ). Amplitude A is the peak height. Frequency f (hertz) is cycles per second; the period T₀ = 1/f is the time for one cycle; angular frequency ω = 2πf is in radians per second. Phase φ says where in its cycle the wave is at t = 0. A phase of 90° turns a sine into a cosine.

Power is about the square

Average power over a period is the mean of x². For A·sin, sin² averages to 1/2, so P = A²/2. Add a constant offset D and P = D² + A²/2: the cross term 2DA·sin averages to zero. RMS = √P. UK mains is 230 V RMS, so its peak is 230·√2 ≈ 325 V.

Why sinusoids are special

Feed a sinusoid into a linear, time-invariant system (a spring, an RC circuit, a digital filter) and a sinusoid of the same frequency comes out, only scaled and shifted. That is why engineers describe systems by how they treat each frequency, and why the spectrum view you just used is so powerful.

Explain it another way: intuitive

Picture a point going round a wheel. Amplitude is the wheel's radius, frequency is how fast it turns, phase is where the point started. The wave is the point's height over time.

Explain it another way: technical

A sinusoid is the projection of a rotating phasor A·e^{j(ωt+φ)}. Phasors add like vectors, so two sinusoids of the same frequency always combine into one sinusoid of that frequency.

Explain it another way: mathematical

P = (1/T₀)∫₀^{T₀} (D + A·sin ωt)² dt = D² + (2DA/T₀)∫sin ωt dt + (A²/T₀)∫sin² ωt dt = D² + 0 + A²/2.

Explain it another way: applied

Power engineers quote RMS because it predicts heating: a 230 V RMS supply heats a kettle element exactly as much as a steady 230 V would, even though the voltage peaks at about 325 V.

Try these examples

Example 1

v(t) = 2 + 4·sin(2π·50·t) V. Find its period, mean, average power (1 Ω) and RMS.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Which property of a sinusoid does the phase φ change?

  • How tall it is
  • How many cycles per second it makes
  • Where in its cycle it is at t = 0
  • Its average power

2. A motor shaft vibrates at f = 25 Hz. What is its angular frequency ω, in rad/s (to 1 decimal place)?

Answer: rad/s

3. UK mains is 230 V RMS. What is its peak voltage, in volts (nearest volt)?

Answer: V

4. A signal is x(t) = 1 + 6·sin(2π·440·t). What is its average power (mean of x², as for a 1 Ω load)?

Answer:

5. 3·sin(2π·5t) + 4·cos(2π·5t) is…

  • A sinusoid at 5 Hz with amplitude 5
  • A sinusoid at 10 Hz
  • Not a sinusoid at all
  • A sinusoid at 5 Hz with amplitude 7

Apply it

In the synthesiser, set component 1 to amplitude 1 at 3 Hz and component 2 to amplitude 1 at 3 Hz with phase 180°. Predict the result before you look, then explain it with phasors. Where would engineers use this effect on purpose?

Reflect

Why do power engineers describe voltages by their RMS value instead of their peak?

Rounding to the nearest step

Why does a 16-bit recording sound clean but an 8-bit one hiss, when both sample just as fast?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Choosing an ADC is choosing how much rounding noise you can tolerate. Too few bits and a sensor's small changes vanish into the steps; too many and you pay in cost, power and speed. Engineers size this with one formula you can derive in five lines.

Goals

Predict

You upgrade an ADC from 8 bits to 9 bits. Roughly how much does the best-case signal-to-noise ratio improve?

  1. About 1 dB
  2. About 6 dB
  3. It doubles to twice as many dB
  4. About 12.5 %

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Start at 3 bits and full amplitude. Note the measured SNR, then add bits one at a time. Then go back to 8 bits and turn the amplitude down to 0.25. How many dB do you lose, and how many bits is that worth?

What the interactive shows, in words

The quantiser shows a sine wave and its staircase approximation. With 3 bits there are 8 levels and the measured SNR is about 20 dB; every extra bit adds about 6 dB, matching 6.02N + 1.76. Reducing the amplitude to 0.25 of full scale costs about 12 dB.

Understand

Steps and codes

An ideal N-bit ADC splits its input range V into 2^N equal steps of size Δ = V/2^N and outputs the code of the step the input falls in. A 12-bit ADC on a 3.3 V range has Δ = 3.3/4096 ≈ 0.81 mV. A rounding quantiser is never more than Δ/2 away from the truth.

Error behaves like noise

For a signal that wanders across many steps, the rounding error looks like random noise spread evenly between ±Δ/2, with power Δ²/12. That is why quantisation is often called quantisation noise, and why the SNR formula works. It fails for very slow or tiny signals, where the error follows the signal and shows up as distortion instead.

Use the whole range

The formula assumes a full-scale sine. A signal using a quarter of the range has 1/16 of the power but the same Δ, so it loses 20·log₁₀ 4 ≈ 12 dB: two bits' worth. Engineers add an amplifier in front of the ADC so the signal fills the range without clipping.

Explain it another way: intuitive

Measuring with a ruler marked only in centimetres, every reading is up to half a centimetre out. Finer marks (more bits) mean smaller errors, but only if the thing you measure is big enough to span many marks.

Explain it another way: technical

Each bit doubles the number of levels. Effective number of bits (ENOB) is quoted from measured SINAD: ENOB = (SINAD − 1.76)/6.02. Real converters lose a bit or two to thermal noise and nonlinearity.

Explain it another way: mathematical

Δ = V/2^N, |e| ≤ Δ/2, σₑ² = Δ²/12, SNR_dB ≈ 6.02N + 1.76 (full-scale sine). Using a fraction k of full scale subtracts 20·log₁₀(1/k) dB.

Explain it another way: applied

CD audio uses 16 bits: about 98 dB of SNR, more than the gap between a quiet room and a loud concert. Many microcontroller ADCs are 10 or 12 bits, plenty for a temperature sensor but marginal for audio.

Derivation: Where 6.02N + 1.76 dB comes from
  1. An N-bit quantiser spanning a full range of 2A (from −A to +A) has step Δ = 2A/2^N.

  2. Rounding error e lies between −Δ/2 and +Δ/2. If it is spread evenly (true for busy signals), its mean square is σₑ² = Δ²/12.

  3. A full-scale sine of amplitude A has power P = A²/2.

  4. SNR = P/σₑ² = (A²/2) / (4A²/(12·4^N)) = 1.5 · 4^N.

  5. In decibels: 10·log₁₀(1.5) + N·10·log₁₀(4) = 1.76 + 6.02N dB.

Try these examples

Example 1

An 8-bit ADC spans 0–5 V. Find Δ, the maximum error and the best-case SNR.

The worked solution is in the online lesson.

Example 2

You need 70 dB of SNR. How many bits?

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. An ideal 10-bit ADC spans 0 to 3.3 V. What is its step Δ, in millivolts (to 2 decimal places)?

Answer: mV

2. Adding one bit to an ideal ADC…

  • Halves Δ and adds about 6 dB of SNR
  • Halves Δ and doubles the SNR in dB
  • Adds 1 dB
  • Only matters for slow signals

3. Using SNR ≈ 6.02·N + 1.76 dB, what is the best signal-to-quantisation-noise ratio of an ideal 10-bit ADC for a full-scale sine wave, in dB?

Answer: dB

4. A full-scale sine on an ideal 12-bit ADC gives 74 dB SNR. The same ADC sees a sine at one tenth of full scale. About what SNR, in dB?

Answer: dB

5. When does 'quantisation error behaves like even, random noise' break down?

  • For a loud, busy music signal
  • For a very slow signal that changes by less than one step
  • Never
  • When N is large

Apply it

A load cell gives 0–20 mV and your microcontroller's 12-bit ADC spans 0–3.3 V. How many steps does the load cell span directly? Choose an amplifier gain to use most of the range without clipping, and say how many dB that recovers.

Reflect

When would you pick a 10-bit ADC over a 16-bit one, even though the 16-bit one is 'better'?

Week 20: Sampling and aliasing

This week you will

How fast is fast enough?

Film a spinning wheel and it can appear to turn slowly backwards. Is the camera lying, or are you?

About 30 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Get the sample rate wrong and no amount of clever software can recover the truth: the data is already corrupted. The Nyquist limit is the first number you check when you design any data logger, audio system or control loop.

Goals

Predict

A guitar note contains frequencies up to 5 kHz. What is the lowest sample rate that can represent it faithfully?

  1. 5 kHz
  2. Just over 10 kHz
  3. 2.5 kHz
  4. 50 kHz

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Keep fs = 20 Hz. Raise f from 1 Hz slowly. At what f does the dashed 'what the samples show' curve stop matching the blue signal? Then set f = 20 Hz exactly and explain what you see.

What the interactive shows, in words

In the sampler at fs = 20 Hz, the samples follow the signal faithfully until f reaches 10 Hz (the Nyquist frequency). Above that, the dots trace a slower false wave: at 12 Hz they look like 8 Hz. At exactly 20 Hz every sample has the same value, so the alias is 0 Hz.

Understand

The sampling theorem

If a signal contains no frequencies at or above B, sampling at fs > 2B keeps all its information: the original can be rebuilt exactly from the samples (by ideal interpolation). fs/2 is called the Nyquist frequency; 2B is the Nyquist rate. Below that, information is lost and, worse, disguised.

Why twice?

To capture a sinusoid you need at least a high sample and a low sample in every cycle, more than two per period. At exactly two samples per cycle you might hit only the zero crossings and see nothing at all. That is why the inequality is strict.

Real systems add margin

CD audio samples at 44.1 kHz to cover hearing up to about 20 kHz: Nyquist is 22.05 kHz, leaving room for an anti-aliasing filter to roll off. Control loops often sample 10–20 times faster than the dynamics they control, because they need the signal's shape, not just its frequency.

Explain it another way: intuitive

To know a swing's rhythm you have to glance at it at least twice per swing, once near each end. Glance less often and you could think it is swinging slowly when it is actually swinging fast.

Explain it another way: technical

Sampling makes copies of the spectrum centred on every multiple of fs. If the signal's band reaches past fs/2, neighbouring copies overlap and no filter can separate them afterwards.

Explain it another way: mathematical

cos(2πf·n/fs) = cos(2π(f + k·fs)·n/fs) for every integer k, and cos is even. So f, fs − f, fs + f, … all give identical samples. They are distinguishable only if we know f < fs/2.

Explain it another way: applied

Vibration-monitoring sensors on wind turbines sample at several kilohertz because bearing faults show up as high-frequency tones; sampling at 100 Hz would fold them into misleading low-frequency readings.

Try these examples

Example 1

An accelerometer measures vibrations up to 400 Hz. Which of 500 Hz, 1 kHz or 2 kHz would you choose?

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. An audio system samples at 48 kHz. What is its Nyquist frequency, in kHz?

Answer: kHz

2. A signal's highest frequency is 300 Hz. Which sample rate is the smallest of these that works?

  • 300 Hz
  • 600 Hz
  • 601 Hz
  • 450 Hz

3. A 330 Hz sinusoid is sampled at fs = 250 Hz. At what frequency (between 0 and fs/2) does it appear in the samples, in hertz?

Answer: Hz

4. A 20 Hz sinusoid is sampled at exactly 20 Hz. What do the samples show?

  • A 20 Hz wave
  • A 10 Hz wave
  • A constant: every sample lands at the same point of the cycle
  • Random values

5. A control loop's fastest dynamics are at 8 Hz and the rule of thumb is to sample 20 times faster. What sample rate, in Hz?

Answer: Hz

Apply it

List three signals on a small robot (wheel encoder ticks, battery voltage, a microphone for voice commands). Estimate each one's highest useful frequency and choose a sample rate with a margin. Which one costs the most memory per minute?

Reflect

Why is aliasing more dangerous than simply missing a frequency?

Predicting the impostor

A 900 Hz whistle is recorded at 1 kHz. Play it back and you hear a low hum instead. Exactly what pitch, and why?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

When a sensor reading shows an oscillation nobody can explain, the first question an experienced engineer asks is: could this be an alias? Being able to compute the exact impostor frequency lets you test that hypothesis in seconds.

Goals

Predict

A 70 Hz sinusoid is sampled at 100 Hz. At what frequency does it appear?

  1. 70 Hz
  2. 30 Hz
  3. 170 Hz
  4. 35 Hz

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Fix fs = 10 Hz. Step f through 3, 7, 13 and 17 Hz and write down the alias each time. What pattern do you see? Predict f = 23 Hz before you try it.

What the interactive shows, in words

With fs = 10 Hz in the sampler: 3 Hz shows as 3 Hz, 7 Hz as 3 Hz, 13 Hz as 3 Hz and 17 Hz as 3 Hz, because each is 3 Hz away from a multiple of 10 Hz. 23 Hz also shows as 3 Hz.

Understand

Folding

Picture the frequency axis folded like a paper fan at every multiple of fs/2. Any frequency lands somewhere in the first panel, 0 to fs/2. That landing place is the alias. With fs = 100 Hz: 30, 70, 130 and 170 Hz all land on 30 Hz.

Negative aliases and backwards wheels

A film camera at 24 frames/s filming a wheel turning 23 times per second sees it advance 23/24 of a turn per frame: indistinguishable from going back 1/24 of a turn. f − fs = −1 Hz: the wheel seems to turn backwards once per second. For a rotation the sign matters; for a cosine on a graph it does not.

Using the formula as a detective

If a log shows a mystery 30 Hz wobble and you sample at 100 Hz, candidates are 30, 70, 130, 170 Hz… Check the machine for anything at those frequencies, like a motor at 4200 rpm (70 Hz). If you find one, you have caught an alias, and the fix is filtering before sampling or sampling faster.

Explain it another way: intuitive

Frequencies above Nyquist bounce off a wall at fs/2 and come back down, like a ball bouncing between the floor (0) and a ceiling (fs/2).

Explain it another way: technical

The DTFT of a sampled signal is periodic in f with period fs. A real signal's spectrum is also symmetric about 0, so everything maps into 0…fs/2.

Explain it another way: mathematical

f_alias = |f − k·fs|, k = round(f/fs). Example: f = 1730 Hz, fs = 500 Hz: k = round(3.46) = 3, f_alias = |1730 − 1500| = 230 Hz ≤ 250 Hz.

Explain it another way: applied

Digital radio receivers use aliasing on purpose ('undersampling'): a 70 MHz signal sampled at 50 MHz lands at 20 MHz, so a slower, cheaper ADC can still capture it, provided a band-pass filter removes everything else.

Derivation: The exact alias formula
  1. Samples of x(t) = cos(2πft) are x[n] = cos(2π·(f/fs)·n).

  2. Adding a whole number of cycles per sample changes nothing: cos(2π(f − k·fs)n/fs) = cos(2πfn/fs − 2πkn) = x[n] for every integer k.

  3. Cosine is even, so a negative frequency gives the same samples as its magnitude: cos(−θ) = cos θ.

  4. Choose k = round(f/fs) so that f − k·fs lies between −fs/2 and +fs/2.

  5. Therefore f_alias = |f − round(f/fs)·fs|, always between 0 and fs/2. (For sine waves the sign of f − k·fs also flips the phase: that is the 'backwards' wheel.)

Try these examples

Example 1

A 4200 rpm fan is sampled by a 100 Hz sensor. What vibration frequency appears in the data?

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A 900 Hz whistle is sampled at 1 kHz. What alias frequency, in Hz, appears?

Answer: Hz

2. Sampled at fs = 100 Hz, which frequency gives exactly the same samples as a 20 Hz cosine?

  • 40 Hz
  • 80 Hz
  • 120 Hz
  • Both 80 Hz and 120 Hz

3. A 330 Hz sinusoid is sampled at fs = 250 Hz. At what frequency (between 0 and fs/2) does it appear in the samples, in hertz?

Answer: Hz

4. A wheel turns 23 times a second and is filmed at 24 frames per second. How many times per second does it appear to turn (use a negative number for backwards)?

Answer: rev/s

5. A 1730 Hz tone is sampled at 500 Hz. What alias, in Hz?

Answer: Hz

Apply it

Your rover's 50 Hz IMU log shows a 6 Hz wobble, but the wheels spin at about 44 Hz. Is the wobble plausibly an alias of the wheels? Show the calculation and propose two fixes.

Reflect

Describe a situation where an alias could cause a real engineering mistake, not just a strange graph.

Stopping aliases before they start

Every audio interface and many sensor boards put a filter in front of the ADC. If the ADC is digital, why does it need an analog guard?

About 30 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Once a high frequency has folded onto a low one, the damage is permanent. The only safe place to stop it is in the analog world, with a filter placed before the sampler. Designing that filter is a classic trade-off between parts cost, sharpness and how much of the wanted band you lose.

Goals

Safety: Simulation only. If you later build an RC filter for real, use a low-voltage battery or a lab supply under supervision; never connect to mains.

Predict

A first-order RC low-pass has its cut-off at 1 kHz. Roughly how much does it reduce the amplitude of a 10 kHz signal?

  1. To about one half
  2. To about one tenth
  3. To zero
  4. It doesn't change it

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Electronics Studio, build a resistor-capacitor low-pass (R in series, C to ground) and probe the capacitor voltage. Compute fc = 1/(2πRC), then try test frequencies at fc/10, fc and 10·fc and compare the output amplitude with 1/√(1 + (f/fc)²).

What the interactive shows, in words

In the electronics activity, an RC low-pass with fc about 1 kHz passes a 100 Hz test signal almost unchanged (gain 0.995), passes 1 kHz at 0.707, and reduces 10 kHz to about 0.1.

Understand

Filter first, sample second

An anti-aliasing filter is a low-pass filter before the ADC that shrinks everything above fs/2 enough that its aliases are buried below the noise floor. Digital filtering after sampling cannot help: by then the alias sits at an allowed frequency and looks exactly like real signal.

The RC low-pass

A resistor in series and a capacitor to ground form the simplest low-pass. Its cut-off fc = 1/(2πRC) is where the output falls to 1/√2 (−3 dB). Above fc the gain falls roughly as fc/f: −20 dB per decade. With R = 1.6 kΩ and C = 100 nF, fc ≈ 995 Hz.

Oversample, then decimate

Real filters roll off gradually. A common trick: sample much faster than needed (oversample), so a gentle analog filter suffices, then use a sharp digital low-pass and keep every Mth sample (decimation). Delta-sigma audio ADCs work this way internally.

Explain it another way: intuitive

It is a bouncer at the door: unwanted high frequencies are turned away before they can sneak in wearing a low-frequency disguise.

Explain it another way: technical

Gain of a first-order RC low-pass: |H(f)| = 1/√(1 + (f/fc)²), phase −arctan(f/fc). An nth-order filter falls at about 20n dB per decade.

Explain it another way: mathematical

fc = 1/(2πRC). For a 12-bit system (≈74 dB SNR) to bury a full-scale tone at 10·fc with a first-order filter you only get 20 dB: far short. A 4th-order filter gives about 80 dB at 10·fc.

Explain it another way: applied

Electrocardiogram front ends low-pass the electrode signal before the ADC so that mains interference and muscle noise cannot alias into the heartbeat band.

Try these examples

Example 1

Choose C for an RC anti-aliasing filter with R = 10 kΩ and fc ≈ 160 Hz.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. An RC low-pass has R = 1.6 kΩ and C = 100 nF. What is fc = 1/(2πRC), in Hz (nearest 5 Hz)?

Answer: Hz

2. Why can't a digital filter after the ADC remove aliases?

  • Digital filters are too slow
  • After sampling, an alias is indistinguishable from a real signal at that frequency
  • Digital filters only work on audio
  • It can, if it has enough taps

3. A first-order RC low-pass has fc = 2 kHz. Using |H| = 1/√(1 + (f/fc)²), what is its gain at 20 kHz (3 decimal places)?

Answer:

4. Why does oversampling make the analog anti-aliasing filter easier to design?

  • It increases the number of bits
  • It pushes fs/2 far above the wanted band, so a gentle roll-off has room to work
  • It removes all noise
  • It lets you skip the filter entirely

5. A 1210 Hz sinusoid is sampled at fs = 1000 Hz. At what frequency (between 0 and fs/2) does it appear in the samples, in hertz?

Answer: Hz

Apply it

Design an anti-aliasing filter for a 1 kHz-sampled vibration sensor whose useful band is 0–200 Hz. Pick R and C, compute the attenuation at 500 Hz and 800 Hz (which aliases to 200 Hz), and say whether first order is enough.

Reflect

Which is cheaper on your design: a better analog filter or a faster ADC? What would change your answer?

Week 21: Frequency-domain intuition

This week you will

Seeing a signal's ingredients

A chord played on a piano is one wobbly line on an oscilloscope. How can a tuner app name every note in it?

About 30 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Many problems that look hopeless in time are easy in frequency. A hum, a squeal or a failing bearing is a tall spike at one frequency even when it is invisible in the waveform. Engineers flip between the two views all day.

Goals

Predict

A signal is 1·sin(2π·2t) + 0.5·sin(2π·5t). What is its average power?

  1. 1.5
  2. 0.625
  3. 1.25
  4. 0.75

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Load 'Three tones'. Read the spectrum bars, then change each phase and watch the time plot. Next put two components at the same frequency and vary one phase: what happens to that bar now?

What the interactive shows, in words

With three tones at 2, 5 and 8 Hz the spectrum shows three bars of heights 1, 0.6 and 0.3. Changing phases changes the waveform's shape but not the bars. Putting two components at the same frequency makes one bar whose height depends on their phase difference (from the sum to the difference of the amplitudes).

Understand

Two views of one signal

The time domain shows value against time. The frequency domain shows how much of each frequency is present. A magnitude spectrum draws a bar of height Aᵢ at each fᵢ. The same information, arranged differently, like a recipe versus the cake.

Phase hides in the time view

Shifting a component's phase reshapes the waveform (peaks can line up or cancel) but leaves its bar the same. That is why two signals that look different can sound identical: your ear cares mostly about magnitudes. A full description keeps the phase too, so the time signal can be rebuilt.

Power adds across frequencies

Sinusoids of different frequencies average to zero when multiplied together, so the cross terms vanish and P = Σ Aᵢ²/2. That is Parseval's theorem in miniature: power computed in time equals power computed from the spectrum. Components at the same frequency are different: they combine as phasors first.

Explain it another way: intuitive

A smoothie tastes like one thing, but its recipe card lists banana, strawberry and yoghurt with amounts. The spectrum is the recipe card of a signal.

Explain it another way: technical

Sinusoids at distinct frequencies are orthogonal over a common period: the average of sin(2πf₁t)·sin(2πf₂t) is 0 when f₁ ≠ f₂ and 1/2 when they are equal. Orthogonality is what lets a spectrum analyser measure each one separately.

Explain it another way: mathematical

x(t) = Σ Aᵢ sin(2πfᵢt + φᵢ). Mean of x² = Σᵢ Σⱼ AᵢAⱼ·mean[sin(…ᵢ) sin(…ⱼ)] = Σᵢ Aᵢ²/2 (distinct fᵢ).

Explain it another way: applied

Noise-cancelling headphones look for strong, steady spectral lines such as engine drone and subtract them; voices, which are spread across many frequencies, pass through.

Try these examples

Example 1

Sketch the spectrum of 3 + 2·cos(2π·10t) + sin(2π·30t).

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. You change only the phase of one component. What changes?

  • The height of its spectrum bar
  • The waveform's shape in time
  • The total power
  • The component's frequency

2. x(t) = 2·sin(2π·50t) + 1·sin(2π·150t). What is its average power?

Answer:

3. 3·sin(2π·5t) + 4·sin(2π·5t + 90°) is a single 5 Hz sinusoid. What is its amplitude?

Answer:

4. A signal is x(t) = 1 + 6·sin(2π·440·t). What is its average power (mean of x², as for a 1 Ω load)?

Answer:

5. Where does a constant offset appear in a spectrum?

  • At the highest frequency
  • Nowhere
  • At 0 Hz
  • Spread evenly over all frequencies

Apply it

Record (or imagine) three sounds: a whistle, a vowel 'aaa' and a hiss. Sketch what you expect each spectrum to look like and justify each sketch in one sentence.

Reflect

Name one problem you would rather solve in the frequency domain than in the time domain, and say why.

A square wave made of curves

A square wave has perfectly sharp corners. Sine waves have none. Yet enough sine waves add up to a square. How many, and what's left over?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Digital clocks and PWM motor drives are square waves, and their sharp edges are made of high harmonics. Those harmonics radiate interference, heat transformers and shape what an oscilloscope must be able to see. Knowing the series tells you exactly how much energy sits at each frequency.

Goals

Predict

Which harmonics appear in a symmetric square wave of frequency f₀?

  1. All of them: f₀, 2f₀, 3f₀, …
  2. Only odd ones: f₀, 3f₀, 5f₀, …
  3. Only even ones
  4. Only f₀

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Start with 1 harmonic, then add them one by one up to 25. Watch the power captured and the peak of the sum. Does the overshoot near the jump get smaller, or only narrower?

What the interactive shows, in words

With 1 harmonic the builder draws a sine of peak 1.27 over the square. Adding odd harmonics (3, 5, 7…) fills in the corners; captured power rises from 81 % to about 98 % with 13 terms; the peak near each jump stays about 1.18, a 9 % overshoot of the jump of 2.

Understand

The series

A square wave swinging between +A and −A is x(t) = (4A/π)·[sin ωt + sin 3ωt/3 + sin 5ωt/5 + …]. Harmonic n has amplitude bₙ = 4A/(nπ) for odd n and 0 for even n. The fundamental is 4/π ≈ 1.27 times taller than the square itself.

Power is concentrated low

The square has power A². The fundamental alone carries (4A/π)²/2 = 8A²/π² ≈ 81 % of it; adding the 3rd and 5th reaches about 93 %. So a square wave through a low-pass filter quickly looks like a sine: that is how some cheap sine-wave inverters work.

Gibbs: the overshoot that won't go away

Near each jump the partial sum overshoots by about 9 % of the jump, however many terms you add. More terms make the overshoot narrower, not lower. In practice, ringing near edges in a band-limited system is the same effect: a sharp edge truly needs infinitely high frequencies.

Explain it another way: intuitive

Each new odd harmonic is a smaller, faster wiggle that fills in more of the corners. You never finish, but you get close enough for any practical purpose.

Explain it another way: technical

Coefficients come from correlation: bₙ = (2/T₀)∫ x(t)·sin(nω₀t) dt. For the square, the integral over each half-period gives 2A(1 − cos nπ)/(nπ), which is 4A/(nπ) for odd n and 0 for even n.

Explain it another way: mathematical

Σ over odd n of (4A/(nπ))²/2 = (8A²/π²)·Σ 1/n² (odd n) = (8A²/π²)·(π²/8) = A²: the harmonics carry exactly the square's power, as Parseval's theorem requires.

Explain it another way: applied

A 100 MHz digital clock has strong harmonics at 300 and 500 MHz. Circuit-board designers slow the edges deliberately and add filtering so those harmonics don't fail electromagnetic-compatibility tests.

Try these examples

Example 1

A ±5 V, 1 kHz square wave drives a speaker. What is the amplitude of the 3 kHz component?

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. What is the amplitude of the fundamental of a ±1 square wave (3 decimal places)?

Answer:

2. What is the amplitude of the 4th harmonic of a symmetric square wave?

  • 4A/(4π)
  • Zero
  • Half the 2nd harmonic
  • The same as the 3rd

3. A square wave swings between +2 and −2 at f₀ = 200 Hz. What is the amplitude of its harmonic number n = 5 (the component at 1000 Hz)? Give 3 decimal places.

Answer:

4. What percentage of a square wave's power is in its fundamental alone (8/π² as a percentage, 1 decimal place)?

Answer: %

5. You add more and more harmonics. What happens to the overshoot near each jump?

  • It shrinks to zero
  • It stays about 9 % of the jump but gets narrower
  • It grows without limit
  • It moves to the middle of the flat parts

Apply it

A PWM motor driver produces a 20 kHz square wave. Which harmonics fall in the human hearing range (up to about 20 kHz)? Why do some cheap drivers whine, and what happens if you move the PWM frequency to 8 kHz?

Reflect

Why does a sharp edge in time need high frequencies? Explain in your own words, without the formula.

The DFT: asking 'how much of this wave?'

A computer only has eight numbers from a sensor. How can it say there is a strong 250 Hz component in them?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

The discrete Fourier transform, usually computed by the fast FFT algorithm, runs inside every spectrum analyser, phone camera, Wi-Fi radio and audio app. It is just multiply-and-add, done cleverly. Seeing it as correlation makes the formula obvious rather than magic.

Goals

Predict

x = [1, 1, 1, 1, 1, 1, 1, 1] (a constant). Which DFT bin is non-zero?

  1. All of them equally
  2. Only k = 0
  3. Only k = 4
  4. None

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Pick 'cos 2 + ½·sin 3'. Step the probe k from 0 to 7, watching the products column. Which k give big sums, and why do the cosine part and the sine part show up in different columns?

What the interactive shows, in words

For the signal cos(2·2πn/8) + ½·sin(3·2πn/8), the probe shows |X[k]| = 4 at k = 2 and 6 (cosine part, through the Σx·cos column) and 2 at k = 3 and 5 (sine part, through the Σx·sin column); every other bin is zero.

Understand

Correlation with probes

X[k] = Σ x[n]·cos(2πkn/N) − j·Σ x[n]·sin(2πkn/N). Each bin multiplies the signal by a probe wave with k cycles in the window and adds up. If the signal contains that wave, products are mostly positive and the sum is big; otherwise positives and negatives cancel. The cosine and sine sums together catch the component whatever its phase.

Bins and frequencies

With N samples at rate fs, bin k corresponds to f = k·fs/N. Resolution is fs/N: to tell close frequencies apart, record for longer. For a real signal, bins above N/2 mirror those below (they are the negative frequencies). A pure cosine of amplitude A exactly on bin k gives |X[k]| = A·N/2.

Small enough to do by hand

For N = 4 the probes take only the values 1, 0 and −1, so X[0] = x0 + x1 + x2 + x3, X[2] = x0 − x1 + x2 − x3, and X[1] = (x0 − x2) − j(x1 − x3). For x = [1, 0, −1, 0], X[1] = 2: one cycle of a cosine, amplitude 1, times N/2 = 2.

Explain it another way: intuitive

It is like testing a bell with tuning forks: hold up each fork in turn and see which one makes the bell hum along. The loudness of the hum is |X[k]|.

Explain it another way: technical

The FFT computes all N bins in about N·log₂N operations instead of N², by reusing shared partial sums. Leakage occurs when a frequency falls between bins; windowing functions reduce it.

Explain it another way: mathematical

X[k] = Σ_{n=0}^{N−1} x[n]·e^{−j2πkn/N}. Probes are orthogonal: Σₙ e^{j2π(k−m)n/N} = N if k = m (mod N), else 0. That orthogonality is why each bin isolates one frequency.

Explain it another way: applied

A condition-monitoring system takes 4096 samples of a pump's vibration at 10 kHz (bin spacing ≈ 2.4 Hz) and watches for growth in the bins near the bearing's characteristic fault frequency.

Try these examples

Example 1

Compute all four DFT bins of x = [2, 1, 0, 1].

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. In an N-point DFT, what does bin k measure?

  • The kth sample
  • How much the signal matches a wave with k cycles in the window
  • The signal's energy up to sample k
  • The kth harmonic of the sample rate

2. x = [1, 0, −1, 0]. What is |X[1]| of its 4-point DFT?

Answer:

3. x[n] = [-1, 1, 1, 1] for n = 0…3. Compute |X[1]|, the magnitude of the 4-point DFT X[k] = Σ x[n]·e^(−j2πkn/4). Give 2 decimal places.

Answer:

4. A 1024-point DFT is taken of a signal sampled at 8 kHz. What frequency, in Hz, does bin k = 64 represent?

Answer: Hz

5. You need to tell 100 Hz and 102 Hz apart. What helps most?

  • A higher sample rate with the same N
  • A longer recording (larger N at the same fs)
  • Fewer bits
  • Taking the DFT twice

Apply it

Write out the eight probe cosines for N = 8, k = 2. Then correlate them by hand with the 'Square' signal [1, 1, 1, 1, −1, −1, −1, −1]. Explain why bin 2 is zero and bin 1 is not, using what you learned about square waves.

Reflect

Why does the DFT need both a cosine and a sine probe for each k?

Week 22: Filters

This week you will

The moving average, seen in frequency

Averaging the last four readings smooths a sensor beautifully. So why does it completely erase one particular frequency?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

The moving average is the most used filter in embedded code: one line, no multiplications. Its frequency response explains both its strength (it kills noise and specific interference) and its weaknesses (lag and leaky high frequencies), so you can choose M on purpose instead of by trial.

Goals

Predict

A 4-point moving average runs at 1 kHz. What happens to a 250 Hz sine?

  1. It passes unchanged
  2. It is halved
  3. It is removed completely
  4. It is doubled

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Choose 'Moving average', low-pass. Set M = 4 and slide the test frequency to find the null. Change M to 8 and 2: where do the nulls go? Watch the step response: how many samples does it take to reach the top?

What the interactive shows, in words

In the explorer, the 4-point moving average has gain 1 at 0, falls to about 0.77 at f/fs = 0.1, and reaches 0 at f/fs = 0.25 (a null), with a small bump after it. With M = 8 the first null moves to 0.125. The step response climbs in M equal steps to 1.

Understand

One line of code

y[n] = (x[n] + x[n−1] + … + x[n−M+1])/M. It is a finite impulse response (FIR) filter: an impulse affects exactly M outputs, then is forgotten. Random noise of standard deviation σ comes out with σ/√M, because independent errors partly cancel.

Nulls and side lobes

Its gain is 1 at DC and falls to exactly zero at fs/M, 2fs/M, …, with bumps (side lobes) in between: the first is about 0.22 for large M. Great for removing a known interference, like 50 Hz mains when fs/M = 50 Hz, but a mediocre general low-pass because the side lobes leak.

The price: lag

The output is centred (M − 1)/2 samples in the past. With M = 9 at 100 Hz that is 40 ms: fine for a thermometer, dangerous inside a fast control loop where delay erodes stability. Doubling M halves the noise power again but doubles the lag.

Explain it another way: intuitive

Averaging the last few readings irons out quick jitters but makes the reading arrive late, like a crowd repeating what the person at the front said.

Explain it another way: technical

FIR filter with M equal taps of 1/M. Linear phase (constant delay), always stable, frequency response a periodic sinc ('Dirichlet kernel').

Explain it another way: mathematical

|H(f)| = |sin(πMf/fs)/(M·sin(πf/fs))|. Example: M = 4, f/fs = 0.1: sin(0.4π)/(4·sin(0.1π)) = 0.951/(4 × 0.309) ≈ 0.769.

Explain it another way: applied

Digital multimeters often average over exactly one mains period (20 ms in the UK), placing a null at 50 Hz and every harmonic, which is why they read steadily next to noisy wiring.

Derivation: The moving-average frequency response
  1. Input x[n] = e^{jωn} with ω = 2πf/fs. Output y[n] = (1/M)·Σ_{k=0}^{M−1} e^{jω(n−k)} = e^{jωn}·H, with H = (1/M)·Σ e^{−jωk}.

  2. That is a geometric series: H = (1/M)·(1 − e^{−jωM})/(1 − e^{−jω}).

  3. Factor out half-angles: (1 − e^{−jθ}) = e^{−jθ/2}·2j·sin(θ/2).

  4. So |H| = |sin(ωM/2) / (M·sin(ω/2))| = |sin(πMf/fs)/(M·sin(πf/fs))|, with a pure delay of (M − 1)/2 samples.

  5. It is 1 at f = 0 and 0 whenever Mf/fs is a whole number (other than multiples of M): nulls at f = fs/M, 2fs/M, …

Try these examples

Example 1

A 5-point moving average filters x = [2, 4, 6, 8, 10, 12]. Find y[4] and y[5].

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A moving average with M = 10 runs at fs = 500 Hz. What is the lowest frequency it removes completely, in Hz?

Answer: Hz

2. A 2-point moving average y[n] = (x[n] + … + x[n−1])/2 filters x = [8, 2, 1, 8, 9, 0, 9] (n = 0…6). What is y[1]?

Answer:

3. How many samples of delay does a 9-point moving average add?

Answer: samples

4. An M = 4 point moving average runs at fs = 8000 Hz. Using |H(f)| = |sin(πMf/fs) / (M·sin(πf/fs))|, what is its gain at f = 2000 Hz? Give 3 decimal places.

Answer:

5. Noise on a sensor is random with standard deviation 4 mV. Roughly what is it after a 16-point moving average?

  • 4 mV
  • 1 mV
  • 0.25 mV
  • 2 mV

Apply it

Your rover's 200 Hz IMU picks up 50 Hz interference from a motor driver. Choose M so a moving average nulls 50 Hz, compute its lag in milliseconds, and say whether that lag is acceptable for a balance controller that must react within 20 ms.

Reflect

When would you choose a moving average over a smarter filter, even knowing its weaknesses?

A filter with memory: first-order IIR

One multiply, one add and a single remembered number can smooth a sensor as well as averaging dozens of readings. How?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

The exponential moving average needs almost no memory, which is why it runs inside battery monitors, drone flight controllers and stock-price charts. Its single knob α trades smoothness for responsiveness, and the maths that tunes it is the same maths as an RC circuit.

Goals

Predict

y[n] = 0.2x[n] + 0.8y[n−1], starting from y = 0, with x jumping to 10 and staying there. Where does y end up?

  1. 2
  2. 8
  3. 10
  4. It keeps growing

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, write a loop that applies y = a*x + (1 - a)*y to a step input of 10 for 30 samples, printing n and y. Try a = 0.5, 0.2 and 0.05. For each, find the first n where y passes 6.3 (63 % of the way).

What the interactive shows, in words

Running the filter on a step of 10: with α = 0.5 the output reaches 6.3 at n = 1 (7.5); with α = 0.2 at n = 4 (6.7); with α = 0.05 at about n = 19. Smaller α is smoother but slower; the final value is always 10.

Understand

Infinite memory in one number

Unlike a moving average, the IIR (infinite impulse response) filter feeds its own output back. An impulse never fully disappears; its influence decays by (1 − α) every sample. The weights on past inputs are α, α(1 − α), α(1 − α)², …: an exponentially fading average.

One knob

Large α (close to 1) follows the input almost immediately; small α smooths heavily but responds slowly (time constant about 1/α samples). It behaves like an RC low-pass with RC ≈ T/α, so the cut-off is roughly fc ≈ α·fs/(2π) for small α.

High-pass for free

x[n] − y[n] keeps what the low-pass removed: fast changes pass and any steady offset decays to zero. Use it to remove a slow drift, such as a gyroscope's bias, while keeping quick motions. Combining a high-passed gyro with a low-passed accelerometer is the complementary filter used on drones.

Explain it another way: intuitive

Each new reading nudges your estimate a fraction α of the way towards it. Small α: you're hard to convince. Large α: you believe the latest reading.

Explain it another way: technical

Single pole at z = 1 − α inside the unit circle, so stable for 0 < α < 2 (and non-oscillating for 0 < α ≤ 1). Group delay at low frequency ≈ (1 − α)/α samples.

Explain it another way: mathematical

y[n] = Σ_{k≥0} α(1 − α)^k x[n−k]. Weights sum to α/(1 − (1 − α)) = 1. Step response y[n] = X(1 − (1 − α)^{n+1}).

Explain it another way: applied

A battery fuel gauge low-passes the noisy current measurement with α around 0.01 at 100 Hz (time constant about 1 s), so the displayed percentage doesn't flicker when a motor starts.

Derivation: Steady state and time constant of the first-order IIR
  1. Filter: y[n] = αx[n] + (1 − α)y[n−1], with 0 < α ≤ 1.

  2. Steady state for constant input X: set y[n] = y[n−1] = y. Then y = αX + (1 − α)y, so αy = αX and *y = X**. DC gain is 1.

  3. Step response from y[−1] = 0: the gap X − y shrinks by (1 − α) each sample, so y[n] = X·(1 − (1 − α)^{n+1}).

  4. Time constant: the gap falls to 1/e (37 %) after n with (1 − α)^n = e^{−1}, so n = −1/ln(1 − α) ≈ 1/α for small α. α = 0.1 gives about 9.5 samples.

  5. Frequency response: H = α/(1 − (1 − α)e^{−jω}). At ω = 0 this is 1; at Nyquist (ω = π) it is α/(2 − α), the strongest attenuation.

Try these examples

Example 1

α = 0.2, step input x = 1 from n = 0, y[−1] = 0. Find y[0], y[1], y[2].

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. y[n] = 0.5x[n] + 0.5y[n−1], y[−1] = 0, and x[n] = 4 for n ≥ 0. What is y[1]?

Answer:

2. For a constant input X, the first-order IIR low-pass settles at…

  • αX
  • (1 − α)X
  • X
  • 0

3. y[n] = 0.2·x[n] + 0.8·y[n−1], with y[−1] = 0. The input is a step: x[n] = 5 for n ≥ 0. What is y[3]? Give 3 decimal places.

Answer:

4. Using n ≈ −1/ln(1 − α), about how many samples is the time constant for α = 0.1 (1 decimal place)?

Answer: samples

5. A gyroscope reading has a slow, steady bias of 0.3 °/s. Which output removes it?

  • The IIR low-pass y
  • x − y (the high-pass)
  • x itself
  • 2y

Apply it

Your greenhouse temperature sensor is sampled at 1 Hz and you want readings to settle within about 30 s without flicker. Choose α, justify it with the time-constant formula, and test it on a step from 18 °C to 24 °C in code.

Reflect

When would you prefer a moving average to a first-order IIR, and the other way round?

Transforms: why engineers change the question

Filtering is a messy running sum in time but a simple multiplication in frequency. What other hard problems become easy when you transform them?

About 30 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Transforms let engineers swap a hard question for an easier one: convolution becomes multiplication, differential equations become algebra. You do not need to compute Laplace transforms yet, but knowing what they are for will make every control and signals course after this one make sense.

Goals

Predict

A signal's spectrum is multiplied by a filter's frequency response that is 1 below 100 Hz and 0 above. What does the output contain?

  1. Only frequencies above 100 Hz
  2. Only frequencies below 100 Hz
  3. The same as the input
  4. Nothing

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Compare four filters: moving average and IIR, each as low-pass and high-pass. For each, read the gain at f/fs = 0, 0.05 and 0.45. Write a one-line description of what each would do to a slowly drifting, noisy sensor.

What the interactive shows, in words

Reading the explorer: both low-pass filters have gain 1 at 0 and small gain near 0.45; both high-pass filters have gain 0 at 0 and close to 1 at high frequencies. On a drifting, noisy sensor the low-pass keeps the drift and removes the noise; the high-pass removes the drift and keeps the noise.

Understand

Filtering = multiplying spectra

In time, a filter output is a weighted running sum of the input (a convolution). In frequency, the same operation is just Y(f) = H(f)·X(f): each component is scaled by the gain at its frequency and shifted by the phase. That is why a frequency response is the most useful single description of a filter.

Low-pass, high-pass, and the rest

Low-pass keeps slow changes (smoothing, anti-aliasing). High-pass keeps fast changes and removes offsets and drift (AC coupling, removing gyro bias). A band-pass keeps a range (radio tuning), and a notch removes one frequency (mains hum). High-pass can be built as 1 − low-pass.

The Laplace transform, conceptually

The Fourier transform describes a signal with steady sinusoids. The Laplace transform uses e^{st} with complex s = σ + jω: sinusoids that can also grow or decay. Differentiation becomes multiplication by s, so a circuit's differential equation becomes algebra, e.g. an RC low-pass has H(s) = 1/(1 + sRC). Where H(s) blows up (its poles) tells you whether a system is stable.

Explain it another way: intuitive

A transform is like translating a problem into a language where it is easier to say. You solve it there, then translate back.

Explain it another way: technical

Convolution theorem: x * h ⟷ X·H. For discrete-time systems the z-transform plays the Laplace role; our IIR filter is H(z) = α/(1 − (1 − α)z⁻¹) with one pole at z = 1 − α.

Explain it another way: mathematical

Laplace: X(s) = ∫₀^∞ x(t)e^{−st} dt. Setting s = jω gives the Fourier transform (for signals where it converges). For dx/dt: L{dx/dt} = sX(s) − x(0).

Explain it another way: applied

Audio equalisers are banks of band-pass filters whose gains you set with sliders, a direct picture of Y(f) = H(f)·X(f). Control engineers read stability margins off H(jω) plots before ever building a controller.

Try these examples

Example 1

A sensor reading is 2.5 V of steady offset plus a 5 Hz vibration plus 200 Hz noise, sampled at 1 kHz. Which filter keeps just the vibration?

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Filtering in time corresponds to what in frequency?

  • Adding the filter's response
  • Multiplying the spectrum by the filter's response
  • Dividing by the sample rate
  • Nothing simple

2. Which job needs a high-pass filter?

  • Smoothing a jittery thermometer
  • Removing a slowly drifting offset from a microphone signal
  • Anti-aliasing before an ADC
  • Averaging a battery voltage

3. A first-order IIR low-pass has α = 0.2. Using α/(2 − α), what is its gain at the Nyquist frequency (3 decimal places)?

Answer:

4. An M = 4 point moving average runs at fs = 8000 Hz. Using |H(f)| = |sin(πMf/fs) / (M·sin(πf/fs))|, what is its gain at f = 2000 Hz? Give 3 decimal places.

Answer:

5. y[n] = 0.5·x[n] + 0.5·y[n−1], with y[−1] = 0. The input is a step: x[n] = 2 for n ≥ 0. What is y[0]? Give 3 decimal places.

Answer:

6. What does the Laplace transform mainly do for an engineer?

  • Speed up sampling
  • Turn differential equations into algebra and reveal stability through poles
  • Compress audio files
  • Replace the DFT in digital filters

Apply it

Write a half-page explainer for a younger learner: what a spectrum is, what a filter does to it, and one real device that uses each of low-pass, high-pass and notch filtering. Use one diagram.

Reflect

What is one problem from earlier this year that might have been easier in the frequency domain?

Week 23: From transistors to logic

This week you will

Doped silicon and the p–n junction

Pure silicon barely conducts. Add one phosphorus atom for every few million silicon atoms and it conducts thousands of times better. Why so dramatic?

About 30 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Every transistor in every chip is built from doped regions of silicon. Understanding the p–n junction is understanding why a MOSFET can be switched by a voltage, why diodes protect circuits, and why chips get hot.

Goals

Safety: Simulation only. Do not experiment with mains, chargers or large batteries; real diode experiments use a low-voltage bench kit and a current-limiting resistor under supervision.

Predict

Silicon atoms have 4 outer electrons. Phosphorus has 5. What does adding phosphorus do?

  1. Removes electrons, making 'holes'
  2. Adds spare free electrons (n-type)
  3. Makes silicon an insulator
  4. Nothing at all

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Electronics Studio, put a diode in series with a 1 kΩ resistor and a variable low-voltage source. Sweep the source from −3 V to +3 V and note the current. Where does current start to flow, and what happens in reverse?

What the interactive shows, in words

In the sweep, current is essentially zero for all negative voltages and for small positive ones, then rises steeply once the source exceeds about 0.7 V; above that, the resistor sets the current at about (V − 0.7)/1000 amps.

Understand

Doping

Pure silicon has very few free charge carriers at room temperature. n-type silicon is doped with atoms like phosphorus (5 outer electrons), adding free electrons. p-type is doped with boron (3), adding holes: gaps that move like positive charges. Tiny amounts change conductivity enormously because pure silicon starts with so few carriers.

The junction

Where p meets n, electrons and holes near the boundary combine, leaving a thin depletion region with no free carriers and a built-in voltage across it. Push current forward (p positive) and, above about 0.6–0.7 V for silicon, the barrier collapses and current flows. Push in reverse and the depletion region widens: almost no current. That is a diode.

From junctions to transistors

A MOSFET has two n-type regions (source and drain) in p-type silicon. Normally the p–n junctions block current between them. A positive voltage on an insulated gate above the gap pulls electrons up into a thin channel that connects source to drain. No gate current flows: the gate's voltage alone opens the switch.

Explain it another way: intuitive

Doping is like adding a few movers to a crowded, frozen dance floor. The p–n junction is a one-way door that only opens when you push hard enough in the right direction.

Explain it another way: technical

Diode current follows the Shockley equation I = I_s(e^{V/(nV_T)} − 1), V_T ≈ 26 mV at room temperature: the current rises about tenfold for every 60 mV, which is why 0.7 V is a good working estimate over a wide current range.

Explain it another way: mathematical

With a 5 V source, a 0.7 V silicon diode and a 1 kΩ resistor: I = (5 − 0.7)/1000 = 4.3 mA. In reverse, I ≈ −I_s, nanoamps or less.

Explain it another way: applied

Solar cells are large p–n junctions: light frees carriers in the depletion region and the built-in field sweeps them out as current. LEDs run the junction the other way, turning recombination into light.

Try these examples

Example 1

A silicon diode and a 470 Ω resistor are in series with a 3.3 V supply. Estimate the current.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Doping silicon with boron (3 outer electrons) makes…

  • n-type: extra electrons
  • p-type: holes that act as positive carriers
  • an insulator
  • a metal

2. A silicon diode (0.7 V drop) is forward biased in series with a 1 kΩ resistor across 5 V. What current flows, in mA?

Answer: mA

3. A diode is reverse biased. What happens to the depletion region?

  • It disappears
  • It widens, so almost no current flows
  • It becomes a conductor
  • It moves to the n side only

4. What controls a MOSFET's channel?

  • Current into the gate
  • The voltage on the insulated gate
  • The temperature of the drain
  • The diode drop

5. You want 10 mA through a diode (0.7 V drop) from a 3.7 V cell. What series resistance, in ohms?

Answer: Ω

Apply it

Explain, with a labelled sketch, how a MOSFET's gate voltage turns the path between source and drain from two back-to-back blocking junctions into a conducting channel.

Reflect

Why does adding such a tiny amount of dopant change silicon so much?

Building gates from switches

A modern chip has billions of transistors and almost all are wired as just three or four patterns. What are they?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

CMOS is the reason your phone lasts a day instead of an hour. By pairing two kinds of switch so one network always blocks, it draws power only when it switches. Learning the pattern lets you read a transistor schematic as logic.

Goals

Predict

In a CMOS NAND gate, how are the two nMOS transistors in the pull-down network connected?

  1. In parallel
  2. In series
  3. Not at all
  4. Through a resistor

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Start with the inverter and toggle A. Then switch to NAND and NOR and try all four input combinations. For each, say which network conducts and confirm there is never a path from VDD to ground.

What the interactive shows, in words

In the gate builder, the inverter's output is 1 when A = 0 (pMOS on) and 0 when A = 1 (nMOS on). The NAND output is 0 only for A = B = 1, when both series nMOS conduct; the NOR output is 1 only for A = B = 0, when both series pMOS conduct. In every case exactly one network conducts.

Understand

Two kinds of switch

An nMOS conducts when its gate is high (1) and is good at pulling a node down to ground. A pMOS conducts when its gate is low (0) and is good at pulling up to VDD. In the switch-level model each is simply on or off; in reality each has some resistance and capacitance.

Pull-up and pull-down networks

A static CMOS gate has a pull-down network of nMOS between the output and ground and a pull-up network of pMOS between VDD and the output. Series nMOS = AND condition for pulling down; parallel nMOS = OR. The pull-up is the dual: series becomes parallel and vice versa. So NAND = series nMOS + parallel pMOS; NOR = parallel nMOS + series pMOS. Each input drives one of each: a 2-input gate has 4 transistors.

Why it costs so little to sit still

For every input combination exactly one network conducts. So in steady state there is no path from VDD to ground and only tiny leakage flows. Power is spent mainly when the output switches and its load capacitance charges or discharges, which is next lesson's topic.

Explain it another way: intuitive

Two teams of doors: one between the output and the high rail, one between the output and the low rail. The teams are wired so that when one opens, the other is shut.

Explain it another way: technical

Natural CMOS gates are inverting (NAND, NOR, NOT, AOI). AND and OR need an extra inverter stage: 6 transistors for a 2-input AND. NAND is often preferred over NOR because series nMOS are faster than series pMOS.

Explain it another way: mathematical

Y = 0 exactly when the pull-down Boolean function is true; the pull-up implements its complement by De Morgan duality. For NAND: pull-down = A·B, pull-up = ¬A + ¬B = ¬(A·B).

Explain it another way: applied

Standard-cell libraries used by chip designers contain hundreds of variants of these patterns at different sizes and drive strengths; synthesis tools turn RTL code into networks of them.

Try these examples

Example 1

Design the transistor networks for a 3-input NOR.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A pMOS transistor conducts when its gate is…

  • 1 (high)
  • 0 (low)
  • floating
  • always

2. A static CMOS gate with inputs A and B is built from two nMOS in series in the pull-down network and two pMOS in parallel in the pull-up network. Write its output Y for AB = 00, 01, 10, 11 as a 4-bit binary number (Y for 00 is the leftmost bit) and give that number in decimal.

Answer:

3. How many transistors are in a static CMOS 3-input NAND gate?

Answer: transistors

4. A student wires both networks of a gate so that, for input 11, both conduct. What happens?

  • The output is a perfect 1
  • A direct path from VDD to ground: large current, undefined output
  • Nothing: CMOS can't draw current
  • The gate becomes a NOR

5. A static CMOS gate with inputs A and B is built from a NOR stage (parallel nMOS, series pMOS) followed by a CMOS inverter. Write its output Y for AB = 00, 01, 10, 11 as a 4-bit binary number (Y for 00 is the leftmost bit) and give that number in decimal.

Answer:

Apply it

Sketch a CMOS gate for Y = NOT(A·B + C) using one pull-down network (A and B in series, that pair in parallel with C) and its dual pull-up. Check all 8 rows of the truth table.

Reflect

Why do you think CMOS won over earlier logic families for phones and laptops?

Where a chip's power goes

Halve a processor's supply voltage and its switching power drops by three quarters. Why the square?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Battery life, fan noise and data-centre electricity bills are all set by CMOS power. Every phone constantly adjusts its voltage and clock using exactly the formula you derive here.

Goals

Predict

A chip's clock frequency is doubled with nothing else changed. What happens to its dynamic power?

  1. Stays the same
  2. Doubles
  3. Quadruples
  4. Halves

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Silicon Studio, pick a small logic block and look at how many nodes switch per clock. Estimate α (the fraction switching each cycle) for an idle input and for a busy one, then use P = αCV²f to compare their power.

What the interactive shows, in words

The silicon activity compares an idle input, where few nodes switch (small α), with a busy one where many do (large α). Power from αCV²f scales directly with α and f and with the square of V.

Understand

Static and dynamic

Static power is leakage: P_static = V·I_leak, small per transistor but significant with billions of them and rising with temperature. Dynamic power is the cost of switching: P ≈ αCV²f. In most busy logic, dynamic power dominates.

The four knobs

Lower α by not switching what you don't need (clock gating). Lower C with smaller transistors and shorter wires. Lower f when there is less work. Lower V for the biggest win, because it is squared, but transistors switch more slowly at low voltage, so f must fall too.

Voltage and frequency scaling

Since lower V forces lower f, reducing both together cuts power roughly with V³ while performance falls only with f. Phones run in a ladder of (V, f) operating points and jump between them many times per second. Energy per operation, CV², falls with V²: slow-and-low is efficient.

Explain it another way: intuitive

Every time a wire flips from 0 to 1 and back, you fill and empty a tiny bucket of charge. Bigger buckets, more flips, or a higher water level (voltage) all cost more.

Explain it another way: technical

Short-circuit current during transitions adds a few percent. Leakage grows as threshold voltage is lowered, which limits how far V can be reduced.

Explain it another way: mathematical

P = αCV²f. With α = 0.1, C = 1 nF, V = 1 V, f = 1 GHz: P = 0.1 × 10⁻⁹ × 1 × 10⁹ = 0.1 W. At V = 0.8 V: × 0.64 = 0.064 W.

Explain it another way: applied

A laptop throttling under heat lowers f and V together; a smartwatch processor spends most of its time at its lowest operating point, waking briefly at a higher one when you tap the screen.

Derivation: Dynamic power P ≈ αCV²f
  1. A gate's output drives a load capacitance C. Charging it from 0 to V through the pMOS draws charge Q = CV from the supply at voltage V: energy taken = QV = CV².

  2. Half of that, ½CV², ends up stored on the capacitor; the other half is lost as heat in the pMOS.

  3. Discharging through the nMOS dumps the stored ½CV² as heat. So one full 0 → 1 → 0 cycle costs CV² from the supply.

  4. If the node completes such a cycle on a fraction α of clock cycles (the activity factor), at clock frequency f, cycles per second = αf.

  5. Power = energy per cycle × cycles per second: P = αCV²f. Summed over all nodes, C is the total switched capacitance.

Try these examples

Example 1

A block has C = 2 nF switched capacitance, α = 0.15, V = 1.2 V, f = 500 MHz. Find P, then P at 0.9 V and 375 MHz.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. α = 0.1, C = 1 nF, V = 1.0 V, f = 1 GHz. What is P = αCV²f, in watts?

Answer: W

2. Halving V (with α, C, f unchanged) changes dynamic power by a factor of…

  • 1/2
  • 1/4
  • 1/8
  • 2

3. A CMOS block switches C = 2 nF of total capacitance with activity factor α = 0.1, at V = 1.2 V and f = 200 MHz. Using P = αCV²f, what is its dynamic power, in watts (to 3 decimal places)?

Answer: W

4. Clock gating switches off the clock to idle blocks. Which term does it reduce?

  • V
  • C of the transistors
  • α, the activity factor
  • Leakage only

5. How much energy, in picojoules, does one full charge-and-discharge cycle of a 10 fF node at 1 V cost (CV²)?

Answer: pJ

Apply it

A sensor node runs at 1.2 V, 48 MHz, using 20 mW when busy. Estimate its power at 0.9 V and 24 MHz. If the task takes 10 ms at full speed, compare the energy per task at both operating points.

Reflect

Why can't chip designers just keep lowering V for ever?

The PN junction: a one-way door for current

Glue a slab of p-type silicon to n-type silicon and, without any battery, a voltage appears across the joint. Where does it come from, and why does it make current flow only one way?

About 45 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Every diode, LED, solar cell and transistor contains PN junctions. The MOSFETs in a CMOS gate sit on junctions that must stay reverse biased; an LED is a junction that turns crossing electrons into light; a solar cell runs the same junction backwards. Understanding one junction explains why a silicon diode 'drops about 0.6–0.7 V', why reverse current is tiny, and why chips leak more when they get hot.

Goals

Predict

A silicon diode carries 1 mA at 0.655 V. Roughly what forward voltage would it need to carry 10 mA?

  1. 6.55 V (ten times the voltage)
  2. About 0.71 V (only about 60 mV more)
  3. 1.31 V (twice the voltage)
  4. It cannot carry more than 1 mA

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Start at 0 V and read the built-in potential for medium doping. Slide into reverse bias (negative V) and watch the depletion region widen while the current stays at a few femtoamps. Then slide forward past 0.6 V: when does the current become visible on the 20 mA scale?

What the interactive shows, in words

The junction explorer shows a p-type block (holes) joined to an n-type block (electrons) with a dashed depletion region between them whose width changes with bias, and an I–V curve below it with a dot at the present bias. A slider sets the bias from −1 V to +0.8 V; buttons choose light, medium or heavy doping. A readout gives the built-in potential (0.655 V, 0.774 V or 0.952 V), the depletion width relative to zero bias, √((V_bi − V)/V_bi), and the current from the Shockley equation with I_S = 10 fA. In reverse bias the region widens and only about −10 fA flows; forward current becomes visible above about 0.6 V and reaches several milliamps by 0.7 V.

Understand

Two kinds of doped silicon

Adding a few boron atoms per million makes p-type silicon with mobile holes (N_A acceptors per cm³). Adding phosphorus makes n-type with mobile electrons (N_D donors per cm³). Each piece is electrically neutral on its own: every mobile carrier is balanced by a fixed ion in the crystal.

Diffusion builds a barrier

Put them together and electrons diffuse from the n side into the p side, holes the other way, and they recombine near the joint. That leaves a thin depletion region with no mobile carriers, only fixed ions: positive on the n side, negative on the p side. Those charges create an electric field pointing from n to p that pushes carriers back. Equilibrium arrives when the field's push balances diffusion. The voltage across the region is the built-in potential, V_bi = V_T·ln(N_A·N_D/n_i²), about 0.6–0.9 V for silicon. A voltmeter cannot read it: contact potentials at the metal leads cancel it.

The band picture

Draw electron energy across the junction. On the n side the conduction band (where free electrons live) sits low; on the p side it sits higher by q·V_bi, so the bands bend through the depletion region like a hill. Electrons must climb the hill to cross. Forward bias (p positive) lowers the hill and narrows the region; reverse bias raises it and widens it. In the simple abrupt model the width scales as √(V_bi − V).

The Shockley equation

Lowering the barrier by V lets exponentially more carriers over it: I = I_S(e^(V/(n·V_T)) − 1). I_S is a tiny saturation current (femtoamps for a small silicon diode), V_T = kT/q ≈ 25.85 mV at 300 K, and the ideality factor n is between 1 and 2 for real diodes. In reverse bias the exponential vanishes and I ≈ −I_S. I_S roughly doubles for every 5 to 10 °C, so hot junctions leak much more.

Explain it another way: intuitive

Think of two crowded rooms joined by a doorway, one full of red balls (holes) and one of blue (electrons). They spill through the doorway and cancel, leaving an empty strip with charged walls that pushes the rest back. Push from one side (forward bias) and the strip shrinks so traffic floods through; push the other way and it widens so almost nothing crosses.

Explain it another way: technical

In equilibrium the Fermi level is flat across the junction, so the band offset equals q·V_bi = kT·ln(N_A·N_D/n_i²). Poisson's equation for an abrupt junction gives a triangular field and a depletion width W = √(2ε(V_bi − V)(N_A + N_D)/(q·N_A·N_D)). Under bias, minority-carrier concentrations at the depletion edges are raised by e^(V/V_T) (the law of the junction); diffusion of those minority carriers gives the ideal Shockley current.

Explain it another way: mathematical

N_A = 10¹⁶, N_D = 10¹⁷ cm⁻³, n_i = 10¹⁰: N_A·N_D/n_i² = 10³³/10²⁰ = 10¹³, ln(10¹³) ≈ 29.93, V_bi ≈ 0.02585 × 29.93 ≈ 0.774 V. For I_S = 10 fA, n = 1: V at 1 mA = 0.02585 × ln(10⁻³/10⁻¹⁴) = 0.02585 × 25.33 ≈ 0.655 V. Reverse bias of 5 V widens the depletion region by √((0.774 + 5)/0.774) ≈ 2.73×.

Explain it another way: applied

Rectifiers in phone chargers use junctions as one-way valves. The source and drain of every MOSFET are junctions held in reverse bias, so their leakage sets a chip's standby power. Varactor diodes use the bias-dependent depletion width as a tunable capacitor in radios. Solar cells and photodiodes collect carriers generated by light in the depletion region's field.

Derivation: Where V_bi = V_T·ln(N_A·N_D/n_i²) comes from
  1. In equilibrium the electron current is zero: the drift caused by the junction field exactly cancels diffusion down the concentration gradient. The same holds for holes.

  2. Zero net current means electron concentration follows a Boltzmann distribution with electric potential φ: n(x) ∝ e^(φ(x)/V_T), where V_T = kT/q.

  3. So the ratio of electron concentrations on the two sides fixes the potential difference: n_n/n_p = e^(V_bi/V_T), i.e. V_bi = V_T·ln(n_n/n_p).

  4. Far from the junction, the n side has n_n ≈ N_D and the p side has n_p = n_i²/N_A (from the mass-action law n·p = n_i²).

  5. Substitute: V_bi = V_T·ln(N_D·N_A/n_i²). Heavier doping on either side raises V_bi, but only logarithmically.

Try these examples

Example 1

Find V_bi for a silicon junction with N_A = 10¹⁵ cm⁻³ and N_D = 10¹⁶ cm⁻³, and again with both sides at 10¹⁸ cm⁻³.

The worked solution is in the online lesson.

Example 2

A diode has I_S = 10 fA and n = 1. Find the current at 0.65 V and at 0.70 V.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. What is left in the depletion region of a PN junction at zero bias?

  • Extra free electrons from the n side
  • Fixed ionised dopant atoms, with almost no mobile carriers
  • Nothing at all: it is a gap in the crystal
  • Equal numbers of free holes and electrons

2. A silicon PN junction at 300 K has N_A = 2 × 10^18 cm⁻³ on the p side and N_D = 2 × 10^14 cm⁻³ on the n side. Taking V_T = 25.85 mV and n_i = 1.0 × 10^10 cm⁻³, what is the built-in potential V_bi, in volts? (3 decimal places)

Answer: V

3. A diode has saturation current I_S = 5 fA and ideality factor n = 1.5. Using I = I_S(e^(V/(n·V_T)) − 1) with V_T = 25.85 mV, what current flows at a forward voltage of 0.98 V, in mA?

Answer: mA

4. A diode with I_S = 5 fA and ideality factor n = 2 must carry 10 mA. With V_T = 25.85 mV, what forward voltage does the Shockley equation predict, in volts? (3 decimal places)

Answer: V

5. What does increasing the reverse bias on a junction do (well below breakdown)?

  • Narrows the depletion region and lets more current through
  • Widens the depletion region; the current stays tiny, about −I_S
  • Removes the built-in potential
  • Makes the diode conduct like a resistor

6. In a simplified abrupt-junction model the depletion width W is proportional to √(V_bi − V). A junction with V_bi = 0.81 V has W = 0.6 µm at zero bias. What is W at a reverse bias of 14 V (so V = −14 V), in µm?

Answer: µm

Apply it

An LED indicator needs about 5 mA. Model it as a diode with I_S = 10⁻²⁰ A and n = 2 (a rough red-LED model). Use the Shockley equation to estimate its forward voltage at 5 mA, then size the series resistor from a 5 V supply. Check your answer in the Electronics Studio with a low-voltage LED circuit and explain any difference.

Reflect

The same PN junction appears in a rectifier, an LED, a solar cell and under every MOSFET. Which property of the junction does each one rely on?

Week 24: Finite-state machines

This week you will

Specifying a state machine

A lock that opens only when you type 1-0-1 has to remember something between key presses. What is the least it needs to remember?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Protocol decoders, vending machines, traffic lights and every processor's control unit are finite-state machines. Writing the table first, before any code or gates, is how engineers make sure every case is handled.

Goals

Predict

A Moore machine detects the pattern 11 (output 1 when the last two inputs were 1). How many states does it need at minimum?

  1. 1
  2. 2
  3. 3
  4. 4

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Choose 'Detect 11' with 3 states and fill in the table until 'Check my machine' passes. Then try 'Detect 101' with 4 states. If a check fails, type the failing string into the input box and trace it.

What the interactive shows, in words

One correct 11 detector: S0 (output 0) goes to S0 on 0 and S1 on 1; S1 (output 0) goes to S0 on 0 and S2 on 1; S2 (output 1) goes to S0 on 0 and stays in S2 on 1. One correct 101 detector uses four states meaning: nothing useful, seen 1, seen 10, seen 101 (output 1, goes to 'seen 10' on 0 and 'seen 1' on 1).

Understand

The ingredients

A finite-state machine has a set of states, a start state, inputs, outputs and a transition function next = f(state, input). In a Moore machine the output depends only on the state; in a Mealy machine it depends on the state and the current input (often fewer states, but outputs can glitch with the input).

The table is the design

A state-transition table lists, for every state and every input, the next state and the output. Every cell must be filled: an empty cell is an unhandled case, which in hardware means undefined behaviour. Name states by what they remember ('seen 10') rather than S2, and the table almost writes itself.

Overlaps and testing

In 1101, the pattern 101 ends at position 4 and its last 1 can start a new match. A correct detector, after finding 101, goes to the state that remembers '1' rather than back to the start. Because inputs are finite, short machines can be tested exhaustively: the designer checks all 510 strings up to 8 bits.

Explain it another way: intuitive

A state is a sticky note saying exactly what you need to remember, no more. The table says, for each note and each new event, which note to write next.

Explain it another way: technical

Minimal state count follows from which input histories must be distinguished (Myhill–Nerode). Equivalent states, those with identical outputs and transitions, can be merged.

Explain it another way: mathematical

Moore machine M = (S, s₀, Σ, Λ, δ, λ) with δ: S × Σ → S and λ: S → Λ. Output after input u is λ(δ*(s₀, u)).

Explain it another way: applied

Serial receivers (UARTs) use an FSM to find a start bit, sample eight data bits and check the stop bit; USB and Ethernet controllers contain dozens of such machines.

Try these examples

Example 1

Fill in the transition table for 'output 1 after an odd number of 1s'.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. In a Moore machine the output depends on…

  • Only the current input
  • Only the current state
  • The state and the current input
  • The clock frequency

2. A Moore machine outputs 1 for one clock whenever the last 2 input bits were 11 (overlaps allowed). Input, first bit first: 011001011100. How many clocks have output 1?

Answer:

3. A 101 detector has just output 1. The next input is 0. Where should it go?

  • Back to the start, forgetting everything
  • To the state meaning 'seen 10'
  • Stay in the match state
  • To the state meaning 'seen 1'

4. A state machine has 6 states. How many flip-flops does a binary state encoding need?

Answer: flip-flops

5. A Moore machine outputs 1 for one clock whenever the last 3 input bits were 110 (overlaps allowed). Input, first bit first: 110011111111. How many clocks have output 1?

Answer:

Apply it

Design a Moore machine for a turnstile: states LOCKED and UNLOCKED, inputs COIN and PUSH. Write its full table, then add a third state ALARM for 'pushed while locked three times in a row' and say what resets it.

Reflect

What did each state in your 101 detector 'mean' in words?

A state machine in hardware

Turn a state-transition table into a circuit and it is always the same shape: a register and a cloud of gates. Why that shape?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Every synchronous digital design, from a traffic-light controller to a CPU's control unit, follows this same template. Once you can turn a table into equations you can build any controller from gates and flip-flops.

Goals

Predict

A toggle machine has one flip-flop Q and input T. Each clock, Q flips if T = 1 and stays if T = 0. What is the next-state equation?

  1. Q⁺ = T
  2. Q⁺ = Q AND T
  3. Q⁺ = Q XOR T
  4. Q⁺ = NOT Q

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the logic lab, build the next-state logic for the parity machine: inputs Q (current state) and T (new bit), output D = Q XOR T. Then build the 2:1 multiplexer preset and explain how a multiplexer could choose between 'hold' and 'load' for a register.

What the interactive shows, in words

In the logic lab, D = Q XOR T gives D = 0, 1, 1, 0 for (Q, T) = 00, 01, 10, 11: the next state is the opposite of Q exactly when T = 1. The 2:1 multiplexer outputs input A when its select is 0 and input B when it is 1, which is how a register chooses between keeping its value and loading a new one.

Understand

The template

State register: n D flip-flops holding the current state code. Next-state logic: combinational gates computing the next code from the current code and the inputs. Output logic: gates computing outputs from the state (Moore) or state and inputs (Mealy). On each rising clock edge the register loads the next state.

From table to equations

Give each state a binary code (S0 = 00, S1 = 01, S2 = 10). Rewrite the table as a truth table with inputs (Q1, Q0, x) and outputs (Q1⁺, Q0⁺). Each column is a Boolean function you can simplify and build from gates. For the 11 detector with this encoding: Q0⁺ = x·¬Q1·¬Q0, Q1⁺ = x·(Q1 + Q0), output = Q1.

Why a clock?

Between edges the gates settle; at the edge, every flip-flop samples together. So the circuit only ever moves from one well-defined state to the next, no matter how messy the gate delays are, as long as the logic settles before the next edge. That timing condition comes back in RTL design.

Explain it another way: intuitive

The register is the machine's short-term memory; the gates are its rulebook. The clock is a metronome telling it when to turn the page.

Explain it another way: technical

Encoding choice matters: binary uses ⌈log₂N⌉ flip-flops; one-hot uses N flip-flops but simpler, faster logic, popular on FPGAs.

Explain it another way: mathematical

Q⁺ = δ(Q, x), y = λ(Q). For the parity machine Q⁺ = Q ⊕ x, y = Q. Test by enumerating all (Q, x) rows against the table.

Explain it another way: applied

Simple controllers in washing machines and lifts were once exactly this: a few flip-flops and a programmable logic array implementing the next-state equations.

Try these examples

Example 1

Verify Q0⁺ = x·¬Q1·¬Q0 and Q1⁺ = x·(Q1 + Q0) for the 11 detector with S0 = 00, S1 = 01, S2 = 10.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Which part of a hardware FSM holds the current state?

  • The output logic
  • The next-state logic
  • The state register (flip-flops)
  • The clock

2. A controller has 9 states with binary encoding. How many flip-flops?

Answer: flip-flops

3. The same 9-state controller uses one-hot encoding. How many flip-flops?

Answer: flip-flops

4. A Moore machine outputs 1 for one clock whenever the last 3 input bits were 101 (overlaps allowed). Input, first bit first: 000101110111. How many clocks have output 1?

Answer:

5. Why does the state register load only on the clock edge?

  • To save power
  • So the state changes only after the next-state logic has settled, avoiding races
  • Because gates can't drive flip-flops otherwise
  • To make the circuit slower on purpose

Apply it

Write the next-state equations for the 'odd number of 1s' machine and for a 2-bit counter that counts 0, 1, 2, 3, 0… when its input E = 1 and holds when E = 0. Build the counter's Q0⁺ logic in the logic lab.

Reflect

What is the trade-off between binary and one-hot state encoding?

A state machine in software

The same traffic-light controller can be twelve gates and four flip-flops, or twenty lines of code in a loop. When would you choose each?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Most embedded firmware is a handful of state machines running in a loop. Writing them explicitly, with one variable for the state and a table-like switch, is what keeps safety-critical controllers like traffic lights auditable.

Goals

Predict

A software traffic controller is in state GREEN_NS for 30 s, then must go to AMBER_NS. Where should the 30 s timer be checked?

  1. In a delay that blocks the whole loop
  2. Inside the GREEN_NS case, comparing elapsed time with 30 s
  3. In a separate program
  4. Nowhere: it happens automatically

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Open the traffic system at Level 2 and build the junction controller as a cycle of timed states. Before running, write the state table on paper. Then run the safety audit and fix anything it flags.

What the interactive shows, in words

The traffic build's Level 2 lets you list timed states (for example north–south green 30 s, amber 3 s, all-red 2 s, east–west green 30 s…) and audits them for conflicts, missing ambers and missing all-red gaps. The same list can be written as a switch statement in a loop.

Understand

The super-loop pattern

One variable holds the state. A loop runs forever: read inputs, then switch (state); each case sets outputs, checks its exit conditions and, if one is true, assigns the next state and records the entry time. Nothing blocks, so the loop runs many times per second and every input is noticed promptly.

Timed states and guards

Most real machines leave a state on a timeout or an event. Store entered = now() when entering a state and test now() − entered ≥ duration. Guard conditions (only go to WALK if the button was pressed AND the all-red has finished) are the software version of AND gates in next-state logic.

Hardware or software?

Hardware FSMs react within one clock cycle and keep running if the processor crashes; they are fixed once built. Software FSMs are easy to change and log but react only as fast as the loop and depend on the code being correct. Safety systems often use both: software for normal control, a simple hardware or independent monitor that forces a safe state.

Explain it another way: intuitive

The state variable is a bookmark. Each time round the loop you open the book at the bookmark, follow that page's instructions, and maybe move the bookmark.

Explain it another way: technical

A table-driven FSM stores transitions in a data structure instead of a switch, which makes it easier to verify automatically and to generate from a specification.

Explain it another way: mathematical

Worst-case reaction time = loop period. If one pass takes at most 2 ms, an event is noticed within 2 ms and acted on within 4 ms (it may arrive just after its check).

Explain it another way: applied

Railway and road signal controllers are specified as state machines with interlocking rules, then checked so that conflicting greens are unreachable from any state.

Try these examples

Example 1

Sketch the super-loop for a two-state blinker: LED_ON for 200 ms, LED_OFF for 800 ms.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Why avoid long blocking delays inside a state machine's loop?

  • They use too much memory
  • Nothing else, including inputs, is checked while the delay runs
  • They make the code longer
  • Delays are illegal in C

2. A super-loop pass takes at most 5 ms. What is the worst-case time, in ms, from an event to the start of the pass that acts on it?

Answer: ms

3. Which is a strength of a hardware FSM over a software one?

  • Easier to change after deployment
  • Reacts within one clock cycle and doesn't depend on a program running correctly
  • Can log events to a file
  • Cheaper to update

4. A Moore machine outputs 1 for one clock whenever the last 3 input bits were 101 (overlaps allowed). Input, first bit first: 000101110111. How many clocks have output 1?

Answer:

5. A junction controller passes a safety audit 'no conflicting greens in any reachable state'. Why check every reachable state, not just a normal cycle?

  • To make the report longer
  • Because rare paths (button presses, emergency pre-emption) reach states the normal cycle never shows
  • Because the clock might stop
  • It is not necessary

Apply it

Write pseudocode for a pedestrian crossing with states GREEN_CARS, AMBER, RED_ALL, WALK, FLASHING. Include the button as an event and every timeout. Then list two input sequences you would test and the states each visits.

Reflect

What would you want a hardware safety monitor to check even if the software controller is correct?

Week 25: Instruction set architecture

This week you will

The contract between code and silicon

Code compiled years ago still runs on brand-new processors with completely different insides. What promise makes that possible?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

An instruction set is one of the most important interfaces in engineering: software teams target it and hardware teams implement it, and neither has to know the other's details. Understanding it explains compilers, emulators and why some chips can't run some apps.

Goals

Predict

BUILD 008's Nibble machine has LOAD, ADD, STORE, JNZ and HALT but no SUBTRACT. Can it subtract 1?

  1. No, never
  2. Yes: ADD 15 in 4-bit arithmetic is the same as subtracting 1
  3. Only with a new chip
  4. Only for even numbers

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Open the Virtual Computer at Level 4 and read the five instructions. Before attempting the multiply task, write a three-line program that copies M0 into M3, run it step by step, and note what each instruction changes: the register A, a flag, memory or the program counter.

What the interactive shows, in words

The Virtual Computer Level 4 shows the Nibble machine: register A, flags Z and C, 16 data cells and a program of up to 16 lines. LOAD a copies M[a] into A, ADD a adds M[a] into A (4 bits, carry into C), STORE a copies A into M[a], JNZ p jumps to line p if A was not zero, HALT stops.

Understand

What an ISA promises

An instruction set architecture defines: the registers visible to programs (Nibble has one, A, plus flags Z and C); the instructions and exactly what each does; their encoding as bits; how operands are found (addressing modes: a constant, a register, a memory address); and how memory and I/O look to software. Anything not in the contract is free for the hardware designer to change.

Architecture vs microarchitecture

Two chips implementing the same ISA can be utterly different inside: one takes 3 clock cycles per instruction, another overlaps many instructions in a pipeline. Both run the same program and get the same answers; only the speed differs. That separation is why software lasts longer than any one chip.

Design styles

Accumulator machines (like Nibble) keep one working register. Load–store / RISC machines (like RISC-V or the TV-16 teaching format) do arithmetic only between registers, with separate load and store instructions. CISC machines allow memory operands in arithmetic. Fewer, simpler instructions make hardware simpler; richer ones make programs shorter.

Explain it another way: intuitive

The ISA is the menu of a restaurant. Diners (programs) order from the menu; the kitchen (hardware) can be reorganised any way it likes, as long as every dish comes out as described.

Explain it another way: technical

An ISA also fixes word size, endianness, the exception and interrupt model, and privilege levels. Extensions (like vector instructions) are added as optional parts of the contract.

Explain it another way: mathematical

With a k-bit opcode field you can name at most 2^k operations; with an r-bit register field, 2^r registers. Nibble: 4-bit opcode (16 possible, 5 used), 4-bit operand (16 addresses).

Explain it another way: applied

Emulators run one ISA's programs on another by decoding each instruction in software. Phone makers can license the Arm ISA and design their own microarchitectures, and RISC-V is an open ISA anyone may implement.

Try these examples

Example 1

Write a Nibble program that sets M3 to M0 + M0.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Which of these is NOT part of an ISA?

  • The list of instructions
  • The number of programmer-visible registers
  • How many clock cycles the cache takes on a miss
  • How instructions are encoded in bits

2. Two processors implement the same ISA. One is three times faster. What can you say?

  • They must have identical circuits
  • The same program gives the same results on both; only timing differs
  • Programs must be rewritten for the faster one
  • The faster one must have more instructions

3. An ISA has a 6-bit opcode field. At most how many different operations can it encode?

Answer: operations

4. TV-16 instructions are 16 bits: opcode = bits 15–12, rd = bits 11–9, rs = bits 8–6, imm = bits 5–0. The word is 0x67B2. What is the rs field, in decimal?

Answer:

5. On the 4-bit Nibble machine, A = 9 and M1 = 8. After ADD 1, what does A hold?

Answer:

Apply it

Propose one new instruction for the Nibble machine that would make its programs shorter. Specify it like an ISA manual: mnemonic, opcode (choose an unused one), what it does to A, flags, memory and PC, and one example.

Reflect

Why might an ISA designer deliberately leave out an instruction that programmers would find useful?

Instructions are just numbers

The hex number 0x1405 can be a price, a colour or an instruction that puts 5 into register 2. How does the processor know which?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Debuggers, disassemblers, bootloaders and emulators all read raw instruction words. Encoding by hand once makes every later encounter with machine code, hex dumps and bit fields far less mysterious.

Goals

Predict

In TV-16, the opcode is bits 15–12. The word is 0xA2C3. What is the opcode in decimal?

  1. 2
  2. 10
  3. 12
  4. 163

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Encode LDI R2, 5 and ADD R1, R2, 0 and write down their hex words. Then type A2C3 into the decoder and explain each field. Finally switch to the Nibble format and encode LOAD 2: why is it 0x12?

What the interactive shows, in words

The encoder shows each bit of the word coloured by field. LDI R2, 5 encodes to 0x1405; ADD R1, R2, 0 to 0x2280; 0xA2C3 decodes to opcode 10 (ADDI), rd = 1, rs = 3, imm = 3. In the Nibble format LOAD 2 is opcode 1 and argument 2, so 0x12 = 18.

Understand

Fields

An instruction word is divided into fields. TV-16 (a teaching format made for these lessons) uses 16 bits: opcode bits 15–12 (16 operations), rd bits 11–9 and rs bits 8–6 (registers R0–R7), and imm bits 5–0 (a constant 0–63). Nibble packs an opcode nibble and a 4-bit argument into 8 bits: word = opcode × 16 + arg.

Encoding and decoding

To encode, shift each field to its position and combine: word = opcode·2¹² + rd·2⁹ + rs·2⁶ + imm. LDI R2, 5 = 1·4096 + 2·512 + 0 + 5 = 5125 = 0x1405. To decode, shift right and mask: rd = (word >> 9) AND 7. In hardware, decoding is just wiring: each field's bits run straight to the circuits that need them.

Bits are a budget

Every field width is a trade-off. More opcode bits allow more instructions; more register bits allow more registers; more immediate bits allow bigger constants. A 16-bit word can't have all three. That is why real ISAs have several formats and why loading a large constant can take two instructions.

Explain it another way: intuitive

An instruction word is like a form with boxes: the first box says what to do, the next boxes say with what. The processor always reads the boxes in the same places.

Explain it another way: technical

Fixed-length encodings (RISC-V, TV-16) make decoding fast and parallel. Variable-length ones (x86) save memory but need more complex decoders. Keeping register fields in the same position across formats lets hardware read registers before the opcode is fully decoded.

Explain it another way: mathematical

field = ⌊word / 2^lo⌋ mod 2^(hi−lo+1). 0xA2C3 = 41667: opcode = ⌊41667/4096⌋ = 10, rd = ⌊41667/512⌋ mod 8 = 1, rs = ⌊41667/64⌋ mod 8 = 3, imm = 41667 mod 64 = 3.

Explain it another way: applied

When a microcontroller crashes, the debugger shows the faulting address and a hex word; decoding that word tells you which instruction faulted and with which registers.

Try these examples

Example 1

Decode TV-16 word 0x2280.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Encode TV-16 'LDI R2, 5' (opcode 1, rd 2, rs 0, imm 5) and give the word in decimal.

Answer:

2. What is the 8-bit Nibble machine code for STORE 7 (STORE has opcode 3), in decimal?

Answer:

3. TV-16 instructions are 16 bits: opcode = bits 15–12, rd = bits 11–9, rs = bits 8–6, imm = bits 5–0. The word is 0x5738. What is the rs field, in decimal?

Answer:

4. TV-16's immediate field is 6 bits, unsigned. What is the largest constant LDI can load in one instruction?

Answer:

5. A designer wants 16 registers instead of 8 in TV-16, keeping 16-bit words and two register fields. What must shrink?

  • Nothing
  • The opcode or immediate fields lose 2 bits in total
  • The word must become 15 bits
  • The registers must become smaller

6. TV-16 instructions are 16 bits: opcode = bits 15–12, rd = bits 11–9, rs = bits 8–6, imm = bits 5–0. The word is 0xD6BB. What is the rs field, in decimal?

Answer:

Apply it

Write a four-instruction TV-16 program that loads 5 and 7 into R1 and R2, adds them into R1 and halts. Encode each instruction in hex, then swap with a partner and decode theirs.

Reflect

Why is fixed-length encoding easier for hardware than variable-length?

Tracing a program, counting cycles

Two programs give the same answer. One takes 12 clock cycles, the other 33. How do you know before you run them?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Performance engineers predict a program's speed by counting what the hardware must do. Tracing by hand also finds bugs that testing misses: off-by-one loops, a flag set by the wrong instruction, a store to the wrong address.

Goals

Predict

In the Nibble 'Count down' program with M0 = 3, how many instructions execute before it halts (counting HALT)?

  1. 5
  2. 8
  3. 11
  4. 15

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Run 'Add two numbers' to the end and record the cycle count and the carry. Then step through 'Count down' one instruction (three clicks) at a time, writing a trace table: line, instruction, A, Z, M0. Check your predicted cycle count.

What the interactive shows, in words

The stepper runs 'Add two numbers' in 4 instructions (12 cycles), leaving M2 = 1 with C = 1. 'Count down' from 3 executes LOAD, three rounds of ADD 15, STORE 0, JNZ 1, then HALT: 11 instructions, 33 cycles, ending with M0 = 0 and Z = 1.

Understand

A trace table

List, for each instruction executed: the program counter, the instruction, and every register, flag and memory cell it changes. Only change what the instruction says it changes: STORE writes memory but leaves A and the flags alone. Most tracing mistakes are updating something an instruction doesn't touch.

Flags are how machines decide

Arithmetic sets flags as a side effect: Z (result was zero) and C (a carry fell off the top). A conditional jump like JNZ reads Z. In 'Count down', ADD 15 sets Z when A reaches 0; STORE in between doesn't disturb Z; JNZ then falls through to HALT.

Counting cycles

Cycles = Σ (instructions executed × cycles per instruction). A loop body of b instructions run n times costs b·n plus setup. In the stepper's model every instruction takes 3 cycles; real processors vary by instruction. The executed count, not the program length, decides speed: a 5-line loop can run thousands of instructions.

Explain it another way: intuitive

Tracing is being the processor with a pencil: read a line, do exactly what it says, update your notes, move to the next line (or jump).

Explain it another way: technical

CPI (cycles per instruction) times instruction count times clock period gives run time: T = IC × CPI × T_clk, the 'iron law' of processor performance.

Explain it another way: mathematical

Count down from M0 = m: instructions = 1 + 3m + 1 = 3m + 2; cycles = 3(3m + 2) = 9m + 6. For m = 3: 33 cycles.

Explain it another way: applied

Embedded engineers count cycles in interrupt handlers to guarantee they finish before the next interrupt; an audio filter that overruns its cycle budget causes audible glitches.

Try these examples

Example 1

Trace 'Add two numbers' with M0 = 9, M1 = 8.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A straight-line program executes 6 instructions on a machine that takes 3 cycles per instruction. How many cycles?

Answer: cycles

2. In the Nibble machine, which instruction does NOT change the Z flag?

  • LOAD
  • ADD
  • STORE
  • All of them change it

3. Using cycles = 9m + 6 for the count-down program, how many cycles does it take from M0 = 7?

Answer: cycles

4. A program spends 2 cycles on setup, then runs a loop 15 times with 8 cycles per pass. A new instruction cuts the loop body to 6 cycles. What is the speed-up (old cycles ÷ new cycles), to 2 decimal places?

Answer:

5. Two 8-bit registers start at A = 0, B = 4. On every clock edge both transfers happen at once: A ← B and B ← (A + B) mod 256. What does B hold after 6 clock cycles?

Answer:

Apply it

Write a Nibble program that adds M0 to itself M1 times without using the multiply answer from the build: instead, explain your loop's trace for M0 = 2, M1 = 3, count its cycles with the 3-cycle model and give a formula for any M1.

Reflect

Which part of your trace table was easiest to get wrong, and how would you check it?

Week 26: Register-transfer-level design

This week you will

Thinking in register transfers

Can you swap two registers in one clock cycle without a spare? In software you need a temporary variable. In hardware you don't. Why?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Register-transfer level (RTL) is the language chip designers actually think in: not individual gates, but values moving between registers on clock edges. Hardware description languages like Verilog and VHDL are written at this level.

Goals

Predict

Registers A = 3, B = 5. On one clock edge both A ← B and B ← A happen. What are A and B afterwards?

  1. A = 5, B = 5
  2. A = 5, B = 3
  3. A = 3, B = 3
  4. It depends on which happens first

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Load the 2:1 multiplexer preset and work out its truth table. Then sketch on paper how two multiplexers and two registers implement 'on each clock: if S = 1 then swap A and B, else hold'.

What the interactive shows, in words

The 2:1 multiplexer outputs A when select S = 0 and B when S = 1. Two of them in front of registers A and B, with S = 1 feeding each register the other's value and S = 0 feeding each its own value, implement 'swap or hold' on each clock edge.

Understand

The notation

A ← A + B means: on the next clock edge, register A loads the value of A + B computed from the current outputs. A condition can guard it: if LOAD: R ← D. Several transfers listed for the same cycle all happen together. RTL hides gate-level detail while keeping exact timing.

Same edge, old values

Every register's input is computed from the values before the edge, and every register loads at the edge. So A ← B and B ← A swap; A ← B and B ← (A + B) steps a Fibonacci pair (3, 5 → 5, 8). Software executes lines in order, so the same two lines would give a different answer: a classic bug when translating between the two.

Datapath building blocks

Registers hold values (with a load-enable). Multiplexers choose which value goes where. The ALU computes (add, subtract, AND…). Buses carry values between them. A control unit sets the multiplexer selects, ALU operation and load-enables each cycle, deciding which transfers happen.

Explain it another way: intuitive

Picture everyone in a room passing a ball on a whistle. On the whistle, everyone throws at once and catches at once, so two people can swap balls without dropping one.

Explain it another way: technical

In Verilog, non-blocking assignments (a <= b; b <= a;) model this simultaneous behaviour inside a clocked block; blocking assignments (=) behave like software and would not swap.

Explain it another way: mathematical

State update as a vector function: (A, B)ₖ₊₁ = F((A, B)ₖ). For A ← B, B ← A + B mod 256 from (3, 5): (5, 8), (8, 13), (13, 21)…

Explain it another way: applied

A processor's program counter is a register with an incrementer and a multiplexer: PC ← PC + 1 normally, PC ← target on a jump. That single RTL line is in every CPU.

Try these examples

Example 1

A = 2, B = 7. Each cycle: A ← A + B, B ← A. Find A and B after 2 cycles.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Why does A ← B, B ← A in one cycle swap correctly in hardware?

  • The hardware secretly uses a temporary register
  • Both registers sample their inputs at the same edge, from the old values
  • A updates first, then B
  • It doesn't; it gives A = B

2. An 8-bit register R starts at 210. Each clock edge performs R ← (R + 7) mod 256. What does R hold after 3 cycles?

Answer:

3. A = 1, B = 1. Each cycle: A ← B, B ← A + B. What is B after 4 cycles?

Answer:

4. Which block lets a register choose between keeping its value and loading a new one?

  • An ALU
  • A multiplexer (or a load-enable built from one)
  • A decoder
  • A clock divider

5. Two 8-bit registers start at A = 0, B = 4. On every clock edge both transfers happen at once: A ← B and B ← (A + B) mod 256. What does B hold after 6 clock cycles?

Answer:

Apply it

Write the RTL (one cycle per line) for a datapath that computes the sum of M[0]…M[3] into register S using a counter I, and say which multiplexers and load-enables the control unit must drive each cycle.

Reflect

What bug would you expect when someone translates RTL directly into ordinary sequential code?

The control unit is a state machine

A processor's datapath can add, store and jump, but it does nothing on its own. What tells each part when to act?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

This is where state machines, register transfers and instruction sets meet. Once you see the control unit as an FSM driving control signals, a processor stops being a black box and becomes something you could design.

Goals

Predict

During the fetch step, which transfer happens?

  1. A ← A + M[a]
  2. IR ← ROM[PC]
  3. M[a] ← A
  4. PC ← a

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Load 'Double twice' and click one cycle at a time. For each cycle write the RTL line and the control signals shown. Which signals appear in every instruction, and which only for ADD?

What the interactive shows, in words

Stepping 'Double twice', every instruction starts with fetch (rom_read, ir_load: IR ← ROM[PC]) and decode (pc_inc: PC ← PC + 1). Execute differs: LOAD asserts ram_read, alu_pass, a_load, flags_load; ADD asserts ram_read, alu_add, a_load, flags_load; STORE asserts ram_write; HALT asserts halt.

Understand

Fetch, decode, execute as RTL

In the stepper's model each instruction takes three cycles. Fetch: IR ← ROM[PC]. Decode: PC ← PC + 1 while the control unit reads the opcode. Execute: the opcode's own transfer, such as A ← A + M[a] with flags updated, or if Z = 0: PC ← a. Then back to fetch.

Control signals

Each transfer happens because control lines are on: rom_read and ir_load in fetch; pc_inc in decode; for ADD, ram_read, alu_add, a_load and flags_load. The control unit is an FSM whose state is the step (fetch, decode, execute) and whose outputs, depending on that state and the opcode, are these signals.

Hard-wired or microcoded

A hard-wired control unit computes the signals with gates. A microcoded one stores them in a small memory addressed by (opcode, step): each row is one cycle's control word. Microcode is easier to change and fix; hard-wired is faster. Ben Eater's breadboard computer uses EEPROMs as microcode.

Explain it another way: intuitive

The datapath is an orchestra; the control unit is the conductor reading a score, telling each section exactly when to play.

Explain it another way: technical

Pipelined processors overlap fetch, decode and execute of different instructions, so the control unit must also handle hazards: a jump makes the already-fetched next instruction wrong.

Explain it another way: mathematical

Microcode ROM size = (number of opcodes) × (steps per instruction) × (control-word width). Nibble with 16 opcodes, 3 steps and 8 signals: 16 × 3 = 48 words of 8 bits.

Explain it another way: applied

Modern x86 processors still contain microcode for complex instructions, and vendors ship microcode updates to fix bugs found after chips are manufactured.

Try these examples

Example 1

List the control signals for STORE 4 in each of its three cycles.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. In the stepper's model, what does the decode step change?

  • A
  • The flags
  • PC ← PC + 1
  • Memory

2. Which control signal is asserted for every instruction in the model?

  • alu_add
  • ram_write
  • ir_load
  • flags_load

3. A microcoded machine has 16 opcodes, 4 steps per instruction and a 12-bit control word. How many bits of microcode ROM?

Answer: bits

4. An 8-bit register R starts at 238. Each clock edge performs R ← (R + 25) mod 256. What does R hold after 4 cycles?

Answer:

5. During JNZ's execute step with Z = 1, what happens?

  • PC ← arg
  • Nothing changes: PC already points at the next line
  • A ← 0
  • The machine halts

Apply it

Write the full control table (opcode × step → signals) for the five Nibble instructions. Then add a new instruction of your choice and the rows it needs.

Reflect

Why might a designer choose microcode even though it is slower?

How fast can the clock tick?

Why can't a processor designer just set the clock to 100 GHz and make everything 25 times faster?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Every chip's top speed is set by its slowest path between two registers. Finding and shortening that path is a core skill of digital designers, and it explains why faster adders, pipelines and multi-cycle designs exist.

Goals

Predict

A path has clock-to-Q 0.2 ns, logic 1.0 ns and setup 0.1 ns. What is the shortest safe clock period?

  1. 1.0 ns
  2. 1.2 ns
  3. 1.3 ns
  4. 0.3 ns

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Open the Virtual Computer at Level 3. Find a pair of 4-bit numbers whose carry ripples through all four columns and count the gate delays on the settle clock. If each gate takes 0.1 ns, how long is the adder's longest path?

What the interactive shows, in words

In the build's ripple adder, 0111 + 1001 makes a carry in column 0 that ripples through every column: the carry out settles after 9 gate delays (1 for the first XOR, then 2 per bit). At 0.1 ns per gate that is 0.9 ns of logic.

Understand

The critical path

Every path from a register output through gates to a register input must settle within one clock period. The longest one sets the clock. In a ripple-carry adder it is the carry rippling through every column: about 2 gate delays per bit, so a 32-bit ripple adder is roughly eight times slower than a 4-bit one.

Shortening it

Designers attack the critical path with faster circuits (carry-lookahead adders compute carries in parallel at the cost of more gates), or by pipelining: putting registers in the middle of a long path so each piece fits a shorter period. The clock speeds up; each operation now takes more cycles, but a new one can start every cycle.

More cycles or faster cycles?

Run time = cycles × T_clk. A single-cycle design does everything in one long cycle; a multi-cycle design (like the 3-step model in the stepper) uses several short ones. Which wins depends on how evenly the work splits: the iron law T = IC × CPI × T_clk keeps every trade-off honest.

Explain it another way: intuitive

A relay race where each runner must finish their leg before the next whistle. The whistle can only blow as often as the slowest leg allows.

Explain it another way: technical

Hold time is the other constraint: the input must not change too soon after the edge, which limits the shortest paths. Clock skew between registers adds to or subtracts from the available time.

Explain it another way: mathematical

f_max = 1/(t_cq + Σ t_gate + t_su). For a 4-bit ripple adder with 9 gate delays of 0.1 ns plus 0.2 ns and 0.1 ns: T = 1.2 ns, f_max ≈ 833 MHz.

Explain it another way: applied

Chip design tools run static timing analysis on every path in a design, millions of them, and report 'slack': how much time is left over. Negative slack means the chip won't work at the target clock.

Derivation: The register-to-register timing constraint
  1. At a clock edge the launching register's output changes after t_clk→Q.

  2. The new value travels through combinational logic; the slowest route, the critical path, takes t_logic.

  3. The capturing register needs its input stable for t_setup before the next edge.

  4. So the next edge must come no sooner than T_clk ≥ t_clk→Q + t_logic + t_setup, and f_max = 1/T_clk.

  5. Example: 0.2 + 10 × 0.1 + 0.1 = 1.3 ns, so f_max = 1/1.3 ns ≈ 769 MHz.

Try these examples

Example 1

A 16-bit ripple adder has 2 gate delays per bit plus 1, at 0.08 ns each, between registers with t_cq = 0.15 ns and t_su = 0.1 ns. Find f_max.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. t_clk→Q = 0.2 ns, logic = 1.0 ns, t_setup = 0.1 ns. What is f_max, in MHz (nearest whole number)?

Answer: MHz

2. What sets the maximum clock frequency of a synchronous design?

  • The shortest register-to-register path
  • The longest register-to-register path (the critical path)
  • The number of registers
  • The supply voltage only

3. A register-to-register path has clock-to-Q delay 0.15 ns, 12 gates of 0.1 ns each on its longest path, and setup time 0.1 ns. What is the maximum clock frequency, in MHz (to 1 decimal place)?

Answer: MHz

4. Adding a pipeline register halfway along the critical path usually…

  • Halves the clock frequency
  • Allows a faster clock but makes each operation take one more cycle
  • Removes the need for a clock
  • Has no effect

5. A register-to-register path has clock-to-Q delay 0.3 ns, 11 gates of 0.05 ns each on its longest path, and setup time 0.1 ns. What is the maximum clock frequency, in MHz (to 1 decimal place)?

Answer: MHz

Apply it

Using the Level 3 data, compare a 4-bit and a 16-bit ripple adder's longest path. Propose one change from this lesson that would let the 16-bit adder run at the 4-bit adder's clock, and state its cost.

Reflect

Why do you think clock frequencies of desktop processors stopped rising quickly after the mid-2000s? (Hint: last week's power formula.)

Week 27: Virtual computing system project

This week you will

Project: program the processor

The Nibble machine can't multiply. By the end of this lesson it will, using only adding, storing and one conditional jump.

About 60 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

This is the first half of the term project: make a real program work on a machine with almost nothing in its instruction set, then measure it like an engineer. The measurement is what makes the second half, speeding it up, possible.

Goals

Predict

Multiplying x by y by repeated addition, roughly how does the number of instructions grow with y?

  1. It stays constant
  2. In proportion to y
  3. In proportion to y²
  4. In proportion to log y

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Do Level 4: write the multiply program (M0 × M1 into M2, with M15 = 15). Plan it as a flowchart first, then write it, step through it for 3 × 4, and run the server's tests. Record how many steps it took for each test pair.

What the interactive shows, in words

Level 4 of the Virtual Computer provides a program editor with LOAD, ADD, STORE, JNZ and HALT, a step-by-step trace, and server tests on six pairs including zeros. The program must leave M0 × M1 (4-bit) in M2 using M15 = 15 as −1.

Understand

Plan with a loop invariant

Before coding, state what stays true each time round the loop, for example: 'M2 + x × (remaining y) = x × original y'. Each pass adds x to M2 and takes 1 off y; when y reaches 0 the invariant gives M2 = x × y. Invariants turn 'I think it works' into an argument.

Test the edges

Test small ordinary cases (3 × 4), the identities (1 × 7), and the zeros (0 × 6, 6 × 0). In 4 bits, results above 15 wrap, and a loop that counts y down with ADD 15 behaves surprisingly when y starts at 0: trace it and explain what happens. The build's own notes describe the behaviour you should be able to justify.

Measure, don't guess

Record instructions executed for several y and fit a formula: instructions = b·y + s, where b is the loop body length and s the setup and HALT. Multiply by cycles per instruction (3 in the stepper's model) for cycles. This table is your 'before' measurement for the speed-up.

Explain it another way: intuitive

You are teaching a very literal helper to multiply using only 'add this', 'remember this' and 'if not zero, go back'. Every detail has to be spelled out.

Explain it another way: technical

Repeated-addition multiply is O(y) time. Shift-and-add multiplication is O(number of bits), which is why real ALUs or ISAs include shifts.

Explain it another way: mathematical

If the loop body has b instructions and runs y times, with s other instructions: N(y) = b·y + s and cycles = CPI · N(y).

Explain it another way: applied

Small microcontrollers without a hardware multiplier still multiply in software routines written exactly this way, carefully optimised because they run constantly in control loops.

Try these examples

Example 1

A different looping program's measured step counts are 14 for y = 2 and 26 for y = 4. Find b and s.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Step counts are 25 for y = 3 and 41 for y = 5. Assuming N = b·y + s, what is b?

Answer: instructions

2. The Nibble machine multiplies 5 × 4 in 4-bit arithmetic. What value ends up in the answer cell?

Answer:

3. Why state a loop invariant before writing the program?

  • It makes the program run faster
  • It gives a reason the result is right when the loop ends, not just a hope
  • The assembler requires it
  • It replaces testing

4. A program spends 2 cycles on setup, then runs a loop 15 times with 8 cycles per pass. A new instruction cuts the loop body to 6 cycles. What is the speed-up (old cycles ÷ new cycles), to 2 decimal places?

Answer:

5. Two 8-bit registers start at A = 0, B = 4. On every clock edge both transfers happen at once: A ← B and B ← (A + B) mod 256. What does B hold after 6 clock cycles?

Answer:

Apply it

Deliverable 1 of the term project: a working multiply program that passes the build's tests, a trace table for one test pair, a table of instructions executed for at least four values of y, and your fitted formula N(y) = b·y + s with cycles at 3 per instruction.

Reflect

Which edge case surprised you most, and how did you explain it?

Project: then speed it up

One new instruction or one new gate path could make your multiply several times faster. Which change gives the most speed for the least hardware?

About 60 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Every real processor feature, from multiply instructions to branch predictors, began as an argument like the one you will make: here is the bottleneck, here is the change, here is what it buys and what it costs. This is architecture as engineers practise it.

Goals

Predict

A loop has 8 instructions per pass and 1 of setup. A new instruction removes 3 instructions from the body. For y = 10, roughly what speed-up?

  1. About 1.1×
  2. About 1.6×
  3. About 3×
  4. About 8×

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Do Level 5: investigate how the adder's longest gate path grows with bit width (ripple versus carry lookahead) using at least four sizes. Then use your findings to estimate the hardware cost of the speed-up you propose for the multiply.

What the interactive shows, in words

Level 5 builds adders of several widths from gates and reports gate counts and longest-path depth: the ripple adder's depth grows by about 2 gate delays per bit, while carry lookahead stays shallower but uses more gates. These numbers give the hardware cost of speed.

Understand

Three kinds of speed-up

Fewer instructions: a new instruction does the work of several (a combined 'decrement and jump if not zero', or a SHIFT for shift-and-add multiply). Fewer cycles per instruction: overlap fetch with execute. Shorter cycle: a faster adder (lookahead) shortens the critical path. The iron law, T = IC × CPI × T_clk, tells you which term each idea attacks.

Quantify it

Speed-up = old time ÷ new time, from your measured baseline. Changes that only touch the loop body help most when y is large; setup costs dominate when y is small. Always state the input you assumed. If a change also lengthens the clock period, include that: a 2× reduction in cycles with a 1.5× longer period is only a 1.33× speed-up.

Price it

New instructions need opcodes (Nibble has spare ones), control-table rows and possibly datapath blocks: a shifter, an extra register, a second adder. Carry lookahead uses more gates to shorten the path. A good design note gives the speed-up, the extra hardware and one risk, and recommends honestly, including 'not worth it'.

Explain it another way: intuitive

You can make a delivery round faster by carrying more parcels per trip, walking faster, or finding a shorter route. Each costs something different.

Explain it another way: technical

Amdahl's law: if a fraction p of the time is sped up by s, overall speed-up = 1/((1 − p) + p/s). Optimising the part that takes 5 % of the time can never give more than 5 % back.

Explain it another way: mathematical

Speed-up = (s + b·n)/(s + b'·n). As n → ∞ it tends to b/b'. Shift-and-add reduces passes from y to the number of bits of y (4 on Nibble), so for y = 15 it can beat any constant-factor tweak.

Explain it another way: applied

Processor teams decide on new instructions by profiling real workloads and estimating exactly these numbers; adding hardware multiply-accumulate to microcontrollers came from signal-processing code like the filters earlier this term.

Try these examples

Example 1

Setup 2 cycles, 10 passes of 24 cycles. A change cuts a pass to 15 cycles but lengthens the clock period by 10 %. Speed-up?

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Setup 1 instruction, loop of 7 instructions run 10 times. A change cuts the loop to 4. Speed-up (2 decimal places)?

Answer: ×

2. As the loop count grows very large, the speed-up from shrinking the body from b to b' approaches…

  • 1
  • b/b'
  • b − b'
  • The setup cost

3. A program spends 2 cycles on setup, then runs a loop 8 times with 8 cycles per pass. A new instruction cuts the loop body to 5 cycles. What is the speed-up (old cycles ÷ new cycles), to 2 decimal places?

Answer:

4. A change makes 60 % of a program's run time 3 times faster. Using Amdahl's law, what is the overall speed-up (2 decimal places)?

Answer: ×

5. A design halves cycle count but makes the clock period 1.5 times longer. Net effect?

  • 2× faster
  • 1.33× faster
  • 1.5× slower
  • No change

Apply it

Deliverables 2 and 3 of the term project: propose one hardware or ISA change, specify it precisely (opcode, RTL for each cycle, new datapath blocks), estimate the new cycle count for your four y values, and write a one-page design note on the speed-up and its gate cost, using your Level 5 data.

Reflect

Would your proposed change still be worth it if most real inputs had y ≤ 2? Why?

Signals meet hardware: the cycle budget

A 48 MHz microcontroller sounds fast. Can it filter a 48 kHz audio signal in real time? It depends on one division.

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

This lesson joins the two halves of the term. A real-time signal system has to finish its work on every sample before the next one arrives. Getting the budget wrong means dropped samples, glitches or a control loop that goes unstable.

Goals

Predict

A 48 MHz processor samples audio at 48 kHz. How many clock cycles does it have per sample?

  1. 48
  2. 1000
  3. 48,000
  4. 2304

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, simulate the pipeline: generate a 50 Hz sine plus noise sampled at 1 kHz, quantise it to 10 bits, then filter it with a moving average and with a first-order IIR. Count the arithmetic operations per sample for each and compare the outputs.

What the interactive shows, in words

In the simulated pipeline, the noisy 50 Hz sine sampled at 1 kHz and quantised to 10 bits is smoothed by both filters. A moving average with a running sum costs about one add and one subtract per sample; the first-order IIR costs two multiplies and one add, and gives a smoother output with a small delay.

Understand

The pipeline

Sensor → analog anti-aliasing filter → ADC (sample rate fs, N bits) → digital filter → decision or output. Each stage has a requirement from this term: fs > 2 × the highest wanted frequency with margin; N bits for the SNR you need; a filter whose response keeps the band and rejects noise; and a processor that keeps up.

The cycle budget

Cycles available per sample = f_clk / fs. Processor load = fs × (cycles per sample) / f_clk. Keep it well under 100 %, because interrupts, communication and the rest of the program need cycles too. A first-order IIR needs about two multiplies and an add per sample; an M-point moving average can be done with a running sum in constant time.

Trading between stages

A better analog filter lets you sample more slowly, saving cycles. More bits cost ADC time and memory but not filter cycles. An IIR filter gives strong smoothing for a handful of cycles but with phase lag; a long FIR filter has linear phase but costs a multiply per tap. Systems engineering is choosing these together, not one at a time.

Explain it another way: intuitive

Samples arrive like items on a conveyor belt. You must finish with each one before the next arrives, or they pile up and fall off.

Explain it another way: technical

Hard real-time systems guarantee the worst-case execution time per sample, not the average. DMA can move samples from the ADC to memory without using the processor's cycles.

Explain it another way: mathematical

Budget B = f_clk/fs. 16 MHz at 8 kHz: B = 2000 cycles. A 64-tap FIR at 4 cycles per tap uses 256 cycles: 12.8 % load.

Explain it another way: applied

Digital hearing aids run filter banks on tiny, low-power processors; their designers balance sample rate, filter length and clock frequency so the battery lasts days, using exactly the P = αCV²f and cycle-budget arithmetic from this term.

Try these examples

Example 1

An 80 MHz processor filters a 44.1 kHz signal with a 128-tap FIR at 3 cycles per tap plus 100 cycles of overhead. What is the load?

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A 16 MHz microcontroller samples at 8 kHz. How many clock cycles are available per sample?

Answer: cycles

2. A 8 MHz processor needs 400 clock cycles to filter one sample. Ignoring everything else, what is the highest sample rate it can keep up with, in kHz?

Answer: kHz

3. A system is at 95 % load. Which change reduces load WITHOUT reducing the frequencies you can capture?

  • Halve the sample rate
  • Replace a long FIR filter with a first-order IIR that meets the smoothing requirement
  • Use fewer ADC bits
  • Lower the clock frequency

4. A 48 MHz processor filters a 48 kHz signal, using 400 cycles per sample. What percentage of its cycles does the filter use?

Answer: %

5. An ideal 16-bit ADC spans 0 to 2.5 V. What is its quantisation step Δ = V / 2^N, in millivolts?

Answer: mV

6. A 13920 Hz sinusoid is sampled at fs = 8000 Hz. At what frequency (between 0 and fs/2) does it appear in the samples, in hertz?

Answer: Hz

Apply it

Term synthesis: specify a vibration monitor for a 0–500 Hz band on a 48 MHz processor. Choose fs, ADC bits (with SNR), an anti-aliasing filter cut-off, a digital filter and its cycle cost, and show the processor load. One page, every number justified.

Reflect

Which decision in your synthesis constrained all the others most?