Arduino:LCD 不会关闭

Arduino: LCD won't turn off

几天前,我开始使用 Arduino。我用 DHT22 建立了一个小项目来读取温度和湿度并将其写入 LCD。这没有问题。现在我只想在按下按钮时打开 LCD 的背光。这也很有效:

void loop() {

  buttonState = digitalRead(BUTTONPIN);

  currentMillisScreen = millis();
  if (buttonState == HIGH) {
    screenOn = true;
    lcd.backlight();
  }

  // DHT22 related code in here

  if (currentMillisScreen - previousMillisScreen >= SCREEN_ON_TIME) {
    previousMillisScreen = currentMillisScreen;
    screenOn = false;
    lcd.noBacklight();
  }
}

问题在于,使用此代码时,背光不会始终保持恰好 5 秒。我认为将 currentMillisScreen = millis() 放在下面的 if 语句中会修复它:

  if (buttonState == HIGH) {
  currentMillisScreen = millis();
  screenOn = true;
  lcd.backlight();
 }

但如果我这样做,背光将不会再次关闭,我不明白为什么。

您没有在循环中更新 currentMillisScreen,这是您的问题。您只需要找到当前时间(等于 millis())和上一次灯亮起的时间之间的差异,如果它达到阈值以上则将其关闭。像这样:

#define SCREEN_ON_TIME 5000
bool screenOn = false;
void setup()
{
    //setup
}
void loop()
{

    buttonState = digitalRead(BUTTONPIN);

    if (buttonState == HIGH)
    {
        previousMillisScreen = millis();
        lcd.backlight();
        screenOn = true;
    }

    // DHT22 related code in here

    // if time passed above SCREEN_ON_TIME after we turned on light
    if ((screenOn) && (millis() - previousMillisScreen >= SCREEN_ON_TIME))
    {
        lcd.noBacklight();
        screenOn = false;
    }
}