Python específico para robots#

Introducción#

El patio de juegos V5RC 25-26 Push Back presenta métodos exclusivos de la construcción diseñada para este patio de juegos, incluidas dos opciones de motor, sensor de visión de inteligencia artificial, sensor óptico y sensor del sistema de posicionamiento de juego (GPS).

Todos los métodos VR estándar de VEXcode están disponibles para su uso en el patio de juegos V5RC 25-26 Push Back.

A continuación se muestra una lista de todos los métodos específicos de Playground disponibles:

Movimiento: mueve y rastrea los motores del robot.

  • Comportamiento

    • spin – Hace girar el motor o el grupo de motores seleccionado indefinidamente.

    • spin_for – Hace girar un motor o grupo durante una distancia específica en grados o vueltas.

    • spin_to_position – Gira un motor o un grupo de motores a una posición establecida.

    • stop – Detiene el giro de un motor o un grupo de motores específico.

  • Mutadores

    • set_position – Establece el valor del codificador de un motor o grupo de motores.

    • set_velocity – Establece la velocidad de un motor o grupo de motores como un porcentaje.

    • set_timeout – Limita el tiempo que un bloque de motor espera antes de darse por vencido si el movimiento está bloqueado.

  • Conseguidores

    • is_done – Devuelve un valor booleano que indica si el motor ya no está girando.

    • is_spinning – Devuelve un valor booleano que indica si el motor está girando actualmente.

    • posición – Devuelve la posición de rotación actual del motor en grados o vueltas.

    • velocidad – Devuelve la velocidad actual del motor en % o rpm.

AI Vision: captura y analiza objetos utilizando el sensor de visión AI.

  • Conseguidores

    • take_snapshot – Devuelve una tupla de objetos detectados según una firma determinada.

  • Propiedades

    • ancho – Ancho del objeto detectado en píxeles.

    • altura – Altura del objeto detectado en píxeles.

    • centerX – Posición X del centro del objeto en píxeles.

    • centerY – Posición Y del centro del objeto en píxeles.

    • originX – Posición X de la esquina superior izquierda del objeto en píxeles.

    • originY – Posición Y de la esquina superior izquierda del objeto en píxeles.

    • id – Clasificación o ID de etiqueta del objeto.

Detección: utilice los distintos sensores del robot.

  • Óptico

    • is_near_object – Devuelve si un objeto detectado está cerca del sensor óptico.

    • color – Devuelve el color detectado por el sensor óptico.

    • brillo – Devuelve el porcentaje de brillo detectado por el sensor.

    • hue – Devuelve el valor de tono del color detectado.

    • object_detected – Registra una función de devolución de llamada para cuando el sensor óptico detecta un objeto.

    • object_lost – Registra una función de devolución de llamada para cuando el sensor óptico pierde un objeto.

  • GPS

    • x_position – Devuelve la coordenada x actual de un sensor GPS en el campo.

    • y_position –Devuelve la coordenada y actual de un sensor GPS en el campo.

    • heading – Devuelve el rumbo al que se enfrenta actualmente el robot según las lecturas del sensor GPS de 0 a 359 grados.

Movimiento#

Actions#

girar#

spin spins a motor or motor group in the specified direction indefinitely.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.spin(direction) — The Intake Motor

conveyor_motor

conveyor_motor.spin(direction) — The Conveyor Motor

Parámetros

Descripción

dirección

The direction for the motor to spin:

  • FORWARD – Spins the Conveyor up or the Intake in the intake direction.
  • REVERSE – Spins the Conveyor down or the Intake in the outtake direction.
def main():
    # Pick up a second Block
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 350, MM)

girar_para#

spin_for spins a motor or motor group for a given amount of degrees or turns.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.spin_for(direction, distance, units, wait) — The Intake Motor

conveyor_motor

conveyor_motor.spin_for(direction, distance, units, wait) — The Conveyor Motor

Parámetros

Descripción

direction

The direction for the motor to spin:

  • FORWARD – Spins the Conveyor up or the Intake in the intake direction.
  • REVERSE – Spins the Conveyor down or the Intake in the outtake direction.

