Skip to content

Commit 5b92569

Browse files
BrandonLWhiteigrr
authored andcommitted
Added micros64 and used to fix and improve gettimeofday.
1 parent 303a71d commit 5b92569

File tree

3 files changed

+20
-7
lines changed

3 files changed

+20
-7
lines changed

cores/esp8266/Arduino.h

+1
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@ void analogWriteRange(uint32_t range);
202202

203203
unsigned long millis(void);
204204
unsigned long micros(void);
205+
uint64_t micros64(void);
205206
void delay(unsigned long);
206207
void delayMicroseconds(unsigned int us);
207208
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);

cores/esp8266/core_esp8266_wiring.c

+7
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,13 @@ unsigned long ICACHE_RAM_ATTR micros() {
7171
return system_get_time();
7272
}
7373

74+
uint64_t ICACHE_RAM_ATTR micros64() {
75+
uint32_t low32_us = system_get_time();
76+
uint32_t high32_us = micros_overflow_count + ((low32_us < micros_at_last_overflow_tick) ? 1 : 0);
77+
uint64_t duration64_us = (uint64_t)high32_us << 32 | low32_us;
78+
return duration64_us;
79+
}
80+
7481
void ICACHE_RAM_ATTR delayMicroseconds(unsigned int us) {
7582
os_delay_us(us);
7683
}

cores/esp8266/time.c

+12-7
Original file line numberDiff line numberDiff line change
@@ -31,23 +31,27 @@ struct timeval {
3131

3232
extern char* sntp_asctime(const struct tm *t);
3333
extern struct tm* sntp_localtime(const time_t *clock);
34+
extern uint64_t micros64();
3435

3536
// time gap in seconds from 01.01.1900 (NTP time) to 01.01.1970 (UNIX time)
3637
#define DIFF1900TO1970 2208988800UL
3738

3839
static int s_daylightOffset_sec = 0;
3940
static long s_timezone_sec = 0;
40-
static time_t s_bootTime = 0;
41+
static bool s_bootTimeSet = false;
42+
static uint64_t s_bootTime_us = 0;
4143

4244
// calculate offset used in gettimeofday
4345
static void ensureBootTimeIsSet()
4446
{
45-
if (!s_bootTime)
47+
// Check just a bool flag instead of the full 64-bit s_bootTime for zero.
48+
if (!s_bootTimeSet)
4649
{
47-
time_t now = sntp_get_current_timestamp();
48-
if (now)
50+
time_t now_s = sntp_get_current_timestamp();
51+
if (now_s)
4952
{
50-
s_bootTime = now - millis() / 1000;
53+
s_bootTime_us = now_s * 1000000ULL - micros64();
54+
s_bootTimeSet = true;
5155
}
5256
}
5357
}
@@ -100,8 +104,9 @@ int _gettimeofday_r(struct _reent* unused, struct timeval *tp, void *tzp)
100104
if (tp)
101105
{
102106
ensureBootTimeIsSet();
103-
tp->tv_sec = s_bootTime + millis() / 1000;
104-
tp->tv_usec = micros();
107+
uint64_t currentTime_us = s_bootTime_us + micros64();
108+
tp->tv_sec = currentTime_us / 1000000ULL;
109+
tp->tv_usec = currentTime_us % 1000000ULL;
105110
}
106111
return 0;
107112
}

0 commit comments

Comments
 (0)