Lesson 7: Limit Switches and Digital Input

Please note that although Encoders use the digital input ports, this lesson is not about Encoders. See Lesson 18 for Encoders.

Getting digital inputs from the roboRIO is super easy. There is a DigitalInput class that allows you to do this. Here's how you set it up:

DigitalInput input;
input = new DigitalInput(0);

You can see that the constructor takes a single integer. Just like motor controllers and joysticks, this represents the port that the digital input is plugged into on the roboRIO. The digital input above is plugged into port 0.

Now, to get the state of the digital input you use the get() method. Limit switches can be wired so that they are defaultly open or defaultly closed. If the limit switch is wired so that it defaultly open, then the get() method will return false when the limit switch is not pressed down, and true when it is pressed down. If the limit switch is wired so that it is defaultly closed, then it is the exact opposite. Here is how the get() method could be implemented:

if (input.get()) {
    // Perform an action, like stopping a motor
}

That's actually all there is to it. Some applications of limit switches are: setting a calibration value, stopping a motor, causing another motor to move (like a shooter), and more. Here is a main robot class with a DigitalInput completely set up:

DigitalInput input;

public void robotInit() {
    input = new DigitalInput(0);
}

public void teleopPeriodic() {
    if(input.get()) {
        // Perform an action, like stopping a motor
    }
}

See if you can incorporate a limit switch into your existing code that we started building in lesson 3.

Exercises


Using Code Red's Robot Library

Something that we are going to touch on in a much later lesson is input virtualization, which our library offers. Code Red's robot library has its own digital input class, called VirtualizableDigitalInput. This class offers no additional features aside from input virtualization. So if you are not planning on taking advantage of input virtualization, then don't bother using our class. However, if you do what to use it so that it is already set up when you get to the virtualization lesson, it is used exactly the same as DigitalInput: just replace DigitalInput in your code with VirtualizableDigitalInput. Here is what the above code would look like if it used Code Red's library:

VirtualizableDigitalInput input;

public void robotInit() {
    input = new VirtualizableDigitalInput(0);
}

public void teleopPeriodic() {
    if(input.get()) {
        // Perform an action, like stopping a motor
    }
}