Data logging problem

hello i am new to arduino i have to submit a rain intensity data logger in a next few hours
anybody please help me

i used the code
#include <SD.h>

const int rainPin = 2; // Digital pin for rain sensor
const int chipSelect = 10; // Chip select pin for SD card module

unsigned long rainDuration = 0; // Duration of rain in milliseconds
float rainIntensity = 0; // Rain intensity in mm/hour

File dataFile;

void setup() {
Serial.begin(9600);

// Initialize SD card
if (SD.begin(chipSelect)) {
Serial.println("SD card initialized.");
} else {
Serial.println("SD card initialization failed.");
return;
}

// Open a file for writing data
dataFile = SD.open("rain_data.txt", FILE_WRITE);

if (dataFile) {
Serial.println("File opened successfully.");
dataFile.println("Rain Intensity (mm/hour) | Rain Duration (seconds)");
} else {
Serial.println("Error opening file.");
}
}

void loop() {
// Read the digital value from the rain sensor
int sensorValue = digitalRead(rainPin);

// Check if it's raining
if (sensorValue == HIGH) {
// Rain detected, calculate and log data
rainIntensity = 5.0; // Set a constant value for rain intensity (you may adjust based on your sensor)
rainDuration += millis();

// Print and log the rain intensity and duration
Serial.print("Rain Intensity: ");
Serial.print(rainIntensity);
Serial.print(" mm/hour   |   Rain Duration: ");
Serial.print(rainDuration / 1000);  // Convert milliseconds to seconds
Serial.println(" seconds");

// Log data to SD card
if (dataFile) {
  dataFile.print(rainIntensity);
  dataFile.print(" | ");
  dataFile.println(rainDuration / 1000);  // Convert milliseconds to seconds
} else {
  Serial.println("Error writing to file.");
}

}

delay(1000); // Delay for 1 second (adjust as needed)
}

this code gives rain intensity and at the next line it prints "error writing to file"
my connections are perfect
i use a 16 gb sd card from san disk

anybody please reply me immediately

Welcome to the forum

Your topic has been moved to the Programming category of the forum. Please take care when deciding where to start future topics

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

No mention of formatting the SD card!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.