I'm doing a project and I want to get the amount of time between two sensor inputs. i.e. the sensor detects something, and it triggers a timer, and when the sensor picks up something else, it stops the timer and stores the amount of time the passed in a variable. Is there a library or a specific function that exists?
4 Answers
Just adding a few notes to the perfectly valid answers you already got:
On your typical AVR-based Arduino, micros()
has a resolution of
4 µs and millis()
is updated every 1024 µs. This last point
implies that millis()
increments most times by 1 ms, but
occasionally by 2 ms. Keep this in mind if time resolution is an
issue.
Both millis()
and micros()
return 32-bit unsigned numbers. This
implies that millis()
overflows (it rolls-over to zero) roughly every
49.7 days and micros()
every 71.6 min. This limits the
maximum interval length you can measure with each of those functions. It
does not limit the maximum run time of your program, since
subtracting two timestamps does work fine across a rollover
event.
It's simple enough to make a "helper" function to give you the number of milliseconds between each call of the function:
uint32_t millisSince() {
static uint32_t lastMillis = millis();
uint32_t now = millis();
uint32_t diff = now - lastMillis;
lastMillis = now;
return diff;
}
Every time you call that it will return the amount of time that has passed since you last called it. The first time it will return 0 since it has never been called before.
Yes, read and store the value from millis() at the first event. Then read millis() again at the second event. Subtract the stored value and you'll have the time, in milliseconds, between the events. millis() returns a long unsigned int and your memory variables for storing its value need to be of the same type.
Yes, you can use millis() or micros() which give the milliseconds resp microseconds since the board started up.
However by substracting two values taken close within time you can measure a time period (for example for your sensors). With this functionality you can program the timer yourself.
See https://www.arduino.cc/en/Reference/HomePage and search for micros/millis.