Creando un programa para el robot¶
Una vez que todo esté instalado, estamos listos para crear un programa para el robot. WPILib viene con una serie de platillas para los programas del robot. El uso de estas plantillas es altamente recomendado para los nuevos usuarios; sin embargo, usuarios avanzados son libres de hacer su código desde cero.
Escogiendo una Clase Base¶
To start a project using one of the WPILib robot program templates, users must first choose a base class for their robot. Users subclass these base classes to create their primary Robot class, which controls the main flow of the robot program. There are various choices available for the base class:
OpModeRobot¶
OpModeRobot is the recommended base class for most users. It structures robot code around individual opmode classes, one per autonomous routine, one per teleoperated configuration, and so on, annotated with @Autonomous, @Teleop, or @Utility (Java) or registered manually (C++). The Driver Station displays a drop-down list of available opmodes for each mode, so operators can select routines without recompiling the robot program. The Robot class holds shared hardware and subsystems, which opmodes receive through their constructors.
See OpMode Framework for full documentation, including the opmode lifecycle, multiple opmode selection, and DS integration.
5package org.wpilib.templates.opmode;
6
7import org.wpilib.framework.OpModeRobot;
8
9/**
10 * The methods in this class are called automatically as described in the OpModeRobot documentation.
11 * OpMode classes anywhere in the package (or sub-packages) where this class is located are
12 * automatically registered to display in the Driver Station. If you change the name of this class
13 * or the package after creating this project, you must also update the Main.java file in the
14 * project.
15 */
16public class Robot extends OpModeRobot {
17 /**
18 * This function is run when the robot is first started up and should be used for any
19 * initialization code.
20 */
21 public Robot() {}
22
23 /** This function is called exactly once when the DS first connects. */
24 @Override
25 public void driverStationConnected() {}
26
27 /**
28 * This function is called periodically anytime when no opmode is selected, including when the
29 * Driver Station is disconnected.
30 */
31 @Override
32 public void nonePeriodic() {}
33}
5#include "Robot.hpp"
6
7#include "opmode/MyAuto.hpp"
8#include "opmode/MyTeleop.hpp"
9
10Robot::Robot() {
11 // Add opmodes to the robot here.
12 AddOpMode<MyTeleop>(wpi::RobotMode::TELEOPERATED, "My Teleop", "",
13 "An example teleop opmode");
14 AddOpMode<MyAuto>(wpi::RobotMode::AUTONOMOUS, "My Auto", "");
15 PublishOpModes();
16}
17
18/** This function is called exactly once when the DS first connects. */
19void Robot::DriverStationConnected() {}
20
21/**
22 * This function is called periodically anytime when no opmode is selected,
23 * including when the Driver Station is disconnected.
24 */
25void Robot::NonePeriodic() {}
TimedRobot¶
The TimedRobot class is an alternative base class that structures robot code around a single Robot class with init(), periodic(), and exit() methods for each mode (autonomous, teleoperated, utility), which are called by WPILib during the corresponding robot states. During these calls, your code typically polls each input device and acts according to the data it receives. For instance, you would typically determine the position of the joystick and state of the joystick buttons on each call and act accordingly. TimedRobot uses Selectable (Java/ C++) for autonomous routine selection via the dashboard.
Nota
Hay disponible una plantilla TimedRobot Skeleton que elimina algunos comentarios informativos y el ejemplo autónomo. Puede usar esto si ya está familiarizado con TimedRobot. El ejemplo que se muestra a continuación es de TimedRobot Skeleton.
7import org.wpilib.framework.TimedRobot;
8
9/**
10 * The methods in this class are called automatically corresponding to each mode, as described in
11 * the TimedRobot documentation. If you change the name of this class or the package after creating
12 * this project, you must also update the Main.java file in the project.
13 */
14public class Robot extends TimedRobot {
15 /**
16 * This function is run when the robot is first started up and should be used for any
17 * initialization code.
18 */
19 public Robot() {}
20
21 @Override
22 public void robotPeriodic() {}
23
24 @Override
25 public void autonomousInit() {}
26
27 @Override
28 public void autonomousPeriodic() {}
29
30 @Override
31 public void teleopInit() {}
32
33 @Override
34 public void teleopPeriodic() {}
35
36 @Override
37 public void disabledInit() {}
38
39 @Override
40 public void disabledPeriodic() {}
41
42 @Override
43 public void utilityInit() {}
44
45 @Override
46 public void utilityPeriodic() {}
47
48 @Override
49 public void simulationInit() {}
50
51 @Override
52 public void simulationPeriodic() {}
53}
5#include "Robot.hpp"
6
7Robot::Robot() {}
8void Robot::RobotPeriodic() {}
9
10void Robot::AutonomousInit() {}
11void Robot::AutonomousPeriodic() {}
12
13void Robot::TeleopInit() {}
14void Robot::TeleopPeriodic() {}
15
16void Robot::DisabledInit() {}
17void Robot::DisabledPeriodic() {}
18
19void Robot::UtilityInit() {}
20void Robot::UtilityPeriodic() {}
21
22void Robot::SimulationInit() {}
23void Robot::SimulationPeriodic() {}
24
25#ifndef RUNNING_WPILIB_TESTS
26int main() {
27 return wpi::StartRobot<Robot>();
28}
29#endif
Los métodos periódicos son llamados cada 20 ms por defecto. Esto puede cambiarse llamando la superclase constructor con la nueva actualización deseada.
Peligro
Changing your robot rate can cause some unintended behavior (loop overruns). Teams can also use Notifiers to schedule methods at a custom rate.
public Robot() {
super(0.03); // Periodic methods will now be called every 30 ms.
}
Robot() : wpi::TimedRobot(30_ms) {}
Timeslice Robot¶
The TimesliceRobot class extends the TimedRobot framework to provide more control over the scheduling of periodic functions. It allows users to allocate specific time slices to different robot operations, running them sequentially within a defined period (typically shorter than TimedRobot’s default 20ms). This class is recommended for users who need more precise timing control and consistent starting times for their robot’s periodic functions.
TimesliceRobot provides the same init(), periodic(), and exit() methods as TimedRobot, but adds the ability to schedule additional periodic functions with custom allocations. This allows for more efficient use of processing time and can lead to improved performance which can make odometry and estimators more accurate and controller outputs change more consistently.
RobotBase¶
La clase RobotBase es la clase base más mínima que se ofrece y, por lo general, no se recomienda para uso directo. No se maneja ningún flujo de control del robot para el usuario; todo debe escribirse desde cero dentro del método startCompetition(). La plantilla por defecto muestra cómo procesar los diferentes modos de operación (teleop, auto, etc.).
Nota
Hay disponible una plantilla `` RobotBase Skeleton`` que ofrece un método startCompetition () en blanco.
Robot a base de comandos¶
The Command Robot framework adds to the basic functionality of a Timed Robot by automatically polling inputs and converting the raw input data into events. These events are tied to user code, which is executed when the event is triggered. For instance, when a button is pressed, code tied to the pressing of that button is automatically called and it is not necessary to poll or keep track of the state of that button directly. The Command Robot framework makes it easier to write compact easy-to-read code with complex behavior, but requires an additional up-front time investment from a programmer in order to understand how the Command Robot framework works.
Teams using Command Robot should see the Command-Based Programming Tutorial.
Romi¶
Los equipos que estén utilizando Romi deberían de utilizar la plantilla Romi - Timed o Romi - Command Bot.
Romi - Timed¶
La plantilla Romi - Timed proporciona la clase RomiDrivetrain que expone un método arcadeDrive(double xaxisSpeed, double zaxisRotate) . Depende del usuario alimentar esta función arcadeDrive.
Esta clase también provee funciones para recuperar y restablecer los encoders integrados de Romi.
Romi - Robot a base de comandos¶
La plantilla Romi - Command Bot proporciona un subsistema RomiDrivetrain que expone un método arcadeDrive (double xaxisSpeed, double zaxisRotate) Depende del usuario alimentar esta función arcadeDrive.
Este subsistema también proporciona funciones para recuperar y restablecer los codificadores integrados de Romi.
No usando una clase base¶
Si así lo desean, los usuarios pueden omitir una clase base entera y simplemente escribir el programa en un método main(), como sería para cualquier otro programa. Esto es altamente no recomendado - los usuarios no deberían «reinventar la rueda» cuando escriben el código de su robot - pero esto está soportado para quienes quieren tener control absoluto en el flujo de su programa.
Advertencia
Los usuarios no deberían modificar el método main() de un programa de robot a menos que estén absolutamente seguros de lo que están haciendo.
Creando un Proyecto Nuevo de WPILib¶
Once we’ve decided on a base class, we can create our new robot project. Bring up the Visual Studio Code command palette with Ctrl+Shift+P. Then, type «WPILib» into the prompt. Since all WPILib commands start with «WPILib», this will bring up the list of WPILib-specific VS Code commands. Now, select the Create a new project command:

