Skip to content

Search is only available in production builds. Try building and previewing the site to test it out locally.

Demo 7.1: From Voltage to Number, and Back

This module has had two halves that never quite met.

The analogue half was about voltages that can take any value at all: a diode’s forward drop, a transistor’s operating point, the output of a divider. The digital half was about voltages allowed only two values, and about groups of those standing for numbers.

Nothing so far has explained how you get from one to the other, and that boundary is where almost every useful device lives. A thermostat, a phone, a hearing aid and an oscilloscope all do the same two things: turn something physical into a number, and turn a number back into something physical.

There are two crossings, and this demonstration is about both.

A physical quantity becomes a voltage, and a voltage becomes a number.

The first step is a transducer plus a little circuit design. A light dependent resistor changes its resistance with light, and nothing on a microcontroller can read a resistance: every input it has measures a voltage. A divider converts one to the other.

The second step is the analogue to digital converter, and the whole of it is one idea: compare the input against a finite set of equally spaced levels and report which one it is nearest. Everything students find surprising about ADCs falls out of “finite”:

  • There is a smallest change the converter can see.
  • There is an error on every reading, and it is not a fault.
  • Outside the range, the answer is just the largest or smallest code, whatever the input does.
  • More bits do not make a measurement more accurate if the reference is wrong or the signal is noisy.

A number becomes a voltage, and the honest answer is that most small microcontrollers cannot do it.

What they have instead is a pin that switches between two voltages very quickly, with the fraction of each period spent high under your control. The average is then what you asked for, and whether that counts as an analogue output depends entirely on whether the thing at the other end averages it. At any instant the pin is at 0 V or 5 V and never in between.

From Voltage to Number, and Back

A sensor onto a wire, a voltage into a number, a number back out as a duty cycle, and the threshold that manufactures the clean ones and zeros everything else has assumed.

A sensor gives you the wrong kind of electrical quantity, and the divider fixes that.

  • A light dependent resistor does exactly what its name says: its resistance falls as the light on it rises. Over the range a room sees, it moves across more than three decades.
  • Nothing on a microcontroller can read a resistance. Every input it has measures a voltage, so the resistance has to be turned into one first.
  • A voltage divider does it: put the sensor in series with a fixed resistor across the supply, and tap the middle. The tap sits at VCC × Rbottom / (Rtop + Rbottom).
  • Which arm the sensor goes in decides whether the voltage rises or falls with light. Both are correct circuits and they answer different questions.
  • The fixed resistor is a real design decision, not a value picked from the drawer. Get it wrong and the output barely moves across the whole range of light you care about.
Light falling on the sensor100 lux
The fixed resistor R4.9 kΩ

The square-root rule says 4.9 kΩ.

Where the sensor sits

Brighter light lowers the top resistance, so Vo rises.

The circuit
+5V0VVo3.781.6 kΩLDR4.9 kΩR
What the tap does across the whole range of light
0123450.11101001000light level (lux, logarithmic)Vo (volts)
sensor resistance now1.6 kΩ
output voltage3.778 V
swing across the useful range94.3 % of the supply
the best any R could give94.3 %
Choosing the fixed resistor, properly
  • Measure the sensor at its two extremes: covered by a finger, and with a light close to it. That is the range your circuit will actually see.
  • Here those are about 165 kΩ in the dark and 144 Ω in the bright, so the sensor moves by a factor of 1146.
  • Now ask which fixed resistor makes the output move the most between those two extremes, because that is what gives you the most to measure.
  • Differentiate the swing with respect to R and set it to zero. It comes out at R = √(Rmin × Rmax), the geometric mean.
  • Here that is √(144 Ω × 165 kΩ) = 4.9 kΩ, and it gives a swing of 94.3 per cent of the supply.
  • It is a genuine maximum rather than a rule of thumb: search numerically over every R and you land on the same value.
  • Try it. Set R to a hundred ohms and the output sits near one rail across almost the whole range: the sensor is always much larger, so it dominates the divider.
  • Set R to a megohm and the same thing happens at the other rail.
  • Only near the geometric mean does the output use most of the supply range, and using the range is what makes the reading worth having.
  • Then round to something in the kit. The maximum is broad, so being a factor of two out costs only a few per cent of swing.
  • Note also that the curve is not a straight line. The relationship between light and voltage is heavily curved, so equal steps in voltage are nothing like equal steps in light.
  • That is fine for detecting bright and dark, and something to be careful about if you ever want to report an actual measurement in lux.
