The idea: from a voltage to a number and back

A microcontroller only knows numbers, but a sensor gives a voltage and a motor or a lamp needs one. Two pieces of hardware sit at the border. An analog-to-digital converter (ADC) turns an input voltage Vin into an n-bit code. A PWM output goes the other way: it switches a pin between 0 V and VDD so fast that the average is the voltage you want. The page uses Vref = VDD = 3.3 V throughout.

A sensor voltage of 2.0 V goes into an 8-bit ADC, which gives code 155 to the CPU; the CPU writes OC1RS = 50 into the timer, whose PWM pin feeds an RC filter that gives 1.65 V.
The ADC turns 2.0 V into code 155; the timer turns the number 50 out of 100 into a 50 % wave that an RC filter averages to 1.65 V.

Successive approximation: a binary search in hardware

The most common microcontroller ADC is the successive-approximation register (SAR) ADC. A sample-and-hold keeps Vin still. Then, once per clock, the register tries one more bit, starting at the MSB. A small DAC turns the trial code into a voltage, trial × Vref / 2n, and a comparator answers one question: is Vin ≥ DAC? If yes, the bit stays 1; if no, it goes back to 0. After n clocks all n bits are known.

For 2.0 V at 8 bits (Demo 1), the first trial is 1000 0000 = 128 → 1.650 V: keep. Then 192 → 2.475 V is too big: clear. The range halves at every step, as in a binary search, and the result is code 155 = 1001 1011.

Eight trials for Vin = 2.0 V at 8 bits: 1.650 keep, 2.475 clear, 2.063 clear, 1.856 keep, 1.959 keep, 2.011 clear, 1.985 keep, 1.998 keep, closing in on the 2.0 V line.
Each trial is half a step closer: after 8 comparisons the DAC sits at 1.998 V, just under Vin.
bittrial codeDACVin ≥ DAC?bit
b71000 0000 = 1281.650 Vyes ✓1
b61100 0000 = 1922.475 Vno ✗0
b51010 0000 = 1602.063 Vno ✗0
b41001 0000 = 1441.856 Vyes ✓1
b31001 1000 = 1521.959 Vyes ✓1
b21001 1100 = 1562.011 Vno ✗0
b11001 1010 = 1541.985 Vyes ✓1
b01001 1011 = 1551.998 Vyes ✓1

A SAR ADC needs one comparator and n clocks per sample, so it is small and fast enough for most sensors (a 12-bit one at 1 million samples a second is common). A flash ADC uses 2n − 1 comparators and finishes in one clock; a sigma-delta ADC uses one bit at a very high rate and filters it, for audio and precise slow signals.

Resolution and quantization error

n bits give 2n codes, so one step, the LSB, is Vref / 2n. Every voltage inside a step gets the same code, so the ADC loses what lies between steps. That loss is the quantization error. The comparator rule above rounds down, so the error is between 0 and 1 LSB. Many ADCs shift their thresholds by half a step, which centres the error between −½ and +½ LSB.

With 3 bits (Demo 3) there are only 8 steps of 412.5 mV, and the sampled sine turns into a coarse staircase. The same 2.0 V comes out as code 4 = 100, which means 1.65 V: 0.35 V lost (Demo 2).

bitscodesLSB at 3.3 V2.0 V giveserror
38412.5 mV4 → 1.650 V350 mV
825612.89 mV155 → 1.998 V1.95 mV
1010243.22 mV620 → 1.998 V1.95 mV
1240960.81 mV2482 → 1.9997 V0.34 mV

Each extra bit halves the LSB (Demo 4). For a signal that fills the range, the error behaves like noise, and the signal-to-quantization-noise ratio is about 6.02·n + 1.76 dB: 50 dB at 8 bits, 74 dB at 12. Past a point more bits stop helping, because the sensor's own noise is bigger than one LSB. How often to sample is a separate question, the Nyquist limit, shown on Sampling and Aliasing.

PWM from a timer and a compare register