distance

La distancia que debe girar el motor, expresada en un número entero.

units

The unit that represents the distance to rotate:

  • DEGREES
  • TURNS

wait

Optional.

  • wait=True (default) - The robot waits until spin_for is complete before executing the next line of code.
  • wait=False - The robot starts the action and moves on to the next line of code right away, without waiting for spin_for to finish.

def main():
    # Pick up a second Block
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 350, MM)

girar a la posición#

spin_to spins a motor or motor group to a given position.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.spin_to_position(angle, units, wait=True) — The Intake Motor

conveyor_motor

conveyor_motor.spin_to_position(angle, units, wait=True) — The Conveyor Motor

Parámetros

Descripción

angle

El ángulo específico o número de vueltas que dará el motor.

units

The unit that represents the angle to rotate to:

  • DEGREES
  • TURNS

wait

Optional.

  • wait=True (default) - The robot waits until spin_to_position is complete before executing the next line of code.
  • wait=False - The robot starts the action and moves on to the next line of code right away, without waiting for spin_to_position to finish.

def main():
    # Pick up a second Block
    conveyor_motor.spin_to_position(150, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 350, MM)

detener#

stop stops a motor or motor group from spinning.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.stop() — The Intake Motor

conveyor_motor

conveyor_motor.stop() — The Conveyor Motor

Parámetros

Descripción

Este método no tiene parámetros.

def main():
    # Pick up a second Block
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 350, MM)
    intake_motor.stop()

Mutators#

posición_establecida#

set_position sets a motor’s or motor group’s encoder position to the given position value.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.set_position(position, units) — The Intake Motor

conveyor_motor

conveyor_motor.set_position(position, units) — The Conveyor Motor

Parámetros

Descripción

position

El entero específico que se debe configurar para el codificador del motor.

units

The unit that represents the angle to rotate to:

  • DEGREES
  • TURNS
def main():
    # Pick up a second Block
    conveyor_motor.set_position(-150, DEGREES)
    conveyor_motor.spin_to_position(0, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 350, MM)

establecer_velocidad#

set_velocity sets the speed of a motor or motor group.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.set_velocity(velocity, units) — The Intake Motor

conveyor_motor

conveyor_motor.set_velocity(velocity, units) — The Conveyor Motor

Parámetros

Descripción

velocity

La velocidad a la que girará el motor V5, que varía de 0 a 100.

units

The unit that represents the new velocity:

  • PERCENT
def main():
    # Pick up a second Block
    conveyor_motor.set_velocity(90, PERCENT)
    conveyor_motor.spin_for(FORWARD, 200, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 400, MM)

establecer_tiempo_de_espera#

set_timeout sets a time limit for a motor’s or motor group’s movement commands. This prevents Motion commands that do not reach their intended position from preventing subsequent commands from running.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.set_timeout(value, units) — The Intake Motor

conveyor_motor

conveyor_motor.set_timeout(value, units) — The Conveyor Motor

Parámetros

Descripción

value

La cantidad de tiempo que el motor esperará antes de detenerse.

units

The unit to represent the timeout:

  • SECONDS
  • MSEC – milliseconds
def main():
    # Pick up a second Block
    conveyor_motor.set_timeout(0.5, SECONDS)
    conveyor_motor.spin_to_position(1000, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 400, MM)

Getters#

está_hecho#

is_done returns a Boolean indicating whether the specified motor or motor group is not spinning.

  • True – The specified motor is not spinning.

  • False – The specified motor is spinning.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.is_done() — The Intake Motor

conveyor_motor

conveyor_motor.is_done() — The Conveyor Motor

Parámetros

Descripción

Este método no tiene parámetros.

def main():
    # Pick up a second Block
    conveyor_motor.spin_to_position(300, DEGREES, wait=False)
    wait(0.1, SECONDS)
    while not conveyor_motor.is_done():
        drivetrain.drive(FORWARD)
        intake_motor.spin(FORWARD)
        wait(5, MSEC)
    drivetrain.stop()
    intake_motor.stop()

