| 1 | 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. |
| 2 | |
| 3 | WPILib provides a great helper class called [https://first.wpi.edu/FRC/roborio/release/docs/java/edu/wpi/first/cameraserver/CameraServer.html CameraServer] that does most of the heavy lifting. You can read about it [https://docs.wpilib.org/en/latest/docs/software/vision-processing/introduction/cameraserver-class.html here] and [https://s3.amazonaws.com/screensteps_live/exported/Wpilib/2078/6264/Read_and_process_video_CameraServer_class.pdf?1483739157 here] |
| 4 | |
| 5 | For more info see |
| 6 | |
| 7 | == Robot.java == |
| 8 | {{{ |
| 9 | package frc.robot; |
| 10 | |
| 11 | import edu.wpi.first.wpilibj.TimedRobot; |
| 12 | |
| 13 | public class Robot extends TimedRobot { |
| 14 | Cameras cameras; |
| 15 | |
| 16 | @Override |
| 17 | public void robotInit() { |
| 18 | cameras = new Cameras(); |
| 19 | cameras.start(); |
| 20 | } |
| 21 | } |
| 22 | }}} |
| 23 | |
| 24 | == Cameras.java == |
| 25 | Create a new file named Cameras.java under src/main/java/frc/robot (same folder as Robot.java): |
| 26 | {{{ |
| 27 | package frc.robot; |
| 28 | |
| 29 | import edu.wpi.first.cameraserver.CameraServer; |
| 30 | import edu.wpi.cscore.UsbCamera; |
| 31 | import edu.wpi.first.wpilibj.XboxController; |
| 32 | import edu.wpi.first.wpilibj.Timer; |
| 33 | |
| 34 | class Cameras extends Thread { |
| 35 | CameraServer camServer; |
| 36 | UsbCamera frontCam, rearCam; |
| 37 | XboxController xbox; |
| 38 | Timer debounce; |
| 39 | |
| 40 | public Cameras() { |
| 41 | camServer = CameraServer.getInstance(); |
| 42 | frontCam = camServer.startAutomaticCapture("front", 0); |
| 43 | rearCam = camServer.startAutomaticCapture("rear", 1); |
| 44 | |
| 45 | xbox = new XboxController(0); |
| 46 | debounce = new Timer(); |
| 47 | } |
| 48 | |
| 49 | public void run() { |
| 50 | debounce.start(); |
| 51 | while (true) { |
| 52 | if (xbox.getAButton()) { |
| 53 | if (debounce.hasPeriodPassed(0.5)) { |
| 54 | if (camServer.getServer().getSource().getName().contentEquals("front")) { |
| 55 | camServer.getServer().setSource(rearCam); |
| 56 | } else { |
| 57 | camServer.getServer().setSource(frontCam); |
| 58 | } |
| 59 | debounce.reset(); |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | }}} |