I am trying to save some data to the SD card using the memory shield module that I read from HC-SR04 Ultrasonic Module. The data that gets printed indicates error. This is how my SD card module is connected.

SD card attached to SPI bus as
VCC -Arduino 5v
GND- Arduino GND
MOSI - pin 11
MISO - pin 12
CLK - pin 13
CS - pin 4

Still, Arduino complains that there was an error opening the file in SD card. My sketch is this:

#include <SPI.h>
#include <SD.h>
#define echoPin 6 // Echo Pin
#define trigPin 7 // Trigger Pin

int maximumRange = 250; // Maximum range needed
int minimumRange = 1; // Minimum range needed
long duration, distance; // Duration used to calculate distance
const int chipSelect = 4;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  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:
  Serial.println("card initialized.");

void loop() {
  if(distance>minimumRange && distance < maximumRange){
    String string = "distance is" + distance;
    // open the file. note that only one file can be open at a time,
    // so you have to close this one before opening another.
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    // if the file is available, write to it:
    if( dataFile ){
      Serial.println( string );
      // if the file isn't open, pop up an error:
      Serial.println("error opening datalog.txt");
    Serial.println("Out of range...");

int readDistance(){
  digitalWrite(trigPin, LOW); 
  digitalWrite(trigPin, HIGH);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration/58.2;


rror opening datalog.txt
rror opening datalog.txt
error opening datalog.txt
rror opening datalog.txt
error opening datalog.txt
error opening datalog.txt
error opening datalog.txt
error opening datalog.txt
error opening datalog.txt

How do I solve this to save the readings to SD card?

  • 1
    Re-opening the file each time through the loop seems like a bad idea. Unfortunately file system abstractions don't map very well to what you want to do. You may want to write a number of readings, then re-open a file, perhaps with a different name in an incrementing pattern. Or you could skip the filesystem and write to raw blocks. Most practically, have a look at the code typically used with Arduino-based uSD data loggers and see what you can learn from how they handle it. – Chris Stratton Mar 10 '16 at 18:51
  • 1
    I think you have fried your SD card. Those cards operate at 3.3V and may not be 5V tolerant. – Maxthon Chan Mar 11 '16 at 7:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.