MATLAB: Hold True Value for finite length of time

finiteholdsimulinktrue

I am fairly new to matlab and have been getting to grips with it over the past month so excuse me if I missed something very obvious.
I am using a relational operator that will output a true value (1) when the input single goes beyond a certain range. What I require is that when the input single goes beyond this certain range and the output single becomes true, to hold this true value (e.g. the constant one) for a period of time e.g. 10 seconds.
I have been trying to use enabled subsystems, switches and zero hold blocks but with little success.
Any help would be much appreciated.
Modeling using Simulink

Best Answer

The easiest solution is using Stateflow: create two states off and on, transition from off to on when the signal is tripped, then return to off using 'after(10,sec)'.
In Simulink it's a little more complicated, but basically you can have an enabled subsystem with a constant one going into an integrator going into a compare to constant block set to less than or equal to -1. That will stay on for 10 seconds once the enable port is on. Then the trick is to latch the enable signal so it will stay on as long as necessary. You can use a relay block for that, but you'll need to feed the output of the enabled subsystem back and add it to the initial signal in order to reset the relay after 10 seconds have passed.
Or use a MATLAB Function block set to a discrete sample time of 0.1 with the following code:
function y = fcn(u)
%#codegen
persistent tick started
if isempty(tick)
tick = 0;
started = 0;
end
y=0;
if u == 1
started = 1;
end
if started
if tick<100
tick=tick+1;
y = 1;
else
tick = 0;
started = 0;
end
end
Related Question