A Pico can switch between low and high quickly, while a resistor and capacitor turn that switching into a slowly varying voltage. The average may look right on a meter even when the remaining ripple is large. Add a load, and the same duty setting can produce half the expected mean without looking very different in a ripple comparison.
This experiment uses an original Raspberry Pi Pico with RP2040 and MicroPython 1.26.0. Pulse-width modulation (PWM) means repeatedly switching an output while controlling the fraction of each period spent high. A resistor-capacitor (RC) low-pass filter reduces fast changes while following slower ones. We compare its mean, its periodic variation and its response to loading. This is an unbuilt design with ideal mathematics and actual-code host checks; no physical output voltage, ripple or Pico execution has been measured.
For the parts and calculations, Ω (ohm) is the unit of electrical resistance; kΩ (kilohm) is 1,000 Ω and MΩ (megohm) is 1,000,000 Ω. F (farad) is the unit of capacitance, the amount of charge a capacitor stores per volt; µF (microfarad) is one millionth of a farad (10⁻⁶ F). V (volt) measures the voltage difference between two points. A (ampere) is the unit of electric current; mA (milliampere) is one thousandth of an ampere (10⁻³ A). A millivolt (mV) is one thousandth of a volt (10⁻³ V), and a millisecond (ms) is one thousandth of a second (10⁻³ s). W (watt) measures power, the rate of energy transfer. Hz (hertz) means one repeating cycle per second; kHz (kilohertz) means 1,000 cycles per second.
Components and what the instruments contribute
| Part | Purpose and selected value |
|---|---|
| Original Pico RP2040 | Hardware PWM on GP16, physical 21. Universal Serial Bus (USB) provides board power and console communication. |
| 10 kΩ, 1% resistor, at least 0.125 W | Series resistance between the switching output and the filtered node. |
| 1 µF, ±5% film capacitor, at least 10 V | Stores charge between pulses; the stated tolerance is for the selected experimental part. |
| Second 10 kΩ, 1% resistor | Optional known load from the filtered node to ground. |
| Digital multimeter (DMM) | Measures direct-current (DC) mean voltage approximately, subject to its input resistance, bandwidth and accuracy. |
| Optional oscilloscope and suitable probe | Observe waveform extrema and switching timing. Record probe loading and settings. |
No analog-to-digital converter (ADC), a circuit that digitizes voltage, is used here. The program changes the output and labels the setting; a person records the meter reading. The general-purpose input/output (GPIO) pin is a switching source, not a calibrated analog reference. Its actual high and low voltages depend on supply and load.
The numerical examples use a meter with a known 10 MΩ DC input resistance. That is an example, not a universal meter specification. Read the actual meter’s manual and record its range. A film capacitor avoids relying on an unidentified ceramic’s voltage-dependent capacitance, but its nominal value and tolerance still need recording. The physical part’s leakage and the instrument’s input capacitance remain outside the simplest model.
Wire the meter after the series resistor

