目前,我正在尝试使用微控制器ESP32创建一个计时器。我正在考虑使用NTP服务器pool.ntp.org来获得几毫秒的精确计时。

我试图做这样的事情

#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;
}


我想从struct tm timeinfo获得毫秒精度。我尝试使用strftimemktime,但我意识到strftimemktime最多只能返回秒。

最佳答案

不确定是否正在使用该结构

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
};


来自arduino-esp32

因为在这种结构中,小分辨率是几秒钟。
为什么不使用集成计时器之一?

关于c - 从NTP服务器获取毫秒,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55201313/

10-13 04:19