Drivetrain Python
En esta guía crearás un drivetrain diferencial moderno utilizando Python y RobotPy, siguiendo el mismo flujo que la versión en Java pero adaptado a la sintaxis y herramientas de Python.
El objetivo es aprender:
- Cómo crear un proyecto FRC con RobotPy
- Cómo funciona un drivetrain diferencial
- Cómo utilizar leaders y followers
- Cómo controlar el robot con un control Xbox
- Cómo configurar motores brushless
- Cómo desplegar código al roboRIO
- Cómo probar el robot desde Driver Station
¿Qué es un Differential Drivetrain?
Section titled “¿Qué es un Differential Drivetrain?”Un Differential Drivetrain utiliza lados izquierdo y derecho independientes para mover el robot, igual que en la versión Java de esta guía.
La mayoría de robots FRC tipo tanque utilizan:
- 2 motores izquierdos
- 2 motores derechos
- Leaders y followers
- Control arcade con control Xbox
- Motores brushless conectados por CAN
Antes de comenzar
Section titled “Antes de comenzar”Asegúrate de tener:
- Python y RobotPy instalados
- VS Code configurado
- roboRIO configurado
- Driver Station funcionando
- Control Xbox conectado
- Motores y controladores correctamente cableados
Crear un nuevo proyecto
Section titled “Crear un nuevo proyecto”Abre una terminal en la carpeta donde quieras crear el proyecto y ejecuta el comando de inicialización de RobotPy.
py -3 -m robotpy initpython3 -m robotpy initEstructura del proyecto
Section titled “Estructura del proyecto”RobotPy genera dos archivos principales en la carpeta del proyecto:
- robot.py
- pyproject.toml
robot.py contiene la clase principal del robot. pyproject.toml define las dependencias del proyecto, incluyendo la versión de RobotPy y las librerías de fabricantes que agregues.
¿Qué vamos a construir?
Section titled “¿Qué vamos a construir?”Crearemos un drivetrain con:
- 4 motores brushless
- Leaders y followers
- Differential Drive
- Control Xbox
- Arcade Drive
La estructura será similar a esta:
Left Side├── Left Leader└── Left Follower
Right Side├── Right Leader└── Right FollowerCAN IDs
Section titled “CAN IDs”Cada controlador de motor necesita un CAN ID único. En este ejemplo utilizaremos los mismos IDs que la versión Java:
| Motor | CAN ID |
|---|---|
| Left Leader | 10 |
| Left Follower | 11 |
| Right Leader | 12 |
| Right Follower | 13 |
Importando librerías
Section titled “Importando librerías”import wpilibimport rev
from wpilib.drive import DifferentialDriveDeclarando la clase del robot
Section titled “Declarando la clase del robot”class MyRobot(wpilib.TimedRobot):
def robotInit(self):
# Left side motors self.leftLeader = rev.SparkMax( 10, rev.SparkLowLevel.MotorType.kBrushless)
self.leftFollower = rev.SparkMax( 11, rev.SparkLowLevel.MotorType.kBrushless)
# Right side motors self.rightLeader = rev.SparkMax( 12, rev.SparkLowLevel.MotorType.kBrushless)
self.rightFollower = rev.SparkMax( 13, rev.SparkLowLevel.MotorType.kBrushless)¿Qué son Leaders y Followers?
Section titled “¿Qué son Leaders y Followers?”En un drivetrain FRC moderno normalmente existen motores leaders y motores followers.
El motor leader recibe comandos directamente desde el código. El follower copia automáticamente el comportamiento del leader del mismo lado.
Esto permite:
- Simplificar el código
- Mantener sincronizados los motores
- Reducir errores
Configurando el control Xbox
Section titled “Configurando el control Xbox”self.controller = wpilib.XboxController(0)Configurando Differential Drive
Section titled “Configurando Differential Drive”self.drive = DifferentialDrive(self.leftLeader, self.rightLeader)Configurando Followers e inversión
Section titled “Configurando Followers e inversión”Dentro de robotInit(), después de crear los motores, se configuran con objetos SparkMaxConfig:
leftFollowerConfig = rev.SparkMaxConfig()leftFollowerConfig.follow(self.leftLeader)self.leftFollower.configure( leftFollowerConfig, rev.ResetMode.kResetSafeParameters, rev.PersistMode.kPersistParameters)
rightFollowerConfig = rev.SparkMaxConfig()rightFollowerConfig.follow(self.rightLeader)self.rightFollower.configure( rightFollowerConfig, rev.ResetMode.kResetSafeParameters, rev.PersistMode.kPersistParameters)
rightLeaderConfig = rev.SparkMaxConfig()rightLeaderConfig.inverted(True)self.rightLeader.configure( rightLeaderConfig, rev.ResetMode.kResetSafeParameters, rev.PersistMode.kPersistParameters)Configurando Arcade Drive
Section titled “Configurando Arcade Drive”Ahora agregaremos control manual dentro de teleopPeriodic().
def teleopPeriodic(self):
speed = -self.controller.getLeftY() rotation = self.controller.getRightX()
self.drive.arcadeDrive(speed, rotation)-self.controller.getLeftY()lee el stick izquierdo para avanzar y retroceder.self.controller.getRightX()lee el stick derecho para girar.self.drive.arcadeDrive(speed, rotation)convierte ambos valores en movimiento para el drivetrain.
¿Cómo funciona Arcade Drive?
Section titled “¿Cómo funciona Arcade Drive?”Con este sistema:
- Stick izquierdo → adelante y atrás
- Stick derecho → giro o pivote
Si avanzas y giras al mismo tiempo, el robot girará suavemente mientras avanza. Este es uno de los métodos de control más utilizados en FRC.
Código completo del robot
Section titled “Código completo del robot”import wpilibimport rev
from wpilib.drive import DifferentialDrive
class MyRobot(wpilib.TimedRobot):
def robotInit(self):
# Left side motors self.leftLeader = rev.SparkMax( 10, rev.SparkLowLevel.MotorType.kBrushless)
self.leftFollower = rev.SparkMax( 11, rev.SparkLowLevel.MotorType.kBrushless)
# Right side motors self.rightLeader = rev.SparkMax( 12, rev.SparkLowLevel.MotorType.kBrushless)
self.rightFollower = rev.SparkMax( 13, rev.SparkLowLevel.MotorType.kBrushless)
# Followers leftFollowerConfig = rev.SparkMaxConfig() leftFollowerConfig.follow(self.leftLeader) self.leftFollower.configure( leftFollowerConfig, rev.ResetMode.kResetSafeParameters, rev.PersistMode.kPersistParameters)
rightFollowerConfig = rev.SparkMaxConfig() rightFollowerConfig.follow(self.rightLeader) self.rightFollower.configure( rightFollowerConfig, rev.ResetMode.kResetSafeParameters, rev.PersistMode.kPersistParameters)
# Invert right side rightLeaderConfig = rev.SparkMaxConfig() rightLeaderConfig.inverted(True) self.rightLeader.configure( rightLeaderConfig, rev.ResetMode.kResetSafeParameters, rev.PersistMode.kPersistParameters)
# Xbox controller self.controller = wpilib.XboxController(0)
# Differential drivetrain self.drive = DifferentialDrive(self.leftLeader, self.rightLeader)
def teleopPeriodic(self):
# Forward and backward speed = -self.controller.getLeftY()
# Rotation rotation = self.controller.getRightX()
# Drive robot self.drive.arcadeDrive(speed, rotation)Métodos importantes
Section titled “Métodos importantes”Se ejecuta una sola vez cuando el programa del robot inicia. Se utiliza para preparar el robot antes de comenzar a operar, inicializando motores, sensores, controles y cualquier configuración necesaria para el resto del código.
Se ejecuta continuamente mientras el robot está en modo Teleoperated. Aquí normalmente se procesa la entrada de joysticks y controles para permitir que el driver maneje el robot manualmente durante el partido.
Se ejecuta repetidamente durante el modo Autonomous. Se utiliza para programar movimientos y acciones automáticas que el robot realiza sin intervención del conductor.
Se ejecuta cuando el robot entra en estado deshabilitado. Generalmente se utiliza para detener sistemas, reiniciar variables o asegurar que el robot permanezca en un estado seguro.
Desplegar código al robot
Section titled “Desplegar código al robot”- Conecta el roboRIO por Ethernet o USB.
- Abre una terminal en la carpeta del proyecto.
- Ejecuta el comando de deploy.
python -m robotpy deployVerificar comunicación
Section titled “Verificar comunicación”Abre Driver Station y verifica:
- Communications = verde
- Robot Code = verde
- Joysticks = verde
Habilitar el robot
Section titled “Habilitar el robot”- Selecciona
Teleoperated - Presiona
Enable - Mueve el joystick
El robot debería responder inmediatamente.
Problemas comunes
Section titled “Problemas comunes”- Verifica conexión al roboRIO
- Revisa el Team Number en
pyproject.toml - Ejecuta
py -3 -m robotpy syncantes de reintentar - Verifica firewall de Windows
- Falta agregar
robotpy[rev]enpyproject.toml - Ejecuta
py -3 -m robotpy syncpara instalar la dependencia
- Revisa inversión de motores
- Verifica CAN IDs
- Confirma followers correctamente configurados
- Follower no configurado
- Motor desconectado
- CAN ID incorrecto
- Breaker apagado
- Robot deshabilitado
- Joystick no detectado
- Driver Station sin comunicación
Siguientes pasos
Section titled “Siguientes pasos”Ahora puedes continuar con:
- Corriendo el programa
- Driver Station
- Command-Based Programming
- Sensores
- Autonomous
- Dashboards
FIRSTHub es un proyecto comunitario independiente. No está afiliado, patrocinado ni respaldado por FIRST. Las traducciones no sustituyen a la documentación oficial: ante cualquier diferencia, manda el documento original.