Can you use events or interrupts with EV3 micropython?

433 views Asked by At

I am attempting to write a program for a LEGO Mindstorms EV3 brick that requires actions to be taken when a specific input is recorded by the sensors. As far as I can tell, the only way to do this in EV3 micropython / pybricks is by busy-waiting. This limits the ability to process other information whilst the sensors are checking, since the brick does seemingly not support multithreading.

It seems, however, that the EV3 Classroom block programming supports using events.

Can this be done using events in pybricks too?

1

There are 1 answers

0
AdarW On

You can use multithreading in pybricks using the threading module. I used that for creating events for the touch sensor, I didn't tested it, it is an old code that after I wrote it I realized that I don't need it. But here is the code:

Thread(target=self.listenForButtonClick).start()

def onButtonClick(self, func):
    """
    Add a function to be called when a button is clicked on the EV3 Brick.
    :param func: the function to be called.
    """
    self.buttonClick.append(func)

def listenForButtonClick(self):
    """
    Listen for button clicks on the EV3 Brick.
    """
    while True:
        if any(self.buttons.pressed()):
            for func in self.buttonClick:
                func(self.buttons.pressed())
        wait(50)

Example Usage:

def click(args):
    print(args)
    # Do Stuff

onButtonClick(click)