sensor reading won't work inside Interrupt function

Hallo everyone,

I have an IMU sensor and all I’m trying to do is to read it’s measurent in a specific time gap using timer interrupts.

I have the examples for both the IMU and the timer interrupts and I just combined them.

Yet, the result is not good.

Each one of the two works separetly, but when I’m trying “imu.read” inside the interrupt - suddenly I get the error: “Failed to detect and initialized IMU!”

my code is:


#include <TimerOne.h>
#include <Wire.h>
#include <LSM6.h>

LSM6 imu;

volatile float ax; // global variable to be changed inside interrupt

void setup()
{
Serial.begin(9600);

// 5 next text lines are copied from the IMU example
Wire.begin();
if (!imu.init())
{
Serial.println(“Failed to detect and initialize IMU!”);
while (1);
}
imu.enableDefault();

// 2 next text lines are copied from the TimerOne example

Timer1.initialize(250000);
Timer1.attachInterrupt(imuMessure);
}

void imuMessure(void) // This is the function I want the interrupt to exacute
{
imu.read();
ax = imu.a.x;
}

void loop()
{
float ax_copy;

noInterrupts(); // stoping the interrupt from a moment just to get the value of ax
ax_copy = ax;
interrupts();

Serial.print("ax is "); // printing ax
// Serial.println(ax_copy);

delay(500);

}

Thank you very much!

Why do you need to call Wire.begin()? Is it because the IMU is an I2C device, and you (or the library) uses Wire methods to read from it?

Those methods all rely on interrupts being enabled, which they are not when your ISR is running.

Interrupts are disabled inside of an ISR. I2C (Wire) uses interrupts. Set a flag in the ISR. Then, in loop(), if the flag is set do the read and clear the flag.