Création de votre programme test Drivetrain (Java/C++/Python)

Une fois que tout est installé, nous sommes prêts à créer un programme de robot. WPILib est livré avec plusieurs modèles pour les programmes de robots. L’utilisation de ces modèles est fortement recommandée pour les nouveaux utilisateurs; cependant, les utilisateurs avancés sont libres d’écrire leur propre code robot à partir de zéro. Cet article explore la création d’un projet à partir de l’un des exemples fournis qui a un certain code déjà écrit pour piloter un robot de base.

Important

This guide includes code examples that involve vendor hardware for the convenience of the user. In this document, PWM refers to the motor controller included in the KOP. The CTRE tab references the Talon FX motor controller (Falcon 500 motor), but usage is similar for TalonSRX and VictorSPX. The REV tab references the CAN SPARK MAX controlling a brushless motor, but it’s similar for brushed motor. There is an assumption that the user has already installed the required vendordeps and configured the device(s) (update firmware, assign CAN IDs, etc) according to the manufacturer documentation (CTRE REV).

Création d’un nouveau projet WPILib (Java/C++)

Affichez la palette de commandes de Visual Studio Code avec Ctrl+Shift+P. Ensuite, tapez « WPILib » dans l’invite. Étant donné que toutes les commandes WPILib commencent par « WPILib », cela affichera la liste des commandes VS Code spécifiques à WPILib. Maintenant, sélectionnez la commande « Créer un nouveau projet »:

Choisissez "WPILib: Create a new project".

Cette opération fera apparaître la fenêtre « New Project Creator Window »:

Les différentes parties de la fenêtre de création du nouveau projet.

Les éléments de la fenêtre New Project Creator sont expliqués ci-dessous :

  1. Project Type: Le genre de projet que nous voulons créer. Pour cet exemple, sélectionnez Example

  2. Language: C’est le langage de programmation (C++ ou Java) qui sera utilisé pour ce projet.

  3. Project Base: Cette zone est utilisée pour sélectionner la classe de base ou l’exemple à utiliser comme source pour générer le projet. Pour cet exemple, sélectionnez Getting Started

  4. Base Folder: Ce paramètre détermine le dossier dans lequel le projet de robot sera situé.

  5. Project Name: Le nom du projet de robot. Ce paramètre spécifie également le nom du dossier de projet si la zone Create New Folder est cochée.

  6. Create a New Folder: Si cette case est cochée, un nouveau dossier sera créé pour contenir le projet dans le dossier précédemment spécifié. Si elle n’est pas cochée, le projet sera situé directement dans le dossier précédemment spécifié. Une erreur sera générée si le dossier n’est pas vide et que cette case n’est pas cochée. Un dossier de projet sera créé si la case Create New Folder est cochée.

  7. Team Number: Numéro d’équipe du projet, qui sera utilisé pour les noms de packages dans le projet et pour localiser le robot au moment du déploiement du code.

  8. Enable Desktop Support: Permet de faire le test unitaire et la simulation. Bien que WPILib prenne en charge cette fonctionnalité, pour les bibliothèques de logiciels tiers cette prise en charge n’est pas garantie. Si les bibliothèques logicielles ne prennent pas en charge les applications de bureau, votre code peut ne pas compiler ou planter. Cette case doit être laissée non cochée à moins que des tests unitaires ou une simulation ne soient nécessaires et que toutes les bibliothèques de logiciels le prennent en charge. Pour cet exemple, ne cochez pas cette case.

Une fois que tout ce qui précède a été configuré, cliquez sur « Generate Project » et le projet robot sera créé.

Note

Toutes les erreurs lors de la génération de projet apparaîtront dans le coin inférieur droit de l’écran.

Avertissement

La création de projets sur OneDrive n’est pas prise en charge car la mise en cache de OneDrive interfère avec le système de build. Certaines installations Windows placent par défaut les dossiers Documents et Bureau sur OneDrive.

Ouverture du nouveau projet

Ouvrir la boîte de dialogue du projet dans VS Code

Après avoir réussi à créer votre projet, VS Code vous donnera la possibilité d’ouvrir le projet comme indiqué ci-dessus. Nous pouvons choisir de le faire maintenant ou plus tard en tapant Ctrl+K puis Ctrl+O (ou simplement Command+O sur macOS) et sélectionner le dossier où nous avons enregistré notre projet.

Boîte de dialogue Espace de travail de confiance dans VS Code.

Cliquez sur Yes I trust the authors. (Oui, je fais confiance aux auteurs.)

Une fois ouvert, nous pouvons voir la hiérarchie du projet à gauche. En double-cliquant sur un fichier, on ouvre ce fichier dans l’éditeur.

Le code robot.java affiché après l'ouverture d'un nouveau projet.

Configurations C++ (C++ uniquement)

Pour les projets C++, il y a une étape de plus pour configurer IntelliSense. Chaque fois que nous ouvrons un projet, nous devrions obtenir un pop-up dans le coin inférieur droit demandant de rafraîchir les configurations C++. Cliquez sur « Yes » pour configurer IntelliSense.

Vous devez choisir "Oui" pour actualiser les configurations C++.

Création d’un nouveau projet WPILib (Python)

Exécuter la commande robotpy init initialisera un nouveau projet de robot.

py -3 -m robotpy init
python3 -m robotpy init
python3 -m robotpy init

Cela créera un fichier robot.py et pyproject.toml, mais n’écrasera pas un fichier existant.

  • Le fichier pyproject.toml contient les exigences pour votre projet, qui sont téléchargées et installées via la commande robotpy sync.

  • Le fichier robot.py est l’endroit où vous mettrez votre classe Robot.

Voir aussi

docs/zero-to-robot/step-2/python-setup:Téléchargement de RobotPy pour roboRIO

Exemple de transmission de base

Tout d’abord, voici à quoi peut ressembler un code simple pour une transmission avec des moteurs contrôlés par PWM (tels que SparkMax).

Note

l’exemple Python ci-dessous provient de https://github.com/robotpy/examples/tree/main/GettingStarted

 1// Copyright (c) FIRST and other WPILib contributors.
 2// Open Source Software; you can modify and/or share it under the terms of
 3// the WPILib BSD license file in the root directory of this project.
 4
 5package edu.wpi.first.wpilibj.examples.gettingstarted;
 6
 7import edu.wpi.first.util.sendable.SendableRegistry;
 8import edu.wpi.first.wpilibj.TimedRobot;
 9import edu.wpi.first.wpilibj.Timer;
10import edu.wpi.first.wpilibj.XboxController;
11import edu.wpi.first.wpilibj.drive.DifferentialDrive;
12import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax;
13
14/**
15 * The methods in this class are called automatically corresponding to each mode, as described in
16 * the TimedRobot documentation. If you change the name of this class or the package after creating
17 * this project, you must also update the manifest file in the resource directory.
18 */
19public class Robot extends TimedRobot {
20  private final PWMSparkMax m_leftDrive = new PWMSparkMax(0);
21  private final PWMSparkMax m_rightDrive = new PWMSparkMax(1);
22  private final DifferentialDrive m_robotDrive =
23      new DifferentialDrive(m_leftDrive::set, m_rightDrive::set);
24  private final XboxController m_controller = new XboxController(0);
25  private final Timer m_timer = new Timer();
26
27  /** Called once at the beginning of the robot program. */
28  public Robot() {
29    SendableRegistry.addChild(m_robotDrive, m_leftDrive);
30    SendableRegistry.addChild(m_robotDrive, m_rightDrive);
31
32    // We need to invert one side of the drivetrain so that positive voltages
33    // result in both sides moving forward. Depending on how your robot's
34    // gearbox is constructed, you might have to invert the left side instead.
35    m_rightDrive.setInverted(true);
36  }
37
38  /** This function is run once each time the robot enters autonomous mode. */
39  @Override
40  public void autonomousInit() {
41    m_timer.restart();
42  }
43
44  /** This function is called periodically during autonomous. */
45  @Override
46  public void autonomousPeriodic() {
47    // Drive for 2 seconds
48    if (m_timer.get() < 2.0) {
49      // Drive forwards half speed, make sure to turn input squaring off
50      m_robotDrive.arcadeDrive(0.5, 0.0, false);
51    } else {
52      m_robotDrive.stopMotor(); // stop robot
53    }
54  }
55
56  /** This function is called once each time the robot enters teleoperated mode. */
57  @Override
58  public void teleopInit() {}
59
60  /** This function is called periodically during teleoperated mode. */
61  @Override
62  public void teleopPeriodic() {
63    m_robotDrive.arcadeDrive(-m_controller.getLeftY(), -m_controller.getRightX());
64  }
65
66  /** This function is called once each time the robot enters test mode. */
67  @Override
68  public void testInit() {}
69
70  /** This function is called periodically during test mode. */
71  @Override
72  public void testPeriodic() {}
73}
 1// Copyright (c) FIRST and other WPILib contributors.
 2// Open Source Software; you can modify and/or share it under the terms of
 3// the WPILib BSD license file in the root directory of this project.
 4
 5#include <frc/TimedRobot.h>
 6#include <frc/Timer.h>
 7#include <frc/XboxController.h>
 8#include <frc/drive/DifferentialDrive.h>
 9#include <frc/motorcontrol/PWMSparkMax.h>
