DokanBoy

Untitled

Oct 27th, 2020
684
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #define DEFAULT_MONITOR_SPEED 115200
  2.  
  3. #define MISCORS_IN_MILLIS 1000
  4. #define MILLIS_IN_SEC 1000
  5. #define SECS_IN_MIN 60
  6. #define MINS_IN_HOUR 60
  7. #define HOURS_IN_DAY 24
  8.  
  9. #include <Arduino.h>
  10. #include <string.h>
  11. #include <math.h>
  12.  
  13. struct Time
  14. {
  15.   unsigned short int days;
  16.   byte hours;
  17.   byte mins;
  18.   byte secs;
  19.   unsigned short int millis;
  20. };
  21.  
  22. void tickTime(Time &time);
  23. String getFormattedTime(Time &time);
  24.  
  25. Time time = {0, 0, 0, 0, 0};
  26. Time oldTime = time;
  27. unsigned long usTime;
  28.  
  29. void setup()
  30. {
  31.   Serial.begin(DEFAULT_MONITOR_SPEED);
  32.   usTime = micros();
  33. }
  34.  
  35. void loop()
  36. {
  37.   unsigned long currTime = micros();
  38.   if (abs(currTime - usTime) >= MISCORS_IN_MILLIS)
  39.   {
  40.     tickTime(time);
  41.     usTime = currTime;
  42.   }
  43.  
  44.   if (oldTime.secs != time.secs)
  45.   {
  46.     Serial.println(getFormattedTime(time));
  47.     oldTime = time;
  48.   }
  49. }
  50.  
  51. void tickTime(Time &time)
  52. {
  53.   time.millis += 1;
  54.  
  55.   // in range [0..24]
  56.   if (time.hours >= (HOURS_IN_DAY - 1))
  57.   {
  58.     time.hours -= HOURS_IN_DAY - 1;
  59.     time.days += 1;
  60.   }
  61.  
  62.   // in range [0..59]
  63.   if (time.mins >= (MINS_IN_HOUR - 1))
  64.   {
  65.     time.mins -= MINS_IN_HOUR - 1;
  66.     time.hours += 1;
  67.   }
  68.  
  69.   // in range [0..59]
  70.   if (time.secs >= (SECS_IN_MIN - 1))
  71.   {
  72.     time.secs -= SECS_IN_MIN - 1;
  73.     time.mins += 1;
  74.   }
  75.  
  76.   // in range [0..999]
  77.   if (time.millis >= (MILLIS_IN_SEC - 1))
  78.   {
  79.     time.millis -= MILLIS_IN_SEC - 1;
  80.     time.secs += 1;
  81.   }
  82. }
  83.  
  84. String getFormattedTime(Time &time)
  85. {
  86.   String formattedTime = "Timer: ";
  87.   formattedTime.concat(time.days);
  88.   formattedTime.concat("d : ");
  89.   formattedTime.concat(time.hours);
  90.   formattedTime.concat("h : ");
  91.   formattedTime.concat(time.mins);
  92.   formattedTime.concat("m : ");
  93.   formattedTime.concat(time.secs);
  94.   formattedTime.concat("s. ");
  95.   formattedTime.concat("System timer value: ");
  96.   formattedTime.concat(usTime);
  97.   formattedTime.concat("us");
  98.  
  99.   return formattedTime;
  100. }
  101.  
RAW Paste Data