Bang Bang
Bang Bang Controllers
A Bang Bang Controller is a type of controller that decreases the amount of time it takes to reach the target speed by running motors at maximum power until they reach a certain threshold, after which it lapses control back to a PID loop.
One-directional bang-bang controller
The following code is an example of a one-directional bang-bang controller that returns 127 when the current velocity is less than the threshold and returns the result of the PID calculation when the current velocity lies above the threshold.
1
2
3
4
5
6
7
8
9
float one_directional_bang_bang(float current_value, float threshold, float target_value) {
if(current_value<threshold) {
return 127;
}
else {
//assuming calculate(float current_value, float target_value) is a function that returns the pid calculation for a sensor reading.
return calculate(current_value, target_value);
}
}
Two-directional bang-bang controller
An improvement over a one-directional controller is a two-directional controller; this will return control over the motor voltages to the bang-bang function whenever the abs(target-current) is greater than the threshold.
The most important advantage of a 2d bang_bang is that it decreases the time taken to return to the target when the current value is greater than said target.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//returns the sign of the input value
float signbit(float value) {
return (value > 0) - (value < 0);
}
float two_directional_bang_bang(float current_value, float threshold, float target_value) {
float error = target_value - current_value;
if(abs(error)>threshold) {
return sgn(error)*127;
}
else {
//assuming calculate(float current_value, float target_value) is a function that returns the pid calculation for a sensor reading.
return calculate(current_value, target_value);
}
}
The 2 direction bang bang controller returns either + or - 127 (when active) depending on whether the error is positive or negative.