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
| Syntax | time = millis(); |
|---|---|
| Parameters | None |
| Return | unsigned long: milliseconds since the program started |
| Overflow | The 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
- An Arduino PLC from Industrial Shields, for example an M-Duino 21, an M-Duino 58 or an Ardbox Analog. All the models of the M-Duino Arduino PLC family work.
- The Industrial Shields boards installed in the Arduino IDE: how to install the Industrial Shields boards.
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.