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 callbacksmode:Timer.ONE_SHOTfor one-time orTimer.PERIODICfor repeated callscallback: 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 toTimer.ONE_SHOTand 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
| Parameter | Description | Example |
|---|---|---|
| id | Timer number (0 to 3) | Timer(0) |
| period | Time in milliseconds between callbacks | period=1000 |
| mode | Timer mode: ONE_SHOT or PERIODIC | mode=Timer.PERIODIC |
| callback | Function called when timer fires | callback=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.