Search code examples
arduinoarduino-unoarduino-idearduino-c++

How to reset a millis() variable back to zero


So the Code is:

#include <LiquidCrystal.h>

int sec = 0;
int mts = 0;
int hrs = 0;

LiquidCrystal lcd(4, 6, 10, 11, 12, 13);

void setup() {
  lcd.begin(16, 2);
}

void loop() {
  sec = millis() / 1000;
  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("Seconds:");
  lcd.setCursor(11, 0);
  lcd.print(sec);
  lcd.setCursor(9, 1);
  lcd.print("Mnt:");
  if (sec >= 59) {
    sec = 0;
    mts = mts + 1;
    lcd.setCursor(13, 1);
    lcd.print(mts);
  } else {
    lcd.setCursor(13,1);
    lcd.print(mts);
  }
  delay(1000)
}

The problem is i can't reset the sec variable to zero,

I have tried many ways but all of them failed.

Is there a way to make it start counting back to start


Solution

  • Your code is not working because the millis is updating the sec variable.

    After the sec reaches the 59 value, your if statement changes the sec to 0. However the millis will again put the latest time value i.e. 60 and lcd.print(sec) will print it. And the cycles continues, without ever resetting the sec value because millis is updating it.

    One more thing, don't use delay(1000) to stop the controller for 1 second, You need make use of the sole purpose of the millis i.e. to avoid delays.

    Here is your solution:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(4, 6, 10, 11, 12, 13);
    long previousMillis = 0;
    unsigned long sec = 0;
    unsigned long mts = 0;
    unsigned long hrs = 0;
    
    void setup() {
        lcd.begin(16, 2);
    }
    
    void loop() {
        unsigned long currentMillis = millis();
        if(currentMillis - previousMillis > 1000) {
            previousMillis = currentMillis;   
            sec +=1;
            lcd.clear();
            lcd.setCursor(3, 0);
            lcd.print("Seconds:");
            lcd.setCursor(11, 0);
            lcd.print(sec);
            lcd.setCursor(7, 1);
            lcd.print("Mnt:");
            if (sec >= 59) {
                sec = 0;
                mts +=1;
            }
            lcd.setCursor(11,1);
            lcd.print(mts);
            }  
        }
    }