/ src / hal / components / limit2.comp
limit2.comp
 1  component limit2 "Limit the output signal to fall between min and max and limit its slew rate to less than maxv per second.  When the signal is a position, this means that position and velocity are limited.";
 2  pin in float in;
 3  pin out float out;
 4  pin in bit load "When TRUE, immediately set \\fBout\\fB to \\fBin\\fR, ignoring maxv";
 5  pin in float min_=-1e20;
 6  pin in float max_=1e20;
 7  pin in float maxv=1e20;
 8  option data limit2_data;
 9  function _;
10  license "GPL";
11  ;;
12  
13  typedef struct { double old_out; } limit2_data;
14  
15  #ifndef clamp
16  static inline double clamp(double v, double sub, double sup) {
17      if(v < sub) return sub;
18      if(v > sup) return sup;
19      return v;
20  }
21  #endif
22  
23  FUNCTION(_) {
24      double tmp = in;
25      double maxdelta = maxv * fperiod;
26      tmp = clamp(tmp, min_, max_);
27      if(load) { out = data.old_out = tmp; return; }
28      tmp = clamp(tmp, data.old_out - maxdelta, data.old_out + maxdelta);
29      data.old_out = tmp;
30      out = tmp;
31  }