PyRasp

11–12. Time and events

A program does not have to do everything in one loop. Sometimes you want a function to run later or every so often, while the main program keeps doing something else. MicroPython gives you Timer, pin interrupts and the Signal output wrapper.

There is one rule that explains every surprise in this module: callbacks here are cooperative. They run at safe points — right after a sleep — not in the middle of your code.

A timeline. The main program sleeps in short steps; each time the timer ticks, your callback runs briefly, then the main program carries on.

This is different from a real Pico, where a timer interrupt can run at almost any instant. It makes the simulation reproducible, and it makes a class of bugs visible instead of mysterious.


Lesson 11 — Timers

You will be able to: blink without sleeping between toggles, run a one-shot action, and stop a timer cleanly.

The idea

A periodic timer calls a function every period, forever. A one-shot timer calls it once. The main program still has to sleep, because that is when callbacks get their turn.

from machine import Pin, Timer
import utime

led = Pin(13, Pin.OUT)

def flip(timer):
    led.toggle()

timer = Timer()
timer.init(period=500, mode=Timer.PERIODIC, callback=flip)

while True:
    utime.sleep_ms(10)

period is in milliseconds. 500 ms per toggle is one full on/off cycle per second.

The exact tools

WhatMicroPython
Create a timertimer = Timer()
Periodictimer.init(period=500, mode=Timer.PERIODIC, callback=fn)
One-shottimer.init(mode=Timer.ONE_SHOT, period=1000, callback=fn)
Stop and releasetimer.deinit()
The callback's argumentthe timer object itself (fn(timer))

Build it

Blink with a timer. Keep the LED on GP13, let the timer flip it every 500 ms, and leave the main loop at sleep_ms(10). Compare it with lesson 2: the same blink, with no sleep between toggles.

One-second glow. Light the LED, then start a one-shot timer to turn it off after 1000 ms:

led.on()

def off(timer):
    led.off()

timer = Timer()
timer.init(mode=Timer.ONE_SHOT, period=1000, callback=off)
while True:
    utime.sleep_ms(10)

Fun fact. A 500 ms period means the timer fires twice per second, and the LED completes one on/off cycle per second. “Period” is the time between callbacks, not the blink rate. Read the units every time.

What you should see

  • Periodic: a clean 1 Hz blink, with the main loop doing nothing but sleeping.
  • One-shot: on for the first second, off afterwards, and it stays off.

Common mistakes

What you seeWhyFix
Nothing happensThe main loop never sleepsAdd utime.sleep_ms(10)
The LED flickers too fastperiod=50 instead of 500Milliseconds, not seconds
Several flips at onceA long sleep let the timer catch upSleep in small steps, or accept the catch-up
The callback crashes the runAn exception inside a callbackKeep callbacks short and safe
NameError for TimerThe import is missingfrom machine import Timer

Check yourself

  1. What is the difference between PERIODIC and ONE_SHOT?
  2. Why does the main loop need a sleep?
  3. Where should the heavy work live: in the callback or the main loop?

Answers: periodic repeats, one-shot fires once · callbacks run after a sleep · the main loop, so the callback stays quick.

Remember

  • Timer.init(period=…, mode=…, callback=…); deinit() releases it.
  • Callbacks are cooperative: no sleep, no tick.
  • Keep callbacks short; let the main loop do the thinking.

Problems: Blink with a timer · One-second glow


Lesson 12 — Pin interrupts

You will be able to: run a function when a pin changes, debounce it, and use Signal for an active-low output.

The idea

Pin.irq() attaches a function to a pin edge. On a real Pico the CPU stops what it is doing and runs the handler; here the handler runs at the next cooperative tick (during a sleep). The API is the same, so the code moves to hardware unchanged.

from machine import Pin
import utime

button = Pin(12, Pin.IN, Pin.PULL_DOWN)
presses = 0

def changed(pin):
    global presses
    presses += 1

irq = button.irq(trigger=Pin.IRQ_FALLING, handler=changed)

while True:
    print("presses", presses)
    utime.sleep_ms(100)

trigger is a bitmask: Pin.IRQ_RISING, Pin.IRQ_FALLING, or both. The handler receives the Pin that changed. irq.off() stops it; irq.on() starts it again.

Signal is a different tool: it wraps a pin as a logical output, with optional inversion.

from machine import Pin, Signal

led = Signal(Pin(15, Pin.OUT), invert=True)
led.on()        # drives the physical pin LOW
led.off()       # drives it HIGH
print(led.value())

That is exactly how an active-low LED or relay is wired on a real board.

The exact tools

WhatMicroPython
Watch a pin edgeirq = pin.irq(trigger=Pin.IRQ_FALLING, handler=fn)
Stop / restartirq.off() / irq.on()
Invert an outputSignal(pin, invert=True)
Set logical levelsignal.on(), signal.off(), signal.value(1)

Build it

  1. Count button presses with Pin.IRQ_FALLING; print the count.
  2. Add debouncing: after the handler fires, wait 20 ms and check the pin again before counting.
  3. Use Pin.IRQ_RISING | Pin.IRQ_FALLING and print both edges.
  4. Wire an active-low LED through Signal(..., invert=True) and prove that on() drives the pin low.

Careful. The simulator checks edges during sleeps. If a pulse is shorter than your longest sleep, it can be missed. For a human button that is fine; for a fast sensor, poll or use a bus device.

Common mistakes

What you seeWhyFix
The handler never runsThe main loop never sleepsAdd a small sleep
One press counts many timesContact bounceDebounce inside the handler
A press is missedThe pulse is shorter than the sleepSleep in smaller steps
Signal does not watch edgesIt is an output wrapper, not an interruptUse Pin.irq() for edges
signal.off() stops the pinSignal is an output wrapper, not an interruptIt drives the logical output low; use irq.off() to stop edges

Check yourself

  1. What triggers a Pin.irq handler?
  2. Why can a short pulse be missed?
  3. What does Signal(pin, invert=True).on() do to the physical pin?

Answers: a configured rising/falling edge · edges are checked during sleeps · it drives the physical pin low.

Remember

  • Use Pin.irq() for edges, not Signal.
  • Cooperative means “during a sleep”, not “instantly”.
  • Debounce human inputs; do not use an interrupt for very fast pulses without checking timing.
  • Signal is for logical, possibly inverted, outputs.

Problems: use the debounce and edge patterns from Press to toggle and Short or long?.


Choosing between a loop, a timer and a signal

You needUseWhy
Read a sensor every 100 msmain loop + sleep_ms(100)Simple, predictable
Blink while doing something elseperiodic TimerIndependent of loop timing
Turn something off once after a delayone-shot TimerNo state machine needed
React to a human pressPin.irq() or pollingBoth are fine; debounce either way
Catch a 1 ms pulsepolling, or a bus deviceA cooperative interrupt may miss it

The design question. “What needs to happen while the program is sleeping?” If the answer is “nothing”, a plain loop is clearer. If the answer is “a blink” or “a timeout”, reach for a timer.

Next