Measure With micros()
Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 16 of 18.
millis() counts whole milliseconds, which is too coarse for short things: a 2.5 ms press would read as 2 or 3. micros() is the same kind of clock, but it counts microseconds, millionths of a second: 1000 of them in each millisecond.
On the Uno it goes up in steps of 4 microseconds, and it returns an unsigned long too. To time something, read it before and after, and subtract:
unsigned long start = micros();
int reading = analogRead(A0);
unsigned long took = micros() - start;
Serial.println(took); // about 110: an analogRead() takes about 0.1 msBecause it counts so fast, micros() runs out of numbers much sooner than millis(): after about 70 minutes it starts again from 0. Use it for short times, and millis() for anything longer than a few minutes.
Challenge
EasyMeasure how long the button is held, in microseconds:
- when the button goes down, store
micros()inpressedAt - when it comes up, print
micros() - pressedAt
Press Run, tap the button, then Check.
Try it yourself
const int buttonPin = 2;
bool wasPressed = false;
unsigned long pressedAt = 0;
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
bool pressed = digitalRead(buttonPin) == LOW;
if (pressed && !wasPressed) {
// the button just went down: remember the time
}
if (!pressed && wasPressed) {
// the button just came up: print how long it was held, in microseconds
}
wasPressed = pressed;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Timing Without Delay
Practice on your own: Arduino playground