Go Down

Topic: Error writing to file with SD card shield on Mega2560 (Read 604 times) previous topic - next topic


Hi everyone,

I am using Arduino 1.8.5 software and Arduino MEGA2560 with the SD card shield. For my project, I have to read the voltage and temperature from the pins connected to the board, which later should be saved as a .csv file.

Here is my code:

//SWITCH part of the code
int inPin = 2;         // the number of the input pin
int outPin = 13;       // the number of the output pin

int state = HIGH;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = LOW;    // the previous reading from the input pin
int goButton;    // press inPin = 2 to go

// the follow variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers

#include "SD.h" //includes SD library
#include"SPI.h" //includes SPI library

const int CSpin = 53;
String dataString = ""; // holds the data to be written to the SD card

const float referenceVolts = 5.0; // the default reference on a 5-volt board
const int batteryPin = 0;         // battery is connected to analog pin 0
const int temperaturePin = 5;       // temperature probe is connected to analogue pin 5 (amp needed)
const int fluxMeterPin = 6;            // Fluxmeter (a TEM)  is connected to analogue pin 6 (?)
const int pwmPin = 7;           // Output voltage to TEM is connected to analogue pin 7 (amp needed)
const int pwmSwitchPin = 4;      // Digital to TEM - switches between heating and cooling.

File sensorData;
File myFile;
int myTime = 0;
void setup()

  pinMode(inPin, INPUT);
  pinMode(outPin, OUTPUT);
  Serial.print("Initializing SD card...");
  pinMode(CSpin, OUTPUT);

Serial.println ("Start of program  ");
  // Check make sure that go switch is off
  // The "go button" gives LOW when depressed and HIGH when not depressed.
  Serial.println ("Depress and then release the go button to start");
  goButton = HIGH;
  while (goButton==HIGH) {
      goButton = digitalRead(inPin);
      Serial.print ("Start button value is   ");
      Serial.println (goButton);
     // Serial.println("Switch the start button off");
  // Now wait until it is on.
  Serial.println ("Awaiting release of go button");
 // Serial.println (goButton);
while (goButton == LOW){
   goButton = digitalRead(inPin);
  // Serial.print ("Start button value is   ");
   //   Serial.println (goButton);
 //  Serial.println ("Awaiting go button.");

Serial.println ("Operation started");
  // see if the card is present and can be initialized:

  if (!SD.begin(CSpin)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
  Serial.println("card initialized.");
  sensorData = SD.open("myData2.csv", FILE_WRITE);
  if (sensorData) {
    Serial.print("Writing file header...");
    sensorData.println("TEM TEST DATA");
    Serial.println("TEM TEST DATA");
    // close the file:
  } else {
    // if the file didn't open, print an error:
    Serial.println("error 10 opening data file");


void loop()

  reading = digitalRead(inPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
      state = HIGH;

    time = millis();

  digitalWrite(outPin, state);

  previous = reading;

  int val = analogRead(batteryPin); // read the value from the sensor
  float volts = (val / 1023.0) * referenceVolts; // calculate the ratio
  //  *******************************************************************
  // Start logging
  float mjtTime = millis(); // Time in milli-seconds
    val = analogRead(temperaturePin); // read the value from the temperature probe.
  float temperVolts = (val / 1023.0) * 80; // Wild guess that f.s.d. = 80 deg C. Check this!
    val = analogRead(fluxMeterPin); // read the value from the sensor
   float fmVolts = (val / 1023.0) * referenceVolts; // Wild guess that f.s.d. = 80 deg C. Check this!

  // Implement simple proportional control with an arbitrary coefficient.
  float spError = setPointTemp(millis())- temperVolts; // set point error.
  float TEMvolts= spError * 0.1;
  if (TEMvolts > 0) {
    digitalWrite (pwmSwitchPin, 1); // Set hardware to heating mode.
  else {
     digitalWrite (pwmSwitchPin, 0); // Set hardware to cooling mode.
   TEMvolts = abs(TEMvolts); // Lose any negative sign
   TEMvolts = max (2, TEMvolts); // Restrict to two volts max
   digitalWrite (pwmPin, TEMvolts); // Write voltage to TEM.

   // Determine output string

   dataString = String(mjtTime)+","+String(temperVolts)+","+String(fmVolts) ;

   while (millis() < mjtTime + 1000){
    // delay loop
   Serial.println ("End of delay loop");

  myTime = myTime + 1;
  // build the data string
  //dataString = String(myTime) + "," + String(volts); // convert to CSV
  if (myTime < 30) {
  else {
    Serial.println ("You can remove the SD card now.");

 // delay(5000); // delay before next write to SD Card, adjust as required
void saveData() {
  // if (SD.exists("myData2.csv")) { // check the card is still there
  // now append new data file
  sensorData = SD.open("myData2.csv", FILE_WRITE);
  if (sensorData) {
    sensorData.close(); // close the file
  // }
  else {
    Serial.println("Error 20 writing to file !");


float setPointTemp(float myTime){
// This returns the set point temp as a function of time
   float amplitude = 0;
   float mean = 25;
   float timePeriod = 2400;
   // At the moment, the set point is a constant 25 deg C. Eventually we shall make this a sinusoidal function.
   // (But lets test it thoroughly first!
  float s = mean +  sin (6.28*amplitude*myTime/timePeriod);
  return s;

The error is:

Operation started
Card failed, or not present
End of delay loop
Error 20 writing to file !

I will be very grateful for your help.


Card failed, or not present
Bad wiring, bad card, bad reader or interference with other attached hardware..

I very much dislike the output of wrong/misleading messages,
locking loops and delays longer than a couple of ms.

Did you write that code, or is it based on something you found somewhere?

Ah, this is obviously some strange usage of the word 'safe' that I wasn't previously aware of. (D.Adams)


I have just started coding on Arduino and I started the code and then it was modified by my supervisor. It used to work with a PushButton, however, once I replaced it with a toggle switch, it started to show this error. At the moment, the person who helped me with the code is away and I don't know which bits of code to change in order to get rid of the error. Help will be very much appreciated.



I have a similar  problem and suspect that the SD card shield itself is the problem

your code seems OK to me- but I agree that long delays are not very elegant in such an application
I read somewhere that supply voltage is an issue if the card reader runs on 3.3 V and you are using a 5V microcontroller (uno  for instance)

anyway I hope you get your system to work and I would be very interested to hear the outcome

best regards


Go Up