我试图在我的程序中使用此Arduino代码,LED将停留在5秒,然后自行关闭
#include <elapsedMillis.h>
int led = 13 ;
elapsedMillis timer0 ;
#define interval 5000
boolean timer0Fired ;
// the setup routine runs once when you press reset:
void setup()
{
pinMode(led, OUTPUT);
digitalWrite(led, HIGH);
timer0Fired = false;
timer0 = 0; // clear the timer at the end of startup
}
void loop()
{
if ((!timer0Fired) && (timer0 > interval))
{
timer0Fired = true; // don't execute this again
digitalWrite(led, LOW); // turn led off after 5 sec
}
}
字符串
我不明白if语句在循环中是如何工作的,!timer 0 Fired应该计算为1,但当我打印出来时,它是0,所以当timer 0超过间隔时,if语句应该计算为false,我在UNO上尝试了它,它工作了。
2条答案
按热度按时间ljsrvy3e1#
!timer 0 Fired的计算结果应该是1,但当我打印出来时,它是0
当你打印它的时候,你是打印“!timer 0 Fired”还是“timer 0 Fired”?这将解释输出。
因此,当timer 0超过间隔时,if语句的计算结果应该为false
目前,“(timer 0> interval)”在timer 0超过interval时计算为true,而不是相反。这不是正确的吗?
wqlqzqxt2#
这只是一个基本的编程逻辑。
想象一下,你想数到5,并在无限循环中调用某个函数,例如
DoSomething
。字符串
从某种意义上说,这可能看起来毫无意义。就等着吧...
然而,你面临的问题是,你没有一个像我的
count
这样简单的计数器,而是使用了一个可能会延迟几毫秒的计时器,即使它迟到了,你仍然希望代码执行。举例来说,您可以:
型
现在,这完全反转了
if
s的值。这样,应用程序几乎总是传递第一个if
,但第二个只传递一次。为了优化这一点,你可以交换if
s:型
现在,您可能已经知道,这些嵌套的
if
语句可以使用&&
操作符轻松地组合成一个。此外,called == false
可以通过使用!called
变得不那么冗长。这最终会导致型
所以现在的情况是:
a)你想只执行一段代码一次
bool called = false; if (!called) called = true;
逻辑或timer0fired
表示B)您希望延迟呼叫,直到某个计时器达到某个数量
count >= 5
或timer >= interval
表示**tl;dr
您的代码运行正常。**