This is the same divider you have already met, doing a different job
  • The demonstration on pull-up and pull-down resistors used a divider to hold a logic input at a defined level, where only the two ends of the range mattered.
  • Here the whole range matters, because the point is the value in the middle rather than which end it is nearer.
  • The arithmetic is identical and only the intent has changed, which is a good sign that the arithmetic is worth knowing.
  • One practical difference: a pull resistor is chosen so that the input current does not disturb it, and a sensing divider is chosen so that the swing is as large as possible. Different criteria, same expression.
  • Whatever reads this tap must also draw negligible current from it, or it becomes a third resistor in the divider. A microcontroller analogue input does, which is why this works at all.

Open The sensor and the divider.

An LDR’s resistance falls as light rises, and it moves a very long way: about 165 kΩ with a finger over it and about 144 Ω under a phone torch. That is a factor of more than a thousand.

Drag the light slider and watch the resistance change, then watch what the divider does with it. Swap the sensor between the top and bottom arms and notice that both are correct circuits answering different questions: with the sensor on top, brighter light raises the output.

Now for the part that is actually a design decision. Drag the fixed resistor R to 100 Ω and watch the output sit near one rail across nearly the whole range of light. Drag it to a megohm and the same thing happens at the other rail. Only in between does the output use most of the supply.

The best value is not a guess:

Maximise the swing R/(R+Rmin) − R/(R+Rmax) by differentiating and setting to zero. You get a(R+b)² = b(R+a)², which rearranges to R = √(Rmin × Rmax), the geometric mean.

Here that is √(144 Ω × 165 kΩ) ≈ 4.9 kΩ, and it gives a swing of 94% of the supply. It is a genuine maximum, not a rule of thumb: search numerically over every possible R and you land within 0.06% of the same value.

Notice also that the curve is heavily non-linear. Equal steps in voltage are nothing like equal steps in light, which is fine for telling bright from dark and something to be careful about if you ever want to report an actual measurement.

Step 2: Watch a continuous voltage become a number

Section titled “Step 2: Watch a continuous voltage become a number”

Open Quantising and pull the resolution down to 3 or 4 bits.

The staircase becomes obvious. The dashed diagonal is the perfect converter nobody can build; the green staircase is what you actually get. Every voltage inside one step gives the same code, so the code cannot tell you where in the step you were.

The amber trace underneath is the difference, and the thing to see is that it never leaves the band of half a step either way. That is quantisation error. It is not a defect of the part, it is the price of describing something continuous with a finite number of names.

Now put it back to 10 bits at 5 V, which is what a typical microcontroller has:

Levels1024
Step size4.88 mV
Largest possible error± 2.44 mV

That step is the smallest input change guaranteed to change the code. Anything smaller may or may not, depending where in a step it falls.

Then push the input past the reference and watch the code stop at 1023 and stay there. That is clipping, and the information is simply gone, and nothing downstream can tell a small overload from a large one.

Open PWM, the pretend DAC.

Set the duty to 128 and choose An oscilloscope as the load. The amber trace lands on top of the cyan one, because a scope is fast enough to follow every edge. What it shows is a square wave between the rails, not a steady 2.5 V.

That is the honest description. The average is a property of the waveform over time, not a voltage present at any instant.

Now switch the load to An LED and your eye, then a multimeter, then a motor. Each is slower than the last, and each smooths more of the switching away until only the average is left. Nothing about the pin changed; only what is listening.

So the answer to “is PWM an analogue output?” is: only if something else does the averaging. Feed it straight into a comparator or an op-amp, which are fast, and they will follow the pulses.

One more thing worth noticing: the duty steps are equally spaced, and therefore so is the average voltage. But brightness is not linear in current, and your eye is not linear in brightness, so an evenly-stepped fade looks fast at the dim end and slow at the bright end. That is not a fault in the PWM; it is a fault in assuming the number, the voltage, the light and the perception are all the same shape.

