How to constantly evaluate a loop?
2 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(1 个)
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 个评论
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!