Combining Aiming and Getting in Range

Knowledge and Equipment Needed

Code

Now that you know how to both aim and get in range of the target, it is time to combine them both at the same time. This example will take the previous two code examples and make them into one function using the same tools as before. With this example, you now have all the knowledge you need to use PhotonVision on your robot in any game.

The following example is from the PhotonLib example repository (Java/C++).

  1/*
  2 * Copyright (C) Photon Vision.
  3 *
  4 * This program is free software: you can redistribute it and/or modify
  5 * it under the terms of the GNU General Public License as published by
  6 * the Free Software Foundation, either version 3 of the License, or
  7 * (at your option) any later version.
  8 *
  9 * This program is distributed in the hope that it will be useful,
 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 * GNU General Public License for more details.
 13 *
 14 * You should have received a copy of the GNU General Public License
 15 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 16 */
 17package org.photonlib.examples.aimandrange;
 18
 19import edu.wpi.first.math.controller.PIDController;
 20import edu.wpi.first.math.util.Units;
 21import edu.wpi.first.wpilibj.TimedRobot;
 22import edu.wpi.first.wpilibj.XboxController;
 23import edu.wpi.first.wpilibj.drive.DifferentialDrive;
 24import edu.wpi.first.wpilibj.motorcontrol.PWMVictorSPX;
 25import org.photonvision.PhotonCamera;
 26import org.photonvision.PhotonUtils;
 27
 28/**
 29 * The VM is configured to automatically run this class, and to call the functions corresponding to
 30 * each mode, as described in the TimedRobot documentation. If you change the name of this class or
 31 * the package after creating this project, you must also update the build.gradle file in the
 32 * project.
 33 */
 34public class Robot extends TimedRobot {
 35    // Constants such as camera and target height stored. Change per robot and goal!
 36    final double CAMERA_HEIGHT_METERS = Units.inchesToMeters(24);
 37    final double TARGET_HEIGHT_METERS = Units.feetToMeters(5);
 38    // Angle between horizontal and the camera.
 39    final double CAMERA_PITCH_RADIANS = Units.degreesToRadians(0);
 40
 41    // How far from the target we want to be
 42    final double GOAL_RANGE_METERS = Units.feetToMeters(3);
 43
 44    // Change this to match the name of your camera
 45    PhotonCamera camera = new PhotonCamera("photonvision");
 46
 47    // PID constants should be tuned per robot
 48    final double LINEAR_P = 0.1;
 49    final double LINEAR_D = 0.0;
 50    PIDController forwardController = new PIDController(LINEAR_P, 0, LINEAR_D);
 51
 52    final double ANGULAR_P = 0.1;
 53    final double ANGULAR_D = 0.0;
 54    PIDController turnController = new PIDController(ANGULAR_P, 0, ANGULAR_D);
 55
 56    XboxController xboxController = new XboxController(0);
 57
 58    // Drive motors
 59    PWMVictorSPX leftMotor = new PWMVictorSPX(0);
 60    PWMVictorSPX rightMotor = new PWMVictorSPX(1);
 61    DifferentialDrive drive = new DifferentialDrive(leftMotor, rightMotor);
 62
 63    @Override
 64    public void teleopPeriodic() {
 65        double forwardSpeed;
 66        double rotationSpeed;
 67
 68        if (xboxController.getAButton()) {
 69            // Vision-alignment mode
 70            // Query the latest result from PhotonVision
 71            var result = camera.getLatestResult();
 72
 73            if (result.hasTargets()) {
 74                // First calculate range
 75                double range =
 76                        PhotonUtils.calculateDistanceToTargetMeters(
 77                                CAMERA_HEIGHT_METERS,
 78                                TARGET_HEIGHT_METERS,
 79                                CAMERA_PITCH_RADIANS,
 80                                Units.degreesToRadians(result.getBestTarget().getPitch()));
 81
 82                // Use this range as the measurement we give to the PID controller.
 83                // -1.0 required to ensure positive PID controller effort _increases_ range
 84                forwardSpeed = -forwardController.calculate(range, GOAL_RANGE_METERS);
 85
 86                // Also calculate angular power
 87                // -1.0 required to ensure positive PID controller effort _increases_ yaw
 88                rotationSpeed = -turnController.calculate(result.getBestTarget().getYaw(), 0);
 89            } else {
 90                // If we have no targets, stay still.
 91                forwardSpeed = 0;
 92                rotationSpeed = 0;
 93            }
 94        } else {
 95            // Manual Driver Mode
 96            forwardSpeed = -xboxController.getRightY();
 97            rotationSpeed = xboxController.getLeftX();
 98        }
 99
100        // Use our forward/turn speeds to control the drivetrain
101        drive.arcadeDrive(forwardSpeed, rotationSpeed);
102    }
103}
 1/*
 2 * Copyright (C) Photon Vision.
 3 *
 4 * This program is free software: you can redistribute it and/or modify
 5 * it under the terms of the GNU General Public License as published by
 6 * the Free Software Foundation, either version 3 of the License, or
 7 * (at your option) any later version.
 8 *
 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
16 */
17
18#pragma once
19
20#include <photonlib/PhotonCamera.h>
21
22#include <frc/TimedRobot.h>
23#include <frc/XboxController.h>
24#include <frc/controller/PIDController.h>
25#include <frc/drive/DifferentialDrive.h>
26#include <frc/motorcontrol/PWMVictorSPX.h>
27#include <units/angle.h>
28#include <units/length.h>
29
30class Robot : public frc::TimedRobot {
31 public:
32  void TeleopPeriodic() override;
33
34 private:
35  // Constants such as camera and target height stored. Change per robot and
36  // goal!
37  const units::meter_t CAMERA_HEIGHT = 24_in;
38  const units::meter_t TARGET_HEIGHT = 5_ft;
39
40  // Angle between horizontal and the camera.
41  const units::radian_t CAMERA_PITCH = 0_deg;
42
43  // How far from the target we want to be
44  const units::meter_t GOAL_RANGE_METERS = 3_ft;
45
46  // PID constants should be tuned per robot
47  const double LINEAR_P = 0.1;
48  const double LINEAR_D = 0.0;
49  frc2::PIDController forwardController{LINEAR_P, 0.0, LINEAR_D};
50
51  const double ANGULAR_P = 0.1;
52  const double ANGULAR_D = 0.0;
53  frc2::PIDController turnController{ANGULAR_P, 0.0, ANGULAR_D};
54
55  // Change this to match the name of your camera
56  photonlib::PhotonCamera camera{"photonvision"};
57
58  frc::XboxController xboxController{0};
59
60  // Drive motors
61  frc::PWMVictorSPX leftMotor{0};
62  frc::PWMVictorSPX rightMotor{1};
63  frc::DifferentialDrive drive{leftMotor, rightMotor};
64};
 1/*
 2 * Copyright (C) Photon Vision.
 3 *
 4 * This program is free software: you can redistribute it and/or modify
 5 * it under the terms of the GNU General Public License as published by
 6 * the Free Software Foundation, either version 3 of the License, or
 7 * (at your option) any later version.
 8 *
 9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
16 */
17
18#include "Robot.h"
19
20#include <photonlib/PhotonUtils.h>
21
22void Robot::TeleopPeriodic() {
23  double forwardSpeed;
24  double rotationSpeed;
25
26  if (xboxController.GetAButton()) {
27    // Vision-alignment mode
28    // Query the latest result from PhotonVision
29    const auto& result = camera.GetLatestResult();
30
31    if (result.HasTargets()) {
32      // First calculate range
33      units::meter_t range = photonlib::PhotonUtils::CalculateDistanceToTarget(
34          CAMERA_HEIGHT, TARGET_HEIGHT, CAMERA_PITCH,
35          units::degree_t{result.GetBestTarget().GetPitch()});
36
37      // Use this range as the measurement we give to the PID controller.
38      // -1.0 required to ensure positive PID controller effort _increases_
39      // range
40      forwardSpeed = -forwardController.Calculate(range.value(),
41                                                  GOAL_RANGE_METERS.value());
42
43      // Also calculate angular power
44      // -1.0 required to ensure positive PID controller effort _increases_ yaw
45      rotationSpeed =
46          -turnController.Calculate(result.GetBestTarget().GetYaw(), 0);
47    } else {
48      // If we have no targets, stay still.
49      forwardSpeed = 0;
50      rotationSpeed = 0;
51    }
52  } else {
53    // Manual Driver Mode
54    forwardSpeed = -xboxController.GetRightY();
55    rotationSpeed = xboxController.GetLeftX();
56  }
57
58  // Use our forward/turn speeds to control the drivetrain
59  drive.ArcadeDrive(forwardSpeed, rotationSpeed);
60}
61
62#ifndef RUNNING_FRC_TESTS
63int main() { return frc::StartRobot<Robot>(); }
64#endif