arduino-audio-tools
PIDController.h
1 
2 
3 #include <cmath>
4 
5 #pragma once
6 
7 namespace audio_tools {
8 
16 public:
17  // dt - loop interval time
18  // max - maximum value of manipulated variable
19  // min - minimum value of manipulated variable
20  // kp - proportional gain
21  // ki - Integral gain
22  // kd - derivative gain
23  void begin(float dt, float max, float min, float kp, float kd,
24  float ki) {
25  this->dt = dt;
26  this->max = max;
27  this->min = min;
28  this->kp = kp;
29  this->kd = kd;
30  this->ki = ki;
31  }
32 
33 
34  // setpoint = desired process value
35  // pv = current process value: return new process value
36  float calculate(float target, float measured) {
37 
38  // Calculate errori
39  float error = target - measured;
40 
41  // Proportional term
42  float pout = kp * error;
43 
44  // Interal term
45  integral += error * dt;
46  float Iout = ki * integral;
47 
48  // Derivative term
49  assert(dt!=0.0);
50 
51  float derivative = (error - preerror) / dt;
52  float dout = kd * derivative;
53 
54  // Calculate total output
55  float output = pout + Iout + dout;
56 
57  // Restrict to max/min
58  if (output > max)
59  output = max;
60  else if (output < min)
61  output = min;
62 
63  // Save error to previous error
64  preerror = error;
65 
66  return output;
67  }
68 
69 protected:
70  float dt = 1.0f;
71  float max = 0.0f;
72  float min = 0.0f;
73  float kp = 0.0f;
74  float kd = 0.0f;
75  float ki = 0.0f;
76  float preerror = 0.0f;
77  float integral = 0.0f;
78 
79 }; // namespace audiotools
80 
81 } // namespace audiotools
A simple header only PID Controller.
Definition: PIDController.h:15
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition: AudioConfig.h:859