How to provide data to a task

Hi!
How can one provide data to a task in micropython?

I have read https://docs.littlevgl.com/en/html/overview/task.html but couldn’t adapt it to micropython. I can create a task and use it properly, but can’t provide input to it.

I also tried the approach used for async callbacks but with no success.

Is there a way? Any help is appreciated.

Hi @Tiago_Almeida

It’s simpler than you think.

In Python, when you pass a function as an argument, you automatically pass its context as well.
This means that a function callback can be a method of an object (and then you can access the object), or a lambda function that can access any variable through its closure.

Here is an example:

def toggle_task(btn_to_toggle):
    btn_to_toggle.toggle()

lv.task_create(lambda task: toggle_task(btn), 1000, lv.TASK_PRIO.HIGH, None)

Online demo

In this example we pass btn as an argument to the callback function toggle_task, using a lambda.
There are many other ways to do it in Python. For example passing an object’s method as the callback.

You can use the same technique with async_call, or any other function that receives a callback.

1 Like

Spot on!! This was exactly what I needed, tested it and it works. Thank you once again!