tricky-circuit-batch-006/images/pico-pwm-rc-filter.svg)With power disconnected, start with an uncharged capacitor. Connect GP16 through the first 10 kΩ resistor to the filtered node VF. Connect the 1 µF capacitor from VF to common ground. Pico ground physical 18, the meter’s common lead and every load return join that ground. The meter’s voltage lead goes to VF using its DC-voltage terminals and range.
The optional second 10 kΩ goes from VF to ground, after the series resistor. Fit or remove it with power off. It is not a replacement series resistor. Do not attach an external voltage source to VF or use a 5 V signal on the Pico pin. This is a low-voltage experiment around one 3.3 V board, not an output for powering another project.
At a nominal 3.3 V transition into a discharged capacitor, the initial current is about 3.3/10,000 = 0.33 mA. This is a resistor-limited calculation, not a measured GPIO limit. The chip’s absolute ratings and selectable drive-strength labels are not normal current targets. Keep the small passive load and the intended board operating conditions.
GP16 is PWM slice 0 channel A. GP17 uses the other channel of the same slice, and GP0 can map to the same channel as GP16. Frequency changes and deinitialization can affect that shared resource. Use this slice only for the experiment; do not combine the trial with another PWM application and assume independent timing.
Mean voltage and ripple answer different questions
The duty fraction D is the part of a period spent high: D = 0.5 means half high, half low. The period is T = 1/f. With an ideal 3.3 V high level and 0 V low level, an unloaded filter has mean 3.3D in periodic steady state, when every cycle repeats the same capacitor trajectory. At 50% duty that mean is 1.65 V.
Ripple is the remaining periodic movement around the mean. Here we report peak-to-peak ripple, the highest voltage minus the lowest within a cycle. A meter on DC volts may show a fairly steady number while that movement remains. An alternating-current (AC) voltage range does not automatically supply the same peak-to-peak quantity; its coupling, bandwidth and scaling must be understood separately.
Derive the loaded filter before using a shortcut
Let R be the series resistor and RL the total resistive load after it. If a meter and an extra resistor are both connected, RL = 1/(1/Rmeter + 1/Rextra). With only the meter, RL is its input resistance. Define the DC gain k = RL/(R + RL) and time constant τ = (R parallel RL)C = RkC. The time constant describes the exponential approach to a constant-input target.
Current balance at VF gives C dv/dt = (Vsource − v)/R − v/RL. During a constant high input, the capacitor approaches H = kVH; during low, it approaches L = kVL. For high time DT and low time (1−D)T, define α = exp(−DT/τ) and β = exp(−(1−D)T/τ). Each exponential describes what fraction of the previous voltage error remains.
If Vmin is the voltage at the beginning of the high phase, then Vmax = H(1−α) + αVmin. The following low phase must return to the same Vmin in steady state: Vmin = L(1−β) + βVmax. Solving those two equations gives the exact ideal extrema:
| Quantity | Exact ideal expression |
|---|---|
| Minimum | Vmin = [L(1−β) + βH(1−α)]/(1−αβ) |
| Maximum | Vmax = H(1−α) + αVmin |
| Peak-to-peak ripple | ΔV = Vmax − Vmin |
| Mean | Vmean = k[D VH + (1−D)VL] |
The mean expression follows because the capacitor’s net charge change over one complete cycle is zero. It is exact for this linear, ideal source/resistor model; it does not require small ripple. The waveform extrema still matter. The loaded mean is not simply D times the Pico supply.
For 50% duty and VL = 0, a useful exact check is ΔV = kVH tanh[T/(4τ)], where tanh is the hyperbolic-tangent function. Only when T is much smaller than τ can it be approximated as ΔV ≈ (VH−VL)D(1−D)T/(RC). The latter approximation’s load cancellation explains why a load can greatly reduce mean voltage while barely changing ripple in this particular fast-switching case. Do not extend that cancellation to a slow PWM waveform or a nonlinear load.