10
11class Robot : public frc::TimedRobot {
12 public:
13  Robot() {
14    wpi::SendableRegistry::AddChild(&m_robotDrive, &m_left);
15    wpi::SendableRegistry::AddChild(&m_robotDrive, &m_right);
16
17    // We need to invert one side of the drivetrain so that positive voltages
18    // result in both sides moving forward. Depending on how your robot's
19    // gearbox is constructed, you might have to invert the left side instead.
20    m_right.SetInverted(true);
21    m_robotDrive.SetExpiration(100_ms);
22    m_timer.Start();
23  }
24
25  void AutonomousInit() override { m_timer.Restart(); }
26
27  void AutonomousPeriodic() override {
28    // Drive for 2 seconds
29    if (m_timer.Get() < 2_s) {
30      // Drive forwards half speed, make sure to turn input squaring off
31      m_robotDrive.ArcadeDrive(0.5, 0.0, false);
32    } else {
33      // Stop robot
34      m_robotDrive.ArcadeDrive(0.0, 0.0, false);
35    }
36  }
37
38  void TeleopInit() override {}
39
40  void TeleopPeriodic() override {
41    // Drive with arcade style (use right stick to steer)
42    m_robotDrive.ArcadeDrive(-m_controller.GetLeftY(),
43                             m_controller.GetRightX());
44  }
45
46  void TestInit() override {}
47
48  void TestPeriodic() override {}
49
50 private:
51  // Robot drive system
52  frc::PWMSparkMax m_left{0};
53  frc::PWMSparkMax m_right{1};
54  frc::DifferentialDrive m_robotDrive{
55      [&](double output) { m_left.Set(output); },
56      [&](double output) { m_right.Set(output); }};
57
58  frc::XboxController m_controller{0};
59  frc::Timer m_timer;
60};
61
62#ifndef RUNNING_FRC_TESTS
63int main() {
64  return frc::StartRobot<Robot>();
65}
66#endif
 1#!/usr/bin/env python3
 2#
 3# Copyright (c) FIRST and other WPILib contributors.
 4# Open Source Software; you can modify and/or share it under the terms of
 5# the WPILib BSD license file in the root directory of this project.
 6#
 7
 8import wpilib
 9import wpilib.drive
10
11
12class MyRobot(wpilib.TimedRobot):
13    def robotInit(self):
14        """
15        This function is called upon program startup and
16        should be used for any initialization code.
17        """
18        self.leftDrive = wpilib.PWMSparkMax(0)
19        self.rightDrive = wpilib.PWMSparkMax(1)
20        self.robotDrive = wpilib.drive.DifferentialDrive(
21            self.leftDrive, self.rightDrive
22        )
23        self.controller = wpilib.XboxController(0)
24        self.timer = wpilib.Timer()
25
26        # We need to invert one side of the drivetrain so that positive voltages
27        # result in both sides moving forward. Depending on how your robot's
28        # gearbox is constructed, you might have to invert the left side instead.
29        self.rightDrive.setInverted(True)
30
31    def autonomousInit(self):
32        """This function is run once each time the robot enters autonomous mode."""
33        self.timer.restart()
34
35    def autonomousPeriodic(self):
36        """This function is called periodically during autonomous."""
37
38        # Drive for two seconds
39        if self.timer.get() < 2.0:
40            # Drive forwards half speed, make sure to turn input squaring off
41            self.robotDrive.arcadeDrive(0.5, 0, squareInputs=False)
42        else:
43            self.robotDrive.stopMotor()  # Stop robot
44
45    def teleopInit(self):
46        """This function is called once each time the robot enters teleoperated mode."""
47
48    def teleopPeriodic(self):
49        """This function is called periodically during teleoperated mode."""
50        self.robotDrive.arcadeDrive(
51            -self.controller.getLeftY(), -self.controller.getRightX()
52        )
53
54    def testInit(self):
55        """This function is called once each time the robot enters test mode."""
56
57    def testPeriodic(self):
58        """This function is called periodically during test mode."""
59
60
61if __name__ == "__main__":
62    wpilib.run(MyRobot)

