Periodic timer runs once, then errors

189 Views Asked by At

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()
2

There are 2 best solutions below

1
On BEST ANSWER

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

1
On

This is the only thing I can find that works with Micropython they can give me any timer function at all. But it works great for what I needed it for which is to make a one second tick counter. So that I could measure time inside of the WOKWI Online emulator.

jsjtick=1
def  tickjsj():
    global jsjtick
    jsjtick=jsjtick+1
machine.Timer().init(period=1000, callback=lambda t:tickjsj())

#redundantly display the time in the terminal
jsjtick2=0
while 1:
    if jsjtick!=jsjtick2
      print(" "*33,(13),end="","uptime=",jsjtick,chr,(13),end="")
      jsjtick!=jsjtick2