Skip to content

Instantly share code, notes, and snippets.

@Foadsf
Last active February 22, 2019 13:35
Show Gist options
  • Save Foadsf/e1d7ba3bb93a04bb877f83909469f90e to your computer and use it in GitHub Desktop.
Save Foadsf/e1d7ba3bb93a04bb877f83909469f90e to your computer and use it in GitHub Desktop.
An energy/model based controller to minimize overshoot and respoonse time of a mass spring system
function F=FmS(x, xy, v)
K = Fmax * abs(xy - x) + k * (xy^2 - x^2) / 2;
if abs(xy - x) < 1e-6 then
F = k * x;
else
if K > 0 then
vm = sqrt(2 * K / m);
F = Fmax * sign(vm - v);
else
F = Fmax * sign(x - xy);
//F = - Fmax * sign(v);
end
end
endfunction
model Model
//constants
parameter Real m = 1;
parameter Real k = 2;
parameter Real Fmax = 3;
parameter Real x0 = 1;
parameter Real x1 = 2;
parameter Real t1 = 5;
parameter Real v0 = -2;
//variables
Real x, v, a, xy, F, vm, K;
initial equation
x = x0;
v = v0;
equation
v = der(x);
a = der(v);
m * a + k * x = F;
algorithm
if time < t1 then
xy := x0;
else
xy := x1;
end if;
K := Fmax * abs(xy - x) + k * (xy^2 - x^2) / 2;
if abs(xy - x) < 1e-6 then
F := k * x;
if noEvent(K > 0) then
vm := sign(xy - x) * sqrt(2 * K / m);
F := Fmax * sign(vm - v);
else
//F := -Fmax * sign(v);
F := -Fmax * sign(xy - x);
end if;
end if;
annotation(
experiment(StartTime = 0, StopTime = 20, Tolerance = 1e-06, Interval = 0.001),
__OpenModelica_simulationFlags(lv = "LOG_STATS", outputFormat = "mat", s = "euler"));
end Model;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment