0
0
Iot-protocolsHow-ToBeginner · 4 min read

How to Use Timer on Raspberry Pi Pico: Simple Guide

On Raspberry Pi Pico, you can use the Timer class from the machine module to run code at regular intervals or after a delay. Create a timer object, then use init() to set the period and callback function that runs when the timer triggers.
📐

Syntax

The Timer class lets you create hardware timers. You first create a timer object with Timer(id), where id is the timer number (0-3). Then call init() with parameters:

  • period: time in milliseconds between callbacks
  • mode: Timer.ONE_SHOT for one-time or Timer.PERIODIC for repeated calls
  • callback: function to run when timer fires

This sets up the timer to call your function on schedule.

python
from machine import Timer

timer = Timer(0)
timer.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:print('Timer fired!'))
💻

Example

This example shows how to blink an LED on the Raspberry Pi Pico every second using a timer callback.

python
from machine import Pin, Timer

led = Pin(25, Pin.OUT)  # Onboard LED

def toggle_led(timer):
    led.toggle()

# Create timer 0
timer0 = Timer(0)
# Call toggle_led every 1000 ms (1 second)
timer0.init(period=1000, mode=Timer.PERIODIC, callback=toggle_led)

# Keep running to see LED blink
import time
while True:
    time.sleep(10)
Output
The onboard LED blinks on and off every second.
⚠️

Common Pitfalls

Common mistakes when using timers on Raspberry Pi Pico include:

  • Not keeping the main program running, so the timer callback never triggers.
  • Using long or blocking code inside the callback, which can delay or block other operations.
  • Forgetting to specify mode, which defaults to Timer.ONE_SHOT and only runs once.
  • Using print statements inside callbacks can sometimes cause issues; keep callbacks short and fast.
python
from machine import Timer

timer = Timer(1)

# Wrong: callback blocks with sleep
# def bad_callback(t):
#     import time
#     time.sleep(2)  # Blocks timer and main program

# Right: quick callback

def good_callback(t):
    print('Timer tick')

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

Quick Reference

ParameterDescriptionExample
idTimer number (0 to 3)Timer(0)
periodTime in milliseconds between callbacksperiod=1000
modeTimer mode: ONE_SHOT or PERIODICmode=Timer.PERIODIC
callbackFunction called when timer firescallback=my_function

Key Takeaways

Use the machine.Timer class to create hardware timers on Raspberry Pi Pico.
Initialize timers with period, mode, and callback to run code on schedule.
Keep timer callbacks short and non-blocking for reliable operation.
Use Timer.PERIODIC mode for repeated actions and ONE_SHOT for single events.
Keep the main program running to allow timer callbacks to execute.