Skip to content

Commit 3a37cb5

Browse files
committed
improve delayMicroseconds accuracy
1 parent 299a91d commit 3a37cb5

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

avr/cores/picocore/Arduino.h

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@
1616

1717
#define min(a,b) ((a)<(b)?(a):(b))
1818
#define max(a,b) ((a)>(b)?(a):(b))
19-
#define abs(x) __builtin_abs(x)
19+
// match abs() definition from stdlib.h
20+
#define abs(__i) __builtin_abs(__i)
2021

2122
#ifdef __cplusplus
2223
class __FlashStringHelper;
@@ -64,17 +65,18 @@ inline void check_valid_digital_pin(uint8_t pin)
6465
*/
6566
}
6667

68+
// delays a specified number of microseconds
69+
// minimum F_CPU = 4M
70+
// todo: add support for 1-3.9M, dividing us by 4
6771
__attribute((always_inline))
6872
static inline void delayMicroseconds(uint16_t us)
6973
{
70-
us >>= 1;
71-
if (us <= 2) return; // function overhead is ~2us
74+
75+
const float fMHz = (F_CPU/1000000.0);
7276
do {
73-
// loop overhead is 4 cycles, so 0.5us @8MHz
74-
_delay_us(1.5);
77+
_delay_us(1.0 - (4.0 / fMHz)); // correct for 4c loop overhead
7578
} while (--us);
7679
}
77-
// #define delayMicroseconds(us) _delay_us(us)
7880

7981
void delay(uint16_t count);
8082

0 commit comments

Comments
 (0)