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