Python específico para robots#
Introducción#
El robot héroe, Flop, incluye un motor de admisión, un motor de brazo y un sensor de visión con IA IQ.
Todos los comandos estándar de VEXcode VR Python están disponibles para su uso en el IQ 26-27 Level Up.
A continuación se muestra una lista de todos los comandos de Python disponibles específicos para Robot:
Movimiento: Mueve y rastrea los motores del robot.
Comportamiento
spin – Hace girar un motor en una dirección indefinidamente.
spin_for – Hace girar un motor durante un número específico de grados o vueltas.
spin_to_position – Hace girar un motor a una posición específica.
stop – Detiene el giro de un motor.
Ajustes
set_velocity – Establece la velocidad de giro de un motor.
set_timeout – Establece cuánto tiempo un motor intentará terminar un movimiento.
set_position – Cambia la posición actual del motor a un nuevo valor.
Valores
is_done – Devuelve si el motor ha terminado de moverse.
is_spinning – Devuelve si el motor está girando.
posición – Devuelve la posición actual del motor.
velocidad – Devuelve la velocidad de giro del motor.
Visión por IA: Captura y analiza objetos utilizando el sensor de visión por IA IQ.
Obtenidos
take_snapshot – Filtra el fotograma actual del sensor a una firma específica y devuelve una tupla de objetos detectados.
Propiedades
.width – Devuelve el ancho del objeto detectado en píxeles.
.altura – Devuelve la altura del objeto detectado en píxeles.
.centerX – Devuelve la coordenada x del centro del objeto detectado.
.centerY – Devuelve la coordenada y del centro del objeto detectado.
.originX – Devuelve la coordenada x de la esquina superior izquierda del cuadro delimitador del objeto detectado.
.originY – Devuelve la coordenada y de la esquina superior izquierda del cuadro delimitador del objeto detectado.
.id – Devuelve el ID de la clasificación de IA detectada.
Los ejemplos de esta página utilizan la posición de inicio predeterminada del Playground.
Movimiento#
Flop tiene dos motores específicos para robots: intake_motor y arm_motorAmbos utilizan comandos de motor estándar.
Constantes de dirección:
intake_motor:FORWARD= admisión (recoge);REVERSE= salida (expulsa)arm_motor:FORWARD= arriba (elevación);REVERSE= abajo (descenso)
girar#
spin hace girar un motor en la dirección indicada indefinidamente. El motor seguirá girando hasta que reciba otra orden.
Usage:
motor.spin(direction)
Parámetros |
Descripción |
|---|---|
|
Dirección de giro: |
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.spin_for(FORWARD, 1, TURNS)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
# VR threads — Do not delete
vr_thread(main)
girar_para#
spin_for hace girar un motor durante una distancia específica. El proyecto espera hasta que el motor termine antes de ejecutar el siguiente comando, a menos que se pase wait=False.
Usage:
motor.spin_for(direction, amount, unit)
Parámetros |
Descripción |
|---|---|
|
Dirección de giro: |
|
La distancia a girar. Puede ser un número entero o decimal. |
|
La unidad de medida: |
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.spin_for(FORWARD, 1, TURNS)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
# VR threads — Do not delete
vr_thread(main)
girar_a_posición#
spin_to_position hace girar un motor a una posición específica. El proyecto espera hasta que el motor termine antes de ejecutar el siguiente comando, a menos que se pase wait=False.
Usage:
motor.spin_to_position(position, unit)
Parámetros |
Descripción |
|---|---|
|
La posición a la que girar. Puede ser un número entero o decimal. |
|
La unidad de medida: |
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.spin_to_position(1, TURNS)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
# VR threads — Do not delete
vr_thread(main)
detener#
stop detiene el giro de un motor.
Usage:
motor.stop()
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.spin_for(FORWARD, 1, TURNS)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
wait(1, SECONDS)
intake_motor.stop()
# VR threads — Do not delete
vr_thread(main)
establecer_velocidad#
set_velocity establece la velocidad de giro de un motor como un porcentaje de 0 a 100.
Usage:
motor.set_velocity(velocity, unit)
Parámetros |
Descripción |
|---|---|
|
La velocidad del motor como porcentaje de 0 a 100. |
|
La unidad de medida: |
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.spin_for(FORWARD, 1, TURNS)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.set_velocity(100, PERCENT)
intake_motor.spin(REVERSE)
# VR threads — Do not delete
vr_thread(main)
establecer_tiempo_de_espera#
set_timeout establece cuántos segundos un motor intentará terminar un movimiento antes de detenerse.
Usage:
motor.set_timeout(timeout, unit)
Parámetros |
Descripción |
|---|---|
|
El número de segundos que el motor intentará completar un movimiento. |
|
La unidad de medida: |
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.set_timeout(2, SECONDS)
arm_motor.spin_for(FORWARD, 1, TURNS)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
# VR threads — Do not delete
vr_thread(main)
posición_de_establecer#
set_position cambia la posición actual del motor a un nuevo valor, reiniciando su codificador.
Usage:
motor.set_position(position, unit)
Parámetros |
Descripción |
|---|---|
|
El nuevo valor de posición. |
|
La unidad de medida: |
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.set_position(0, DEGREES)
arm_motor.spin_for(FORWARD, 1, TURNS)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
# VR threads — Do not delete
vr_thread(main)
está_hecho#
is_done devuelve un valor booleano que indica si el motor ha terminado su movimiento.
True– El motor ha terminado de moverse.False– El motor sigue en movimiento.
Usage:
motor.is_done()
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.spin_for(FORWARD, 1, TURNS, wait=False)
while not arm_motor.is_done():
wait(5, MSEC)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
# VR threads — Do not delete
vr_thread(main)
está_girando#
is_spinning devuelve un valor booleano que indica si el motor está girando actualmente.
True– El motor está girando.False– El motor no está girando.
Usage:
motor.is_spinning()
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.spin_for(FORWARD, 1, TURNS)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
while intake_motor.is_spinning():
wait(5, MSEC)
intake_motor.stop()
# VR threads — Do not delete
vr_thread(main)
posición#
La posición position devuelven la posición actual del motor.
Usage:
motor.position(unit)
Parámetros |
Descripción |
|---|---|
|
La unidad de medida: |
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
while arm_motor.position(DEGREES) < 360:
arm_motor.spin(FORWARD)
wait(2, MSEC)
arm_motor.stop()
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
# VR threads — Do not delete
vr_thread(main)
velocidad#
velocity devuelve la velocidad a la que gira actualmente el motor como un porcentaje de -100 a 100.
Usage:
motor.velocity(unit)
Parámetros |
Descripción |
|---|---|
|
La unidad de medida: |
def main():
# Score a Bean Bag in a Blue Goal
drivetrain.turn_for(LEFT, 90, DEGREES)
drivetrain.drive_for(FORWARD, 35, INCHES)
drivetrain.turn_for(RIGHT, 90, DEGREES)
arm_motor.spin_for(FORWARD, 1, TURNS)
drivetrain.drive_for(FORWARD, 40, INCHES)
intake_motor.spin(REVERSE)
wait(0.2, SECONDS)
brain.screen.print(intake_motor.velocity(PERCENT))
# VR threads — Do not delete
vr_thread(main)
Visión por IA#
tomar_instantánea#
take_snapshot filtra los datos del fotograma del sensor de visión IQ AI a una única firma (una descripción guardada de algo que el sensor puede reconocer, como un elemento del juego en el campo) y devuelve una tupla.
The tuple stores objects ordered from largest to smallest by width, starting at index 0. Each object’s properties can be accessed using its index. An empty tuple is returned if no matching objects are detected.
Usage:
ai_vision.take_snapshot(signature)
Parámetros |
Descripción |
|---|---|
|
Filtra el conjunto de datos para incluir solo los datos de la firma dada. Las firmas disponibles son:
|
def main():
# Drop the preloaded Bean Bag
intake_motor.spin_for(REVERSE, 180, DEGREES)
drivetrain.turn_for(LEFT, 90, DEGREES)
# Turn to face a red Bean Bag
drivetrain.set_turn_velocity(30, PERCENT)
while True:
ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
for ai_object in ai_objects:
if ai_object.id == GameElements.RED_BEANBAG:
if ai_object.centerX < 140:
drivetrain.turn(LEFT)
elif ai_object.centerX > 180:
drivetrain.turn(RIGHT)
else:
drivetrain.stop()
return
break
# VR threads — Do not delete
vr_thread(main)
Propiedades#
Hay siete propiedades que se incluyen con cada objeto almacenado en una tupla después de que se utiliza take_snapshot.
Todos los valores de propiedad, excepto .id describen la posición y el tamaño del objeto detectado en la vista del sensor de visión IQ AI en el momento en que se utilizó take_snapshot Estos valores se miden en píxeles, según la resolución de 320 por 240 píxeles del sensor.
.ancho#
.width devuelve el ancho del objeto detectado en píxeles, que es un número entero entre 1 y 320.
def main():
# Drop the preloaded Bean Bag
intake_motor.spin_for(REVERSE, 180, DEGREES)
drivetrain.turn_for(LEFT, 90, DEGREES)
# Approach the Bean Bag, then pick it up
drivetrain.set_drive_velocity(30, PERCENT)
while True:
ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
for ai_object in ai_objects:
if ai_object.id == GameElements.RED_BEANBAG:
if ai_object.width > 200:
drivetrain.stop()
intake_motor.spin(FORWARD)
return
else:
drivetrain.drive(FORWARD)
break
# VR threads — Do not delete
vr_thread(main)
.altura#
.height devuelve la altura del objeto detectado en píxeles, que es un número entero entre 1 y 240.
def main():
# Drop the preloaded Bean Bag
intake_motor.spin_for(REVERSE, 180, DEGREES)
drivetrain.turn_for(LEFT, 90, DEGREES)
# Approach the Bean Bag, then pick it up
drivetrain.set_drive_velocity(30, PERCENT)
while True:
ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
for ai_object in ai_objects:
if ai_object.id == GameElements.RED_BEANBAG:
if ai_object.height > 110:
drivetrain.stop()
intake_motor.spin(FORWARD)
return
else:
drivetrain.drive(FORWARD)
break
# VR threads — Do not delete
vr_thread(main)
.centerX#
.centerX devuelve la coordenada x del centro del objeto detectado en píxeles, que es un número entero entre 0 y 320.
def main():
# Drop the preloaded Bean Bag
intake_motor.spin_for(REVERSE, 180, DEGREES)
drivetrain.turn_for(LEFT, 90, DEGREES)
# Steer to keep the Bean Bag centered
drivetrain.set_turn_velocity(30, PERCENT)
drivetrain.set_drive_velocity(30, PERCENT)
while True:
ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
for ai_object in ai_objects:
if ai_object.id == GameElements.RED_BEANBAG:
if ai_object.centerX < 140:
drivetrain.turn_for(LEFT, 5, DEGREES)
else:
drivetrain.drive_for(FORWARD, 150, MM)
intake_motor.spin(FORWARD)
return
break
# VR threads — Do not delete
vr_thread(main)
.centroY#
.centerY devuelve la coordenada y del centro del objeto detectado en píxeles, que es un número entero entre 0 y 240.
def main():
# Drop the preloaded Bean Bag
intake_motor.spin_for(REVERSE, 180, DEGREES)
drivetrain.turn_for(LEFT, 90, DEGREES)
# Print the y-position of the Bean Bag
ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
for ai_object in ai_objects:
if ai_object.id == GameElements.RED_BEANBAG:
brain.screen.print(ai_object.centerY)
break
# VR threads — Do not delete
vr_thread(main)
.originX#
.originX devuelve la coordenada x de la esquina superior izquierda del cuadro delimitador del objeto detectado en píxeles, que es un número entero entre 0 y 320.
def main():
# Drop the preloaded Bean Bag
intake_motor.spin_for(REVERSE, 180, DEGREES)
drivetrain.turn_for(LEFT, 90, DEGREES)
# Steer to keep the left edge centered
drivetrain.set_turn_velocity(30, PERCENT)
drivetrain.set_drive_velocity(30, PERCENT)
while True:
ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
for ai_object in ai_objects:
if ai_object.id == GameElements.RED_BEANBAG:
if ai_object.originX < 100:
drivetrain.turn_for(LEFT, 5, DEGREES)
else:
drivetrain.drive_for(FORWARD, 150, MM)
intake_motor.spin(FORWARD)
return
break
# VR threads — Do not delete
vr_thread(main)
.origenY#
.originY devuelve la coordenada y de la esquina superior izquierda del cuadro delimitador del objeto detectado en píxeles, que es un número entero entre 0 y 240.
def main():
# Drop the preloaded Bean Bag
intake_motor.spin_for(REVERSE, 180, DEGREES)
drivetrain.turn_for(LEFT, 90, DEGREES)
# Print the y-position of the Bean Bag's top edge
ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
for ai_object in ai_objects:
if ai_object.id == GameElements.RED_BEANBAG:
brain.screen.print(ai_object.originY)
break
# VR threads — Do not delete
vr_thread(main)
.identificación#
.id devuelve el ID de la clasificación de IA detectada como un número entero.
Clasificación de IA |
identificación |
|---|---|
BlueBeanBag |
0 |
Puf rojo |
1 |
Bolsa de frijoles amarilla |
2 |
def main():
# Drop the preloaded Bean Bag
intake_motor.spin_for(REVERSE, 180, DEGREES)
drivetrain.turn_for(LEFT, 90, DEGREES)
# Pick up the Bean Bag if it's red
drivetrain.set_drive_velocity(30, PERCENT)
ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
for ai_object in ai_objects:
if ai_object.id == GameElements.RED_BEANBAG:
intake_motor.spin(FORWARD)
drivetrain.drive_for(FORWARD, 150, MM)
break
# VR threads — Do not delete
vr_thread(main)
def main():
# Stop when you see the Red Goal
drivetrain.set_turn_velocity(30, PERCENT)
drivetrain.turn(RIGHT)
while True:
ai_objects = ai_vision.take_snapshot(AiVision.ALL_TAGS)
for ai_object in ai_objects:
if ai_object.id == 1:
drivetrain.stop()
brain.screen.print("Found the Red Goal!")
return
# VR threads — Do not delete
vr_thread(main)