How to pass in a subsystem on wpilib

Hello, I am coding right now and don’t know how to pass in a subsystem

You can pass in a subsystem the same way you pass in any other object. If you are trying to pass subsystem A to subsystem B, you need to make sure B has a parameter of type A in the constructor, then you just pass in A to B when you initialize B.

Example: say you want your drive subsystem to have access to your LED subsystem. DriveSubsystem.java might look like this:

import frc.robot.subsystems.Lights

public class DriveSubsystem extends SubsystemBase {
    private Lights lights;
    public DriveSubsystem(Lights lightsSubsystem){
        this.lights = lightsSubsystem;
    }
}

This tells DriveSubsystem that it takes a Lights object and stores it.

Then in RobotContainer.java:

import frc.robot.subsystems.Lights;
import frc.robot.subsystems.DriveSubsystem;

private final Lights lights = new Lights();
public final DriveSubsystem drive = new DriveSubsystem(lights);

This initalizes our lights subsystem, and initializes our DriveSubsystem which includes passing in lights.

2 Likes

Just don’t forget to require the subsystem with addRequirements in the command.

2 Likes

You need to do this in most cases, but if you read the same value from one subsystem to use with multiple subsystems without changing anything else then do not add that one subsystem to addRequirements() as this will not let it be read from simultaneously.

In that case, it’d be better to pass only a DoubleSupplier etc that returns the relevant measurement.

3 Likes

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.