Examinons maintenant différentes parties du code.

Imports/Includes

1import edu.wpi.first.util.sendable.SendableRegistry;
2import edu.wpi.first.wpilibj.TimedRobot;
3import edu.wpi.first.wpilibj.Timer;
4import edu.wpi.first.wpilibj.XboxController;
5import edu.wpi.first.wpilibj.drive.DifferentialDrive;
6import edu.wpi.first.wpilibj.motorcontrol.PWMSparkMax;
5#include <frc/TimedRobot.h>
6#include <frc/Timer.h>
7#include <frc/XboxController.h>
8#include <frc/drive/DifferentialDrive.h>
9#include <frc/motorcontrol/PWMSparkMax.h>
8import wpilib
9import wpilib.drive
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import com.ctre.phoenix6.hardware.TalonFX;
#include <frc/TimedRobot.h>
#include <frc/Timer.h>
#include <frc/XboxController.h>
#include <frc/drive/DifferentialDrive.h>
#include <ctre/phoenix6/TalonFX.hpp>
import wpilib               # Used to get the joysticks
import wpilib.drive         # Used for the DifferentialDrive class
import phoenix6             # CTRE library
import com.revrobotics.CANSparkMax;
import com.revrobotics.CANSparkLowLevel.MotorType;
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
#include <frc/TimedRobot.h>
#include <frc/Timer.h>
#include <frc/XboxController.h>
#include <frc/drive/DifferentialDrive.h>
#include <frc/motorcontrol/PWMSparkMax.h>
#include <rev/CANSparkMax.h>
import wpilib           # Used to get the joysticks
import wpilib.drive     # Used for the DifferentialDrive class
import rev              # REV library
import edu.wpi.first.wpilibj.TimedRobot;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX;
#include <frc/TimedRobot.h>
#include <frc/Timer.h>
#include <frc/XboxController.h>
#include <frc/drive/DifferentialDrive.h>
#include <ctre/phoenix/motorcontrol/can/WPI_TalonSRX.h>
import wpilib           # Used to get the joysticks
import wpilib.drive     # Used for the DifferentialDrive class
import ctre             # CTRE library

Our code needs to reference the components of WPILib that are used. In C++ this is accomplished using #include statements; in Java and Python it is done with import statements. The program references classes for XBoxController (for driving), PWMSparkMax / TalonFX / CANSparkMax / WPI_TalonSRX (for controlling motors), TimedRobot (the base class used for the example), Timer (used for autonomous), and DifferentialDrive (for connecting the Xbox controller to the motors).

Définition des variables de notre prototype de robot