This will bring up the «WPILIb New Project Creator»

The Project Type chooses between an empty template project of one of the base classes, or a WPILib example project. Additionally, templates exist for Commands v2 and Commands v3 projects, which are built on the TimedRobot base class but include a number of additional features - this type of robot program is highly recommended for new teams.
After making the selections, click Next.
This will bring up the language and base selection window.

Lenguaje: Este es el lenguaje (C++ o Java) que será usado en el proyecto.
Project Base: This box is used to select the base class or example to generate the project from.
After making the selections, click Next.
This will bring up the Project and Configuration window.

Base Folder: This determines the folder in which the robot project will be located.
Nombre del Proyecto: El nombre del proyecto del robot. Esto también especifica el nombre que la carpeta del proyecto tendrá si la caja de Crear Nueva Carpeta está marcada.
Cree una Nueva Carpeta: Si se marca esta casilla, se creará una nueva carpeta para mantener el proyecto dentro de la carpeta previamente especificada. Si se marca no, el proyecto se ubicará directamente en la carpeta previamente especificada. Se producirá un error si la carpeta no está vacía y no está marcada.
Número del Equipo: El número del equipo para la carpeta, que es el que se usará para empacar nombres con el proyecto y localizarlo en el robot cuando se corra el código.
Enable Desktop Support: Enables unit test and simulation support (see Introducción a la Simulación del Robot).
Advertencia
Creating projects on OneDrive is not supported as OneDrive’s caching interferes with the build system. Some Windows installations put the Documents and Desktop folders on OneDrive by default.
Once all the above have been configured, click Next.
This will bring up the Review and Create window.

Double check all the settings and click Create Project. If anything is not correct, click Back and make the necessary corrections.
Nota
Ningún error en la generación de proyecto debe aparecer en la esquina inferior derecha de la pantalla.
Abriendo El Nuevo Proyecto¶
After successfully creating your project, VS Code will give the option of opening the project as shown below. We can choose to do that now or later by typing Ctrl+K then Ctrl+O (or just Command+O on macOS) and select the folder where we saved our project.

Una vez que abrimos, vamos a ver el proyecto jerarquizado a la izquierda. Dando doble click en el archivo abrirá ese archivo en el editor.

Configuraciones de C++ (Solo C++)¶
Para proyectos C++, hay un paso más para configurar IntelliSense. Cada vez que abrimos un proyecto, debería aparecernos una ventana emergente en la esquina inferior derecha pidiendo actualizar las configuraciones de C++. Haga clic en «Yes» para configurar IntelliSense
