Skip to content

Commit c17e868

Browse files
committed
Fix millis rollover
1 parent b924b59 commit c17e868

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

cores/esp8266/core_esp8266_wiring.c

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,12 @@ extern void esp_schedule();
3030
extern void esp_yield();
3131

3232
static os_timer_t delay_timer;
33+
static os_timer_t micros_overflow_timer;
34+
static uint32_t micros_at_last_overflow_tick = 0;
35+
static uint32_t micros_overflow_count = 0;
3336
#define ONCE 0
3437
#define REPEAT 1
3538

36-
unsigned long millis()
37-
{
38-
unsigned long m = system_get_time() / 1000;
39-
return m;
40-
}
4139

4240
void delay_end(void* arg)
4341
{
@@ -62,10 +60,24 @@ void delay(unsigned long ms)
6260
}
6361
}
6462

63+
void micros_overflow_tick(void* arg)
64+
{
65+
uint32_t m = system_get_time();
66+
if (m < micros_at_last_overflow_tick)
67+
++micros_overflow_count;
68+
micros_at_last_overflow_tick = m;
69+
}
70+
71+
unsigned long millis()
72+
{
73+
uint32_t m = system_get_time();
74+
uint32_t c = micros_overflow_count + ((m < micros_at_last_overflow_tick) ? 1 : 0);
75+
return c * 4294967 + m / 1000;
76+
}
77+
6578
unsigned long micros()
6679
{
67-
unsigned long m = system_get_time();
68-
return m;
80+
return system_get_time();
6981
}
7082

7183
void delayMicroseconds(unsigned int us)
@@ -76,4 +88,6 @@ void delayMicroseconds(unsigned int us)
7688
void init()
7789
{
7890
initPins();
91+
os_timer_setfn(&micros_overflow_timer, (os_timer_func_t*) &micros_overflow_tick, 0);
92+
os_timer_arm(&micros_overflow_timer, 60000, REPEAT);
7993
}

0 commit comments

Comments
 (0)