Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 37 · Memory, Registers and Peripherals

ADC and PWM Basics

Learn how a microcontroller reads analog voltages with an ADC (resolution, reference, sampling, filtering) and makes analog-like output with PWM (duty cycle, frequency, LEDs, servos).

The real world is analog: temperature, light, pressure and battery voltage change smoothly, while a microcontroller works with discrete numbers and two-level pins. Two peripherals bridge the gap. The ADC (analog-to-digital converter) turns a voltage into a number. PWM (pulse-width modulation) turns a number into an average voltage, using a fast digital pulse train whose on-time you control. Together they let firmware read sensors and dim LEDs, drive motors and position servos.

This lesson explains the numbers behind both peripherals, how to convert raw values to physical units, how to reduce noise, and how to compute PWM settings from a timer's registers. Everything runs as a simulation, with the real register patterns shown for reference.

The ADC

An ADC measures the voltage on an input pin relative to a reference voltage (Vref, often the supply, such as 3.3 V) and returns an integer.

  • Resolution: the number of bits N. A 12-bit ADC has 2¹² = 4096 levels, codes 0 to 4095.
  • LSB size (step): Vref / 2^N. For 12 bits and 3.3 V, that is 0.806 mV per step.
  • Conversion: code = floor(Vin / Vref * (2^N)), clamped to 2^N - 1; the inverse is Vin = code * Vref / 2^N.
  • Conversion time: microseconds, set by the ADC clock and the sampling time.
  • Channels: several pins share one converter through a multiplexer.

(Datasheets disagree on whether to divide by 2^N or 2^N - 1; the difference is under one LSB, and a real design calibrates against known voltages.)

C ADC conversion and quantization error

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

From counts to physical units

A raw code means nothing until you convert it. Example: a thermistor, an analog temperature sensor such as the TMP36 (10 mV per degree C, 500 mV at 0 degrees C) or the battery through a voltage divider. Integer math avoids floating point on small chips: millivolts as (uint32_t)code * 3300 / 4096, then temperature in tenths of degrees (mv - 500).

C TMP36 reading to temperature, integer math only

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Noise, averaging and oversampling

ADC readings jitter by a few counts because of electrical noise. Three common fixes:

  1. Average N samples. Noise falls by about the square root of N.
  2. Moving average or exponential filter: smoother, cheap, continuous. The exponential filter y += (x - y) / 8 needs only one variable and a shift.
  3. Oversampling and decimation: summing 4^k samples and shifting right by k bits gives k extra bits of resolution (when noise is at least about one LSB).

Also: keep the reference clean, add an RC low-pass filter at the input, give the sampling capacitor enough sampling time if the source resistance is high, and read each channel on a schedule rather than in an interrupt that triggers other noisy activity.

C Filtering a noisy ADC signal

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

ADC in registers (read-only)

On a real chip the sequence is: enable the ADC clock, select the channel, set the sampling time, start a conversion, wait for the end-of-conversion flag, read the data register. With STM32 registers:

C
ADC1->SQR3 = 5;                       // channel 5 first in the sequence
ADC1->CR2 |= ADC_CR2_ADON;            // power on
ADC1->CR2 |= ADC_CR2_SWSTART;         // start
while (!(ADC1->SR & ADC_SR_EOC)) { }  // wait for end of conversion
uint16_t code = (uint16_t)ADC1->DR;   // reading DR clears EOC

For continuous sampling you do not poll: use a timer to trigger conversions and DMA to write results into a buffer in RAM, then process it in blocks (see chapter 5 for timers and interrupts).

PWM

A digital pin can only be fully high or fully low. Pulse-width modulation switches it on and off quickly, and the fraction of time it is on, the duty cycle, sets the average voltage: 25 % duty at 3.3 V averages 0.825 V. Anything slower than the pulse train smooths it: an LED looks dimmer (the eye averages flashes above ~100 Hz), a motor's inertia averages the current, and an RC low-pass filter turns PWM into a real analog voltage (a cheap DAC).

Two numbers define a PWM signal:

  • Frequency (period): how often the cycle repeats. LEDs need > 200 Hz to avoid visible flicker, motors 1 to 20 kHz (above the audible range to avoid whine), servos exactly 50 Hz.
  • Duty cycle: on-time divided by the period (0 to 100 %).

A timer generates it. It counts from 0 up to a value ARR (auto-reload), so the period is (ARR + 1) / f_timer. A compare register CCR sets the point at which the output switches: high while the counter is below CCR. So duty = CCR / (ARR + 1).

TEXT
counter:   0 1 2 3 4 5 6 7 8 9 0 1 2 ...
CCR = 3:   ▮▮▮▯▯▯▯▯▯▯ ▮▮▮▯▯▯▯▯▯▯     (30 % duty, ARR = 9)
C PWM settings from a timer clock (and a waveform)

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Servos and motors

A hobby servo wants a pulse every 20 ms (50 Hz) whose width is 1.0 to 2.0 ms (1.5 ms centered): the pulse width, not the duty percentage, encodes the angle. A DC motor gets a PWM signal through a transistor or H-bridge driver; duty sets speed. For a motor, the PWM frequency belongs well above 1 kHz, and direction is selected by two other pins.

C Servo angle to pulse width and timer compare value

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Smooth fades

Human eyes see brightness logarithmically, so a linear PWM ramp looks like it jumps quickly at first and then barely changes. For smooth LED fades use a gamma table (brightness^2.2 or a precomputed const table in flash) mapping the perceived level to the duty value.

Checklist for analog work

  1. Know Vref and its accuracy; a USB-powered 3.3 V rail can wobble.
  2. Use integer or fixed-point math for conversion where possible.
  3. Never exceed the input range (0 to Vref); add a series resistor and clamping diodes for exposed inputs.
  4. Filter in hardware (RC) and software (average), but keep the signal bandwidth in mind (Nyquist: sample at more than twice the highest frequency).
  5. Set PWM frequency to suit the load (LED, motor, servo); change duty only through the compare register so the output never glitches.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. A 12-bit ADC with Vref = 3.3 V has an LSB of about:

    3.3 V / 4096 = 0.806 mV.
  2. 2. How many extra bits of resolution does summing 16 samples and right-shifting by 2 give (assuming enough noise)?

    Oversampling by 4^k and shifting by k gives k extra bits; 16 = 4^2 so 2 bits.
  3. 3. A timer runs at 16 MHz with ARR = 15999 and CCR = 4000. What is the PWM frequency and duty cycle?

    Period = 16000 ticks at 16 MHz = 1 ms = 1 kHz; duty = 4000 / 16000 = 25 %.
  4. 4. What determines the angle of a standard hobby servo?

    A pulse of about 1 ms to 2 ms every 20 ms encodes the position.

Summary

  • An ADC converts a voltage into a code: code = Vin / Vref * 2^N; resolution, reference accuracy and noise determine real precision.
  • Convert counts to physical units with integer math, and reduce noise with averaging, exponential filters and oversampling.
  • PWM produces an average voltage through duty cycle: duty = CCR / (ARR + 1), with frequency from the timer clock, prescaler and ARR.
  • Choose PWM frequency for the load: LEDs above 200 Hz, motors 1 to 20 kHz, servos 50 Hz with 1 to 2 ms pulses.
  • Respect the input range and sampling theory, and use gamma tables for smooth LED fades.

Next: Interrupts and Interrupt Service Routines