blob: ee8382c1ef98b8fb59dd8b663eddb32a5cb586d5 [file] [log] [blame]
Austin Schuh812d0d12021-11-04 20:16:48 -07001// 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
12using namespace frc;
13
14PIDController::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
18PIDController::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
23PIDController::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
27PIDController::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
35PIDController::~PIDController() {
36 // Forcefully stopping the notifier so the callback can successfully run.
37 m_controlLoop->Stop();
38}
39
40void PIDController::Enable() {
41 {
42 std::scoped_lock lock(m_thisMutex);
43 m_enabled = true;
44 }
45}
46
47void 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
60void PIDController::SetEnabled(bool enable) {
61 if (enable) {
62 Enable();
63 } else {
64 Disable();
65 }
66}
67
68bool PIDController::IsEnabled() const {
69 std::scoped_lock lock(m_thisMutex);
70 return m_enabled;
71}
72
73void PIDController::Reset() {
74 Disable();
75
76 PIDBase::Reset();
77}
78
79void PIDController::InitSendable(wpi::SendableBuilder& builder) {
80 PIDBase::InitSendable(builder);
81 builder.AddBooleanProperty(
82 "enabled", [=] { return IsEnabled(); },
83 [=](bool value) { SetEnabled(value); });
84}