Most microcontrollers have no real DAC pin, but they all have timers. On a PIC32 (the board of Embedded I/O), Timer2 counts TMR2 = 0, 1, … PR2 and then wraps to 0, so one period is PR2 + 1 ticks. Output Compare 1 watches it: the OC1 pin goes high when TMR2 wraps and low when TMR2 reaches OC1RS. The fraction of the time the pin is high is the duty cycle:

duty=OC1RSPR2+1,Vavg=duty·VDD

With a 1 MHz timer clock and PR2 = 99, the period is 100 µs (10 kHz). OC1RS = 25 gives 25 % and an average of 0.825 V; OC1RS = 75 gives 75 % and 2.475 V (Demo 5). The hardware makes the wave by itself; the program only writes a new OC1RS to change it. PR2 + 1 also sets the PWM's resolution: 100 counts are 100 duty levels, about 6.6 bits.

Average voltage: LEDs and the RC filter

An LED on the pin blinks 10 000 times a second. The eye cannot follow that and sees the average, so 25 % looks dim and 75 % bright. A motor's inductance averages the same way. To get a real DC voltage, put an RC low-pass filter after the pin. It keeps the average and shrinks the switching into a small ripple. A bigger RC gives less ripple but reacts more slowly: the output needs about 5·RC to settle after the duty changes (Demo 6).

A 50 % PWM wave between 0 and 3.3 V; below it the RC output for RC = T swings from 1.25 to 2.05 V, and for RC = 10 T it stays between 1.61 and 1.69 V around the 1.65 V average.
Same 50 % wave, same 1.65 V average: RC = T leaves 0.808 V of ripple, RC = 10 T only 0.082 V.
dutyaverageripple, RC = Tripple, RC = 10 T
25 %0.825 V0.609 V0.062 V
50 %1.650 V0.808 V0.082 V
75 %2.475 V0.609 V0.062 V

The ripple is largest at 50 % and, when RC is much bigger than the period T, close to VDD · duty · (1 − duty) · T / RC. A faster PWM (smaller T) lowers it as well, at the cost of fewer duty levels for the same timer clock. A PWM pin plus a filter is a cheap DAC; QAM modulation needs a real, fast DAC to draw its waves.

Servo pulses

A hobby servo does not use the average. It expects one pulse every 20 ms (50 Hz) and reads the pulse's width: 1 ms means one end (0°), 1.5 ms the middle (90°), 2 ms the other end (180°). With the timer at 1 MHz, PR2 = 19999 gives the 20 ms period, and OC1RS = 1000, 1500 or 2000 gives the three pulses (Demo 7). The duty is only 5 % to 10 %; the servo's own controller turns the horn until it matches the pulse.

Sensors and other chips with their own ADCs often send their readings over a two-wire bus instead; see I²C bus transactions. The timer itself is a counter like the ones on Flip-Flops and Counter Design.

See also FIR and IIR filters, which smooths sampled readings with a moving average or a one-multiply feedback filter.

See also PID control of a motor's speed, where a feedback loop writes a new PWM duty every 10 ms.

See also driving loads from an MCU pin, where a thermistor in a voltage divider is read by the 12-bit ADC at 25 °C and 50 °C.

See also the watchdog timer, which resets the chip if a control loop like this one stops running.

What the page leaves out

The ADC is ideal: no offset, gain or linearity errors, no noise, and an exact reference. The sample-and-hold, the acquisition time, input impedance and the ADC's own clock are not drawn, and neither are the PIC32 register settings (AD1CON1, AD1CHS, the prescaler bits of T2CON, OC1CON). The RC output is shown in steady state, not while it settles, and the filter is a single RC stage with no load on it. Centre-aligned PWM, dead time for motor bridges, and real servo ranges (often 0.5 to 2.5 ms) are left out.

On the mind map

