Código Creado con RobotBuilder

El Diseño de un Proyecto Generado de RobotBuilder.

../../../../../_images/robotbuilder-created-code-java.png ../../../../../_images/robotbuilder-created-code-cpp.png

Un proyecto generado por RobotBuilder consta de un paquete (en Java) o una carpeta (en C++) para los comandos y otra para los subsistemas. Cada comando u objeto de subsistema se almacena bajo esos contenedores. En el nivel superior del proyecto se encuentra el programa principal del robot (RobotContainer.java/C++).

Para más información sobre la organización de un robot basado en comandos, consulte Estructuración de un proyecto de robot basado en comandos

Código Autogenerado

// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS
m_chooser.setDefaultOption("Autonomous", new Autonomous());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS

SmartDashboard.putData("Auto Mode", m_chooser);

Cuando la descripción del robot es modificada y el código es re-exportado, RobotBuilder está diseñado para no modificar ningún cambio que haya hecho en el archivo, preservando así tu código. Esto hace de RobotBuilder una herramienta de ciclo de vida completo. Para saber qué código está bien para ser modificado por RobotBuilder, genera secciones que potencialmente tendrán que ser reescritas delimitadas con algunos comentarios especiales. Estos comentarios se muestran en el ejemplo anterior. No añada ningún código dentro de estos bloques de comentarios, se reescribirá la próxima vez que el proyecto se exporte desde RobotBuilder.

Si el código dentro de uno de estos bloques debe ser modificado, los comentarios pueden ser eliminados, pero esto evitará que se produzcan más actualizaciones más adelante. En el ejemplo anterior, si los comentarios //BEGIN y //END fueran removidos, y más tarde se añadió otro subsistema necesario en RobotBuilder, no se generaría en esa próxima exportación.

// ROBOTBUILDER TYPE: Robot.

Additionally, each file has a comment defining the type of file. If this is modified or deleted, RobotBuilder will completely regenerate the file deleting any code added both inside and outside the AUTOGENERATED CODE blocks.

Programa Principal del Robot

 11// ROBOTBUILDER TYPE: Robot.
 12
 13package frc.robot;
 14
 15import edu.wpi.first.hal.FRCNetComm.tInstances;
 16import edu.wpi.first.hal.FRCNetComm.tResourceType;
 17import edu.wpi.first.hal.HAL;
 18import edu.wpi.first.wpilibj.TimedRobot;
 19import edu.wpi.first.wpilibj2.command.Command;
 20import edu.wpi.first.wpilibj2.command.CommandScheduler;
 21
 22/**
 23 * The VM is configured to automatically run this class, and to call the
 24 * functions corresponding to each mode, as described in the TimedRobot
 25 * documentation. If you change the name of this class or the package after
 26 * creating this project, you must also update the build.properties file in
 27 * the project.
 28 */
 29public class Robot extends TimedRobot { // (1)
 30
 31    private Command m_autonomousCommand;
 32
 33    private RobotContainer m_robotContainer;
 34
 35    /**
 36     * This function is run when the robot is first started up and should be
 37     * used for any initialization code.
 38     */
 39    @Override
 40    public void robotInit() {
 41        // Instantiate our RobotContainer.  This will perform all our button bindings, and put our
 42        // autonomous chooser on the dashboard.
 43        m_robotContainer = RobotContainer.getInstance();
 44        HAL.report(tResourceType.kResourceType_Framework, tInstances.kFramework_RobotBuilder);
 45    }
 46
 47    /**
 48    * This function is called every robot packet, no matter the mode. Use this for items like
 49    * diagnostics that you want ran during disabled, autonomous, teleoperated and test.
 50    *
 51    * <p>This runs after the mode specific periodic functions, but before
 52    * LiveWindow and SmartDashboard integrated updating.
 53    */
 54    @Override
 55    public void robotPeriodic() {
 56        // Runs the Scheduler.  This is responsible for polling buttons, adding newly-scheduled
 57        // commands, running already-scheduled commands, removing finished or interrupted commands,
 58        // and running subsystem periodic() methods.  This must be called from the robot's periodic
 59        // block in order for anything in the Command-based framework to work.
 60        CommandScheduler.getInstance().run();  // (2)
 61    }
 62
 63
 64    /**
 65    * This function is called once each time the robot enters Disabled mode.
 66    */
 67    @Override
 68    public void disabledInit() {
 69    }
 70
 71    @Override
 72    public void disabledPeriodic() {
 73    }
 74
 75    /**
 76    * This autonomous runs the autonomous command selected by your {@link RobotContainer} class.
 77    */
 78    @Override
 79    public void autonomousInit() {
 80        m_autonomousCommand = m_robotContainer.getAutonomousCommand();  // (3)
 81
 82        // schedule the autonomous command (example)
 83        if (m_autonomousCommand != null) {
 84            m_autonomousCommand.schedule();
 85        }
 86    }
 87
 88    /**
 89    * This function is called periodically during autonomous.
 90    */
 91    @Override
 92    public void autonomousPeriodic() {
 93    }
 94
 95    @Override
 96    public void teleopInit() {
 97        // This makes sure that the autonomous stops running when
 98        // teleop starts running. If you want the autonomous to
 99        // continue until interrupted by another command, remove
100        // this line or comment it out.
101        if (m_autonomousCommand != null) {
102            m_autonomousCommand.cancel();
103        }
104    }
105
106    /**
107     * This function is called periodically during operator control.
108     */
109    @Override
110    public void teleopPeriodic() {
111    }
112
113    @Override
114    public void testInit() {
115        // Cancels all running commands at the start of test mode.
116        CommandScheduler.getInstance().cancelAll();
117    }
118
119    /**
120    * This function is called periodically during test mode.
121    */
122    @Override
123    public void testPeriodic() {
124    }
125
126}

