Supplier photo of an assembled infinity mirror light cube illuminated on a dark background.
Supplier photo
Temu affiliate offer · Project idea

Build an infinity light cube

Listing specifies 5-volt direct current. Soldering required; battery and glue not included.

View kit on Temu

Tricky Circuit may earn a commission through these links. Product ideas have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

Pico Tasks Without Long Sleeps: Deadlines, Cancellation and Late Loops

A program can turn a lamp on for five seconds without spending five seconds unable to read its button. This experiment gives a Pico three small jobs: watch a button, keep a heartbeat LED changing, and run a cancellable five-second work light. Then deliberately stop servicing the loop briefly and examine what the program can still promise.

Use an original Raspberry Pi Pico RP2040 with official MicroPython 1.26.0. This is a cooperative loop: each job performs a short step and returns so another job can run. It is not simultaneous execution, an interrupt-driven scheduler or a real-time guarantee. Host tests execute the actual delivered state machine and cleanup paths with injected inputs and clocks. No Pico execution, target firmware build or physical timing measurement has been performed.

Parts and current

Use two Kingbright WP7113ID red light-emitting diodes (LEDs), two separate 1 kΩ resistors rated at least 0.125 W, a normally-open push button and one 10 kΩ pullup. The pullup gives an unpressed input a defined high level; the switch connects it to ground when pressed. A Universal Serial Bus (USB) cable powers and communicates with the Pico. General-purpose input/output (GPIO) pins are programmable signal connections, not supply outputs for arbitrary loads.

For an illustrative red forward drop of 1.9 V, one LED current is approximately (3.3−1.9)/1000=1.4 mA. That drop is an example, not a guaranteed value at this current. Even the zero-forward-drop bound is only 3.3 mA through 1 kΩ, before resistor tolerance and actual rail error. The button pullup draws about 3.3/10000=0.33 mA while pressed. These are small intended loads, not a use of an absolute maximum as a normal current setting.

One input, two outputs

Original Pico GP16 and GP17 each drive a separate WP7113ID LED through 1 kΩ to ground; GP14 connects a normally-open button to ground and its own 10 kΩ pullup to 3.3 V.
Original circuit schematic. Dots join wires. Each LED has its own resistor; the button has a separate pullup.
Pico connection Purpose
GP16, physical 21 Heartbeat output through its 1 kΩ resistor, LED anode, LED cathode to ground.
GP17, physical 22 Work output through its own resistor and LED to ground.
GP14, physical 19 Button input, 10 kΩ to 3V3 OUT physical 36, normally-open switch to ground.
GND, physical 18 Common return for the button and both LEDs.

Disconnect power before wiring and identify the actual board labels. On the specified LED, verify anode and cathode from the manufacturer drawing, rather than trusting a cut lead’s length. Do not connect 5 V to the button or outputs. The original Pico’s GPIO domain is 3.3 V. This circuit has no actuator, relay or external powered input.

Deadlines are different from sleeps

A deadline is the counter value at which a job becomes due. The program stores a work deadline five seconds after a settled press. Every loop checks it and returns; it does not wait inside a five-second sleep. A second settled press cancels that work. At startup a held button cannot start the lamp: the input must first settle released, then pressed. Contact settling requires 30 ms with the same observed level; this is a declared software policy, not a measurement of every switch bounce.

The heartbeat has a 250 ms edge period, giving a nominal 500 ms full cycle. Its next edge remains on the original schedule. If a call is late, the program calculates how many edge periods elapsed, updates the final parity once and advances the deadline by that many periods. It does not issue a rapid burst of missed physical pulses. Two missed edges can leave the visible state unchanged; a current state cannot reconstruct the transitions the loop failed to produce.

MicroPython’s millisecond counter wraps. ticks_add() creates deadlines and ticks_diff() compares them using the documented modular rules. Ordinary arithmetic on raw tick values is unsuitable across a wrap. Our longest intended deadline is only five seconds, and regular calls are assumed. A pause hiding complete counter wraps cannot be discovered from the counter alone. After uncertain debugger history, restart deliberately.

Synthetic button, heartbeat and work output traces from the actual program, including a 700 ms loop gap, cancellation, a second start and completion five seconds later.
Original trace generated from the delivered state code. Lines show commanded output states held between calls; event times are synthetic, not measurements of a Pico.

Complete program

Save the complete file on the Pico and run it from an editor’s serial console. The application programming interface (API), the callable functions supplied by MicroPython, provides pin and clock access. The read–evaluate–print loop (REPL) is the interactive console reached after Ctrl+C. Download the complete program (ZIP; file: tricky-circuit-batch007-campaigns63-68/code/pico-cooperative-deadlines.py).

"""Original Pico RP2040 / MicroPython 1.26.0: cooperative timing experiment."""
class Debounce:
    def __init__(self, diff):
        self.diff=diff; self.candidate=None; self.stable=None; self.since=None
    def update(self, raw, now):
        if type(raw) is not int or raw not in (0,1):
            raise ValueError('button must return integer0 or1')
        if raw != self.candidate:
            self.candidate=raw;self.since=now
        if self.diff(now,self.since)>=30 and self.stable!=raw:
            self.stable=raw;return raw
        return None

