timernonetypemicropythonraspberry-pi-picorp2040

Periodic timer runs once, then errors


On a Raspberry Pi Pico v1.19.1, when I define my timer the first execution works fine. However subsequent periods fail with:

'TypeError: 'NoneType' object isn't callable

import machine, time
from machine import Timer


class app():
    def __init__(self):
        self.pulse = machine.Timer(-1)
        self.pulse.init(mode=Timer.PERIODIC, period=1000, callback=self.cb_pulse())

    def cb_pulse(self):
        print("whai!")

app()

Solution

  • You must specify the callback function themself, so without the ()

    # Good 
    self.pulse.init(mode=Timer.PERIODIC, period=200, callback=self.cb_pulse)
    # Bad
    self.pulse.init(mode=Timer.PERIODIC, period=200, callback=self.cb_pulse())
    
    

    With the added (), you are actually passing the result/output of the callback method to the timer. And as that returns nothing == None, so the timer tries to call 'None', which is indeed not a callable.

    Working sample in simulator: https://wokwi.com/projects/354050429354521601