Millis() Value Random

I’m working on building a clock with my UNO but have run into a problem while using Millis(), my clock’s timing is completely controlled by Millis() while printing the values it was counting up and then went all over the place, here’s a Pastebin of the Serial Monitor https://pastebin.com/0V2FDqVd

Here’s my code

#include <math.h>

#define yellow 6
#define green 5
#define red 4
#define blue 3

/*
Every 30 Seconds green light turns on  | 30000 milliseconds
Every 60 Seconds yellow light turns on | 60000 milliseconds
Every 10 Minutes red light turns on    | 600000 milliseconds
Every 60 Minutes blue light turns on   | 3600000 milliseconds
*/
unsigned long Mil = millis();
unsigned long Mil0;
unsigned long time0=Mil, time1=Mil, time2=Mil, time3=Mil;

bool is_Delay = false;
int milRound;


void setup() {
  Serial.begin(9600);
  while(!Serial);
  pinMode(blue,OUTPUT);
  pinMode(red,OUTPUT);
  pinMode(green,OUTPUT);
  pinMode(yellow,OUTPUT);
}

void loop() {
  if(is_Delay==false){
    Mil=millis();
    //Serial.println("is_Delay=False \n");
  } else {
    Mil=millis()-1000;
    //Serial.println("is_Delay=True");  
  }
  milRound = Mil/1000;
  milRound = floor(milRound);
  Mil = milRound*1000; 
  Serial.print("Mil = "); 
    Serial.println(Mil); 
  /* Prints Seconds
  if (TestTime+1000==Mil){
     Serial.print(Mil/1000);
     Serial.println(" Seconds"); 
     TestTime=Mil; 
  }*/
  
  if (time0+30000==Mil){
        Serial.println("Green, 30 Seconds");        
        digitalWrite(green,HIGH);
        time0=Mil;
  }
  if (time1+60000==Mil){
        Serial.println("Yellow,1 Minute");        
        digitalWrite(yellow,HIGH);          
        time1=Mil;
  }
  if (time2+600000==Mil){
        Serial.println("Red, 10 Minutes");        
        digitalWrite(red,HIGH);
        time2=Mil;
  }
  if (time3+3600000==Mil){
        Serial.println("Blue, Hour");        
        digitalWrite(blue,HIGH);
        time3=Mil;
  } 
  delay(1000);
  is_Delay = true;
  digitalWrite(blue,LOW); 
  digitalWrite(red,LOW);
  digitalWrite(yellow,LOW); 
  digitalWrite(green,LOW);   
}

Here’s your problem.
delay(1000);

millis is always incrementing so looking for an exact match like
time2+600000==Mil will be random. Millis is updating during the delay().

1 Like

Just solved the problem, if anyone else is having this the Int needs to be a Double/Float to do the Floor() function

Hi,
I tested it here using an arduino and the error replicated itself.
I defined this line:
int milRound;
as
unsigned long milRound;
and it worked correctly.

RV mineirin