millis() can be use to simulate multi-tasking / threads. millis() returns a unsigned long that will overflow eventually. This code demonstrate how to eliminate this problem.
// ====================================================================== // test millis() overflow // // solution to millis() overflow problem for pseudo threads, etc // // ---------------------------------------------------------------------- // start = millis(); // start of wait interval // while(true) // { // current = millis(); // if (current - start < interval) { continue; } // Serial.print("do your interval thing here"); // start = current; // ignore time doing interval thing // // start = millis(); // skip over time doing interval thing // } // ---------------------------------------------------------------------- // OR // ---------------------------------------------------------------------- // start = millis(); // start of wait interval // while(true) // { // current = millis(); // if (current - start >= interval) // { // Serial.print("do your interval thing here"); // start = current; // ignore time doing interval thing // // start = millis(); // skip over time doing interval thing // } // } // ====================================================================== #define BAUDRATE 19200 // ---------------------------------------------------------------------- // ---- setup // ---------------------------------------------------------------------- void setup() { Serial.begin(BAUDRATE); } // ---------------------------------------------------------------------- // ---- test overflow using unsigned long // ---- (millis() returns unsigned long) // // c = current (simulate millis()) // s = start of interval // i = interval // ---------------------------------------------------------------------- void overflow_test() { int i = 3; // interval unsigned long c = 4294967294; // unsigned long maximum value - 1 unsigned long s = c; // start = current int x = 1; // clock tick counter while(x < 8) // simulate clock ticks { c++; // next current time Serial.println("-------------------------------------------"); Serial.print("interval = "); Serial.println(i); Serial.print("start = "); Serial.println(s); Serial.print("current = "); Serial.println(c); Serial.print("current - start = "); Serial.println(c - s); if (c - s < i) // reached end of interval? { x++; // increment clock tick counter continue; } Serial.println("--- do your interval thing here ---"); s = c; // start = current x++; // increment clock tick counter } } // ---------------------------------------------------------------------- // ---- loop // ---------------------------------------------------------------------- bool dotest = true; void loop() { if(dotest) { overflow_test(); Serial.flush(); dotest = false; } }