Page 1 of 1
Issue with a timer callback
Posted: Tue Oct 20, 2020 9:15 pm
by pipponefrancone
Hello there,
I am trying to use an object's method as a timer callback:
Code: Select all
#creating a new object a
>>> a = test()
>>> a.mymethod
<bound_method>
>>> timer = Timer(0)
>>> timer.init(period=50, mode=1, callback=a.mymethod)
At this point, each time the timer runs it gives me this error:
Code: Select all
TypeError: function takes 1 positional arguments but 2 were given
How do I solve this?
Re: Issue with a timer callback
Posted: Tue Oct 20, 2020 10:21 pm
by jimmo
What does mymethod look like? The Timer will expect that it takes an instance of the timer that fired the IRQ.
Code: Select all
class test:
...
def mymethod(self, timer):
print('hello')
I'm guessing you just have "def mymethod(self):" ?
Re: Issue with a timer callback
Posted: Wed Oct 21, 2020 11:32 am
by pipponefrancone
Yes the function only takes the self parameter, I totally forgot to add one for the timer instance.
jimmo wrote: ↑Tue Oct 20, 2020 10:21 pm
Code: Select all
def mymethod(self, timer):
print('hello')
This solves it, thank you. But what if I want to pass other parameters?
Re: Issue with a timer callback
Posted: Wed Oct 21, 2020 10:37 pm
by jimmo
As long as to the Timer, it looks like a method that takes one argument, then you can. This is already happening with the "self" argument, but ignoring classes for a second, you can bind arguments any way you like. Lambdas are my favourite way but there are other alteratives.
Code: Select all
def handler(timer):
pass
timer.irq(callback=handler)
Code: Select all
def handler_with_other_args(timer, x, y):
pass
timer.irq(callback=lambda t: handler(t, 1, 2))
Re: Issue with a timer callback
Posted: Fri Oct 23, 2020 8:53 am
by pipponefrancone
That's very interesting, thank for your help!
I would also like to ask another question about timers, should I add it here or crate a new thread? Sorry I'm not very familiar with forums
Re: Issue with a timer callback
Posted: Fri Oct 23, 2020 11:30 am
by jimmo
pipponefrancone wrote: ↑Fri Oct 23, 2020 8:53 am
I would also like to ask another question about timers, should I add it here or crate a new thread?
Probably best make a new thread.