How to constantly evaluate a loop?

7 Ansichten (letzte 30 Tage)
Sean Dunkelman
Sean Dunkelman am 11 Jun. 2021
Bearbeitet: Adam Danz am 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!

Antworten (1)

Adam Danz
Adam Danz am 11 Jun. 2021
Bearbeitet: Adam Danz am 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 Kommentare
Sean Dunkelman
Sean Dunkelman am 11 Jun. 2021
Thanks Adam! This is pretty much what I was planning on implementing as a backup plan if I wasn't able to figure out a simpler way, but I would be worried about some latency issues as it will be a fairly lengthy program.
Adam Danz
Adam Danz am 11 Jun. 2021
Bearbeitet: Adam Danz am 14 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by