thoraz
thoraz

Reputation: 229

How set epoch on ESP32 and Arduino IDE to update the timedate without external RTC and Wifi?

On my ESP32 I want to have information about actual time without Wifi connection or an external RTC chip. I started with this simple code

time_t now;
struct tm* timeinfo;

void Check_Time(void) {
  time(&now);
  timeinfo = localtime(&now);
  Serial.println(timeinfo);
}

void setup() {
  Serial.begin(115200);
}

void loop() {
  Check_Time();
  delay(1000);
}

It works since the output is

Thu Jan  1 00:07:57 1970
Thu Jan  1 00:07:58 1970
Thu Jan  1 00:07:59 1970
Thu Jan  1 00:08:00 1970
...

and naturally it starts from 1 Jan 1970. Now I want to update this time to the actual one but I haven't found a direct solution. I know that I could convert a date to a time_t data with the mktime function (is it right?) but how I can pass it to the system? How I should manage this problem?

Upvotes: 2

Views: 3080

Answers (1)

null321
null321

Reputation: 31

I got it to work by using:

#include <sys/time.h>
// ...
struct timeval tv;
tv.tv_sec = /* seconds since epoch here */;
tv.tv_usec = /* microseconds here */;
settimeofday(&tv, NULL);

Replacing the comments with the variable that stores the times.

I am updating my time over Bluetooth Low Energy.

Here is it working:

1970 1 1 0 0 16
1970 1 1 0 0 17
1970 1 1 0 0 18
Time set
2020 12 6 22 45 32
2020 12 6 22 45 33
2020 12 6 22 45 34

Upvotes: 3

Related Questions