Connect a Pico output to a Pico input and ask two questions: how many rising edges appeared during a window, and how long did a group of complete periods take? The answers can differ without either calculation being broken. This controlled experiment makes counting steps, missed observations and a shared clock visible.
Verification: the supplied observation algorithm, wrap handling and cleanup paths have been exercised on a host computer with simulated pin and clock inputs. The program has not been run on a Pico, and no waveform or frequency has been measured on hardware. Numerical traces below are constructed examples, not successful bench results.
A deliberately small frequency experiment
Frequency is the number of complete repeating cycles per second; its unit is hertz (Hz). A period is the time for one complete cycle. A rising edge is the transition from a low logic level to a high one. One rising edge per cycle gives a useful event to count, provided the observer actually sees the low state between successive high states.
Use an original Raspberry Pi Pico Rev3 with the RP2040 microcontroller and the official MicroPython 1.26.0 RP2 build for RPI_PICO. MicroPython is Python adapted for microcontrollers; RP2 names this firmware’s Raspberry Pi microcontroller port. This lesson is scoped to that board and version, not an interchangeable recipe for every Pico-branded board. Keep its default clock configuration and do not run unrelated tasks during an observation.
The source uses pulse width modulation (PWM), hardware that repeatedly drives a pin high and low. Its duty cycle is the fraction of a cycle spent high. Here the requested duty is approximately 50%, and the source requests only 10, 17 and 50 Hz. The pinned RP2 documentation places these settings above its stated 8 Hz PWM minimum at the default 125 MHz clock (MHz means megahertz, or one million clock cycles per second). Do not extend the exercise to 1 Hz by changing one number and assuming that the same peripheral can produce it.
For the wiring and timing, Ω (ohm) is the unit of electrical resistance, and kΩ (kilohm) is 1,000 Ω. V (volt) measures the voltage difference between two points; W (watt) measures power, the rate of energy transfer. A (ampere) is the unit of electric current; µA (microampere) is one millionth of an ampere (10⁻⁶ A). A second is the unit of time: µs (microsecond) is one millionth of a second (10⁻⁶ s), and ms (millisecond) is one thousandth of a second (10⁻³ s).
Two resistors and three named connections

tricky-circuit-batch-006/images/pico-frequency-observation.svg)- One original Pico Rev3 with its existing headers, a breadboard, short jumpers and a USB data cable. USB means Universal Serial Bus; it supplies the board and carries the serial console. No external supply is required.
- R1 = 1 kΩ ±5%, at least 0.125 W, in series between GP0 and the input junction. A resistor limits current; this one reduces accidental pin-conflict current in this small fixture. It is not a voltage translator or a complete input protector.
- R2 = 100 kΩ ±5%, at least 0.125 W, from the input junction to ground. This pull-down gives the input a defined low state if the signal jumper opens.
| Pico connection | Physical header position | Purpose |
|---|---|---|
| GP0 | Pin 1 | PWM source; R1 leads from here to the sense junction. |
| GP16 | Pin 21 | General-purpose input/output (GPIO) pin configured as an input only. Connect it to the sense junction. |
| GND | Pin 18 | Ground, the common zero-volt return for R2 and both functions on the same board. |
Identify physical pins using the official Rev3 pinout, with USB at the top. GP16 is a signal name; it does not mean physical pin 16. Make every wiring change with USB disconnected. Check that split breadboard rails are actually joined where intended, and never connect VBUS, the USB supply rail, to the sense junction.
Only this board’s own nominal 0–3.3 V signal belongs on the input. The RP2040 electrical specification distinguishes recommended conditions from absolute stress limits. Neither a stress limit nor the series resistor licenses an unknown 5 V signal, a negative voltage or an unpowered-board input. External instruments, other power domains and mains measurements are outside this circuit.
Ignoring input leakage and output resistance, a high state draws 3.3 V / (1 kΩ + 100 kΩ) ≈ 32.7 µA and puts about 3.267 V at the input. This is a nominal loading calculation, not a measured logic margin. R2 defines the unplugged state but cannot identify an unplugged cable: an intentionally stopped low source looks the same to a digital reader.
A resource trap: GP0 and GP16 can both carry PWM slice 0, channel A. A slice is a shared hardware counter. This program creates PWM only on GP0 and keeps GP16 as Pin.IN, an input. Creating a second PWM object on GP16 would configure the sense pin as another output of that same resource. Stopping slice 0 also stops its other channel, so reserve this slice for the lesson. The complete connection list, not just a pin number, defines the experiment.
Count-window and reciprocal estimates
A gate is the observation interval, not a transistor gate in this context. The program asks for 0.5 s and 2 s windows. It reads the input repeatedly, notices low-to-high changes and timestamps read completions. It includes the final sample that reaches the requested duration, then uses the actual elapsed time, T, in fCOUNT = N / T, where N is the number of observed rising edges. T is expressed in seconds in this equation.
One extra counted edge changes the result by 1/T. A 0.5 s window therefore has approximately 2 Hz counting steps, while a 2 s window has approximately 0.5 Hz steps. At a hypothetical exact 17 Hz, a half-second observation can contain eight or nine edges depending on phase, the starting position within the cycle. That gives 16 or 18 Hz. Repeating windows is more informative than adding decimal places to one count.
For the other estimate, keep the timestamps of the first and last observed rising edges. If N edges are seen, there are N−1 complete edge-to-edge intervals between them. The reciprocal estimate is fPERIOD = (N−1) / (tLAST−tFIRST). Five evenly spaced edges spanning 0.4 s indicate 10 Hz, not 12.5 Hz. Using N in that numerator is a common off-by-one error.

