Skip to Content

How to measure time on an Arduino PLC with millis()

December 10, 2018 by
How to measure time on an Arduino PLC with millis()
Alejandro Jabalquinto

millis() returns the number of milliseconds since the Arduino PLC started running the current program, as an unsigned long. Compare two readings to measure time or to run actions at regular intervals without stopping the program with delay().

This function is very useful when you want to control a process by comparing times: timeouts, periodic readings, outputs that switch on and off, and several tasks in the same loop.

The millis() function

Syntaxtime = millis();
ParametersNone
Returnunsigned long: milliseconds since the program started
OverflowThe value goes back to 0 after about 49.7 days (232 ms)

The overflow is not a problem if you always compare times with a subtraction, millis() - start >= interval, and store them in unsigned long variables. The unsigned subtraction gives the right result even when the counter has gone back to 0.

Requirements

Example: blink a digital output every second

This example switches the digital output Q0.0 on and off every second with millis(). The loop never stops, so the program can do other tasks between changes.

unsigned long actualtime = 0;
unsigned long beforetime = 0;
unsigned long deltatime = 1000;  // 1000 ms = 1 s
bool laststate = true;

void setup() {
  Serial.begin(9600);
  pinMode(Q0_0, OUTPUT);
}

void loop() {
  // Save the current time (ms since the program started)
  actualtime = millis();
  // Check if one second has passed
  if (actualtime - beforetime >= deltatime) {
    if (laststate) {
      // Digital output Q0.0 HIGH
      digitalWrite(Q0_0, HIGH);
      laststate = false;
    }
    else {
      // Digital output Q0.0 LOW
      digitalWrite(Q0_0, LOW);
      laststate = true;
    }
    // Save the time of this change, in milliseconds
    beforetime = actualtime;
  }
}

deltatime is the interval in milliseconds. Each time the difference between the current time and beforetime reaches 1000 ms, the output changes state and beforetime stores the time of the change. Q0.0 is a digital output on M-Duino Arduino PLCs; on another model, use a digital output of your PLC.

The example compiles for the M-Duino 21, the M-Duino 21+ and the M-Duino 58+ with the Industrial Shields AVR boards package 1.2.1.

​Search in our Blog

How to measure time on an Arduino PLC with millis()
Alejandro Jabalquinto December 10, 2018
Share this post

Looking for your ideal Programmable Logic Controller?

Take a look at this product comparison with other industrial controllers Arduino-based. 

We are comparing inputs, outputs, communications and other features with the ones of the relevant brands.

PLC Comparison