Program used to log data will not log data into text file

Hi! So I coded a program to log data from a sensor to a text file, but it won’t work and the data is not being logged into the text file. The Serial monitor outputs the data right, but it won’t appear in the text file. The text file is just blank when I run this code.

Code

#include <SPI.h>
#include <SD.h>
#include <Wire.h>

const int chipSelect = 10;

int sensor = 0;

File logfile;

String dataString;


void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }


  Serial.print("Initializing SD card...");

  pinMode(10, OUTPUT);

  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");
}



void loop() {
  String dataString = "";
  sensor = analogRead(A0);
  dataString += String(sensor);

  File logfile = SD.open("datalog.txt", FILE_WRITE);
  if (logfile) {
    Serial.println(dataString);
    logfile.println(dataString);
    logfile.close();
  }
  else {
    Serial.println("can't access file");
  }

I don’t really know what I am doing so help would be greatly appreciated.
Thanks!

Welcome to the forum!

What Arduino board do you use?
What size has the SD card?

The code you show does not compile.
The code looks quite similar to the code used as example for the data logger shield (but missing some lines):

#include <SPI.h>
#include <SD.h>
#include <Wire.h>

const int chipSelect = 10;
int sensor = 0;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");
}

void loop() {
  String dataString = "";
  sensor = analogRead(A0);
  dataString += String(sensor);

  File logfile = SD.open("datalog.txt", FILE_WRITE);
  if (logfile) {
    Serial.println(dataString);
    logfile.println(dataString);
    logfile.close();
  }
  else {
    Serial.println("can't access file");
  }
  delay(5000);
}

When I run this code with my data logger shield mounted on an Arduino UNO, I get the expected results (file “datalog.txt” with sensor data).

Show your complete code please.

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