Data type byte and millis() together

I have written a short program.

unsigned long current_time = 0;
unsigned long previous_time = 0;
byte time_interval = 30000;

void setup() {
  Serial.begin(9600);
}

void loop() {
  current_time = millis();
   if ( current_time - previous_time > time_interval)
   {
    Serial.println("I am in if section");
    previous_time = current_time;
   }

Problem: if i set the data type of time_intervial variable to byte, then it comes right after 2 to 3 seconds into if block. It was supposed to come into if block after 30s.
If i set the data type of time_interval variable to int, then everything is fine. Whats wrong with byte data type???

thank you

Please, reread

1 Like

When in doubt, rtfm:

image

@kangaroodle @anon73444976

It was just my silly mistake, although i was familiar with the byte that it is 8 bits data type. I wasted my 2h :slight_smile:

Can you make that a ">="

if ( current_time - previous_time >= time_interval)

Use "unsigned long" for the "time_interval" as well, that is nicer, even if there is no need for it.

Not at all, you just spent 2 hours learning two things:

  1. The capacity of a byte
  2. The need to research data types when they lead to unexpected behavior.

Also:

// this
previous_time = current_time;

// should be this
previous_time += time_interval;

This keeps your timing more consistent as it ignores however long it takes to run the code between.

This is safer. The timing will be delayed when the sketch is very busy, but the sketch does not clog up when delays are combined with millis. It is the right choice to blink a led and for a beginner:

previous_time = current_time;

This keeps the timing in sync with time. Use it only when needed, for example for a clock:

previous_time += time_interval;

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.