C++ 中布尔值的 NOT 运算符

问题描述 投票:0回答:2

我尝试在我的程序中使用这个 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 语句在循环内是如何工作的,!timer0Fired 的计算结果应该是 1,但是当我打印出来时它是 0,所以当 timer0 超过 间隔 if 语句应该评估为 false,我在 UNO 上尝试过,它有效。

c++ if-statement arduino logical-operators
2个回答
0
投票

!timer0Fired 的计算结果应该为 1,但是当我打印出来时,它是 0

打印时,打印的是“!timer0Fired”还是“timer0Fired”?它会解释输出。

所以当timer0超过间隔时,if语句应该评估 是假的

目前,当timer0超过间隔时,“(timer0>interval)”计算结果为真,反之则不然。是不是很正确?


0
投票

这只是一个基本的编程逻辑。

想象一下您想要数到 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
的值。这样,应用程序几乎总是通过第一个
if
,但仅通过第二个一次。为了优化这一点,您只需交换
if

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 >= 5
timer >= interval
表示

tl;博士
您的代码工作正常。

© www.soinside.com 2019 - 2024. All rights reserved.