2

How do I get the Arduino to write the measurement data onto the micro SD card when the write function only accepts integers?

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

int CS_PIN = 10;
int ledPin = 13;
int EP =9;



File file;

void setup()
{

  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(EP, INPUT);

  initializeSD();



}


void loop(){
  long measurement =TP_init();
  delay(50);
 // Serial.print("measurment = ");
  Serial.println(measurement);

  createFile("test.txt");
  writeToFile(measurement);
  closeFile();
}



long TP_init(){
  delay(10);
  long measurement=pulseIn (EP, HIGH);  //wait for the pin to get HIGH and   returns measurement
  return  String(measurement);

}





void initializeSD()
{
  Serial.println("Initializing SD card...");
  pinMode(CS_PIN, OUTPUT);

  if (SD.begin())
  {
    Serial.println("SD card is ready to use.");
  } else
  {
    Serial.println("SD card initialization failed");
    return;
  }
}

int createFile(char filename[])
{
  file = SD.open(filename, FILE_WRITE);

  if (file)
  {
    Serial.println("File created successfully.");
    return 1;
  } else
  {
    Serial.println("Error while creating file.");
    return 0;
  }
}

int writeToFile(char text[])
{
  if (file)
  {
    file.println(text);
    Serial.println("Writing to file: ");
    Serial.println(text);
    return 1;
  } else
  {
    Serial.println("Couldn't write to file");
    return 0;
  }
}

void closeFile()
{
  if (file)
  {
    file.close();
    Serial.println("File closed");
  }
}

int openFile(char filename[])
{
  file = SD.open(filename);
  if (file)
  {
    Serial.println("File opened with success!");
    return 1;
  } else
  {
    Serial.println("Error opening file...");
    return 0;
  }
}

String readLine()
{
  String received = "";
  char ch;
  while (file.available())
  {
    ch = file.read();
    if (ch == '\n')
    {
      return String(received);
    }
    else
    {
      received += ch;
    }
  }
  return "";
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ABD DUDE
  • 21
  • 1
  • 2
  • Why you are declaring the returned value of `TP_init()` as a `long` and returning inside the function a `String` (`return String(measurement);`) ? – J. Piquard Mar 04 '17 at 23:54

1 Answers1

1

You can write a 4-byte long value using the variant of the write function that accepts a buffer and a byte count. Just pass the address of the variable you want to write out and the size of the type:

long measurement;

file.write((byte*)&measurement, sizeof(long)); // write 4 bytes

You can read it like this:

file.read((byte*)&measurement, sizeof(long)); // read 4 bytes
samgak
  • 23,944
  • 4
  • 60
  • 82
  • What do you mean, would i put the file,write stuff in the write to file function? – ABD DUDE Mar 05 '17 at 09:59
  • The writeToFile function writes a string of characters, so you can't put it there. Write another function writeLongToFile or similiar – samgak Mar 05 '17 at 19:02