19public class Robot extends TimedRobot {
20  private final PWMSparkMax m_leftDrive = new PWMSparkMax(0);
21  private final PWMSparkMax m_rightDrive = new PWMSparkMax(1);
22  private final DifferentialDrive m_robotDrive =
23      new DifferentialDrive(m_leftDrive::set, m_rightDrive::set);
24  private final XboxController m_controller = new XboxController(0);
25  private final Timer m_timer = new Timer();
50 private:
51  // Robot drive system
52  frc::PWMSparkMax m_left{0};
53  frc::PWMSparkMax m_right{1};
54  frc::DifferentialDrive m_robotDrive{
55      [&](double output) { m_left.Set(output); },
56      [&](double output) { m_right.Set(output); }};
57
58  frc::XboxController m_controller{0};
59  frc::Timer m_timer;
60};
12class MyRobot(wpilib.TimedRobot):
13    def robotInit(self):
14        """
15        This function is called upon program startup and
16        should be used for any initialization code.
17        """
18        self.leftDrive = wpilib.PWMSparkMax(0)
19        self.rightDrive = wpilib.PWMSparkMax(1)
20        self.robotDrive = wpilib.drive.DifferentialDrive(
21            self.leftDrive, self.rightDrive
22        )
23        self.controller = wpilib.XboxController(0)
24        self.timer = wpilib.Timer()
25
26        # We need to invert one side of the drivetrain so that positive voltages
27        # result in both sides moving forward. Depending on how your robot's
28        # gearbox is constructed, you might have to invert the left side instead.
29        self.rightDrive.setInverted(True)
public class Robot extends TimedRobot {
   private final TalonFX m_leftDrive = new TalonFX(1);
   private final TalonFX m_rightDrive = new TalonFX(2);
   private final DifferentialDrive m_robotDrive =
     new DifferentialDrive(m_leftDrive::set, m_rightDrive::set);
   private final XboxController m_controller = new XboxController(0);
   private final Timer m_timer = new Timer();
12 public:
13  Robot() {
17    // We need to invert one side of the drivetrain so that positive voltages
18    // result in both sides moving forward. Depending on how your robot's
19    // gearbox is constructed, you might have to invert the left side instead.
20    m_right.SetInverted(true);
21    m_robotDrive.SetExpiration(100_ms);
22    m_timer.Start();
23  }
private:
 // Robot drive system
 ctre::phoenix6::hardware::TalonFX m_left{1};
 ctre::phoenix6::hardware::TalonFX m_right{2};
 frc::DifferentialDrive m_robotDrive{
   [&](double output) { m_left.Set(output); },
   [&](double output) { m_right.Set(output); }};
 frc::XboxController m_controller{0};
 frc::Timer m_timer;
class MyRobot(wpilib.TimedRobot):
  def robotInit(self):
     """
     This function is called upon program startup and
     should be used for any initialization code.
     """
     self.leftDrive = phoenix6.hardware.TalonFX(1)
     self.rightDrive = phoenix6.hardware.TalonFX(2)
     self.robotDrive = wpilib.drive.DifferentialDrive(
         self.leftDrive, self.rightDrive
     )
     self.controller = wpilib.XboxController(0)
     self.timer = wpilib.Timer()
     # We need to invert one side of the drivetrain so that positive voltages
     # result in both sides moving forward. Depending on how your robot's
     # gearbox is constructed, you might have to invert the left side instead.
     self.rightDrive.setInverted(True)
public class Robot extends TimedRobot {
  private final CANSparkMax m_leftDrive = new CANSparkMax(1, MotorType.kBrushless);
  private final CANSparkMax m_rightDrive = new CANSparkMax(2, MotorType.kBrushless);
  private final DifferentialDrive m_robotDrive =
    new DifferentialDrive(m_leftDrive::set, m_rightDrive::set);
  private final XboxController m_controller = new XboxController(0);
  private final Timer m_timer = new Timer();
12 public:
13  Robot() {
17    // We need to invert one side of the drivetrain so that positive voltages
18    // result in both sides moving forward. Depending on how your robot's
19    // gearbox is constructed, you might have to invert the left side instead.
20    m_right.SetInverted(true);
21    m_robotDrive.SetExpiration(100_ms);
22    m_timer.Start();
23  }
private:
 // Robot drive system
 rev::CANSparkMax m_left{1, rev::CANSparkMax::MotorType::kBrushless};
 rev::CANSparkMax m_right{2, rev::CANSparkMax::MotorType::kBrushless};
 frc::DifferentialDrive m_robotDrive{
   [&](double output) { m_left.Set(output); },
   [&](double output) { m_right.Set(output); }};
 frc::XboxController m_controller{0};
 frc::Timer m_timer;
13class MyRobot(wpilib.TimedRobot):
14    def robotInit(self):
15        """
16        This function is called upon program startup and
17        should be used for any initialization code.
18        """
19        self.leftDrive = rev.CANSparkMax(1, rev.CANSparkMax.MotorType.kBrushless)
20        self.rightDrive = rev.CANSparkMax(2, rev.CANSparkMax.MotorType.kBrushless)
21        self.robotDrive = wpilib.drive.DifferentialDrive(
22            self.leftDrive, self.rightDrive
23        )
24        self.controller = wpilib.XboxController(0)
25        self.timer = wpilib.Timer()
26
27        # We need to invert one side of the drivetrain so that positive voltages
28        # result in both sides moving forward. Depending on how your robot's
29        # gearbox is constructed, you might have to invert the left side instead.
30        self.rightDrive.setInverted(True)
public class Robot extends TimedRobot {
   private final WPI_TalonSRX m_leftDrive = new WPI_TalonSRX(1);
   private final WPI_TalonSRX m_rightDrive = new WPI_TalonSRX(2);
   private final DifferentialDrive m_robotDrive = new DifferentialDrive(m_leftDrive1::set, m_rightDrive2::set);
   private final XboxController m_controller = new XboxController(0);
   private final Timer m_timer = new Timer();
12 public:
13  Robot() {
17    // We need to invert one side of the drivetrain so that positive voltages
18    // result in both sides moving forward. Depending on how your robot's
19    // gearbox is constructed, you might have to invert the left side instead.
20    m_right.SetInverted(true);
21    m_robotDrive.SetExpiration(100_ms);
22    m_timer.Start();
23  }
private:
 // Robot drive system
 ctre::phoenix::motorcontrol::can::WPI_TalonSRX m_left{1};
 ctre::phoenix::motorcontrol::can::WPI_TalonSRX m_right{2};
 frc::DifferentialDrive m_robotDrive{
   [&](double output) { m_left.Set(output); },
   [&](double output) { m_right.Set(output); }};
 frc::XboxController m_controller{0};
 frc::Timer m_timer;
13class MyRobot(wpilib.TimedRobot):
14    def robotInit(self):
15        """
16        This function is called upon program startup and
17        should be used for any initialization code.
18        """
19        self.leftDrive = ctre.WPI_TalonFX(1)
20        self.rightDrive = ctre.WPI_TalonFX(2)
21        self.robotDrive = wpilib.drive.DifferentialDrive(
22            self.leftDrive, self.rightDrive
23        )
24        self.controller = wpilib.XboxController(0)
25        self.timer = wpilib.Timer()
26
27        # We need to invert one side of the drivetrain so that positive voltages
28        # result in both sides moving forward. Depending on how your robot's
29        # gearbox is constructed, you might have to invert the left side instead.
30        self.rightDrive.setInverted(True)

The sample robot in our examples will have an Xbox Controller on USB port 0 for arcade drive and two motors on PWM ports 0 and 1 (Vendor examples use CAN with IDs 1 and 2). Here we create objects of type DifferentialDrive (m_robotDrive), XboxController (m_controller) and Timer (m_timer). This section of the code does three things:

