Timer callback function

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
thejoker
Posts: 11
Joined: Sat Aug 04, 2018 2:14 pm

Timer callback function

Post by thejoker » Thu Aug 30, 2018 7:01 pm

Dear reader,

I am trying to make sense of the micropython timer.callback() function, but I can't say I understand it very well.

My idea was to use the following code to call a function every 1 second:

Code: Select all

import pyb
import time


def tick():
    print(time.ticks_ms())


# Create timer which calls the function 'tick' every second
tim = pyb.Timer(1, freq=1)
tim.callback(tick)
However, I get the following error:

Code: Select all

>>> uncaught exception in Timer(1) interrupt handler
TypeError:
Does anyone know why this happens and what a possible solution is?
Many thanks in advance!

thejoker
Posts: 11
Joined: Sat Aug 04, 2018 2:14 pm

Re: Timer callback function

Post by thejoker » Thu Aug 30, 2018 7:21 pm

I found the problem:
Note: Memory can’t be allocated during a callback (an interrupt) and so exceptions raised within a callback don’t give much information

User avatar
dhylands
Posts: 2858
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Timer callback function

Post by dhylands » Thu Aug 30, 2018 8:09 pm

This page has quite a bit of information about writing interrupt handlers in MicroPython. In particular, to get more detailed information about exceptions, you should allocate an emergency exception buffer:
http://docs.micropython.org/en/latest/p ... ion-buffer

User avatar
pythoncoder
Posts: 2991
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Timer callback function

Post by pythoncoder » Fri Aug 31, 2018 6:06 am

There is a bug in the code. If you read the timer docs you will find that the callback takes one argument, the timer object. The following works:

Code: Select all

import pyb
import time

def tick(_):  # Accept and discard the arg
    print(time.ticks_ms())

# Create timer which calls the function 'tick' every second
tim = pyb.Timer(1, freq=1)
tim.callback(tick)
Peter Hinch

Post Reply