From b3f669843ee2e6b24cbb19b2b5b6d4d6df3d03d2 Mon Sep 17 00:00:00 2001 From: "Dirk O. Kaar" <19971886+dok-net@users.noreply.github.com> Date: Fri, 27 Sep 2019 11:11:54 +0200 Subject: [PATCH 1/2] Update wiring.c Cyclically call yield() in delay - compatibility fix for Arduino Scheduler (and similar libs) Correct understanding of overflow with uint32_t makes for much simpler code. --- cores/arduino/wiring.c | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/cores/arduino/wiring.c b/cores/arduino/wiring.c index a94a9240..5dd6e302 100644 --- a/cores/arduino/wiring.c +++ b/cores/arduino/wiring.c @@ -152,18 +152,7 @@ unsigned long micros() { void delay(unsigned long ms) { uint32_t start_time = micros(), delay_time = 1000*ms; - - /* Calculate future time to return */ - uint32_t return_time = start_time + delay_time; - - /* If return time overflows */ - if(return_time < delay_time){ - /* Wait until micros overflows */ - while(micros() > return_time); - } - - /* Wait until return time */ - while(micros() < return_time); + while(micros() - start_time < delay_time) yield(); } /* Delay for the given number of microseconds. Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */ @@ -407,4 +396,4 @@ void init() sei(); } -void setup_timers(void) __attribute__((weak)); \ No newline at end of file +void setup_timers(void) __attribute__((weak)); From acf06add94ee2484348485453a21a0e31f97b8e3 Mon Sep 17 00:00:00 2001 From: "Dirk O. Kaar" <19971886+dok-net@users.noreply.github.com> Date: Fri, 27 Sep 2019 11:39:02 +0200 Subject: [PATCH 2/2] Update wiring.c Improved delay() that allows over 49 days delay instead of less than 1.2 hours. --- cores/arduino/wiring.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/cores/arduino/wiring.c b/cores/arduino/wiring.c index 5dd6e302..7a20630e 100644 --- a/cores/arduino/wiring.c +++ b/cores/arduino/wiring.c @@ -151,8 +151,13 @@ unsigned long micros() { void delay(unsigned long ms) { - uint32_t start_time = micros(), delay_time = 1000*ms; - while(micros() - start_time < delay_time) yield(); + uint32_t start_time = micros(); + + while (ms > 0) { + while (micros() - start_time < 1000) yield(); + --ms; + start_time += 1000; + } } /* Delay for the given number of microseconds. Assumes a 1, 8, 12, 16, 20 or 24 MHz clock. */