  1. Définit les variables en tant que membres de notre classe Robot.

  2. Initialise les variables.

Note

L’initialisation des variables en C++ se trouve dans la section private en bas du programme. Cela signifie qu’elles sont privées à la classe Robot. Le code C++ configure également le paramètre Motor Safety expiration à 0,1 seconde (le déplacement s’arrêtera si nous ne lui donnons pas une commande à toutes les 0,1 secondes) et démarre le Timer utilisé pour le mode autonome.

Initialisation du robot

27  /** Called once at the beginning of the robot program. */
28  public Robot() {
29    // We need to invert one side of the drivetrain so that positive voltages
30    // result in both sides moving forward. Depending on how your robot's
31    // gearbox is constructed, you might have to invert the left side instead.
32    m_rightDrive.setInverted(true);
33  }
12 public:
13  Robot() {
14    // We need to invert one side of the drivetrain so that positive voltages
15    // result in both sides moving forward. Depending on how your robot's
16    // gearbox is constructed, you might have to invert the left side instead.
17    m_right.SetInverted(true);
18    m_robotDrive.SetExpiration(100_ms);
19    m_timer.Start();
20  }
def robotInit(self):

The Robot constructor for our sample program inverts the right side of the drivetrain. Depending on your drive setup, you might need to invert the left side instead.

Exemple de mode autonome simple

38  /** This function is run once each time the robot enters autonomous mode. */
39  @Override
40  public void autonomousInit() {
41    m_timer.restart();
42  }
43
44  /** This function is called periodically during autonomous. */
45  @Override
46  public void autonomousPeriodic() {
47    // Drive for 2 seconds
48    if (m_timer.get() < 2.0) {
49      // Drive forwards half speed, make sure to turn input squaring off
50      m_robotDrive.arcadeDrive(0.5, 0.0, false);
51    } else {
52      m_robotDrive.stopMotor(); // stop robot
53    }
54  }
25  void AutonomousInit() override { m_timer.Restart(); }
26
27  void AutonomousPeriodic() override {
28    // Drive for 2 seconds
29    if (m_timer.Get() < 2_s) {
30      // Drive forwards half speed, make sure to turn input squaring off
31      m_robotDrive.ArcadeDrive(0.5, 0.0, false);
32    } else {
33      // Stop robot
34      m_robotDrive.ArcadeDrive(0.0, 0.0, false);
35    }
36  }
31    def autonomousInit(self):
32        """This function is run once each time the robot enters autonomous mode."""
33        self.timer.restart()
34
35    def autonomousPeriodic(self):
36        """This function is called periodically during autonomous."""
37
38        # Drive for two seconds
39        if self.timer.get() < 2.0:
40            # Drive forwards half speed, make sure to turn input squaring off
41            self.robotDrive.arcadeDrive(0.5, 0, squareInputs=False)
42        else:
43            self.robotDrive.stopMotor()  # Stop robot

La méthode AutonomousInit est exécutée une seule fois au moment où le robot passe au mode autonomie à partir d’un autre mode. Dans le programme, nous redémarrons le Timer dans cette méthode.

AutonomousPeriodic est exécuté une fois par période lorsque que le robot est en mode autonome. Dans la classe TimedRobot la période est de durée fixe et par défaut est égale à 20ms. Dans cet exemple, le code périodique vérifie si la minuterie est inférieure à 2 secondes et, dans ce cas, fait avancer le robot à mi-vitesse à l’aide de la méthode ArcadeDrive de la classe DifferentialDrive. S’il s’est écoulé plus de 2 secondes, le code met fin au déplacement du robot.

Contrôle par Joystick pendant le mode téléopéré

56  /** This function is called once each time the robot enters teleoperated mode. */
57  @Override
58  public void teleopInit() {}
59
60  /** This function is called periodically during teleoperated mode. */
61  @Override
62  public void teleopPeriodic() {
63    m_robotDrive.arcadeDrive(-m_controller.getLeftY(), -m_controller.getRightX());
64  }
38  void TeleopInit() override {}
39
40  void TeleopPeriodic() override {
41    // Drive with arcade style (use right stick to steer)
42    m_robotDrive.ArcadeDrive(-m_controller.GetLeftY(),
43                             m_controller.GetRightX());
44  }
45    def teleopInit(self):
46        """This function is called once each time the robot enters teleoperated mode."""
47
48    def teleopPeriodic(self):
49        """This function is called periodically during teleoperated mode."""
50        self.robotDrive.arcadeDrive(
51            -self.controller.getLeftY(), -self.controller.getRightX()
52        )

Like in Autonomous, the Teleop mode has a TeleopInit and TeleopPeriodic function. In this example we don’t have anything to do in TeleopInit, it is provided for illustration purposes only. In TeleopPeriodic, the code uses the ArcadeDrive method to map the Y-axis of the left thumbstick of the XBoxController to forward/back motion of the drive motors and the X-axis to turning motion.

Mode test

66  /** This function is called once each time the robot enters test mode. */
67  @Override
68  public void testInit() {}
69
70  /** This function is called periodically during test mode. */
71  @Override
72  public void testPeriodic() {}
73}
45  void TestInit() override {}
46
47  void TestPeriodic() override {}
54    def testInit(self):
55        """This function is called once each time the robot enters test mode."""
56
57    def testPeriodic(self):
58        """This function is called periodically during test mode."""

Le mode test est utilisé afin de tester la fonctionnalité du robot. À l’instar de TeleopInit, les méthodes TestInit et TestPeriodic sont fournies ici uniquement à des fins d’illustration.

Déploiement du code projet sur un robot