Este es el programa principal generado por RobotBuilder. Hay un número de partes en este programa (secciones resaltadas):

  1. Esta clase extiende TimedRobot. TimedRobot llamará a los métodos autonomousPeriodic() y teleopPeriodic() cada 20 ms.

  2. En el método robotPeriodic que se llama cada 20ms, hacer un pase de horario.

  3. El comando autónomo proporcionado está programado al inicio del autónomo en el método autonomousInit() y se cancela al final del periodo autónomo en teleopInit().

RobotContainer

 11// ROBOTBUILDER TYPE: RobotContainer.
 12
 13package frc.robot;
 14
 15import frc.robot.commands.*;
 16import frc.robot.subsystems.*;
 17import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
 18import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
 19
 20// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
 21import edu.wpi.first.wpilibj2.command.Command;
 22import edu.wpi.first.wpilibj2.command.InstantCommand;
 23import edu.wpi.first.wpilibj.Joystick;
 24import edu.wpi.first.wpilibj2.command.button.JoystickButton;
 25import frc.robot.subsystems.*;
 26
 27    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
 28
 29
 30/**
 31 * This class is where the bulk of the robot should be declared.  Since Command-based is a
 32 * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
 33 * periodic methods (other than the scheduler calls).  Instead, the structure of the robot
 34 * (including subsystems, commands, and button mappings) should be declared here.
 35 */
 36public class RobotContainer {
 37
 38  private static RobotContainer m_robotContainer = new RobotContainer();
 39
 40    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
 41// The robot's subsystems
 42    public final Wrist m_wrist = new Wrist(); // {1}
 43    public final Elevator m_elevator = new Elevator();
 44    public final Claw m_claw = new Claw();
 45    public final Drivetrain m_drivetrain = new Drivetrain();
 46
 47// Joysticks
 48private final Joystick joystick2 = new Joystick(2); // {3}
 49private final Joystick joystick1 = new Joystick(1);
 50private final Joystick logitechController = new Joystick(0);
 51
 52    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
 53
 54
 55  // A chooser for autonomous commands
 56  SendableChooser<Command> m_chooser = new SendableChooser<>();
 57
 58  /**
 59  * The container for the robot.  Contains subsystems, OI devices, and commands.
 60  */
 61  private RobotContainer() {
 62        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=SMARTDASHBOARD
 63    // Smartdashboard Subsystems
 64    SmartDashboard.putData(m_wrist);
 65    SmartDashboard.putData(m_elevator);
 66    SmartDashboard.putData(m_claw);
 67    SmartDashboard.putData(m_drivetrain);
 68
 69
 70    // SmartDashboard Buttons
 71    SmartDashboard.putData("Close Claw", new CloseClaw( m_claw )); // {6}
 72    SmartDashboard.putData("Open Claw: OpenTime", new OpenClaw(1.0, m_claw));
 73    SmartDashboard.putData("Pickup", new Pickup());
 74    SmartDashboard.putData("Place", new Place());
 75    SmartDashboard.putData("Prepare To Pickup", new PrepareToPickup());
 76    SmartDashboard.putData("Set Elevator Setpoint: Bottom", new SetElevatorSetpoint(0, m_elevator));
 77    SmartDashboard.putData("Set Elevator Setpoint: Platform", new SetElevatorSetpoint(0.2, m_elevator));
 78    SmartDashboard.putData("Set Elevator Setpoint: Top", new SetElevatorSetpoint(0.3, m_elevator));
 79    SmartDashboard.putData("Set Wrist Setpoint: Horizontal", new SetWristSetpoint(0, m_wrist));
 80    SmartDashboard.putData("Set Wrist Setpoint: Raise Wrist", new SetWristSetpoint(-45, m_wrist));
 81    SmartDashboard.putData("Drive: Straight3Meters", new Drive(3, 0, m_drivetrain));
 82    SmartDashboard.putData("Drive: Place", new Drive(Drivetrain.PlaceDistance, Drivetrain.BackAwayDistance, m_drivetrain));
 83
 84    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=SMARTDASHBOARD
 85    // Configure the button bindings
 86    configureButtonBindings();
 87
 88    // Configure default commands
 89        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=SUBSYSTEM_DEFAULT_COMMAND
 90    m_drivetrain.setDefaultCommand(new TankDrive( m_drivetrain ) ); // {5}
 91
 92
 93    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=SUBSYSTEM_DEFAULT_COMMAND
 94
 95    // Configure autonomous sendable chooser
 96        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS
 97
 98    m_chooser.setDefaultOption("Autonomous", new Autonomous()); // {2}
 99
100    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=AUTONOMOUS
101
102    SmartDashboard.putData("Auto Mode", m_chooser);
103  }
104
105  public static RobotContainer getInstance() {
106    return m_robotContainer;
107  }
108
109  /**
110   * Use this method to define your button->command mappings.  Buttons can be created by
111   * instantiating a {@link GenericHID} or one of its subclasses ({@link
112   * edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then passing it to a
113   * {@link edu.wpi.first.wpilibj2.command.button.JoystickButton}.
114   */
115  private void configureButtonBindings() {
116        // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=BUTTONS
117// Create some buttons
118final JoystickButton r1 = new JoystickButton(logitechController, 12);        // {4}
119r1.whenPressed(new Autonomous() ,true);
120    SmartDashboard.putData("R1",new Autonomous() );
121
122final JoystickButton l1 = new JoystickButton(logitechController, 11);
123l1.whenPressed(new Place() ,true);
124    SmartDashboard.putData("L1",new Place() );
125
126final JoystickButton r2 = new JoystickButton(logitechController, 10);
127r2.whenPressed(new Pickup() ,true);
128    SmartDashboard.putData("R2",new Pickup() );
129
130final JoystickButton l2 = new JoystickButton(logitechController, 9);
131l2.whenPressed(new PrepareToPickup() ,true);
132    SmartDashboard.putData("L2",new PrepareToPickup() );
133
134final JoystickButton dpadLeft = new JoystickButton(logitechController, 8);
135dpadLeft.whenPressed(new OpenClaw(1.0, m_claw) ,true);
136    SmartDashboard.putData("Dpad Left",new OpenClaw(1.0, m_claw) );
137
138final JoystickButton dpadRight = new JoystickButton(logitechController, 6);
139dpadRight.whenPressed(new CloseClaw( m_claw ) ,true);
140    SmartDashboard.putData("Dpad Right",new CloseClaw( m_claw ) );
141
142final JoystickButton dpadDown = new JoystickButton(logitechController, 7);
143dpadDown.whenPressed(new SetElevatorSetpoint(0, m_elevator) ,true);
144    SmartDashboard.putData("Dpad Down",new SetElevatorSetpoint(0, m_elevator) );
145
146final JoystickButton dpadUp = new JoystickButton(logitechController, 5);
147dpadUp.whenPressed(new SetElevatorSetpoint(0.3, m_elevator) ,true);
148    SmartDashboard.putData("Dpad Up",new SetElevatorSetpoint(0.3, m_elevator) );
149
150
151
152    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=BUTTONS
153  }
154
155    // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
156public Joystick getLogitechController() {
157        return logitechController;
158    }
159
160public Joystick getJoystick1() {
161        return joystick1;
162    }
163
164public Joystick getJoystick2() {
165        return joystick2;
166    }
167
168
169    // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
170
171  /**
172   * Use this to pass the autonomous command to the main {@link Robot} class.
173   *
174   * @return the command to run in autonomous
175  */
176  public Command getAutonomousCommand() {
177    // The selected command will be run in autonomous
178    return m_chooser.getSelected();
179  }
180
181
182}

Este es el RobotContainer generado por RobotBuilder que es donde se definen los subsistemas y la interfaz del operador. Este programa consta de varias partes (secciones resaltadas):

  1. Aquí se declara cada uno de los subsistemas. Se pueden pasar como parámetros a cualquier comando que los requiera.

  2. Si hay un comando autónomo proporcionado en las propiedades del robot de RobotBuilder, se añade al selector de envíos para ser seleccionado en el dashboard

  3. Aquí se genera el código de todos los componentes de la interfaz del operador.

  4. Además el código para enlazar los botones OI con los comandos que deben ejecutarse también se genera aquí.

  5. Aquí se definen los comandos que se ejecutan en un subsistema cuando no hay otros comandos en ejecución.

  6. Aquí se definen los comandos que se ejecutan a través de un dashboard.