我正在使用ESP32模块我在试着把NTP的时间毫秒..。我使用struct和函数getLocalTime()成功地获得了以秒为单位的时间,没有任何问题。
我在论坛和互联网上读到了我不得不使用的东西结构时间和函数
gettimeofday()取而代之的是实现这一点。因此,我在代码中相应地替换了结构和函数,但现在我不能再有时间了……
我的代码如下:
void printLocalTime()
{
//When using struct tm and getLocalTime() I can get the time without poblem in seconds
struct timeval tv;
if (!gettimeofday(&tv, NULL)) {
Serial.println("Failed to obtain time");
return;
}
long int sec = tv.tv_sec*1000LL;
Serial.println(sec);
long int temp = tv.tv_usec/1000LL;
Serial.println(temp);
}
当我运行这个程序时,我得到的只是“无法获得时间”...
PS:我使用的是arduino IDE,并且包含了sys/time.h
有人能帮我吗?
非常感谢
发布于 2020-05-16 05:45:33
因为(原始) POSIX命令具有以下结构
int gettimeofday(struct timeval *tv, struct timezone *tz);
错误号从1到6
if (gettimeofday(&tv, NULL) != 0) {
Serial.println("Failed to obtain time");
return;
}
因为它返回int,而不是bool,因为您之前使用的函数是定义的:
bool getLocalTime(struct tm * info, uint32_t ms)
在esp32-hal-time.c和as
extern "C" bool getLocalTime(struct tm * info, uint32_t ms = 5000);
在Arduino.h中
编辑
作为gettimeofday()表示UNIX之后的时间_Epoch (1970)先试试这个:
printf("TimeVal-sec = %lld\n", (long long) tv.tv_sec);
printf("TimeVal-usec = %lld\n", (long long) tv.tv_usec);
将打印如下内容
TimeVal-sec = 1493735463
TimeVal-usec = 525199 // already usec part
要“撕开”几秒钟,您可以执行以下操作
// Form the seconds of the day
long hms = tv.tv_sec % SEC_PER_DAY;
hms += tz.tz_dsttime * SEC_PER_HOUR;
hms -= tz.tz_minuteswest * SEC_PER_MIN;
// mod `hms` to ensure positive range of [0...SEC_PER_DAY)
hms = (hms + SEC_PER_DAY) % SEC_PER_DAY;
// Tear apart hms into h:m:s
int hour = hms / SEC_PER_HOUR;
int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN
此函数为您提供所有usec
static int64_t getNowUs() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (int64_t)tv.tv_usec + tv.tv_sec * 1000000ll;
}
如果您需要“真实”日期,则必须添加
const unsigned long long EPOCH = 2208988800ULL;
uint64_t tv_ntp = tv.tv_sec + EPOCH;
为了测量运行时间,您使用sec处理sec,使用usec处理usec。希望这次编辑能解决另一个POSIX/UNIX之谜。
发布于 2020-05-16 20:54:48
我正在使用arduino IDE我尝试了您所说的内容,如下所示:
char usec[30];
struct timeval tv;
if (gettimeofday(&tv, NULL)!= 0) {
Serial.println("Failed to obtain time");
return;
}
sprintf(sec, "%lld",(long long)tv.tv_sec);
sprintf(usec, "%lld", (long long)tv.tv_usec);
//long long seconds = (long long)tv.tv_sec;
//long long microseconds = (long long)tv.tv_usec;
Serial.print("TimeVal-sec = ");
Serial.print(sec);
Serial.print("TimeVal-usec = ");
Serial.print(usec);
但是我得到的是: TimeVal-sec = 5TimeVal-usec = 792802
我也在Windows上,有问题吗?
发布于 2021-02-24 16:02:42
serve = 'pool.ntp.org'
ntp = ntplib.NTPClient()
ntpResponse = ntp.request(serve)
if (ntpResponse):
# calculate the ntp time and convert into microseconds
ntp_time = float(ntpResponse.tx_time * 1000000)
#print("ntp_time",ntp_time)
上面的代码是正确的,可以获取ntp_服务器时间,以微秒为单位
https://stackoverflow.com/questions/61826937
复制相似问题