How can I use ADXL345 in timer interrupt with Arduino mega

761 Views Asked by At

I want to use ADXL345 in timer interrupt with Arduino mega.

But it can't not work.

Here is my code :

    #include <Wire.h>

    #define Register_ID 0
    #define Register_2D 0x2D
    #define Register_X0 0x32
    #define Register_X1 0x33
    #define Register_Y0 0x34
    #define Register_Y1 0x35
    #define Register_Z0 0x36
    #define Register_Z1 0x37

    int ADXAddress = 0xA7>>1;
    int reading = 0;
    int val = 0;
    int X0,X1,X_out;
    int Y0,Y1,Y_out;
    int Z1,Z0,Z_out;
    double Xg,Yg,Zg;

    unsigned long t1, t2;

    void setup()
    {
      Serial.begin(9600);
      Wire.begin();  //初始化I2C
      delay(100);
      Wire.beginTransmission(ADXAddress);
      Wire.write(Register_2D);
      Wire.write(8);
      Wire.endTransmission();

      delay(500);

      noInterrupts();           // disable all interrupts

      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1  = 0;
      OCR1A = 2500;            // compare match register //250 = 1ms//500=2ms
      TCCR1B |= (1 << WGM12);   // CTC mode
      TCCR1B |= (1 << CS10) + (1 << CS11);    // 64 prescaler 
      TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt

      interrupts();             // enable all interrupts


    }

    void loop()
    {

      Serial.println(Z_out);

      delay(500);  


    }

    ISR(TIMER1_COMPA_vect){

      Wire.beginTransmission(ADXAddress);
      Wire.write(Register_Z0);
      Wire.write(Register_Z1);
      Wire.endTransmission();
      Wire.requestFrom(ADXAddress,2);
      if(Wire.available()<=2);
      {
        Z0 = Wire.read();
        Z1 = Wire.read();
        Z1 = Z1<<8;
        Z_out = Z0+Z1;
      }

    }

ISR() function executes every 1 millisecond, but the codes in ISR() only take 650 microseconds.

I don't know why it couldn't work.

If I do all things in the loop(), it can work normally.

Can any one help me?

Thanks in advance,

2

There are 2 best solutions below

0
On

You shouldn'y handle I2C communications in the ISR. Try using the timer interrupt to change the value of a flag. Check that flag in the main loop and read the value.

0
On

You cannot use the Wire library inside an ISR, as interrupts have been disabled. The Wire library uses interrupts.