-1

I’m brainstorming a project using Arduino. I want to write a function that I can run at anytime and when it runs, it simply counts how many days it’s been running since I ran it.

For example, if I run it at 9:50 AM today (Friday), the count should be 3 days on Monday at 9:50 AM.

I then what to take that number (3) and run some conditionals based on how long the function has been running. The program will run uninterrupted for 60-90 days.

Mehdi Charife
  • 722
  • 1
  • 7
  • 22
  • You say "how many days it's *been* running", but what you describe sounds more like how many days *since it first ran* . Which is it, really? – John Bollinger May 05 '23 at 14:14
  • Either way, to measure elapsed time you should record a timestamp at the beginning of the period you want to measure, and afterward compute elapsed times by subtracting the start timestamp from a current timestamp. – John Bollinger May 05 '23 at 14:17
  • Does this answer your question? [elapsed time in C](https://stackoverflow.com/questions/6179419/elapsed-time-in-c) – Mehdi Charife May 05 '23 at 14:30

1 Answers1

1

you can create a new sketch and use the following code:

#include <Arduino.h>

unsigned long startTime;
byte daysPassed = 0;
unsigned long previousMillis = 0;
const long interval = 86400000; // 24 hours in milliseconds

void setup() {
  Serial.begin(9600);
  startTime = millis();
}

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    daysPassed++;
    Serial.print("Days passed: ");
    Serial.println(daysPassed);
  }

  // Your code with conditionals based on 'daysPassed' goes here
  if (daysPassed == 3) {
    // Do something when 3 days have passed
  } else if (daysPassed == 7) {
    // Do something when 7 days have passed
  }
}

This code sets up a basic Arduino sketch that counts the days since it started running. It uses the millis() function to track the time elapsed and increments the daysPassed variable every 24 hours. You can add your conditionals based on the daysPassed variable in the loop() function, as shown in the example.

Keep in mind that the millis() function will roll over (go back to zero) after approximately 50 days, so you may want to consider using a Real-Time Clock (RTC) module if you need to track time for longer periods or if you need more accurate timekeeping.

Djamel
  • 798
  • 8
  • 21