I have a working ADXL345 connected to an Arduino UNO, I need to limit the rate at which the ADXL345 takes in readings. I am using the SparkFun library for this sensor. I have read about the delay function and it works in the loop function but I was wondering if there might be a better way that is much more efficient?

1 Answer 1


Everytime you get a value from the sensor (for example with getX() or others) the library communicates with the sensor over I2C or SPI. So you can limit the usage of these function in your sketch. One way is with using delay(), but this is considered unefficient in most cases, since you are basically busy waiting during execution of delay(). You will not be able to do anything else in the future during this time span (if you want to add functionality to your device).

It's better to use non-blocking code, that only checks, if it is time to do something and if not going further through the program. Image like you yourself would bake a pizza. You would not stare at the clock for 20 min, until the time is up. You would periodically check, if the time has come to take the pizza out.

You can achieve this on an Arduino with use of the millis() function, which returns the number of milliseconds since the last powerup/reset. (Note that it overflows after about 50 days). There are plenty of tutorials for that out there. You can start with the BlinkWithoutDelay example from the Arduino IDE, which perfectly shows, how this is to be coded.

Note: If you are using the sensor with a battery, then you might want to limit its power usage. For this the library can set the corresponding registers in the sensor to set the datarate in the sensor (The rate at which the data in the sensor is updated). A smaller rate will lower the power consumption. So you can set the rate at about the rate of the reading in your sketch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.