Open the Computer Architecture mind mapComputerArchitectureAbstraction and numbers: layers and bit patternsAbstraction and numbersCombinational logic: output depends only on inputsCombinational logicSequential logic: state held by a clockSequential logicMIPS software: how C becomes machine wordsMIPS softwareThe processor: datapath plus controlThe processorPipelines and parallelism: more instructions at oncePipelines and parallelismMemory and I/O: small fast near, big slow farMemory and I/OMemory arraysMemory arraysdecoder picks wordline, bitlines readCPU cacheCPU cachetag, index, offset; hit or missCache address breakdownCache address breakdownsets = lines/ways; tag = rest of addressCache Write PoliciesCache Write PoliciesWrite-back sends dirty lines at evictionLoop tiling and interchangeLoop tiling and interchangeWalk rows; tile so reused data fitsMemory hierarchyMemory hierarchyAMAT = hit time + miss rate × penaltyDRAM timingDRAM timingopen row is fast, row change is slowMESI and false sharingMESI and false sharinga write invalidates other copiesVirtual memoryVirtual memoryTLB caches the page tableEmbedded I/OEmbedded I/Odevices are addresses; poll or interruptMCU startup to mainMCU startup to mainCopy .data, zero .bss, then mainButton debounce FSMButton debounce FSMTwo equal 10 ms samples = one pressI2C BusI2C BusWired-AND bus: ACK, stretch, arbitrateUSB enumerationUSB enumerationAddress 0, descriptors, SET_CONFIGURATIONCAN bus arbitrationCAN bus arbitrationDominant 0 wins: lowest ID sends unharmedModbus RTU and TCPModbus RTU and TCPone master asks; bad CRC means silenceTDMA time-triggered busTDMA time-triggered busFixed slots; FTA drops extremes, averagesAMBA AXI, AHB, APBAMBA AXI, AHB, APBVALID and READY both 1 on the edgePCIe TLPsPCIe TLPsRequests by address, completions by IDBus vs Crossbar vs NoCBus vs Crossbar vs NoCBus: one at a time; NoC: links in parallelADC and PWMSAR = binary search; duty = OC1RS/(PR2+1)PID ControlPID ControlI removes error; clamp stops windupOpen the Computer Architecture mind mapComputer Architecturesmall fast near, big slow farMemory and I/OMemory arraysMemory arraysdecoder picks wordline, bitlines readCPU cacheCPU cachetag, index, offset; hit or missCache address breakdownCache address breakdownsets = lines/ways; tag = rest of addressCache Write PoliciesCache Write PoliciesWrite-back sends dirty lines at evictionLoop tiling and interchangeLoop tiling and interchangeWalk rows; tile so reused data fitsMemory hierarchyMemory hierarchyAMAT = hit time + miss rate × penaltyDRAM timingDRAM timingopen row is fast, row change is slowMESI and false sharingMESI and false sharinga write invalidates other copiesVirtual memoryVirtual memoryTLB caches the page tableEmbedded I/OEmbedded I/Odevices are addresses; poll or interruptMCU startup to mainMCU startup to mainCopy .data, zero .bss, then mainButton debounce FSMButton debounce FSMTwo equal 10 ms samples = one pressI2C BusI2C BusWired-AND bus: ACK, stretch, arbitrateUSB enumerationUSB enumerationAddress 0, descriptors, SET_CONFIGURATIONCAN bus arbitrationCAN bus arbitrationDominant 0 wins: lowest ID sends unharmedModbus RTU and TCPModbus RTU and TCPone master asks; bad CRC means silenceTDMA time-triggered busTDMA time-triggered busFixed slots; FTA drops extremes, averagesAMBA AXI, AHB, APBAMBA AXI, AHB, APBVALID and READY both 1 on the edgePCIe TLPsPCIe TLPsRequests by address, completions by IDBus vs Crossbar vs NoCBus vs Crossbar vs NoCBus: one at a time; NoC: links in parallelADC and PWMSAR = binary search; duty = OC1RS/(PR2+1)PID ControlPID ControlI removes error; clamp stops windup
This page on the Computer Architecture mind map · 79 pages in 7 branches · open it to see the whole map and test yourself in recall mode.