Reading sensor every 5 ms

I want to read an accelerometer (ADXL345) exactly every 5 ms. The accelerometer & code work great when data is free-running. No problems getting x, y, z data out. Here's the problem. I'm using the library MsTimer2 that calls a function which reads the ADXL345 (code= adxl.readAccel(&x, &y, &z));. This read does not work within the MsTimer2 called function. If I comment out the adxl.readAccel command, then everything else with the timer called function works.

Are there other methods to get a sensor to read every 5 ms?

Thanks,
Gerry

That timer library uses interrupts to call back to your code. Obviously the author thought this was a reasonable approach, and no doubt there are projects where it works fine, but IMO it's a very poor choice for general use because of all the issues that using interrupts causes, none of which are described or even hinted at in the documentation for for that library. In my opinion that whole library is a trap for the unwary. You don't need anything like that to run code at regular intervals, just use the polling approach demonstrated in the 'blink without delay' example sketch. This is no harder than using the library, avoids all the pratfalls that come from using interrupts, and means that you can incorporate times event handling into your code in the same way you handle all the other sorts of events. Here's a trivial example that just blinks an LED which you could easily adapt to do your timed polling:

void blinkLed()
{
	static const int LED_PIN = 13;
	static const unsigned long BLINK_INTERVAL = 500; // duration of each blink phase
	static unsigned long lastBlinkTime = 0;
	
	if(millis() - lastBlinkTime >= BLINK_INTERVAL)
	{
		digitalWrite(LED_PIN, !digitalRead(LED_PIN));
		lastBlinkTime += BLINK_INTERVAL;
	}
}

Thanks PeterH! That should work as long as the processing duration within your if statement is less than the designated 5 ms read interval. I'll do an error check to make sure the time duration is less than "BLINK_INTERVAL".

This is my first exposure to Arduino. I don't have any idea yet as to how long it takes to store the sensor data (x, y, z) into a SD card. Hopefully a lot less than 5 ms.

Hopefully a lot less than 5 ms

Use serial print and millis before you write and then after you write, the difference will be the time it takes.

Gerry48:
I don't have any idea yet as to how long it takes to store the sensor data (x, y, z) into a SD card.

In general it depends how you write it, but one call writing a large amount of data is much more efficient than splitting the data across several calls.

Check out writing with the SDfat.h library.
I believe it writes in block of 512 bytes for fast, efficient writes.
https://code.google.com/p/sdfatlib/