Trapos#
Introducción#
Los hilos permiten que un robot ejecute varias tareas simultáneamente dentro del mismo programa. Facilitan la multitarea, permitiendo que el robot realice acciones independientes al mismo tiempo.
Nota: Primero debe definir una función para usarla con un hilo.
Constructor – Crea e inicia nuevos hilos.
Thread– Starts a new thread that runs the specified function in parallel with the main program.
Acción: Controlar los hilos en ejecución.
stop– Stops a thread manually, useful for halting background behavior.
Constructor#
Thread#
Thread creates and starts a thread. When you create a thread, you can name it to manage it individually in your project.
Uso:
my_thread = Thread(my_function)
Parámetros |
Descripción |
|---|---|
|
Opcional. Un nombre para el nuevo hilo. |
|
El nombre de una función definida previamente. |
Nota: Una función debe siempre estar definida antes de ser llamada.
def move_square():
# Move in a square path
while True:
arm.move_inc(100, 0, 0)
arm.move_inc(0, 100, 0)
arm.move_inc(-100, 0, 0)
arm.move_inc(0, 100, 0)
move_square_thread = Thread(move_square)
signal_tower.set_color(SignalTower.BLUE, signal_tower.BLINK)
# Run multiple threads simultaneously
def move_square():
# Move in a square path
while True:
arm.move_inc(100, 0, 0)
arm.move_inc(0, 100, 0)
arm.move_inc(-100, 0, 0)
arm.move_inc(0, 100, 0)
def lights():
while True:
# Turn on all LEDs
signal_tower.set_colors(SignalTower.ON, SignalTower.ON, SignalTower.ON, SignalTower.ON, SignalTower.ON)
wait(0.25, SECONDS)
# Turn on just the red LED
signal_tower.set_colors(SignalTower.ON, SignalTower.OFF, SignalTower.OFF, SignalTower.OFF, SignalTower.OFF)
wait(0.25, SECONDS)
move_square_thread = Thread(move_square)
lights_thread = Thread(lights)
Acción#
stop#
stop stops a thread manually, which is useful when a task is no longer needed or when a program needs to reset or reassign threads. Once a thread is stopped, it cannot be restarted. To run it again, you must create a new thread using Thread.
Uso:
my_thread.stop()
Parámetros |
Descripción |
|---|---|
|
A previously started thread object. This is the name assigned when the thread was created using |
"""
Run multiple threads simultaneously
Move the end effector, flash lights and display the x position at once
Stop blinking after 2 seconds
"""
def lights():
while True:
# Turn on all LEDs
signal_tower.set_colors(SignalTower.ON, SignalTower.ON, SignalTower.ON, SignalTower.ON, SignalTower.ON)
wait(0.25, SECONDS)
# Turn on just the red LED
signal_tower.set_colors(SignalTower.ON, SignalTower.OFF, SignalTower.OFF, SignalTower.OFF, SignalTower.OFF)
wait(0.25, SECONDS)
def display_x():
while True:
brain.clear_row()
brain.set_cursor(1, 1)
brain.print("X Position: {}".format(arm.get_x()))
wait(50, MSEC)
lights_thread = Thread(lights)
display_x_thread = Thread(display_x)
arm.move_to(200, 140, 210)
wait(2, SECONDS)
lights_thread.stop()