Austin Schuh | 812d0d1 | 2021-11-04 20:16:48 -0700 | [diff] [blame] | 1 | // Copyright (c) FIRST and other WPILib contributors. |
| 2 | // Open Source Software; you can modify and/or share it under the terms of |
| 3 | // the WPILib BSD license file in the root directory of this project. |
| 4 | |
| 5 | #include "frc/PIDController.h" |
| 6 | |
| 7 | #include <wpi/sendable/SendableBuilder.h> |
| 8 | |
| 9 | #include "frc/Notifier.h" |
| 10 | #include "frc/PIDOutput.h" |
| 11 | |
| 12 | using namespace frc; |
| 13 | |
| 14 | PIDController::PIDController(double Kp, double Ki, double Kd, PIDSource* source, |
| 15 | PIDOutput* output, double period) |
| 16 | : PIDController(Kp, Ki, Kd, 0.0, *source, *output, period) {} |
| 17 | |
| 18 | PIDController::PIDController(double Kp, double Ki, double Kd, double Kf, |
| 19 | PIDSource* source, PIDOutput* output, |
| 20 | double period) |
| 21 | : PIDController(Kp, Ki, Kd, Kf, *source, *output, period) {} |
| 22 | |
| 23 | PIDController::PIDController(double Kp, double Ki, double Kd, PIDSource& source, |
| 24 | PIDOutput& output, double period) |
| 25 | : PIDController(Kp, Ki, Kd, 0.0, source, output, period) {} |
| 26 | |
| 27 | PIDController::PIDController(double Kp, double Ki, double Kd, double Kf, |
| 28 | PIDSource& source, PIDOutput& output, |
| 29 | double period) |
| 30 | : PIDBase(Kp, Ki, Kd, Kf, source, output) { |
| 31 | m_controlLoop = std::make_unique<Notifier>(&PIDController::Calculate, this); |
| 32 | m_controlLoop->StartPeriodic(units::second_t(period)); |
| 33 | } |
| 34 | |
| 35 | PIDController::~PIDController() { |
| 36 | // Forcefully stopping the notifier so the callback can successfully run. |
| 37 | m_controlLoop->Stop(); |
| 38 | } |
| 39 | |
| 40 | void PIDController::Enable() { |
| 41 | { |
| 42 | std::scoped_lock lock(m_thisMutex); |
| 43 | m_enabled = true; |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | void PIDController::Disable() { |
| 48 | { |
| 49 | // Ensures m_enabled modification and PIDWrite() call occur atomically |
| 50 | std::scoped_lock pidWriteLock(m_pidWriteMutex); |
| 51 | { |
| 52 | std::scoped_lock mainLock(m_thisMutex); |
| 53 | m_enabled = false; |
| 54 | } |
| 55 | |
| 56 | m_pidOutput->PIDWrite(0); |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | void PIDController::SetEnabled(bool enable) { |
| 61 | if (enable) { |
| 62 | Enable(); |
| 63 | } else { |
| 64 | Disable(); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | bool PIDController::IsEnabled() const { |
| 69 | std::scoped_lock lock(m_thisMutex); |
| 70 | return m_enabled; |
| 71 | } |
| 72 | |
| 73 | void PIDController::Reset() { |
| 74 | Disable(); |
| 75 | |
| 76 | PIDBase::Reset(); |
| 77 | } |
| 78 | |
| 79 | void PIDController::InitSendable(wpi::SendableBuilder& builder) { |
| 80 | PIDBase::InitSendable(builder); |
| 81 | builder.AddBooleanProperty( |
| 82 | "enabled", [=] { return IsEnabled(); }, |
| 83 | [=](bool value) { SetEnabled(value); }); |
| 84 | } |