arduino-audio-tools
Loading...
Searching...
No Matches
PIDController.h
Go to the documentation of this file.
1
2
3#include <cmath>
4
5#pragma once
6
7namespace 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 bool begin(float dt, float max, float min, float kp, float ki, float kd) {
24 this->dt = dt;
25 this->max = max;
26 this->min = min;
27 this->kp = kp;
28 this->kd = kd;
29 this->ki = ki;
30 return true;
31 }
32
35 void setDt(float dt) { this->dt = dt; }
36
41 void reset() {
42 integral = 0.0f;
43 preerror = 0.0f;
44 }
45
46 // target = desired process value
47 // measured = current process value:
48 // returns new process value
49 float calculate(float target, float measured) {
50 // Calculate errori
51 float error = target - measured;
52
53 // Proportional term
54 float pout = kp * error;
55
56 // Interal term
57 integral += error * dt;
58 float Iout = ki * integral;
59
60 // Derivative term
61 assert(dt != 0.0);
62
63 float derivative = (error - preerror) / dt;
64 float dout = kd * derivative;
65
66 // Calculate total output
67 float output = pout + Iout + dout;
68
69 // Restrict to max/min
70 if (output > max)
71 output = max;
72 else if (output < min)
73 output = min;
74
75 // Save error to previous error
76 preerror = error;
77
78 return output;
79 }
80
81 protected:
82 float dt = 1.0f;
83 float max = 0.0f;
84 float min = 0.0f;
85 float kp = 0.0f;
86 float kd = 0.0f;
87 float ki = 0.0f;
88 float preerror = 0.0f;
89 float integral = 0.0f;
90
91}; // namespace audiotools
92
93} // namespace audio_tools
#define assert(T)
Definition avr.h:10
A simple header only PID Controller.
Definition PIDController.h:15
float ki
Definition PIDController.h:87
float calculate(float target, float measured)
Definition PIDController.h:49
float integral
Definition PIDController.h:89
void setDt(float dt)
Definition PIDController.h:35
float kp
Definition PIDController.h:85
float max
Definition PIDController.h:83
float preerror
Definition PIDController.h:88
float dt
Definition PIDController.h:82
void reset()
Definition PIDController.h:41
float min
Definition PIDController.h:84
float kd
Definition PIDController.h:86
bool begin(float dt, float max, float min, float kp, float ki, float kd)
Definition PIDController.h:23
Generic Implementation of sound input and output for desktop environments using portaudio.
Definition LMSEchoCancellationStream.h:6