blob: cf3849b790d9d830a3c7d48d3c0fa2f051a374b1 [file] [log] [blame]
Brian Silvermanf7f267a2017-02-04 16:16:08 -08001/*----------------------------------------------------------------------------*/
2/* Copyright (c) FIRST 2014-2017. All Rights Reserved. */
3/* Open Source Software - may be modified and shared by FRC teams. The code */
4/* must be accompanied by the FIRST BSD license file in the root directory of */
5/* the project. */
6/*----------------------------------------------------------------------------*/
7
8#include "PIDController.h"
9#include "PIDOutput.h"
10#include "PIDSource.h"
11#include "TestBench.h"
12#include "Timer.h"
13#include "gtest/gtest.h"
14
15using namespace frc;
16
17class PIDToleranceTest : public testing::Test {
18 protected:
19 const double setpoint = 50.0;
20 const double range = 200;
21 const double tolerance = 10.0;
22 class fakeInput : public PIDSource {
23 public:
24 double val = 0;
25 void SetPIDSourceType(PIDSourceType pidSource) {}
26 PIDSourceType GetPIDSourceType() { return PIDSourceType::kDisplacement; }
27 double PIDGet() { return val; }
28 };
29 class fakeOutput : public PIDOutput {
30 void PIDWrite(double output) {}
31 };
32 fakeInput inp;
33 fakeOutput out;
34 PIDController* pid;
35 void SetUp() override {
36 pid = new PIDController(0.5, 0.0, 0.0, &inp, &out);
37 pid->SetInputRange(-range / 2, range / 2);
38 }
39 void TearDown() override { delete pid; }
40 void Reset() { inp.val = 0; }
41};
42
43TEST_F(PIDToleranceTest, Absolute) {
44 Reset();
45 pid->SetAbsoluteTolerance(tolerance);
46 pid->SetSetpoint(setpoint);
47 pid->Enable();
48 EXPECT_FALSE(pid->OnTarget())
49 << "Error was in tolerance when it should not have been. Error was "
50 << pid->GetAvgError();
51 inp.val = setpoint + tolerance / 2;
52 Wait(1.0);
53 EXPECT_TRUE(pid->OnTarget())
54 << "Error was not in tolerance when it should have been. Error was "
55 << pid->GetAvgError();
56 inp.val = setpoint + 10 * tolerance;
57 Wait(1.0);
58 EXPECT_FALSE(pid->OnTarget())
59 << "Error was in tolerance when it should not have been. Error was "
60 << pid->GetAvgError();
61}
62
63TEST_F(PIDToleranceTest, Percent) {
64 Reset();
65 pid->SetPercentTolerance(tolerance);
66 pid->SetSetpoint(setpoint);
67 pid->Enable();
68 EXPECT_FALSE(pid->OnTarget())
69 << "Error was in tolerance when it should not have been. Error was "
70 << pid->GetAvgError();
71 inp.val = setpoint +
72 (tolerance) / 200 *
73 range; // half of percent tolerance away from setpoint
74 Wait(1.0);
75 EXPECT_TRUE(pid->OnTarget())
76 << "Error was not in tolerance when it should have been. Error was "
77 << pid->GetAvgError();
78 inp.val =
79 setpoint +
80 (tolerance) / 50 * range; // double percent tolerance away from setPoint
81 Wait(1.0);
82 EXPECT_FALSE(pid->OnTarget())
83 << "Error was in tolerance when it should not have been. Error was "
84 << pid->GetAvgError();
85}