#include <Wire.h>
#include <SPI.h>
#include <SD.h>
const int MPU_addr = 0x68; // I2C address of the MPU-6050
const int SD_chipSelect = 9; // chip select pin for SD card
int16_t AcX, AcY, AcZ, GyX, GyY, GyZ;
float Accel_Y;
void setup() {
Serial.begin(9600);
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
if (!SD.begin(SD_chipSelect)) {
Serial.println("Card failed, or not present");
return;
}
Serial.println("card initialized.");
}
void loop() {
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
// convert raw acceleration data to g units
Accel_Y = (float)AcY / 16384.0;
// write data to SD card
File dataFile = SD.open("accel_data.txt", FILE_WRITE);
if (dataFile) {
dataFile.println(Accel_Y);
dataFile.close();
Serial.println("Acceleration data (y-axis) recorded to SD card.");
} else {
Serial.println("Error opening file.");
}
delay(500);
}