wiki:ControlSystems/SoftwareTeam/Training/GettingStarted/CameraSwitching

Version 1 (modified by David Albert, 5 years ago) (diff)

--

Often it's desirable to have more than one camera on a robot, for example to provide front and back views. As always, camera code should always run in its own thread to prevent camera errors from taking down the main robot thread. The example below shows how to create a new thread class called Cameras that creates two cameras and lets you switch between them using an Xbox controller.

WPILib provides a great helper class called CameraServer that does most of the heavy lifting. You can read about it here and here

For more info see

Robot.java

package frc.robot;

import edu.wpi.first.wpilibj.TimedRobot;

public class Robot extends TimedRobot {
  Cameras cameras;

  @Override
  public void robotInit() {
    cameras = new Cameras();
    cameras.start();
  }
}

Cameras.java

Create a new file named Cameras.java under src/main/java/frc/robot (same folder as Robot.java):

package frc.robot;

import edu.wpi.first.cameraserver.CameraServer;
import edu.wpi.cscore.UsbCamera;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.Timer;

class Cameras extends Thread {
    CameraServer   camServer;
    UsbCamera      frontCam, rearCam;
    XboxController xbox;
    Timer          debounce;

    public Cameras() {
        camServer = CameraServer.getInstance();
        frontCam = camServer.startAutomaticCapture("front", 0);
        rearCam  = camServer.startAutomaticCapture("rear", 1);

        xbox = new XboxController(0);
        debounce = new Timer();
    }

    public void run() {
        debounce.start();
        while (true) {
            if (xbox.getAButton()) {
                if (debounce.hasPeriodPassed(0.5)) {
                    if (camServer.getServer().getSource().getName().contentEquals("front")) {
                        camServer.getServer().setSource(rearCam);
                    } else {
                        camServer.getServer().setSource(frontCam);
                    }
                    debounce.reset();
                }
            }
        }
    }
}