blob: 45270fe3f711c3171a2eba28ef73d6fc90a7cb77 [file] [log] [blame]
jerrymf1579332013-02-07 01:56:28 +00001/*----------------------------------------------------------------------------*/
2/* Copyright (c) FIRST 2008. 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 $(WIND_BASE)/WPILib. */
5/*----------------------------------------------------------------------------*/
6
7#include "PIDController.h"
8#include "NetworkCommunication/UsageReporting.h"
9#include "Notifier.h"
10#include "PIDSource.h"
11#include "PIDOutput.h"
12#include <math.h>
13#include "Synchronized.h"
14
15static const char *kP = "p";
16static const char *kI = "i";
17static const char *kD = "d";
18static const char *kF = "f";
19static const char *kSetpoint = "setpoint";
20static const char *kEnabled = "enabled";
21
22
23/**
24 * Allocate a PID object with the given constants for P, I, D
25 * @param Kp the proportional coefficient
26 * @param Ki the integral coefficient
27 * @param Kd the derivative coefficient
28 * @param source The PIDSource object that is used to get values
29 * @param output The PIDOutput object that is set to the output value
30 * @param period the loop time for doing calculations. This particularly effects calculations of the
31 * integral and differental terms. The default is 50ms.
32 */
33PIDController::PIDController(float Kp, float Ki, float Kd,
34 PIDSource *source, PIDOutput *output,
35 float period) :
36 m_semaphore (0)
37{
38 Initialize(Kp, Ki, Kd, 0.0f, source, output, period);
39}
40
41/**
42 * Allocate a PID object with the given constants for P, I, D
43 * @param Kp the proportional coefficient
44 * @param Ki the integral coefficient
45 * @param Kd the derivative coefficient
46 * @param source The PIDSource object that is used to get values
47 * @param output The PIDOutput object that is set to the output value
48 * @param period the loop time for doing calculations. This particularly effects calculations of the
49 * integral and differental terms. The default is 50ms.
50 */
51PIDController::PIDController(float Kp, float Ki, float Kd, float Kf,
52 PIDSource *source, PIDOutput *output,
53 float period) :
54 m_semaphore (0)
55{
56 Initialize(Kp, Ki, Kd, Kf, source, output, period);
57}
58
59
60void PIDController::Initialize(float Kp, float Ki, float Kd, float Kf,
61 PIDSource *source, PIDOutput *output,
62 float period)
63{
64 m_table = NULL;
65
66 m_semaphore = semMCreate(SEM_Q_PRIORITY);
67
68 m_controlLoop = new Notifier(PIDController::CallCalculate, this);
69
70 m_P = Kp;
71 m_I = Ki;
72 m_D = Kd;
73 m_F = Kf;
74
75 m_maximumOutput = 1.0;
76 m_minimumOutput = -1.0;
77
78 m_maximumInput = 0;
79 m_minimumInput = 0;
80
81 m_continuous = false;
82 m_enabled = false;
83 m_setpoint = 0;
84
85 m_prevError = 0;
86 m_totalError = 0;
87 m_tolerance = .05;
88
89 m_result = 0;
90
91 m_pidInput = source;
92 m_pidOutput = output;
93 m_period = period;
94
95 m_controlLoop->StartPeriodic(m_period);
96
97 static INT32 instances = 0;
98 instances++;
99 nUsageReporting::report(nUsageReporting::kResourceType_PIDController, instances);
100
101 m_toleranceType = kNoTolerance;
102}
103
104/**
105 * Free the PID object
106 */
107PIDController::~PIDController()
108{
109 semFlush(m_semaphore);
110 delete m_controlLoop;
111}
112
113/**
114 * Call the Calculate method as a non-static method. This avoids having to prepend
115 * all local variables in that method with the class pointer. This way the "this"
116 * pointer will be set up and class variables can be called more easily.
117 * This method is static and called by the Notifier class.
118 * @param controller the address of the PID controller object to use in the background loop
119 */
120void PIDController::CallCalculate(void *controller)
121{
122 PIDController *control = (PIDController*) controller;
123 control->Calculate();
124}
125
126 /**
127 * Read the input, calculate the output accordingly, and write to the output.
128 * This should only be called by the Notifier indirectly through CallCalculate
129 * and is created during initialization.
130 */
131void PIDController::Calculate()
132{
133 bool enabled;
134 PIDSource *pidInput;
135
136 CRITICAL_REGION(m_semaphore)
137 {
138 if (m_pidInput == 0) return;
139 if (m_pidOutput == 0) return;
140 enabled = m_enabled;
141 pidInput = m_pidInput;
142 }
143 END_REGION;
144
145 if (enabled)
146 {
147 float input = pidInput->PIDGet();
148 float result;
149 PIDOutput *pidOutput;
150
151 {
152 Synchronized sync(m_semaphore);
153 m_error = m_setpoint - input;
154 if (m_continuous)
155 {
156 if (fabs(m_error) > (m_maximumInput - m_minimumInput) / 2)
157 {
158 if (m_error > 0)
159 {
160 m_error = m_error - m_maximumInput + m_minimumInput;
161 }
162 else
163 {
164 m_error = m_error + m_maximumInput - m_minimumInput;
165 }
166 }
167 }
168
169 if(m_I != 0)
170 {
171 double potentialIGain = (m_totalError + m_error) * m_I;
172 if (potentialIGain < m_maximumOutput)
173 {
174 if (potentialIGain > m_minimumOutput)
175 m_totalError += m_error;
176 else
177 m_totalError = m_minimumOutput / m_I;
178 }
179 else
180 {
181 m_totalError = m_maximumOutput / m_I;
182 }
183 }
184
185 m_result = m_P * m_error + m_I * m_totalError + m_D * (m_error - m_prevError) + m_setpoint * m_F;
186 m_prevError = m_error;
187
188 if (m_result > m_maximumOutput) m_result = m_maximumOutput;
189 else if (m_result < m_minimumOutput) m_result = m_minimumOutput;
190
191 pidOutput = m_pidOutput;
192 result = m_result;
193 }
194
195 pidOutput->PIDWrite(result);
196 }
197}
198
199/**
200 * Set the PID Controller gain parameters.
201 * Set the proportional, integral, and differential coefficients.
202 * @param p Proportional coefficient
203 * @param i Integral coefficient
204 * @param d Differential coefficient
205 */
206void PIDController::SetPID(float p, float i, float d)
207{
208 CRITICAL_REGION(m_semaphore)
209 {
210 m_P = p;
211 m_I = i;
212 m_D = d;
213 }
214 END_REGION;
215
216 if (m_table != NULL) {
217 m_table->PutNumber("p", m_P);
218 m_table->PutNumber("i", m_I);
219 m_table->PutNumber("d", m_D);
220 }
221}
222
223/**
224 * Set the PID Controller gain parameters.
225 * Set the proportional, integral, and differential coefficients.
226 * @param p Proportional coefficient
227 * @param i Integral coefficient
228 * @param d Differential coefficient
229 * @param f Feed forward coefficient
230 */
231void PIDController::SetPID(float p, float i, float d, float f)
232{
233 CRITICAL_REGION(m_semaphore)
234 {
235 m_P = p;
236 m_I = i;
237 m_D = d;
238 m_F = f;
239 }
240 END_REGION;
241
242 if (m_table != NULL) {
243 m_table->PutNumber("p", m_P);
244 m_table->PutNumber("i", m_I);
245 m_table->PutNumber("d", m_D);
246 m_table->PutNumber("f", m_F);
247 }
248}
249
250/**
251 * Get the Proportional coefficient
252 * @return proportional coefficient
253 */
254float PIDController::GetP()
255{
256 CRITICAL_REGION(m_semaphore)
257 {
258 return m_P;
259 }
260 END_REGION;
261}
262
263/**
264 * Get the Integral coefficient
265 * @return integral coefficient
266 */
267float PIDController::GetI()
268{
269 CRITICAL_REGION(m_semaphore)
270 {
271 return m_I;
272 }
273 END_REGION;
274}
275
276/**
277 * Get the Differential coefficient
278 * @return differential coefficient
279 */
280float PIDController::GetD()
281{
282 CRITICAL_REGION(m_semaphore)
283 {
284 return m_D;
285 }
286 END_REGION;
287}
288
289/**
290 * Get the Feed forward coefficient
291 * @return Feed forward coefficient
292 */
293float PIDController::GetF()
294{
295 CRITICAL_REGION(m_semaphore)
296 {
297 return m_F;
298 }
299 END_REGION;
300}
301
302/**
303 * Return the current PID result
304 * This is always centered on zero and constrained the the max and min outs
305 * @return the latest calculated output
306 */
307float PIDController::Get()
308{
309 float result;
310 CRITICAL_REGION(m_semaphore)
311 {
312 result = m_result;
313 }
314 END_REGION;
315 return result;
316}
317
318/**
319 * Set the PID controller to consider the input to be continuous,
320 * Rather then using the max and min in as constraints, it considers them to
321 * be the same point and automatically calculates the shortest route to
322 * the setpoint.
323 * @param continuous Set to true turns on continuous, false turns off continuous
324 */
325void PIDController::SetContinuous(bool continuous)
326{
327 CRITICAL_REGION(m_semaphore)
328 {
329 m_continuous = continuous;
330 }
331 END_REGION;
332
333}
334
335/**
336 * Sets the maximum and minimum values expected from the input.
337 *
338 * @param minimumInput the minimum value expected from the input
339 * @param maximumInput the maximum value expected from the output
340 */
341void PIDController::SetInputRange(float minimumInput, float maximumInput)
342{
343 CRITICAL_REGION(m_semaphore)
344 {
345 m_minimumInput = minimumInput;
346 m_maximumInput = maximumInput;
347 }
348 END_REGION;
349
350 SetSetpoint(m_setpoint);
351}
352
353/**
354 * Sets the minimum and maximum values to write.
355 *
356 * @param minimumOutput the minimum value to write to the output
357 * @param maximumOutput the maximum value to write to the output
358 */
359void PIDController::SetOutputRange(float minimumOutput, float maximumOutput)
360{
361 CRITICAL_REGION(m_semaphore)
362 {
363 m_minimumOutput = minimumOutput;
364 m_maximumOutput = maximumOutput;
365 }
366 END_REGION;
367}
368
369/**
370 * Set the setpoint for the PIDController
371 * @param setpoint the desired setpoint
372 */
373void PIDController::SetSetpoint(float setpoint)
374{
375 CRITICAL_REGION(m_semaphore)
376 {
377 if (m_maximumInput > m_minimumInput)
378 {
379 if (setpoint > m_maximumInput)
380 m_setpoint = m_maximumInput;
381 else if (setpoint < m_minimumInput)
382 m_setpoint = m_minimumInput;
383 else
384 m_setpoint = setpoint;
385 }
386 else
387 {
388 m_setpoint = setpoint;
389 }
390 }
391 END_REGION;
392
393 if (m_table != NULL) {
394 m_table->PutNumber("setpoint", m_setpoint);
395 }
396}
397
398/**
399 * Returns the current setpoint of the PIDController
400 * @return the current setpoint
401 */
402float PIDController::GetSetpoint()
403{
404 float setpoint;
405 CRITICAL_REGION(m_semaphore)
406 {
407 setpoint = m_setpoint;
408 }
409 END_REGION;
410 return setpoint;
411}
412
413/**
414 * Retruns the current difference of the input from the setpoint
415 * @return the current error
416 */
417float PIDController::GetError()
418{
419 float error;
420 CRITICAL_REGION(m_semaphore)
421 {
422 error = m_setpoint - m_pidInput->PIDGet();
423 }
424 END_REGION;
425 return error;
426}
427
428/*
429 * Set the percentage error which is considered tolerable for use with
430 * OnTarget.
431 * @param percentage error which is tolerable
432 */
433void PIDController::SetTolerance(float percent)
434{
435 CRITICAL_REGION(m_semaphore)
436 {
437 m_toleranceType = kPercentTolerance;
438 m_tolerance = percent;
439 }
440 END_REGION;
441}
442
443/*
444 * Set the percentage error which is considered tolerable for use with
445 * OnTarget.
446 * @param percentage error which is tolerable
447 */
448void PIDController::SetPercentTolerance(float percent)
449{
450 CRITICAL_REGION(m_semaphore)
451 {
452 m_toleranceType = kPercentTolerance;
453 m_tolerance = percent;
454 }
455 END_REGION;
456}
457
458/*
459 * Set the absolute error which is considered tolerable for use with
460 * OnTarget.
461 * @param percentage error which is tolerable
462 */
463void PIDController::SetAbsoluteTolerance(float absTolerance)
464{
465 CRITICAL_REGION(m_semaphore)
466 {
467 m_toleranceType = kAbsoluteTolerance;
468 m_tolerance = absTolerance;
469 }
470 END_REGION;
471}
472
473/*
474 * Return true if the error is within the percentage of the total input range,
475 * determined by SetTolerance. This asssumes that the maximum and minimum input
476 * were set using SetInput.
477 * Currently this just reports on target as the actual value passes through the setpoint.
478 * Ideally it should be based on being within the tolerance for some period of time.
479 */
480bool PIDController::OnTarget()
481{
482 bool temp;
483 CRITICAL_REGION(m_semaphore)
484 {
485 switch (m_toleranceType) {
486 case kPercentTolerance:
487 temp = fabs(GetError()) < (m_tolerance / 100 * (m_maximumInput - m_minimumInput));
488 break;
489 case kAbsoluteTolerance:
490 temp = fabs(GetError()) < m_tolerance;
491 break;
492 //TODO: this case needs an error
493 case kNoTolerance:
494 temp = false;
495 }
496 }
497 END_REGION;
498 return temp;
499}
500
501/**
502 * Begin running the PIDController
503 */
504void PIDController::Enable()
505{
506 CRITICAL_REGION(m_semaphore)
507 {
508 m_enabled = true;
509 }
510 END_REGION;
511
512 if (m_table != NULL) {
513 m_table->PutBoolean("enabled", true);
514 }
515}
516
517/**
518 * Stop running the PIDController, this sets the output to zero before stopping.
519 */
520void PIDController::Disable()
521{
522 CRITICAL_REGION(m_semaphore)
523 {
524 m_pidOutput->PIDWrite(0);
525 m_enabled = false;
526 }
527 END_REGION;
528
529 if (m_table != NULL) {
530 m_table->PutBoolean("enabled", false);
531 }
532}
533
534/**
535 * Return true if PIDController is enabled.
536 */
537bool PIDController::IsEnabled()
538{
539 bool enabled;
540 CRITICAL_REGION(m_semaphore)
541 {
542 enabled = m_enabled;
543 }
544 END_REGION;
545 return enabled;
546}
547
548/**
549 * Reset the previous error,, the integral term, and disable the controller.
550 */
551void PIDController::Reset()
552{
553 Disable();
554
555 CRITICAL_REGION(m_semaphore)
556 {
557 m_prevError = 0;
558 m_totalError = 0;
559 m_result = 0;
560 }
561 END_REGION;
562}
563
564std::string PIDController::GetSmartDashboardType(){
565 return "PIDController";
566}
567
568void PIDController::InitTable(ITable* table){
569 if(m_table!=NULL)
570 m_table->RemoveTableListener(this);
571 m_table = table;
572 if(m_table!=NULL){
573 m_table->PutNumber(kP, GetP());
574 m_table->PutNumber(kI, GetI());
575 m_table->PutNumber(kD, GetD());
576 m_table->PutNumber(kF, GetF());
577 m_table->PutNumber(kSetpoint, GetSetpoint());
578 m_table->PutBoolean(kEnabled, IsEnabled());
579 m_table->AddTableListener(this, false);
580 }
581}
582
583ITable* PIDController::GetTable(){
584 return m_table;
585}
586
587void PIDController::ValueChanged(ITable* source, const std::string& key, EntryValue value, bool isNew){
588 if (key==kP || key==kI || key==kD || key==kF) {
589 if (m_P != m_table->GetNumber(kP) || m_I != m_table->GetNumber(kI) || m_D != m_table->GetNumber(kD) || m_F != m_table->GetNumber(kF) ) {
590 SetPID(m_table->GetNumber(kP, 0.0), m_table->GetNumber(kI, 0.0), m_table->GetNumber(kD, 0.0), m_table->GetNumber(kF, 0.0));
591 }
592 } else if (key==kSetpoint && m_setpoint != value.f) {
593 SetSetpoint(value.f);
594 } else if (key==kEnabled && m_enabled != value.b) {
595 if (value.b) {
596 Enable();
597 } else {
598 Disable();
599 }
600 }
601}
602
603void PIDController::UpdateTable() {
604
605}
606
607void PIDController::StartLiveWindowMode() {
608 Disable();
609}
610
611void PIDController::StopLiveWindowMode() {
612
613}