Hi all,
I have been working on building a swinging Pendulum and I have decided to add an accelerometer and SDcard to collect the data from the accelerometer but I'm having trouble with how to write my pitch angle onto the SDcard and the serial monitor.
Here's my code. If anyone has any ideas that would be amazing. The accelerometer I'm using is the MMA8452Q with an Arduino Uno.
#include <math.h>
#include <SPI.h>
#include <SD.h>
#include <Wire.h> // Must include Wire library for I2C
#include "SparkFun_MMA8452Q.h" // Click here to get the library: http://librarymanager/All#SparkFun_MMA8452Q
MMA8452Q accel; // create instance of the MMA8452 class
const int chipSelect = 4; // pin 4 for Uno
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
// see if the card is present and can be initialized:
if (!SD.begin(chipSelect)) {
Serial.println("Card failed, or not present");
// don't do anything more:
while (1);
}
Serial.println("card initialized.");
Wire.begin();
if (accel.begin() == false) {
Serial.println("Not Connected. Please check connections and read the hookup guide.");
while (1);
}
}
void loop() {
if (accel.available()) {
Serial.print(accel.getCalculatedX(), 3);
Serial.print("\t");
Serial.print(accel.getCalculatedY(), 3);
Serial.print("\t");
Serial.print(accel.getCalculatedZ(), 3);
Serial.println();
}
File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
if (accel.available()) {
dataFile.print(accel.getCalculatedX(), 3);
dataFile.print("\t");
dataFile.print(accel.getCalculatedY(), 3);
dataFile.print("\t");
dataFile.print(accel.getCalculatedZ(), 3);
dataFile.print("\t");
dataFile.println();
}
else {
Serial.print("accel not available");
}
dataFile.close();
// print to the serial port too:
}
// if the file isn't open, pop up an error:
else {
Serial.println("error opening datalog.txt");
}
}
void checkTilt() {
if (accel.available() == true) {
accel.read();
float aX = float(accel.x);
float aY = float(accel.y);
float aZ = float(accel.z);
int pitch = atan2(-aX, aZ) * 180 / M_PI; // rotation on Y axis
int roll = atan2(-aY, aZ) * 180 / M_PI; // rotation on X axis
/*
If accelerometer is level, pitch and roll will both be 0
Pitch: Tilted Up = 1 to 180, Tilted Down = -1 to -180
Roll: Tilted Right = 1 to 180, Tilted Left = -1 to -180
*/
}
}