MATLAB Answers

How to constantly evaluate a loop?

1 view (last 30 days)
Sean Dunkelman
Sean Dunkelman on 11 Jun 2021
Edited: Adam Danz on 14 Jun 2021
Hi everyone,
I am programming an automated machine and as one of the safety features, there is a sensor that monitors whether or not the doors are closed. In this case, all operations should stop immediately if the doors open. How can I create a feature in my code that constantly evaluates the door sensor and will stop if it trips? My initial thought was a while loop, but since this only evaluates at the beginning of the loop, it doesn't stop the code if the door opens after the cycle has begun.
Thanks!

Answers (1)

Adam Danz
Adam Danz on 11 Jun 2021
Edited: Adam Danz on 11 Jun 2021
> Since this only evaluates at the beginning of the loop, it doesn't stop the code if the door opens after the cycle has begun
Depending on the length and complexity of your loop, you could check the door state many times within the loop using a simple conditional statement. Simply checking the state of a binary variable (true|false, open|closed) takes nanoseconds so you could check this 100s of times within the loop without sacrificing any perceivable amount of time. If the condition is met, use break to exit the loop.
  2 Comments
Adam Danz
Adam Danz on 11 Jun 2021
The loop below contains a condition that tests if the value of flag is false and the test is repeated 1000 times. The entire process for all 1000 tests takes less than 5ms (<0.005 sec). That's 1/3 the time of an average blink, for all 1000 tests.
You might be able to solve this with a listener or perhaps a timer function but it won't be faster than 5ms (for 1000 tests).
flag = true;
tic
for i = 1:1000
if ~flag
% do something
end
end
toc
Elapsed time is 0.004961 seconds.

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by