está girando#

is_spinning returns a Boolean indicating whether the specified motor or motor group is spinning.

  • True – The specified motor is spinning.

  • False – The specified motor is not spinning.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.is_spinning() — The Intake Motor

conveyor_motor

conveyor_motor.is_spinning() — The Conveyor Motor

Parámetros

Descripción

Este método no tiene parámetros.

def main():
    # Pick up a second Block
    conveyor_motor.spin_to_position(300, DEGREES, wait=False)
    wait(0.1, SECONDS)
    while conveyor_motor.is_spinning():
        drivetrain.drive_for(FORWARD, 200, MM)
        intake_motor.spin(FORWARD)

posición#

position returns the total distance the specified motor or motor group has rotated.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.position(units) — The Intake Motor

conveyor_motor

conveyor_motor.position(units) — The Conveyor Motor

Parámetros

Descripción

units

The units that represent the motor’s position:

  • DEGREES
  • TURNS
def main():
    # Pick up a second Block
    while conveyor_motor.position(DEGREES) < 150:
        conveyor_motor.spin(FORWARD)
        wait(2, MSEC)
    conveyor_motor.stop()
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 400, MM)

velocidad#

velocity returns the current rotational speed of the motor or motor group.

Uso:
Se puede utilizar uno de los dos objetos de motor disponibles con este método, como se muestra a continuación:

motor

Dominio

intake_motor

intake_motor.velocity(units) — The Intake Motor

conveyor_motor

conveyor_motor.velocity(units) — The Conveyor Motor

Parámetros

Descripción

units

The unit that represent the motor’s position:

  • PERCENT
def main():
    # Pick up a second block
    conveyor_motor.set_velocity(100, PERCENT)
    conveyor_motor.spin_to_position(300, DEGREES, wait=False)
    wait(0.2, SECONDS)
    brain.screen.print(conveyor_motor.velocity(PERCENT))
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 400, MM)

Visión de IA#

Getters#

tomar_instantánea#

take_snapshot filters the data from the AI Vision Sensor frame to return a tuple.

La tupla almacena objetos ordenados de mayor a menor por ancho, comenzando en el índice 0. Se puede acceder a las propiedades de cada objeto mediante su índice. Si no se detectan objetos coincidentes, se devuelve una tupla vacía.

Usage:
ai_vision.take_snapshot(signature)

Parámetros

Descripción

signature

¿De qué firma se obtienen los datos? La única firma disponible es:

  • AiVision.ALL_AIOBJS - Detecta bloques rojos y azules.

def main():
    # If an object is detected, pick it up
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    while True:
        ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
        if ai_objects:
            intake_motor.spin(FORWARD)
            drivetrain.drive(FORWARD)
            while not bumper.pressing():
                wait(2, MSEC)
            drivetrain.stop()
            break

Properties#

Hay siete propiedades que se incluyen con cada objeto almacenado en una tupla después de utilizar take_snapshot.

Some property values are based off of the detected object’s position in the AI Vision Sensor’s view at the time that take_snapshot was used. The AI Vision Sensor has a resolution of 320 by 240 pixels.

.ancho#

.width returns the width of the detected object in pixels, which is an integer between 1 and 320.

def main():
    # If an object is detected, approach and pick it up
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    while True:
        ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
        if ai_objects:
            if ai_objects[0].width > 65:
                drivetrain.stop()
                break
            else:
                intake_motor.spin(FORWARD)
                drivetrain.drive(FORWARD)

.altura#

.height returns the height of the detected object in pixels, which is an integer between 1 and 240.

def main():
    # If an object is detected, approach and pick it up
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    while True:
        ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
        if ai_objects:
            if ai_objects[0].height > 55:
                drivetrain.stop()
                break
            else:
                intake_motor.spin(FORWARD)
                drivetrain.drive(FORWARD)

.centroX#

.centerX returns the x-coordinate of the detected object’s center in pixels, which is an integer between 0 and 320.

def main():
    # Pick up a Block from the top left group
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    drivetrain.turn_for(LEFT, 80, DEGREES)
    drivetrain.drive_for(FORWARD, 200, MM)
    drivetrain.set_turn_velocity(20, PERCENT)
    drivetrain.turn(LEFT)
    while True:
        ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
        if ai_objects:
            if 140 < ai_objects[0].centerX < 180:
                intake_motor.spin(FORWARD)
                drivetrain.drive(FORWARD)
                while not bumper.pressing():
                    wait(2, MSEC)
                drivetrain.stop()

.centerY#

.centerY returns the y-coordinate of the detected object’s center in pixels, which is an integer between 0 and 240.

def main():
    # If an object is detected, approach and pick it up
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    while True:
        ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
        if ai_objects:
            if ai_objects[0].centerY > 140:
                drivetrain.stop()
                break
            else:
                intake_motor.spin(FORWARD)
                drivetrain.drive(FORWARD)

.origenX#

.originX returns the x-coordinate of the top-left corner of the detected object’s bounding box in pixels, which is an integer between 0 and 320.

def main():
    # Pick up a Block from the top left group
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    drivetrain.turn_for(LEFT, 80, DEGREES)
    drivetrain.drive_for(FORWARD, 300, MM)
    drivetrain.set_turn_velocity(20, PERCENT)
    drivetrain.turn(RIGHT)
    while True:
        ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
        if ai_objects:
            if 100 < ai_objects[0].originX < 140:
                intake_motor.spin(FORWARD)
                drivetrain.drive(FORWARD)
                while not bumper.pressing():
                    wait(2, MSEC)
                drivetrain.stop()

.origenY#

.originY returns the y-coordinate of the top-left corner of the detected object’s bounding box in pixels, which is an integer between 0 and 240.

def main():
    # If an object is detected, approach and pick it up
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    while True:
        ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
        if ai_objects:
            if ai_objects[0].originY > 120:
                drivetrain.stop()
                break
            else:
                intake_motor.spin(FORWARD)
                drivetrain.drive(FORWARD)

.identificación#

.id returns the ID of the detected AI Classification as an integer.

Clasificación de IA

identificación

Firma

Bloque azul

1

GameElements.BLUE_BLOCK

Bloque rojo

2

GameElements.RED_BLOCK

def main():
    # Pick up a Red Block from the top left group
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    drivetrain.turn_for(LEFT, 80, DEGREES)
    drivetrain.drive_for(FORWARD, 300, MM)
    while True:
        ai_objects = ai_vision.take_snapshot(AiVision.ALL_AIOBJS)
        if ai_objects:
            drivetrain.drive(FORWARD)
            if (ai_objects[0].id) == 2:
                intake_motor.spin(FORWARD)
                while not bumper.pressing():
                    wait(2, MSEC)
                drivetrain.stop()
                break

Detección#

Optical#

está_cerca_del_objeto#

is_near_object returns a Boolean indicating whether or not the Optical Sensor detects an object close to the sensor.

  • True – The object is close to the Optical Sensor.

  • False – The object is not close to the Optical Sensor.

Usage:
optical.is_near_object()

Parámetros

Descripción

Este método no tiene parámetros.

def main():
    # Move the preloaded Block to the top of the Conveyor
    conveyor_motor.spin(FORWARD)
    while not optical.is_near_object():
        wait(2, MSEC)
    conveyor_motor.stop()

color#

color returns the color detected by the Optical Sensor:

Color devuelto:

  • NONE – No color detected.
  • RED
  • GREEN
  • BLUE
  • YELLOW
  • ORANGE
  • PURPLE
  • CYAN

Usage:
optical.color()

Parámetros

Descripción

Este método no tiene parámetros.

def main():
    # Pick up and move a Blue Block to the top of the Conveyor
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 360, MM)
    conveyor_motor.spin(FORWARD)
    while not optical.color() == BLUE:
        wait(2, MSEC)
    conveyor_motor.stop()

brillo#

brightness returns the brightness value detected by the Optical Sensor as a percent from 0% to 100%.

Usage:
optical.brightness()

Parámetros

