From 051eb371a6c277a9df95fd88f8a5abdd7fa60440 Mon Sep 17 00:00:00 2001 From: "David A. Mellis" Date: Wed, 26 Nov 2008 14:14:59 +0000 Subject: Adding micros() function. --- cores/arduino/wiring.c | 17 +++++++++++++++++ cores/arduino/wiring.h | 1 + 2 files changed, 18 insertions(+) (limited to 'cores/arduino') diff --git a/cores/arduino/wiring.c b/cores/arduino/wiring.c index 157d1d2..2896647 100755 --- a/cores/arduino/wiring.c +++ b/cores/arduino/wiring.c @@ -24,11 +24,13 @@ #include "wiring_private.h" +volatile unsigned long timer0_overflow_count = 0; volatile unsigned long timer0_clock_cycles = 0; volatile unsigned long timer0_millis = 0; SIGNAL(TIMER0_OVF_vect) { + timer0_overflow_count++; // timer 0 prescale factor is 64 and the timer overflows at 256 timer0_clock_cycles += 64UL * 256UL; while (timer0_clock_cycles > clockCyclesPerMicrosecond() * 1000UL) { @@ -51,6 +53,21 @@ unsigned long millis() return m; } +unsigned long micros() { + unsigned long m, t; + uint8_t oldSREG = SREG; + + cli(); + t = TCNT0; + if ((TIFR0 & _BV(TOV0)) && (t == 0)) + t = 256; + + m = timer0_overflow_count; + SREG = oldSREG; + + return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond()); +} + void delay(unsigned long ms) { unsigned long start = millis(); diff --git a/cores/arduino/wiring.h b/cores/arduino/wiring.h index 46d5334..9600a0f 100755 --- a/cores/arduino/wiring.h +++ b/cores/arduino/wiring.h @@ -113,6 +113,7 @@ int serialRead(void); void serialFlush(void); unsigned long millis(void); +unsigned long micros(void); void delay(unsigned long); void delayMicroseconds(unsigned int us); unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout); -- cgit v1.2.3-18-g5258