0

Currently I'm trying to create a lap timer using a microcontroller ESP32. I'm thinking of using NTP server pool.ntp.org to get a precision timing of several milliseconds.

I tried to do something like this

#include <WiFi.h>
#include "time.h"
String time_str;
time_t epoch;
const char* ssid     = "SSID";
const char* password = "PASSWORD";

void setup() { 
  Serial.begin(115200);
  Start_WiFi(ssid,password);
  configTime(0, 0, "pool.ntp.org");
}

void loop() {
  setenv("TZ", "  WIB-7", 1);
  Serial.println("  Jakarta Time  = "+printLocalTime());
  Serial.println();
  delay(100);
}

String printLocalTime(){
  struct tm timeinfo;
  if(!getLocalTime(&timeinfo)){
    Serial.println("Failed to obtain time");
    return "Time Error";
  }
  char output[80];
  //epoch = mktime(&timeinfo);
  //return epoch;
  strftime(output, 80, "%d-%b-%y, %H:%M:%S", &timeinfo);
  time_str = String(output);
  return time_str;
}

int Start_WiFi(const char* ssid, const char* password){
  int connAttempts = 0;
  Serial.println("\r\nConnecting to: "+String(ssid));
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED ) {
    delay(500);
    Serial.print(".");
    if(connAttempts > 20) return -5;
    connAttempts++;
  }
  return 1;
}

I would like to get millisecond precision from struct tm timeinfo. I tried to use strftime and mktime but i realise that both strftime and mktime returns only up to second.

1 Answers1

0

Not sure if you are using the struct

struct tm
{
  int   tm_sec;
  int   tm_min;
  int   tm_hour;
  int   tm_mday;
  int   tm_mon;
  int   tm_year;
  int   tm_wday;
  int   tm_yday;
  int   tm_isdst;
#ifdef __TM_GMTOFF
  long  __TM_GMTOFF;
#endif
#ifdef __TM_ZONE
  const char *__TM_ZONE;
#endif
};

from arduino-esp32.

Because in this struct the smalles resolution is seconds. Why not using one of the integrated timers?

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
j0j0j0
  • 97
  • 2
  • 8
  • Yes sys/time.h with timeval is better: https://github.com/espressif/arduino-esp32/blob/master/tools/sdk/include/newlib/sys/time.h – eckes Mar 16 '19 at 20:59
  • I never know that there's another library. Sorry, I'm new to microcontroller programming. I'll try to use sys/time.h and update the results ASAP – Prajogo Atmaja Mar 16 '19 at 21:03
  • In that case it’s C not related to microcontrollers. You will need to format the nanoseconds yourself https://stackoverflow.com/questions/1469495/unix-programming-struct-timeval-how-to-print-it-c-programming – eckes Mar 16 '19 at 21:12
  • @eckes is there any similar function to getLocalTime for timeval type? – Prajogo Atmaja Mar 16 '19 at 21:30
  • `gettimeofday()` fills this structure – eckes Mar 16 '19 at 21:35