Descripción

Este método no tiene parámetros.

def main():
    # Move the preloaded Block to the top of the Conveyor
    conveyor_motor.spin(FORWARD)
    while not 0 < optical.brightness():
        wait(2, MSEC)
    conveyor_motor.stop()

matiz#

hue returns the hue detected by the Optical Sensor.

Los valores de tono varían de 0 a 359 grados, correspondientes a las posiciones en la rueda de color que se muestran a continuación.

Una rueda de color circular que muestra un espectro completo de tonos etiquetados con valores de grados alrededor del perímetro, que aumentan en incrementos de 30 grados desde 0° en la parte superior hasta 360°.

Usage:
optical.hue()

Parámetros

Descripción

Este método no tiene parámetros.

def main():
    # Pick up and move a Blue Block to the top of the Conveyor
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive_for(FORWARD, 360, MM)
    conveyor_motor.spin(FORWARD)
    while not 220 < optical.hue() < 260:
        wait(2, MSEC)
    conveyor_motor.stop()

objeto_detectado#

object_detected registers a callback function for when the Optical Sensor detects an object.

Usage:
optical.object_detected(callback, arg)

Parámetros

Descripción

callback

Una función que se llamará cuando se detecte un objeto.

arg

Opcional. Una tupla que se utiliza para pasar argumentos a la función de devolución de llamada.

def ready_block():
  # Stop the conveyor when Block is at the Sensor
  conveyor_motor.stop()

def main():
  # Move the preloaded Block near the top of the Conveyor
  conveyor_motor.spin(FORWARD)
  optical.object_detected(ready_block)

objeto_perdido#

object_lost registers a callback function for when the Optical Sensor loses a previously detected object.

Usage:
optical.object_lost(callback, arg)

Parámetros

Descripción

callback

Una función que se llamará cuando se pierda un objeto detectado.

arg

Opcional. Una tupla que se utiliza para pasar argumentos a la función de devolución de llamada.

def ready_block():
  # Stop the conveyor when Block is at the top
  conveyor_motor.stop()

def main():
  # Move the preloaded Block to the top of the Conveyor
  conveyor_motor.spin(FORWARD)
  optical.object_lost(ready_block)

GPS#

Todos los ejemplos de sensores GPS (Game Positioning System™) en esta página utilizan la posición de inicio del patio de juegos predeterminada, C.

posición x#

x_position returns the current x coordinate of a GPS (Game Positioning System™) Sensor on the Field.

Usage:
gps.x_position(units)

Parámetros

Descripción

unidades

The unit of the offset value, INCHES or MM (Millimeters).

def main():
    # Pick up a second Block
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive(FORWARD)
    while not gps.x_position(MM) > -795:
        wait(2, MSEC)
    drivetrain.stop()

posición y#

y_position returns the current y coordinate of a GPS (Game Positioning System™) Sensor on the Field.

Usage:
gps.y_position(units)

Parámetros

Descripción

unidades

The unit of the offset value, INCHES or MM (Millimeters).

def main():
    # Pick up a second Block
    conveyor_motor.spin_for(FORWARD, 150, DEGREES)
    intake_motor.spin(FORWARD)
    drivetrain.drive(FORWARD)
    while not -450 > gps.y_position(MM):
        wait(2, MSEC)
    drivetrain.stop()

título#

heading returns the heading that the robot is currently facing based on the GPS (Game Positioning System™) Sensor’s readings from 0 to 359 degrees.

Usage:
gps.heading()

Parámetros

Descripción

Este método no tiene parámetros.

def main():
    # Score the preloaded Block into a Center Goal
    drivetrain.set_turn_velocity(30, PERCENT)
    drivetrain.turn(LEFT)
    while not 40 > gps.heading():
        wait(2, MSEC)
    drivetrain.drive_for(FORWARD, 1000, MM)
    drivetrain.turn(RIGHT)
    while not gps.heading() > 310:
        wait(2, MSEC)
    drivetrain.drive_for(REVERSE, 400, MM)
    conveyor_motor.spin(FORWARD)