arduino uno + adxl345

Elektronik- och mekanikrelaterad mjukvara/litteratur. (T.ex schema-CAD, simulering, böcker, manualer mm. OS-problem hör inte hit!)
hussik
Inlägg: 1
Blev medlem: 27 mars 2012, 00:45:31

arduino uno + adxl345

Inlägg av hussik »

hej, finns det någon här som har en fungerande kod där man kan få värdena från accelerometern i grader istället för i g?
just nu sitter jag på den här koden men den visar mig typ 90 grader i horisontellt läge, vet någon hur man gör så att den blir till 0?

Kod: Markera allt


#include <math.h>
// Include the Wire library so we can start using I2C.
#include <Wire.h>
// Include the Love Electronics ADXL345 library so we can use the accelerometer.
#include <C:\Users\Huss\Desktop\arduino prog\koden\ADXL345_Example\ADXL345.h>

// Declare a global instance of the accelerometer.
ADXL345 accel;

// Set up a pin we are going to use to indicate our status using an LED.
int statusPin = 2; // I'm using digital pin 2.

void setup()
{
  // Begin by setting up the Serial Port so we can output our results.
  Serial.begin(9600);
  // Start the I2C Wire library so we can use I2C to talk to the accelerometer.
  Wire.begin();
  
  // Ready an LED to indicate our status.
  pinMode(statusPin, OUTPUT);
  
  // Create an instance of the accelerometer on the default address (0x1D)
  accel = ADXL345();
  
  // Check that the accelerometer is infact connected.
  if(accel.EnsureConnected())
  {
    Serial.println("Connected to ADXL345.");
    digitalWrite(statusPin, HIGH); // If we are connected, light our status LED.
  }
  else 
  {
    Serial.println("Could not connect to ADXL345.");
    digitalWrite(statusPin, LOW); // If we are not connected, turn our LED off.
  }
  
  // Set the range of the accelerometer to a maximum of 2G.
  accel.SetRange(2, true);
  // Tell the accelerometer to start taking measurements.
  accel.EnableMeasurements();
}

void loop()
{
  if(accel.IsConnected) // If we are connected to the accelerometer.
  {
    // Read the raw data from the accelerometer.
    AccelerometerRaw raw = accel.ReadRawAxis();
    //This data can be accessed like so:
    int xAxisRawData = raw.XAxis;
    
    // Read the *scaled* data from the accelerometer (this does it's own read from the accelerometer
    // so you don't have to ReadRawAxis before you use this method).
    // This useful method gives you the value in G thanks to the Love Electronics library.
    AccelerometerScaled scaled = accel.ReadScaledAxis();
    double R = sqrt(pow(scaled.XAxis, 2) + pow(scaled.YAxis, 2) + pow(scaled.ZAxis, 2)); // Calculate the force vector
    double angleX = acos(scaled.XAxis / R) * RAD_TO_DEG;
    double angleY = acos(scaled.YAxis / R) * RAD_TO_DEG;

    // We output our received data.
    //Output(raw, scaled);
 
    Serial.print(angleX,DEC);
    Serial.print("\t");
    Serial.println(angleY,DEC);
  }
}