class Experiment:
    def __init__(self, now, add, diff):
        self.add,self.diff=add,diff;self.last=now;self.next=add(now,250)
        self.heartbeat=0;self.finish=None;self.armed=False;self.button=Debounce(diff)
    def step(self, now, raw):
        gap=self.diff(now,self.last)
        if gap<0 or gap>1000:
            raise ValueError('LATE_STOP: restart after uncertain loop history')
        self.last=now;event=None;skipped=0
        late=self.diff(now,self.next)
        if late>=0:
            periods=1+late//250
            self.heartbeat^=periods&1;self.next=self.add(self.next,periods*250)
            skipped=periods-1
        if self.finish is not None and self.diff(now,self.finish)>=0:
            self.finish=None;event='COMPLETED'
        edge=self.button.update(raw,now)
        if edge==1:self.armed=True
        if edge==0 and self.armed:
            self.armed=False
            if self.finish is None:self.finish=self.add(now,5000);event='STARTED'
            else:self.finish=None;event='CANCELLED'
        return {'heartbeat':self.heartbeat,'work':int(self.finish is not None),
                'event':event,'coalesced_edges':skipped,'loop_gap_ms':gap}

def run(read_button, write_heartbeat, write_work, ticks_ms, add, diff, sleep_ms,
        emit=print, limit=None):
    try:
        write_heartbeat(0);write_work(0)
        experiment=Experiment(ticks_ms(),add,diff);count=0
        while limit is None or count<limit:
            row=experiment.step(ticks_ms(),read_button())
            write_heartbeat(row['heartbeat']);write_work(row['work'])
            if row['event'] is not None or row['coalesced_edges']:
                emit(row)
            count+=1;sleep_ms(2)
    except (OSError,ValueError) as exc:
        emit({'event':'FAULT_STOP','current_work':None,'error':str(exc)})
    finally:
        # Try both outputs even if one cleanup operation fails.
        try:write_heartbeat(0)
        finally:write_work(0)

if __name__=='__main__':
    from machine import Pin
    from time import ticks_ms,ticks_add,ticks_diff,sleep_ms
    heartbeat=Pin(16,Pin.OUT,value=0);work=Pin(17,Pin.OUT,value=0)
    button=Pin(14,Pin.IN)
    run(button.value,heartbeat.value,work.value,ticks_ms,ticks_add,ticks_diff,sleep_ms)

Each ordinary iteration requests a 2 ms sleep. This limits busy spinning but does not prove a two-millisecond sample period: printing, interpreter work and the operating environment add delay. The work deadline is checked on the next serviced call, so actual completion can be late. Input sampling also cannot see a short press wholly between calls.

A detected loop gap above 1000 ms, backwards/ambiguous counter result, invalid input or input/output error stops the run. The finally block attempts both outputs LOW, even if one cleanup operation fails. Ctrl+C also reaches cleanup. Reset, disconnected power or an interpreter failure outside Python’s cleanup are different events; this is an experiment, not a safety controller. The lamp is a software command indicator, not proof that a separate physical task finished.

Experiment with responsiveness and missed history

  1. Record board, firmware, resistor values and wiring. Start with the button released and observe the heartbeat. Hold the button at boot once; confirm no work starts until release and a new press.
  2. Press once. The work LED should turn on after a settled press while the heartbeat continues. Let a run finish; record start and completion observations without claiming stopwatch precision from nominal constants.
  3. Start again and press a second time before completion. Record cancellation and continued heartbeat. Holding the button must not repeatedly start and cancel work.
  4. In a disposable copy, insert one 700 ms sleep in the loop. Record the frozen output and coalesced edge count. Restore the original before comparing. Inject a gap above one second in host tests to reproduce FAULT_STOP without treating debugger duration as a calibrated clock.
  5. Use the blank observation sheet (ZIP; file: tricky-circuit-batch007-campaigns63-68/code/pico-cooperative-deadlines-observations-blank.csv). Preserve ignored short presses and late events as useful results.
Challenge: should we replay every missed heartbeat edge?

No. Rapid catch-up edges would be new pulses at the wrong times, not the missed historical waveform. For an indicator this example coalesces state. A dosing pump or a pulse-count protocol would need a different policy, a bounded hardware mechanism and its own fault analysis.

Sources and boundaries

This extends the idea of nonblocking blinking into explicit cancellation, missed-edge policy and a bounded loop-history refusal; it is not a replacement for the site’s existing Arduino blinking overview. Review the electronics lessons for circuit basics. Host checks cover actual button settling, held startup, deadlines, wrap, coalescing and cleanup; physical timing and target operation remain unverified.

📡Broadcast the signal — amplify the connection.

Leave a Reply

Temu affiliate offers

Find your next electronics project

Explore these do-it-yourself project kits. Check the selected option, included parts and instructions on each offer.

Tricky Circuit may earn a commission if you buy through these Temu affiliate links. These are product ideas; they have not been bench-tested by Tricky Circuit and are not verified lesson parts lists.

Supplier photo of a breadboard, jumper wires and assorted electronic components in a plastic storage case.

Supplier product photo

Try breadboard experiments

Breadboard, wires and assorted parts. Arduino controller board not included.

View kit on Temu

Supplier photo of an assembled blue surface-mount soldering practice board with a circular ring of small lights.

Supplier product photo

Solder a chasing-light board

Surface-mount soldering practice. Battery and battery holder not included.

View kit on Temu

Supplier photo of an assembled two-wheeled line-following car with a blue circuit board, two motors and an empty battery holder.

Supplier product photo

Build a line-following car

Soldering and assembly required. Check battery and track requirements before buying.

View kit on Temu