如何在 if 语句中调用 void 函数 (Arduino)

How to call a void function within if statement (Arduino)

我写了一段代码应该执行以下操作:如果我在循环 void btnpress() 中按下一个按钮,程序将被发送到另一个函数 void blink2(),然后一个 LED 会亮起,然后3 秒后 LED 应该熄灭,它也应该通过 btnpress(); 再次 return 到 void btnpress()。 问题是,如果我按下按钮并释放,led 继续并保持无限亮,程序似乎不执行以下最后部分 digitalWrite(LED_BUILTIN, LOW);btnpress();

const int btnpin = 9;
int btnstate = 0;
unsigned long currentTime;
unsigned long previousTime;
const long period = 3000;

// the setup
void setup()
{
    pinMode(LED_BUILTIN, OUTPUT);
    pinMode(btnpin, INPUT);
    Serial.begin(9600);
}

// the loop
void loop()
{
    btnpress();
}

void btnpress()
{
    Serial.println("Press button");
    delay(500);
    btnstate = digitalRead(btnpin);
    if (btnstate == HIGH) {
        previousTime = millis();
        blink2();
    }
}

void blink2()
{
    if (currentTime - previousTime >= period) {
        Serial.println("Led on");
        previousTime = currentTime;
        digitalWrite(LED_BUILTIN, HIGH); // turn the LED on
    }
    else {
        Serial.println("Led off");
        digitalWrite(LED_BUILTIN, LOW);
        btnpress();
    }
}

if I press one button while in loop void btnpress(), the program is sent to another function void blink2(), and then one led goes on and after 3 secs the led should go off, and it should also return to void btnpress() again via btnpress();

根据这个说法,我建议您使用下面的代码来确定您的功能是否按照您的要求工作。

const int btnpin = 9;
int btnstate = 0;
//unsigned long currentTime;
//unsigned long previousTime;
const long period = 3000;

// the setup
void setup()
{
    pinMode(LED_BUILTIN, OUTPUT);
    pinMode(btnpin, INPUT);
    Serial.begin(9600);
}

// the loop
void loop()
{
    btnpress();
}

void btnpress()
{
    Serial.println("Press button");
    delay(500);
    btnstate = digitalRead(btnpin);
    if (btnstate == HIGH) {
       // previousTime = millis();
        blink2();
    }
}

void blink2()
{
        Serial.println("Led on");
        digitalWrite(LED_BUILTIN, HIGH);
        delay(3000);

        Serial.println("Led off");
        digitalWrite(LED_BUILTIN, LOW);
        //btnpress(); It's already inside the Void loop            
}

如果它运行良好,那么函数调用就可以了。 并且“如何在 if 语句(Arduino)中调用 void 函数”没有问题

问题可能出在你的 if 语句中,

if (currentTime - previousTime >= period) {
        Serial.println("Led on");
        previousTime = currentTime;
        digitalWrite(LED_BUILTIN, HIGH); // turn the LED on
    }

这里,currentTime没有定义。