#include <SD.h>
#include <SPI.h>
File myFile;
char fileName[] = "sample.txt";
const int chipSelect = 10;
char charRead;
//char SampleText[] = "Hello World";
void setup()
{
Serial.begin(9600);
if (SD.begin(chipSelect))
{
Serial.println("SD card is present & ready");
}
else
{
Serial.println("SD card missing or failure");
}
}
void loop()
{
char ReceiveArray[20]="";
Serial.println("Enter a string less than 6 bytes");
Serial.println();
for(int k = 0; k < 7; k++) {
while ((Serial.available())==0);
charRead = tolower(Serial.read()); //force ucase
// Serial.write(charRead); //write it back to Serial window
if (charRead == '\n') //end of line (or 10)
{
exit;
}
else
ReceiveArray[k] = charRead;
}
myFile = SD.open(fileName, FILE_WRITE);
if (myFile) // it opened OK
{
Serial.println("Writing to sample.txt");
myFile.println(ReceiveArray);
myFile.close();
Serial.println("Done");
}
else
Serial.println("Error opening sample.txt");
delay (1000);
readFromFile(); //read
delay (1000);
if (SD.exists(fileName))
{
Serial.println("Removing sample.txt");
SD.remove(fileName);
}
}
void readFromFile()
{
byte i=0; //counter
char inputString[100]; //string to hold read string
//now read it back and show on Serial monitor
// Check to see if the file exists:
if (!SD.exists(fileName))
Serial.println("sample.txt doesn't exist.");
Serial.println("Reading from sample.txt:");
myFile = SD.open(fileName);
while (myFile.available())
{
char inputChar = myFile.read(); // Gets one byte from serial buffer
if (inputChar == '\n') //end of line (or 10)
{
inputString[i] = 0; //terminate the string correctly
Serial.println(inputString);
i=0;
}
else
{
inputString[i] = inputChar; // Store it
i++; // Increment where to write next
if(i> sizeof(inputString))
{
Serial.println("Incoming string longer than array allows");
Serial.println(sizeof(inputString));
while(1);
}
}
}
}