Put numbers on the prediction, then respect their limits
For R = 10 kΩ, C = 1 µF and a 10 MΩ meter, k ≈ 0.999001 and τ ≈ 9.990 ms. At ideal 50% duty, the predicted mean is about 1.64835 V. Exact peak-to-peak ripple is about 82.48 mV at 1 kHz and 8.25 mV at 10 kHz. These extra digits identify reproducible calculations; they do not claim five-digit output accuracy.
Add the 10 kΩ load while keeping the same meter. The total load becomes about 9990.01 Ω, k ≈ 0.49975 and τ ≈ 4.9975 ms. The predicted mean falls to about 0.82459 V. At 1 kHz the predicted ripple is still about 82.43 mV. A nearly unchanged ripple therefore does not demonstrate an unchanged output level.
The resistor and capacitor tolerances already move the nominal unloaded RC product from about 9.405 to 10.605 ms, before instrument loading, leakage, source impedance and temperature effects. Actual high/low GPIO levels and quantized PWM timing can change predictions. The ideal model assumes constant linear resistances and capacitance; it does not model output transistors, capacitor dielectric effects or probe wiring.
Startup is not periodic steady state
For a fixed setting, the voltage observed at the same beginning-of-high phase approaches Vmin according to Vn = Vmin + (V0−Vmin) exp(−nT/τ). Here n is a whole number of periods and V0 is the initial capacitor voltage at that phase. This does not say that an arbitrary instantaneous sample equals the mean.
The trial requests a one-second settling allowance before printing each drive setting and leaves four more seconds for a manual observation. That is much longer than the nominal time constant, but is an application delay rather than a measured settling certificate. When the trial ends, the program restores the pin to a low digital output. The capacitor then discharges through the resistor network; forcing the pin low does not instantly force VF to zero.
Complete calculator and hardware trial
Download the full program (ZIP; file: tricky-circuit-batch-006/code/pico-pwm-rc-filter.py). On a computer using Python 3.12, running the file prints four labelled ideal predictions. The calculator uses the standard desktop math.expm1 function for stable evaluation of small exponential differences. On the selected MicroPython Pico, the same file runs the hardware trial; that path does not call the host calculator or require expm1.
"""Two roles, one complete listing: CPython3.12 ideal RC calculator and
MicroPython1.26.0 hardware-PWM trial on original Pico GP16.
The hardware loop never measures voltage. No target execution is claimed.
"""
import math
import sys
def parallel_load(meter_ohm, extra_ohm=None):
for value in (meter_ohm,) if extra_ohm is None else (meter_ohm, extra_ohm):
if not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
raise ValueError('Known finite positive load resistance required')
return meter_ohm if extra_ohm is None else 1.0 / (1.0 / meter_ohm + 1.0 / extra_ohm)
def steady_state(frequency, duty, r=10000.0, c=1e-6, high=3.3, low=0.0, load=None):
"""CPython3.12 exact exponential ideal model; not a voltage measurement.
MicroPython drive() does not call this host calculator or require expm1.
"""
values = (frequency, duty, r, c, high, low)
if not all(isinstance(x, (int, float)) and math.isfinite(x) for x in values):
raise ValueError('Finite model values required')
if frequency <= 0 or r <= 0 or c <= 0 or not 0 <= duty <= 1 or high <= low:
raise ValueError('Positive f/R/C,0..1 duty and high>low required')
if load is not None and (not isinstance(load, (int, float)) or not math.isfinite(load) or load <= 0):
raise ValueError('Use positive finite load, or None for open circuit')
gain = 1.0 if load is None else load / (r + load)
tau, period = r * gain * c, 1.0 / frequency
if not math.isfinite(tau) or tau <= 0 or not math.isfinite(period):
raise ValueError('Model time scale is outside numerical range')
h, l = gain * high, gain * low
one_a = -math.expm1(-duty * period / tau)
one_b = -math.expm1(-(1.0 - duty) * period / tau)
one_ab = -math.expm1(-period / tau)
if one_ab == 0:
raise ValueError('Time scale is below numerical resolution')
v_min = (l * one_b + (1.0 - one_b) * h * one_a) / one_ab
v_max = h * one_a + (1.0 - one_a) * v_min
return {'period_s': period, 'tau_s': tau, 'dc_gain': gain,
'mean_v': gain * (duty * high + (1.0 - duty) * low),
'v_min': v_min, 'v_max': v_max, 'ripple_v': max(0.0, v_max - v_min)}
def cycle_start(v0, cycles, prediction):
"""Voltage at the same beginning-of-HIGH phase after integer full cycles."""
if not isinstance(v0, (int, float)) or not math.isfinite(v0) or type(cycles) is not int or cycles < 0:
raise ValueError('Finite initial voltage and nonnegative integer cycle count required')
return prediction['v_min'] + (v0 - prediction['v_min']) * math.exp(
-cycles * prediction['period_s'] / prediction['tau_s'])
def drive(make_pwm, drive_low, sleep_ms, emit=print, steps=None):
if steps is None:
steps = [(f, d) for f in (1000, 10000) for d in (0, 16384, 32768, 49152, 65535)]
steps = list(steps)
if not steps or any(type(f) is not int or f not in (1000, 10000) or
type(d) is not int or not 0 <= d <= 65535 for f, d in steps):
raise ValueError('Use1kHz/10kHz and integer duty codes0..65535')
drive_low()
pwm = None
try:
pwm = make_pwm()
for requested, code in steps:
pwm.freq(requested)
pwm.duty_u16(code)
sleep_ms(1000) # Ideal settling allowance, not a measured guarantee.
configured = pwm.freq()
if type(configured) is not int or configured <= 0:
raise ValueError('Invalid configured-frequency response')
emit({'status': 'DRIVE_SET', 'requested_hz': requested,
'configured_hz': configured, 'duty_u16': code,
'requested_fraction': code / 65535.0,
'physical_duty_measured': False, 'voltage_measured_v': None})
sleep_ms(4000) # Manual DMM observation window.
except (OSError, ValueError) as exc:
emit({'status': 'DRIVE_ERROR', 'configured_hz': None,
'voltage_measured_v': None, 'error': str(exc)})
finally:
try:
if pwm is not None:
pwm.deinit()
finally:
drive_low() # Switch pin function back to output LOW.
def main():
from machine import Pin, PWM, freq
from time import sleep_ms
pin = Pin(16, Pin.OUT, value=0)
print({'system_clock_hz_reported': freq(), 'hardware_measurement': False})
drive(lambda: PWM(pin, freq=1000, duty_u16=0),
lambda: pin.init(Pin.OUT, value=0), sleep_ms)
def calculator_demo():
import json
print('IDEAL PREDICTIONS, NOT MEASUREMENTS; exact0.5 duty for these examples.')
for extra in (None, 10000.0):
load = parallel_load(1e7, extra)
for frequency in (1000, 10000):
result = steady_state(frequency, .5, load=load)
result.update(frequency_hz=frequency, meter_ohm=1e7, extra_load_ohm=extra)
print(json.dumps(result))
if __name__ == '__main__':
if sys.implementation.name == 'micropython':
main()
else:
calculator_demo()
The hardware trial requests 1 kHz and 10 kHz with five duty codes at each frequency. MicroPython defines duty_u16 as a request scaled by 65535, while the hardware applies discrete counter values. Code 32768 is a nominal half-scale request; the numerical examples deliberately use mathematical D = 0.5. Exact physical duty and frequency must be observed if they matter. The frequency getter reports configuration, not a measurement of the wire or clock accuracy.
The loop never invents a voltage result: voltage_measured_v is always None (no measurement). A failed setter or invalid frequency response prints DRIVE_ERROR and stops the sequence. Cleanup deinitializes PWM and restores the pin function to output low, including the operator’s normal interruption path. A complete power loss or process failure is outside that software cleanup guarantee. Invalid planned settings are refused before creating a new PWM object.
A comparison that a reader can repeat
- Record the exact board/firmware, resistor values, capacitor type/value/tolerance, meter model, DC range and input resistance. Build with power off and no extra load. Confirm that every return joins Pico ground.
- Run the trial and match each console setting to its manual meter observation. Begin with 0% and 100% requests to inspect endpoint behavior, then compare the middle settings after the allowance. Do not type calculated voltages into the results column.
- Compare the nominal half-scale requests at 1 kHz and 10 kHz. The ideal mean is nearly unchanged; remaining ripple is predicted to be much smaller at the higher frequency. A stable DC display alone cannot verify that ripple prediction.
- Power off, install the extra 10 kΩ from VF to ground, then repeat. Compare the loaded mean against the model including the meter. Keep the two resistor roles distinct.
- If an oscilloscope is available, record frequency, duty, mean and peak-to-peak waveform with its actual probe resistance/capacitance. Start on a DC-coupled view that shows the mean before magnifying ripple; include the probe load in the calculation. A different trace with the same average is an important observation.
- Observe a change from a low to a middle setting and the final return to low. If the response is too fast for the meter, record that limit instead of inferring a measured time constant.
- Use the host fault cases for failed software calls and invalid parameters. Diagnose unexpected hardware values by verifying wiring, actual component values, source endpoints and instrument loading before editing several settings together.
The blank observation sheet (ZIP; file: tricky-circuit-batch-006/code/pico-pwm-rc-filter-observations-blank.csv) and bench log contain no physical results. The 32 author host checks execute the actual calculator, its command-line entry point and the supplied hardware-drive interface using injected functions. They include an independent numerical integration of the ideal differential equation, endpoint/symmetry/load tests, numeric-scale errors and cleanup failures. This is not a target firmware build, physical circuit simulation or measured ripple qualification.
Challenge: Doubling the PWM frequency makes the meter voltage recover after adding a 10 kΩ load. Should the ideal model predict that? Answer: No. For fixed duty and a linear resistive load, frequency changes ripple and approach to steady state, while the DC gain still sets the mean. Investigate whether the reading was unsettled, the meter responded to ripple, another PWM channel changed, or the physical source/load differed from the assumed model.
Primary sources and related learning
- MicroPython 1.26.0 PWM application programming interface (API): duty scale, configuration getter, quantization and shared-resource limitations.
- MicroPython RP2 quick reference: original-board clock baseline, PWM slices and GPIO aliases.
- Current official RP2040 datasheet: PWM hardware, GPIO electrical conditions and Appendix B errata.
- Original Pico physical pinout: GP16 and ground header locations.
Source and errata review: 20 October 2026. No unaddressed PWM-specific erratum was identified for this simple free-running trial in the checked primary documentation; that is not a guarantee of absence, and no silicon revision was physically identified. This steady-periodic/loading experiment differs from the earlier single capacitor-charge lesson and from a dedicated converter-chip output. Revisit the loaded divider experiment and the electronics lessons when comparing the equations with real instruments.



