**Hi all, **
I am new to Arduino. I used the below codes to ask the SD card to write the data file. In the serial monitor, it shows the data of acceleration with an error writing to data file>
Please, help me out !!!
Card: SanDisk
GY521
#include <MPU6050.h>
#include <Wire.h>
#include <SD.h>
int16_t ax, ay, az;
int16_t gx, gy, gz;
MPU6050 mpu;
const int chipSelect = 10; // CS pin for the SD card module
File dataFile;
void setup() {
Serial.begin(9600);
Wire.begin();
if (!SD.begin(chipSelect)) {
Serial.println("SD card initialization failed. Check your connections.");
while (1);
}
Serial.println("SD card initialized successfully");
Serial.println("Initializing MPU6050...");
mpu.initialize();
Serial.println("Testing MPU6050 connections...");
if (mpu.testConnection()) {
Serial.println("MPU6050 connection successful");
} else {
Serial.println("MPU6050 connection failed. Please check wiring and try again.");
while (1);
}
Serial.println("Calibrating gyro...");
mpu.CalibrateGyro();
Serial.println("Gyro calibration complete");
dataFile = SD.open("acceleration_data.txt", FILE_WRITE);
if (!dataFile) {
Serial.println("Error opening data file");
}
}
void loop() {
// Read raw sensor data
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
// Get current time in milliseconds
unsigned long currentTime = millis();
// Print data to the serial monitor
Serial.print("Time: ");
Serial.print(currentTime);
Serial.print(" Accel: ");
Serial.print(ax);
Serial.print(", ");
Serial.print(ay);
Serial.print(", ");
Serial.print(az);
Serial.print(" Gyro: ");
Serial.print(gx);
Serial.print(", ");
Serial.print(gy);
Serial.print(", ");
Serial.println(gz);
// Write data to the SD card
if (dataFile) {
dataFile.print("Time: ");
dataFile.print(currentTime);
dataFile.print(" Accel: ");
dataFile.print(ax);
dataFile.print(", ");
dataFile.print(ay);
dataFile.print(", ");
dataFile.print(az);
dataFile.print(" Gyro: ");
dataFile.print(gx);
dataFile.print(", ");
dataFile.print(gy);
dataFile.print(", ");
dataFile.println(gz);
dataFile.flush(); // Ensure data is written to the SD card
} else {
Serial.println("Error writing to data file");
}
delay(1000); // Adjust the delay as needed
}
Serial Monitor>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
04:26:24.890 -> Accel: -8388, -9496, 8324 Gyro: 3, 0, -19463
04:26:24.922 -> Error writing to data file