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 run in its own thread to prevent a camera exception (e.g. if a camera fails or gets unplugged) 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 about using multiple cameras, see here
Robot.java
package frc.robot; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.XboxController; public class Robot extends TimedRobot { Cameras cameras; XboxController xbox; @Override public void robotInit() { xbox = new XboxController(0); // create xbox controller object cameras = new Cameras(); // create the Cameras thread cameras.start(); // start thread and launch its run() method } @Override public void robotPeriodic() { if (xbox.getAButton()) { cameras.selectFront(); } else if (xbox.getBButton()) { cameras.selectRear(); } } }
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.cscore.VideoSource.ConnectionStrategy; class Cameras extends Thread { CameraServer camServer; UsbCamera frontCam, rearCam; public Cameras() { // Camera server manages all cameras and streams camServer = CameraServer.getInstance(); // Start serving front camera (USB port 0) frontCam = camServer.startAutomaticCapture("cameras", 0); // Create additional camera(s) rearCam = new UsbCamera("rear", 1); // keep video streams open for fast switching //frontCam.setConnectionStrategy(ConnectionStrategy.kKeepOpen); //rearCam.setConnectionStrategy(ConnectionStrategy.kKeepOpen); } public void selectFront() { camServer.getServer().setSource(frontCam); } public void selectRear() { camServer.getServer().setSource(rearCam); } // Run method is invoked when start method is called public void run() { while (true) { // run forever } } }