活动#

介绍#

事件允许您并行运行函数。您无需按顺序调用函数,而是可以将多个函数注册到一个事件中,并一次性触发它们。每个注册的函数都在其自身的线程中运行,从而使您的机器人能够同时执行多个任务——例如在行驶过程中在屏幕上显示数值。

要创建和使用事件,请按以下步骤操作:

  1. Create the event with Event.

  2. Register a function to trigger when the Event is broadcast by calling the event object with the function as an argument.

  3. Broadcast an Event:

    • broadcast – Triggers all registered functions in an event object to run concurrently.

    • broadcast_and_wait – Triggers all registered functions in an event object and waits for them to finish before continuing.

创建活动#

Event creates an event object that manages function execution in separate threads.

Usage:
Event()

参数

描述

此构造函数没有参数。

def move_square():
    for index in range(4):
        robot.drive_for(FORWARD, 1, STEPS)
        robot.turn_for(RIGHT, 90)

# Creating the move_event Event
move_event = Event()
move_event(move_square)
move_event.broadcast()
robot.led.glow(GREEN)

将函数注册到事件#

当您将一个函数注册到某个事件时,当该事件被广播时,该函数将在单独的线程中执行。

Usage:
event(callback, args)

参数

描述

event

先前创建的事件对象的名称。

callback

预先定义的函数,将在事件广播时执行。

args

可选。要传递给回调函数的参数元组

def move_square():
    for index in range(4):
        robot.drive_for(FORWARD, 1, STEPS)
        robot.turn_for(RIGHT, 90)

move_event = Event()
# Register the move_square function to the move_event Event
move_event(move_square)
move_event.broadcast()
robot.led.glow(GREEN)

直播活动#

broadcast#

broadcast triggers an event, starting all registered functions in separate threads. This method does not pause execution of any subsequent code.

Usage:
event.broadcast()

参数

描述

event

先前创建的事件对象的名称。

def move_square():
    for index in range(4):
        robot.drive_for(FORWARD, 1, STEPS)
        robot.turn_for(RIGHT, 90)

move_event = Event()
move_event(move_square)
# Broadcasting the move_event Event
move_event.broadcast()
robot.led.glow(GREEN)

broadcast_and_wait#

broadcast_and_wait starts an event but waits for all registered functions to finish before continuing with subsequent functions.

Usage:
event.broadcast_and_wait()

参数

描述

event

先前创建的事件对象的名称。

def move_square():
    for index in range(4):
        robot.drive_for(FORWARD, 1, STEPS)
        robot.turn_for(RIGHT, 90)

# Set up and call the move_square event
move_event = Event()
move_event(move_square)
# Broadcast the move_event Event and wait
move_event.broadcast_and_wait()
robot.led.glow(GREEN)