Open The round trip.

Light → resistance → voltage → code → duty → brightness. Drag the light slider and watch every stage update.

The awkward join is in the middle. The converter gives 0–1023 and the output takes 0–255, so the numbers do not fit. Dividing by four is the usual answer and it is exact, because 1024 ÷ 4 = 256: no rounding, no remainder, no special cases at the ends.

What it does mean is that four different readings now produce the same output. Look at the list of codes that collapse together: that is 19.5 mV of input voltage mapping onto one output setting. The converter could tell them apart. Nothing downstream ever will.

That is fine here, because no eye can distinguish 1024 brightness levels. It would not be fine if the number were going into a calculation.

Then flip to Darker room, brighter LED and watch only the last step change. Inverting a relationship is one subtraction: 255 − x is just a relabelling of the same 256 settings.

The general form is worth being able to write down:

out = (in − inmin) × (outmax − outmin) / (inmax − inmin) + outmin

Dividing by four is that expression with the numbers arranged so nicely that everything cancels.

Step 5: Find out where logic levels come from

Section titled “Step 5: Find out where logic levels come from”

Open One bit is enough and press Show me the problem.

Not every measurement needs a number. Often the only question is whether something is above a level or below it, and a circuit that answers that has an analogue input and a single digital output, which makes it a converter with one bit of resolution. It is called a comparator.

This is the tab that closes the loop on the whole module. Every demonstration in the digital half assumed a wire carries a clean 0 or a clean 1. The world does not supply those. A threshold manufactures them.

Now look at what the output is doing: 12 changes of state, where the signal genuinely rises once and falls once. The circuit is not faulty: it is faithfully reporting every one of the crossings that a noisy signal makes while creeping past the level.

Press Show me the fix. Two levels instead of one: a higher one to go up and a lower one to come back down. Twelve transitions become two. That gap is hysteresis, and it is the most useful idea on the tab.

Then press Show me too much. The band is now wider than the signal reaches, so the event is missed entirely, with 0 transitions. Hysteresis is not free: any change smaller than the band cannot be detected at all.

Finally, set the noise slider to zero and put the band back to zero. Two transitions, perfectly clean. The problem does not exist in theory, only in the circuit you actually build.

Quiz
Select 0/1

A 10-bit converter with a 5 V reference reads a sensor. What is the smallest input change that is guaranteed to alter the code?

Quiz
Select 0/1

You have an LDR that measures 200 Ω in bright light and 200 kΩ in darkness. What fixed resistor gives the largest output swing from a voltage divider?

Quiz
Select 0/1

A microcontroller pin is set to a PWM duty of 50%. What would an oscilloscope show at the pin?

Concept Match

Match each item to what it is

Quiz
Select 0/4

A program reads a sensor with analogRead, getting 0 to 1023, and writes the result to a PWM output that takes 0 to 255. Which statements are true? Select all that apply.

Six things to take away.

  1. A sensor gives you the wrong kind of quantity. A divider turns a varying resistance into a varying voltage, and the fixed resistor is a real design decision: R = √(Rmin·Rmax) maximises the swing.
  2. A converter has a finite number of levels, and everything else follows. N bits gives 2^N levels; the step is Vref/2^N; the error is up to half a step and cannot be removed.
  3. Resolution is not accuracy. A wrong reference or a noisy signal makes extra bits worthless.
  4. PWM is not an analogue output. It is a switched output plus something slow enough to average it. At every instant the pin is at a rail.
  5. Rescaling throws information away. 1023 → ÷4 → 255 is exact and still discards three quarters of the distinctions, which is fine when you know it is happening.
  6. A threshold is a one-bit converter, and it is where the clean logic levels the whole digital half assumed actually come from. On a real, noisy signal it needs hysteresis, and too much hysteresis misses the event altogether.

The idea worth carrying furthest is the first sentence of point 2. Almost every surprise about digital measurement, whether it is readings that jitter in the last digit, a sensor that seems to have a resolution limit, or audio files having a bit depth at all, is that one fact about finite levels seen from a different angle.

The next demonstration puts all of this on an actual microcontroller: the pins that do the converting, the pins that do the switching, and the two functions that everything on such a board runs inside.