Advertisement
markruff

Arduino timer clock modulus delay

Jan 19th, 2016
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. /*
  2.  * Testing how much a modulus operation can delay time based
  3.  * operation of Arduino.
  4.  *
  5.  * Modulus is slow, so including it in calculations using
  6.  * millis() prior to setting your prevMillis = millis() for
  7.  * incremental time keeping can slow things down
  8.  *
  9.  * // The wrong way
  10.  * something = (millis() - prevMillis) % something_else;
  11.  * // long operation happend before we set prevMillis... DELAY
  12.  * prevMillis = millis();
  13.  
  14.  * // The right way
  15.  * increment = millis() - prevMillis;
  16.  * prevMillis = millis();
  17.  * // long operation happens after we have set prevMillis
  18.  * something = increment % something_else;
  19.  *
  20.  * The times I get in my code are:
  21.  *  with % operation: 1332ms
  22.  *  sans % operation: 165ms
  23.  */
  24.  
  25. unsigned long int millisSinceStart = 0;
  26. unsigned long int prevMillis = 0;
  27.  
  28. void setup() {
  29.   Serial.begin(9600);
  30. }
  31.  
  32. void loop() {
  33.  
  34.   unsigned long int start = millis();
  35.   unsigned long int finish;
  36.  
  37.   // Caculate how many milliseconds since Arduino was reset
  38.   // rolling over every 24 hours (used in clock program)
  39.   for (int i = 0 ; i < 32000 ; i++ ) {  
  40.     millisSinceStart =
  41.       (millisSinceStart + millis() - prevMillis) % 86400000;
  42.     prevMillis = millis();
  43.   }
  44.   finish = millis();
  45.  
  46.  
  47.   Serial.print("Calculation with % operation: ");
  48.   Serial.println(finish - start);
  49.  
  50.   // Same without modulus operation (no rollover - will last
  51.   // for 49.5 days then rollover to 0.
  52.   start = millis();
  53.  
  54.   for (int i = 0 ; i < 32000 ; i++ ) {  
  55.     millisSinceStart =
  56.       (millisSinceStart + millis() - prevMillis);
  57.     prevMillis = millis();
  58.   }
  59.   finish = millis();
  60.  
  61.   Serial.print("Calculation sans % operation: ");
  62.   Serial.println(finish - start);
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement