필터 지우기
필터 지우기

How to constantly evaluate a loop?

조회 수: 9 (최근 30일)
Sean Dunkelman
Sean Dunkelman 2021년 6월 11일
편집: Adam Danz 2021년 6월 14일
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!

답변 (1개)

Adam Danz
Adam Danz 2021년 6월 11일
편집: Adam Danz 2021년 6월 11일
> 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
Sean Dunkelman
Sean Dunkelman 2021년 6월 11일
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 2021년 6월 11일
편집: Adam Danz 2021년 6월 14일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by