sparkfun / SparkFun_ADXL345_Arduino_Library

Arduino Library for the ADXL345
47 stars 52 forks source link

Library not working correctly on Feather nRF52 SPI connection #15

Open DrAma999 opened 5 years ago

DrAma999 commented 5 years ago

Hello, I’m experiencing some issue in trying to make ADXL345 accelerometer works in SPI by using an nRF52 feather.

Here are the connections

nrf52              ADXL345
SCK                SCL
MISO              SDO
MOSI              SDA
PIN 11              CS

The same code I’m posting works perfectly on my Arduino Uno, but if I try to run it on the feather it get stuck on powerOn method.

#include <SparkFun_ADXL345.h>         // SparkFun ADXL345 Library

ADXL345 adxl = ADXL345(11);           // USE FOR SPI COMMUNICATION, ADXL345(CS_PIN);

void setup(){

  Serial.begin(115200);                 // Start the serial terminal
    while ( !Serial ) delay(10);   // for nrf52840 with native usb
  pinMode(11, OUTPUT);
  Serial.println("SparkFun ADXL345 Accelerometer Hook Up Guide Example");
  Serial.println();
  adxl.powerOn();                     // Power on the ADXL345
  Serial.println("Setting range");

  adxl.setRangeSetting(16);           
  Serial.println("Setting 4 wire");
  adxl.setSpiBit(0);                  // Configure the device to be in 4 wire SPI mode when set to '0' or 3 wire SPI mode when set to 1

}

void loop(){

  // Accelerometer Readings
  int x,y,z;   
  adxl.readAccel(&x, &y, &z);         // Read the accelerometer values and store them in variables declared above x,y,z

  // Output Results to Serial
  Serial.print(x);
  Serial.print(", ");
  Serial.print(y);
  Serial.print(", ");
  Serial.println(z); 

}

To manage the ADXL345 I’m using the SparkFun library, investigating it’s source code I’m trying to figure out what could be wrong. The initialization code in sparkfun starts the SPI Library and sets the mode to 3, it also configure the CS pin to OUTPUT as it supposed to be, the it puts the CS to HIGH.

ADXL345::ADXL345(int CS) {
    // ... other code
    _CS = CS;
    I2C = false;
    SPI.begin();
    SPI.setDataMode(SPI_MODE3);
    pinMode(_CS, OUTPUT);
    digitalWrite(_CS, HIGH);
}

The powerOn function sets the power settings on the sensor:

void ADXL345::powerOn() {
    // ... other code
    //ADXL345 TURN ON
    writeTo(ADXL345_POWER_CTL, 0);  // Wakeup     
    writeTo(ADXL345_POWER_CTL, 16); // Auto_Sleep
    writeTo(ADXL345_POWER_CTL, 8);  // Measure
}

My code hangs exactly when I call powerOn(). I do not understand why since on my Arduino Uno works perfectly.

Thanks, Andrea

MathisEngels commented 1 year ago

Hi. I just found out the way to fix this. You just need to call the SPI constructor inside the setup fonction (because SPI functions, pinMode or digitalWrite can't be called outside the setup or loop function