The period estimate avoids the partial cycles at the gate boundaries, but timestamps still arrive after the physical transitions. Jitter means variations in that delay. If each detected edge is delayed by at most d under the fixture assumptions, the error in the difference of the two edge times can approach d in either direction; a more conservative independent ±d uncertainty on each timestamp gives ±2d. Neither is an absolute accuracy certificate. Longer edge spans reduce the relative effect of a given timing uncertainty.
A number is conditional on observing the signal
Polling means repeatedly reading a value in ordinary program execution. It does not capture every physical edge in hardware. The supplied algorithm records the largest gap between read-completion timestamps and the largest time spent around an individual pin read. If either exceeds 2,000 µs, or 2 ms, it returns SAMPLING_GAP with both frequency estimates unset.
At the fastest chosen source, 50 Hz and approximately 50% duty, each high or low state lasts about 10 ms. A verified gap no larger than 2 ms is comfortably shorter than either state for this known, clean waveform. Read duration is checked too: a long blocked read must not disguise a long blind interval. These are chosen acceptance rules for this fixture. They do not prove that a noisy input has no extra pulses, or that an unknown narrow pulse could not occur entirely between reads.
Intervals are computed with ticks_diff, not ordinary subtraction of wrapping clock values. The pinned time API documentation requires differences smaller than half the clock’s modular period. The exercise uses at most two-second gates and frequent samples on the specified RP2 build. Do not preserve raw timestamps across arbitrary long pauses. A frozen or excessively slow clock is not repaired by an ever-growing loop: the acquisition also has a finite sample cap.
No observed edges means NO_EDGES_OBSERVED, with no numeric frequency. One edge means INSUFFICIENT_EDGES. A constant high input, an open signal connection, a stopped source, or a frequency outside the fixture assumptions cannot be distinguished by that observation alone. Invalid logic values, impossible clock ordering and input exceptions also suppress estimates. Recording the status is part of the measurement.
Complete program
Download the full program (ZIP; file: tricky-circuit-batch-006/code/pico_frequency_observer.py) and save it on the Pico as pico_frequency_observer.py. From the MicroPython serial console run import pico_frequency_observer as lab and then lab.run(). It produces eighteen result dictionaries: three frequencies, two gates and three trials. A dictionary is a collection of named values; copy the entire row, including status and timing diagnostics. Import alone does not start the source.
The file prints only after each observation ends. Printing inside the sampling loop would change the thing being tested. On normal completion, an exception or a console interruption, nested cleanup attempts to stop PWM and explicitly configure GP0 as a low output. This software cleanup cannot promise a pin state after abrupt power loss or a hardware failure.
Complete Python program
"""Pico / MicroPython 1.26.0: qualified polling of a known 10-50 Hz fixture.
No hardware edge capture or calibrated timebase is used. Missed edges are lost.
Importing this file on CPython does not import machine or start hardware.
"""
class Window:
def __init__(self, gate_us, max_gap_us=2000):
if type(gate_us) is not int or not 10000 <= gate_us <= 2000000:
raise ValueError("gate_us must be 10000..2000000")
if type(max_gap_us) is not int or not 1 <= max_gap_us <= 2000:
raise ValueError("max_gap_us must be 1..2000")
self.gate = gate_us
self.limit = max_gap_us
self.previous = None
self.last = 0
self.first_edge = None
self.last_edge = None
self.edges = 0
self.max_gap = 0
self.max_read = 0
self.done = False
self.fault = None
def fail(self, reason):
self.fault = reason
self.done = True
def feed(self, level, elapsed_us, read_us=0):
if self.done:
return
if type(level) not in (int, bool) or level not in (0, 1):
self.fail("INVALID_LEVEL")
return
if (type(elapsed_us) is not int or type(read_us) is not int
or read_us < 0 or elapsed_us < self.last):
self.fail("CLOCK_ORDER")
return
self.max_read = max(self.max_read, read_us)
if self.previous is None:
if elapsed_us != 0:
self.fail("INITIAL_TIME")
return
else:
self.max_gap = max(self.max_gap, elapsed_us - self.last)
if self.max_gap > self.limit or self.max_read > self.limit:
self.fail("SAMPLING_GAP")
return
if self.previous == 0 and level == 1:
if self.last_edge is not None and elapsed_us <= self.last_edge:
self.fail("CLOCK_ORDER")
return
self.edges += 1
if self.first_edge is None:
self.first_edge = elapsed_us
self.last_edge = elapsed_us
self.previous = level
self.last = elapsed_us
self.done = elapsed_us >= self.gate
def result(self):
status = self.fault or ("OK" if self.done else "INCOMPLETE")
if status == "OK" and self.edges < 2:
status = "NO_EDGES_OBSERVED" if self.edges == 0 else "INSUFFICIENT_EDGES"
good = status == "OK"
span = None if self.edges < 2 else self.last_edge - self.first_edge
return {"status": status, "edges": self.edges,
"elapsed_us": self.last, "max_gap_us": self.max_gap,
"max_read_us": self.max_read,
"count_hz": self.edges * 1000000 / self.last if good else None,
"edge_span_us": span,
"period_hz": (self.edges - 1) * 1000000 / span if good else None}
def acquire(read, ticks, diff, gate_us, max_gap_us=2000,
pause_us=0, wait=None, max_samples=1000000):
"""Timestamp read completions. Bounded memory; sample cap catches stuck clocks.
diff must implement MicroPython ticks_diff's modular half-period contract.
Do not print, allocate growing lists, or run other user work in this loop.
"""
if type(max_samples) is not int or max_samples < 1:
raise ValueError("max_samples must be positive")
if type(pause_us) is not int or pause_us < 0 or (pause_us and wait is None):
raise ValueError("pause_us needs a wait function")
window = Window(gate_us, max_gap_us)
try:
before = ticks()
level = read()
origin = ticks()
window.feed(level, 0, diff(origin, before))
for _ in range(max_samples):
if window.done:
return window.result()
if pause_us:
wait(pause_us)
before = ticks()
level = read()
after = ticks()
window.feed(level, diff(after, origin), diff(after, before))
if not window.done:
window.fail("SAMPLE_LIMIT")
except Exception:
window.fail("ACQUISITION_ERROR")
return window.result()
def run(machine_module=None, time_module=None, emit=print, pause_us=0):
if machine_module is None:
import machine as machine_module
if time_module is None:
import time as time_module
Pin, PWM = machine_module.Pin, machine_module.PWM
source = Pin(0, Pin.OUT, value=0)
pwm = None
try:
sense = Pin(16, Pin.IN) # External 100k pull-down; no PWM object here.
pwm = PWM(source, freq=10, duty_u16=32768)
for requested in (10, 17, 50):
pwm.freq(requested)
time_module.sleep_ms(200)
reported = pwm.freq() # Driver report, not an independent measurement.
for gate in (500000, 2000000):
for trial in range(1, 4):
row = acquire(sense.value, time_module.ticks_us,
time_module.ticks_diff, gate,
pause_us=pause_us, wait=time_module.sleep_us)
row.update({"requested_hz": requested,
"driver_report_hz": reported,
"requested_gate_us": gate, "trial": trial})
emit(row) # Only after observation ends.
finally:
try:
if pwm is not None:
pwm.deinit() # Stops slice 0, both channels.
finally:
Pin(0, Pin.OUT, value=0) # Select normal GPIO output; leave it LOW.
if __name__ == "__main__":
run()
Compare, interrupt and diagnose
- With USB removed, assemble and inspect the three named connections. Reconnect, confirm the firmware version in the console and run the file. If a wiring mistake or unexpected board behavior appears, disconnect before changing wiring.
- Record all eighteen rows. Compare count-window steps at 17 Hz between the two gates. Gate timing is allowed to run slightly beyond its requested duration; use the printed
elapsed_usrather than replacing it with a tidy nominal number. - Compare the count and period estimates alongside their edge count and maximum gap. A row marked OK means the observation satisfied this software’s timing rule and saw enough edges. It is not proof of instrument calibration or a real 17.000 Hz source.
- Disconnect USB, remove only the signal jumper, and rerun after reconnecting power. The external pull-down should lead to no observed edges. Record what actually happens; do not type an expected success into the sheet.
- Restore the jumper unpowered. Try
lab.run(pause_us=12000). This intentionally inserts a 12 ms pause between samples and should refuse an estimate withSAMPLING_GAP. The experiment demonstrates a diagnostic, not a way to measure during the blind time. - Restore
lab.run()and compare again. Keep source settings, firmware version, wiring state and any console interruption beside the recorded rows.
The blank observation sheet (ZIP; file: tricky-circuit-batch-006/code/pico-frequency-observations-blank.csv) has space for real observations and a separate note on whether a case was simulated or run on hardware. A logic analyzer, an instrument that records digital transitions, or an oscilloscope, an instrument displaying voltage versus time, can be a later independent comparison. Neither is required for assembling this fixture, and no traces from one are claimed here.
Why agreement does not calibrate the clock
The output waveform and observation timebase are both derived from the same Pico’s clock system. A shared clock error can largely cancel when one measures the other. The PWM driver’s integer frequency report describes its configuration calculation; it is not an independent instrument reading. A stable reciprocal result and a matching count therefore teach internal consistency, not absolute frequency accuracy. Absolute calibration requires a suitably characterized independent reference and a separate error budget.
This is a 10–50 Hz classroom observer, not a general frequency counter. Faster signals, very short duty cycles, contact bounce and electrical noise require a different acquisition design and input conditioning. The existing voltage-monitor lessons answer a different question: several voltage channels do not automatically provide simultaneous edge timing. Continue with the electronics lessons for input, timing and resistor foundations.
Challenge: eight edges span seven periods in a 0.5 s gate. Which duration belongs in each formula?
Count-window frequency uses eight divided by the actual whole-window duration. Reciprocal frequency uses seven divided by the time from the first edge to the eighth. If that span is 0.4118 s, the reciprocal estimate is about 17.0 Hz while the nominal half-second count estimate is 16 Hz. Neither formula permits inventing a ninth edge. If the sampling-gap rule failed, both estimates remain unavailable even if their arithmetic would look plausible.
Primary sources and the verification boundary
- Raspberry Pi Pico Rev3 official pinout, for named signals and physical positions.
- RP2040 datasheet, manufacturer-hosted build dated 20 February 2025, for GPIO, PWM and the timer; Appendix B includes silicon errata. In particular E7 concerns oscillator COUNT registers; this program does not access those registers. No relevant special workaround for this polling fixture was identified in that appendix review. This is not a promise against later notices.
- Official MicroPython v1.26.0 RP2 quick reference, pinned to the taught software, for PWM resource sharing and shutdown behavior.
- Official v1.26.0 time documentation, for wrapping timestamp arithmetic and delay limitations.
The host tests execute this delivered Python code against constructed waveforms, wrapping/frozen clocks, acquisition failures and cleanup failures. They do not execute MicroPython firmware, validate physical thresholds, compile a target binary, or measure a Pico. Keep those verification stages separate when you carry out the bench procedure.



