FRC_7130_5th
  • NEW!
    NEW!  Connect Ideas Across Notes
    Save time and share insights. With Paragraph Citation, you can quote others’ work with source info built in. If someone cites your note, you’ll see a card showing where it’s used—bringing notes closer together.
    Got it
        • Sharing URL Link copied
        • /edit
        • View mode
          • Edit mode
          • View mode
          • Book mode
          • Slide mode
          Edit mode View mode Book mode Slide mode
        • Customize slides
        • Note Permission
        • Read
          • Owners
          • Signed-in users
          • Everyone
          Owners Signed-in users Everyone
        • Write
          • Owners
          • Signed-in users
          • Everyone
          Owners Signed-in users Everyone
        • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invite by email
        Invitee

        This note has no invitees

      • Publish Note

        Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

        Your note will be visible on your profile and discoverable by anyone.
        Your note is now live.
        This note is visible on your profile and discoverable online.
        Everyone on the web can find and read all notes of this public team.

        Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

        Explore these features while you wait
        Complete general settings
        Bookmark and like published notes
        Write a few more notes
        Complete general settings
        Write a few more notes
        See published notes
        Unpublish note
        Please check the box to agree to the Community Guidelines.
        View profile
      • Commenting
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
        • Everyone
      • Suggest edit
        Permission
        Disabled Forbidden Owners Signed-in users Everyone
      • Enable
      • Permission
        • Forbidden
        • Owners
        • Signed-in users
      • Emoji Reply
      • Enable
      • Versions and GitHub Sync
      • Note settings
      • Note Insights New
      • Engagement control
      • Make a copy
      • Transfer ownership
      • Delete this note
      • Insert from template
      • Import from
        • Dropbox
        • Google Drive
        • Gist
        • Clipboard
      • Export to
        • Dropbox
        • Google Drive
        • Gist
      • Download
        • Markdown
        • HTML
        • Raw HTML
    Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
    Menu
    Options
    Engagement control Make a copy Transfer ownership Delete this note
    Import from
    Dropbox Google Drive Gist Clipboard
    Export to
    Dropbox Google Drive Gist
    Download
    Markdown HTML Raw HTML
    Back
    Sharing URL Link copied
    /edit
    View mode
    • Edit mode
    • View mode
    • Book mode
    • Slide mode
    Edit mode View mode Book mode Slide mode
    Customize slides
    Note Permission
    Read
    Owners
    • Owners
    • Signed-in users
    • Everyone
    Owners Signed-in users Everyone
    Write
    Owners
    • Owners
    • Signed-in users
    • Everyone
    Owners Signed-in users Everyone
    Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    ###### tags: `程式組教程` {%hackmd theme-dark %} # Command Based Programming A simplified note with our experience included If you want a more complete but more sophisticated explanation of command based programming, visit [WPILib's Doc](https://docs.wpilib.org/en/stable/docs/software/commandbased/index.html) Table of Contents * [Introduction of Concepts](#Introduction-of-Concepts) * [What is Command Based Programming](#What-is-Command-Based-Programming) * [Command Structure](#Command-Structure) * [Subsystems](#Subsystems) * [Command Based Project Structure](#Command-Based-Project-Structure) * [The Basics](#The-Basics) * [Creating a command based project](#Creating-a-command-based-project) * [Subsystems](#Subsystems1) * [Subsystem Structure: the details](#Subsystem-Structure-the-details) * [Subsystem Tips](#Subsystem-Tips) * [Commands](#Commands) * [Command Structure: the details](#Command-Structure-the-details) * [Command Tips](#Command-Tips) * [CommandScheduler](#CommandScheduler) * [What is it?](#What-is-it) * [How do I use it?](#How-do-I-use-it) * [Advanced Usage](#Advanced-Usage) * [Command Groups](#Command-Groups) * [Inline Command](#Inline-Command) ## Introduction of Concepts ### What is Command Based Programming? In its essence, command based programming is a type of robot code structure in which complicated robot instruction and code are simplified and packaged into "commands" that we can use repetitively. It is very similar to how we use functions to simplify complicated process. However, commands comes with a lot of handy tools that the wpilib library provides. ### Command Structure Each command is a java class that extends one of wpilib's command superclasses (Usually CommandBase). For example: ```java= public class IntakeCmd extends CommandBase ``` Each command must implement the following methods: * Constructor: IntakeCmd() * initialize() * execute() * end() Usually, you will also need isFinished() or interrupted() Here is how it works! ![](https://i.imgur.com/24bK1O3.png) After constructing the command instance and calling it, **initialize()** will be called. This is similar to things like TeleopInit(), in which necessary things are done before the actions take place. Then the **execute()** method is called, this is where most actions are done during the process. For example, the intake motors will move so that the ball is carried into the robot's carrier. Lastly, after executing all actions, the **end()** method will be called. This method make sure that everything is returned to necessary condition after finishing (for example, setting motor speed back to 0) ### Subsystems You may or may not have heard about subsystems, but they are a crucial part of command based programming. Normally, we just directly refer to the motors and other parts of our robot in our robot.java file. You might have noticed that as the number of devices increase, this makes the robot.java file increasingly complex. To make everything less like a spaghetti code, we organize related parts of the robot into subsystems: a collection of devices and functions to control them. For example, the drive subsystem DriveTrain will include all motors on the base that controls the movement of the robot, as well as functions like drive() that controls them. ### Command Based Project Structure Here's part of the project structure from last year ![](https://i.imgur.com/nXUUHGZ.png) This might look complicated, but it's actually pretty simple. We have one folder Subsystems that contains all the java files that defines the subsystems of the robot. The Commands folder has sub-folders according to the subsystems, and respective commands in them. The other files are located at the base folder. ## The Basics ### Creating a command based project The easiest way to do this is to use the template in WPILib Visual Studio Code. 1. In WPILib Visual Studio Code, execute the command "Create a new project" ![](https://i.imgur.com/yxGDqdj.png) 2. When selecting project type, select "Template", "java", "Command Robot" 3. Enter the rest of the information as usual 4. Create the project, you should see the default structure show up as follows: ![](https://i.imgur.com/GuXnWrv.png) ### Subsystems #### Subsystem Structure: the details Let's take a look at the more detailed part of a subsystem using an example. I use the intake subsystem from 2022 code base because it's one of the more simple one. ```java= package frc.robot.subsystems; import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants.IntakeConstants; //import frc.robot.Constants.TransporterConstants; import frc.robot.Constants.TransporterConstants; public class Intake extends SubsystemBase { private final WPI_TalonSRX intaker = new WPI_TalonSRX(IntakeConstants.kIntakeID);; private final WPI_TalonSRX downTransporter = new WPI_TalonSRX(TransporterConstants.kDownTransporterID); /** Creates a new IntakeSubsystem. */ public Intake() { } @Override public void periodic() { // This method will be called once per scheduler run } public void intakeRun(){ intaker.set(IntakeConstants.intakeSpeed); downTransporter.set(IntakeConstants.transportSpeed); } public void intakeSet(double speed) { intaker.set(speed); downTransporter.set(speed); } public void intakeStop(){ intaker.set(0); downTransporter.set(0); } public void intakeReverse() { intaker.set(-IntakeConstants.intakeSpeed); downTransporter.set(-IntakeConstants.transportSpeed); } public void downRun() { downTransporter.set(-IntakeConstants.transportSpeed); } public void downStop() { downTransporter.set(0); } } ``` We can analyze this subsystem section by section: **1.Class declaration** ```java= public class Intake extends SubsystemBase { ``` Every subsystem must extend the class SubsystemBase from WPILib. Make sure to include the corresponding import. **2.Field declaration** ```java= private final WPI_TalonSRX intaker = new WPI_TalonSRX(IntakeConstants.kIntakeID);; private final WPI_TalonSRX downTransporter = new WPI_TalonSRX(TransporterConstants.kDownTransporterID); ``` Here we declare the devices and possibly other variables that we will use in the subsystem. The declared ones are the 2 motors for the intake subsystem using WPI_TalonSRX motor controller. Notice the use of **private** keyword. Although it is not necessary, it is usually a good practice to limit the access of fields. Also be mindful of the **final** keyword. We only use it here because the motors are unchanging and the subsystem will always use these two motors. **3.Constructor** ```java= public Intake() { } ``` The constructor of the intake subsystem is not particularly interesting, but as you can see in the Turret subsystem constructor, we usually set up the property of certain important fields such as devices in the constructor. ```java= public Turret() { masterFlyWheel.setInverted(true); slaveFlyWheel.setInverted(false); slaveFlyWheel.follow(masterFlyWheel, true); } ``` **4.periodic()** This function will be executed periodically starting from the point when the subsystem's constructor is called. Take a look at Drive subsystem's periodic() ```java= public void periodic() { // System.out.println(m_mecanumOdometry.getPoseMeters()); m_differentialOdometry.update( m_gyro.getRotation2d(), motorFL.getSelectedSensorPosition() * DriveConstants.kEncoderDistancePerPulse / 10, motorFR.getSelectedSensorPosition() * DriveConstants.kEncoderDistancePerPulse / 10 ); } ``` Since the odometry (essentially the robot's predicted position) need to be updated whenever the base motor moves, the subsystem periodically updates it from the point when the Drive subsystem is initiated. **5.Other methods** According to each subsystem, other functions/methods might be added to make the subsystem easier to use. For example, the intake subsystem has the following functions: ```java= public void intakeRun(){ intaker.set(IntakeConstants.intakeSpeed); downTransporter.set(IntakeConstants.transportSpeed); } public void intakeSet(double speed) { intaker.set(speed); downTransporter.set(speed); } public void intakeStop(){ intaker.set(0); downTransporter.set(0); } public void intakeReverse() { intaker.set(-IntakeConstants.intakeSpeed); downTransporter.set(-IntakeConstants.transportSpeed); } public void downRun() { downTransporter.set(-IntakeConstants.transportSpeed); } public void downStop() { downTransporter.set(0); } ``` Each serves to simplify the working of a subsystem. To sum up, the structure of a subsystem is: ``` imports class declaration { fields constructor periodic() other methods } ``` #### Subsystem Tips * **Avoid refering to other subsystems when writing a subsystem**: each subsystem should be able to work individually without cross reference. The reference may cause potential tangling of access priority to hardware. * **Do not involve inputs from higher level**: For example, do not include joystick input into the subsystem (that is, unless it is a joystick subsystem). These higher level input should be deal with at a higher level (usually robotContainer.java). Using it at lower level will likely cause conflict for the control of the access to the device. * **Organize constants by subsystems**: 1. always put the constants in constants.java instead of the subsystem itself for easier organization. 2. always organize the constants by their respective subsystem. For example, in constants.java, constants used for Drive subsystem should be under DriveConstants class. For instance, DriveConstants.wheelDiameter. * **Be careful about the encapsulation**:You shouldn't be able to directly access the subsystem's motor using things like subsystem.motor1. The motor and other fields should be encapsulated using **private** or other suitable keyword. ### Commands #### Command Structure: the details Besides the previously explained initiate(), execute(), and end(), there are other things a command will need. Let's explore this by writing an example. First, declare the command. We may want to start from an easy one, like DriveForward. ```java= public class DriveForward extends CommandBase { } ``` We'll then need to add the needed fields. Most importantly, the subsystem that we'll use. Remember that each command will use at least one subsystem. We'll need to declare them here. Since we are driving, we'll need the DriveSubsystem. ```java= public class DriveForward extends CommandBase { private DriveSubsystem drive; } ``` To use the subsystem, however, we'll need to get the subsystem from a higher level. Hence, we'll need the constructor. ```java= public class DriveForward extends CommandBase { private DriveSubsystem drive; public DriveForward(DriveSubsystem drive) { this.drive = drive; addRequirements(drive); } } ``` This make sure that when we declared the command later, we can get to use the subsystem. The **addRequirements()** function is very important because it makes sure that other commands will not conflict with the usage of certain subsystem. Let's say we want this command to let the robot go forward for 5 second at 50% speed. We'll need to add some necessary fields and initialize ```java= public class DriveForward extends CommandBase { private DriveSubsystem drive; double initTime; public DriveForward(DriveSubsystem drive) { this.drive = drive; addRequirements(drive); } @Override public void initialize(){ initTime=Timer.getFPGATimestamp(); } } ``` Then the execution part, where the robot actually moves. ```java= public class DriveForward extends CommandBase { private DriveSubsystem drive; double initTime; public DriveForward(DriveSubsystem drive) { this.drive = drive; addRequirements(drive); } @Override public void initialize(){ initTime=Timer.getFPGATimestamp(); } @Override public void execute(){ drive.arcadeDrive(0.5,0); } } ``` Lastly, we want the bot to stop at the end. ```java= public class DriveForward extends CommandBase { private DriveSubsystem drive; double initTime; public DriveForward(DriveSubsystem drive) { this.drive = drive; addRequirements(drive); } @Override public void initialize(){ initTime=Timer.getFPGATimestamp(); } @Override public void execute(){ drive.arcadeDrive(0.5,0); } @Override public void end(boolean Interrupted){ drive.arcadeDrive(0,0); } } ``` You might wonder that how does the bot know when to stop? This is where **isFinished()** kicks in. isFinished() will tell the bot when this command should end. It returns true when the command should end, false if it should continue. In this case, we want the command to end after 5 seconds. ```java= public class DriveForward extends CommandBase { private DriveSubsystem drive; double initTime; public DriveForward(DriveSubsystem drive) { this.drive = drive; addRequirements(drive); } @Override public void initialize(){ initTime=Timer.getFPGATimestamp(); } @Override public void execute(){ drive.arcadeDrive(0.5,0); } @Override public void end(boolean Interrupted){ drive.arcadeDrive(0,0); } @Override public boolean isFinished(){ if (Timer.getFPGATimestamp()>initTime+5){ return true; } return false; } } ``` In some commands, you might need another special function, **interrupted()**. Sometimes, a command is set to end only when other command is scheduled in its place. Therefore, we need a way to turn off the executing devices when this happens. Interrupted() will execute when the command is interrupted, solving the issue. For example: ```java= public void interrupted(){ drive.arcadeDrive(0,0); } ``` This will make sure that when the command is interrupted, the robot will stop automatically. To sum up, the structure of a command is: ``` imports class declaration { fields (usually subsystems) constructor() initialize() execute() end() isFinished() interrupted() //optional } ``` #### Command Tips * **Do not create a new instance of a subsystem inside the command**:always use the subsystem by passing it in from a higher level. Creation of another subsystem instance maybe often cause conflict for the access of devices. * **Make sure there is always a way to stop the command**: be careful when designing isFinished() and interrupted() so that the command can be ended correctly. Try not to use interruption as a way to end the command, as this usually will make the program a lot more complex, especially with the **CommandScheduler**(sometimes this might be necessary though). ### CommandScheduler #### What is it? Now, we have learned how to build commands, but how do we use them? This is the job of the CommandScheduler The CommandScheduler allows us to **schedule** command, which it will run accordingly. The CommandScheduler is the highest level access point of commands, and should be positioned inside robotContainer.java CommandScheduler is a class with one single instance (singleton), so to get it, you must use CommandScheduler.getInstance() #### How do I use it? First, add CommandScheduler.getInstance().run() to the robotPeriodic() function in robot.java, this allows the scheduled commands to actually execute. Then, inside robot container, you may use CommandScheduler.getInstance().schedule() to add any command into the queue and execute it. For example: ```java= CommandScheduler.getInstance().schedule(new DriveForward(drive)) // drive is a DriveSubsystem instance ``` This is the basic of using CommandScheduler, and usually you won't need much beside this knowledge. However, if you are interested, or if you encountered strange issues, check [WPILib's explanation](https://docs.wpilib.org/en/stable/docs/software/commandbased/command-scheduler.html) ## Advanced Usage ### Command Groups Sometimes, we want to organize multiple commands together into a larger command, or we might want multiple commands to execute in a certain way. This is the job of command groups. There are several types of command groups, each with its own special function. * SequentialCommandGroup SequentialCommandGroup, as its name suggests, execute the commands sequentially. Meaning it execute command1, command2, command3... Example: ```java= SequentialCommandGroup group = new SequentialCommandGroup(new Command1(), new Command2()) ``` * ParallelCommandGroup Runs all commands concirrently (meaning at the same time). One of the most important command group because it allows parallel execution of complex actions. **This command group ends only when every command inside of it finished** * ParallelRaceGroup Same as ParallelCommandGroup. **Except it ends whenever any command inside it finished** * ParallelDeadlineGroup Same as ParallelCommandGroup. However, it ends when the deadline command ends. During its declaration, the first command in the constructor will be set as the deadline command ```java= new ParallelDeadlineGroup(new Command1(), new Command2()) //Command1 is the deadline ``` **Declaring Command Groups** We usually just declare commands using its inline form as shown above. However, you can also create a new java class for the command group as well. ```java= public class ExampleCommandGroup extends SequentialCommandGroup { public ExampleCommandGroup() { addCommands( new Command1(), new Command2() ) } } ``` **Recursive Command Group Statement** You can have command groups within command groups, for instance: ```java= new SequentialCommandGroup( new Command1(), new ParallelCommandGroup( new Command2(), new Command3() ) ) ``` ### Inline Command As we mentioned before, although most commands will extend class CommandBase, there are other commands available for us. However, instead of extending these classes, we usually declare these other commands inline, which is why we call them inline commands. There are too many types of inline commands, so I won't include them in this tutorial. You can easily access them at [WPILib's doc](https://docs.wpilib.org/en/stable/docs/software/commandbased/convenience-features.html). (It's a bit down in the page though) Some frequently used inline commands are **ConditionalCommand** and **RunCommand**, which I strongly suggests you to take a look.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully