C++中的NOT运算符

wwtsj6pe  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(129)

我试图在我的程序中使用此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上尝试了它,它工作了。

ljsrvy3e

ljsrvy3e1#

!timer 0 Fired的计算结果应该是1,但当我打印出来时,它是0
当你打印它的时候,你是打印“!timer 0 Fired”还是“timer 0 Fired”?这将解释输出。
因此,当timer 0超过间隔时,if语句的计算结果应该为false
目前,“(timer 0> interval)”在timer 0超过interval时计算为true,而不是相反。这不是正确的吗?

wqlqzqxt

wqlqzqxt2#

这只是一个基本的编程逻辑。
想象一下,你想数到5,并在无限循环中调用某个函数,例如DoSomething

int count = 0;
bool called = false; // DoSomething not called yet

while (true) // main loop
{
    ++count;

    if (count == 5)
    {
        // the count is 5
        if (called == false)
        {
            // function not called yet, call it!
            called = true;
            DoSomething();
        }
    }
}

字符串
从某种意义上说,这可能看起来毫无意义。就等着吧...
然而,你面临的问题是,你没有一个像我的count这样简单的计数器,而是使用了一个可能会延迟几毫秒的计时器,即使它迟到了,你仍然希望代码执行。
举例来说,您可以:

int count = 0;
bool called = false; // DoSomething not called yet

while (true) // main loop
{
    count += 2; // emulate counter being late

    if (count >= 5) // note that count == 5 will be always false here...
    {
        // the count is 5 or more
        if (called == false)
        {
            // function not called yet, call it!
            called = true;
            DoSomething();
        }
    }
}


现在,这完全反转了if s的值。这样,应用程序几乎总是传递第一个if,但第二个只传递一次。为了优化这一点,你可以交换if s:

if (called == false)
{
    if (count >= 5)
    {
        called = true;
        DoSomething();
    }
}


现在,您可能已经知道,这些嵌套的if语句可以使用&&操作符轻松地组合成一个。此外,called == false可以通过使用!called变得不那么冗长。这最终会导致

while (true) // main loop
{
    count += 2; // emulate counter being late

    if (!called && count >= 5)
    {
        // function not called yet and count is already 5 or more
        called = true;
        DoSomething();
    }
}


所以现在的情况是:
a)你想只执行一段代码一次

  • 在代码中用bool called = false; if (!called) called = true;逻辑或timer0fired表示
    B)您希望延迟呼叫,直到某个计时器达到某个数量
  • 在示例中用count >= 5timer >= interval表示

**tl;dr

您的代码运行正常。**

相关问题