c - 从 NTP 服务器获取毫秒

标签 c arduino ntp

目前我正在尝试使用微 Controller 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/

相关文章:

javascript - Arduino 网络服务器更新

datetime - Ubuntu shell 脚本 : Get and echo time from ntp server without synchronization

c - c中 float 的精确表示

c - ATLAS 多线程 BLAS 例程中的 valgrind "uninitialized value"警告是否为误报?

c - 是否有理由使用像这样的 C 语言指针 &(*foo)?

c - 如何向扬声器发送声音

c - 使用 C 对 JSON 或任何纯文本进行二进制序列化

c - 错误:std::fopen 不是 std 的成员

c# - 如何将 DateTime.Now 与 NTP 服务器同步?

logic - NTP 时钟纪律如何工作?