Page 1 of 1

Timer callback function

Posted: Thu Aug 30, 2018 7:01 pm
by thejoker
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!

Re: Timer callback function

Posted: Thu Aug 30, 2018 7:21 pm
by thejoker
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

Re: Timer callback function

Posted: Thu Aug 30, 2018 8:09 pm
by dhylands
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

Re: Timer callback function

Posted: Fri Aug 31, 2018 6:06 am
by pythoncoder
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)