I need to display measurements of a sensor which need to be presented on a precise time-scale. Since the loop function is not quite precise, how can i make sure that i can measure at say for example exactly 1ms? ( I am using an ADXL345 sensor ) Thanks a lot!
2 Answers
The ADXL345 has both a FIFO and data rate setting. This allows sampling to be done with a precise frequency without having to use timers, etc, on the MCU. The MCU/Arduino has to fetch data before the FIFO overflows. The max sampling frequency depends on the communication protocol (I2C or SPI), i.e. how fast the MCU can empty the FIFO.
It is possible to use the ADXL345 in stream mode, collect samples at a fixed rate, and get an interrupt when the FIFO has been filled to a specified level (watermark). The samples can then be read in burst mode.
The samples will be on a "precise time-scale".
There are even more advanced usages of the device with tap, double-tap and free fall detect.
Please see Data Rate setting and FIFO control in datasheet.
Cheers!
PS: Using I2C at 100 KHz will take 1 ms just to address the device. Addressing a register will take another ms and a ms per data byte. Reading the data register (six bytes) will take at least 8 ms. Realistic max sample rate with I2C at 100 KHz is 10-100 Hz. There is also limited amount of memory for buffers.
Microcontrollers have built in peripherals called Timers. They are used for many purposes, including working out when something should be done.
There are plenty of good Timer libraries around for the Arduino, including the popular TimerOne/TimerThree libraries.