Example of using the SDFileSystem library on a K64F to write data to files and also read data into dynamically created arrays.

Dependencies:   mbed

Revision:
0:5448330e1a33
Child:
1:caceb9d9d17a
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Fri Mar 11 16:07:41 2016 +0000
@@ -0,0 +1,173 @@
+/* 2545_SD_Card Example
+
+Example of writing data to SD card.
+
+Based on FTF2014_lab4 Example
+
+https://developer.mbed.org/teams/Freescale/wiki/FTF2014_workshop
+
+Craig A. Evans, University of Leeds, Mar 2016
+
+*/
+
+#include "mbed.h"
+#include "SDFileSystem.h"
+
+// Connections to SD card holder on K64F (SPI interface)
+SDFileSystem sd(PTE3, PTE1, PTE2, PTE4, "sd"); // MOSI, MISO, SCK, CS
+Serial serial(USBTX, USBRX);  // for PC debug
+
+void delete_file(char filename[]);
+
+int main()
+{
+    serial.baud(115200);  // full-speed!
+    serial.printf("#### SD Card Example #####\n");
+    FILE *fp; // this is our file pointer
+    wait(1);
+
+    // Various examples below - can comment out ones you don't need
+
+    /////////////////////// Deleting file example ////////////////////////
+
+    // comment this line out if you don't want to delete the file!
+    delete_file("/sd/test.txt");
+
+    ////////////////////// Simple writing example //////////////////////////
+
+    // open file for writing ('w') - creates file if it doesn't exist and overwrites
+    // if it does. If you wish to add a score onto a list, then you can
+    // append instead 'a'. This will open the file if it exists and start
+    // writing at the end. It will create the file if it doesn't exist.
+    fp = fopen("/sd/topscore.txt", "w");
+    int top_score = 56;  // random example
+
+    if (fp == NULL) {  // if it can't open the file then print error message
+        serial.printf("Error! Unable to open file!\n");
+    } else {  // opened file so can write
+        serial.printf("Writing to file....");
+        fprintf(fp, "%d",top_score); // ensure data type matches
+        serial.printf("Done.\n");
+        fclose(fp);  // ensure you close the file after writing
+    }
+
+    ////////////////////// Simple reading example //////////////////////////
+
+    // now open file for reading
+    fp = fopen("/sd/topscore.txt", "r");
+    int stored_top_score = -1;  // -1 to demonstrate it has changed after reading
+
+    if (fp == NULL) {  // if it can't open the file then print error message
+        serial.printf("Error! Unable to open file!\n");
+    } else {  // opened file so can write
+        fscanf(fp, "%d",&stored_top_score); // ensure data type matches - note address operator (&)
+        serial.printf("Read %d from file.\n",stored_top_score);
+        fclose(fp);  // ensure you close the file after reading
+    }
+
+    ///////////////////// Writing list to file example //////////////////////
+    
+    // for this example, I'll create some numbers to write to file in a big list
+    // a data logger for example will usually append to a file - at a reading
+    // at the end rather than creating a new file
+    fp = fopen("/sd/test.txt", "a");
+
+    if (fp == NULL) {  // if it can't open the file then print error message
+        serial.printf("Error! Unable to open file!\n");
+    } else {  // opened file so can write
+        serial.printf("Writing to file....");
+        for(int i = 1; i <= 50; i++) {
+            float dummy = 1000.0F/i;  // dummy variable
+            fprintf(fp, "%d,%f\n",i,dummy);  // print formatted string to file (CSV)
+        }
+        serial.printf("Done.\n");
+        fclose(fp);  // ensure you close the file after writing
+    }
+    
+    // you can comment out the writing example to check that the writing has
+    // worked - when you run it after commenting, it should still open the
+    // file that exists on the SD card - assuming you didn't delete it!
+
+    /////////////////////// Reading from file example ////////////////////////
+
+    // now open file for reading...note the 'r'
+    fp = fopen("/sd/test.txt", "r");
+    if (fp == NULL) {  // if it can't open the file then print error message
+        serial.printf("Error! Unable to open file!\n");
+    } else {
+        serial.printf("Reading file....\n");
+        int i;    // create suitable variables to store the data in the file
+        float value;
+
+        // in this example, we keep reading (using fscanf) until we reach
+        // the 'end of file'. Note we use the address operator & to write
+        // to the variables. Also the format of the string must match what
+        // is in the file
+        while (fscanf(fp, "%d,%f", &i, &value) != EOF) {
+            serial.printf("%d,%f\n",i,value);
+        }
+        serial.printf("Done.\n");
+        fclose(fp);  // ensure you close the file after reading
+    }
+
+    ///////////////// Advanced Reading from file example ///////////////////
+
+    // the previous example just read the values into variables and printed to
+    // serial, we'll now read files into an array.
+
+    // now open file for reading...note the 'r'
+    fp = fopen("/sd/test.txt", "r");
+
+    int n=0;  // going to store the number of lines in the file
+    int *index_array;  // pointers to create dynamic arrays later
+    float *value_array; // note memory will be in heap rather than on the stack
+
+    if (fp == NULL) {  // if it can't open the file then print error message
+        serial.printf("Error! Unable to open file!\n");
+    } else {
+        serial.printf("Counting lines in file....\n");
+        //Since we may not know the
+        // number of lines in the files ahead of time, we'll first count them
+        // * means scan but don't save
+        while (fscanf(fp, "%*d,%*f") != EOF) {
+            n++;  // increment counter when read a line
+        }
+
+
+        serial.printf("Read %d lines\n",n);
+        serial.printf("Creating dynamic arrays...\n");
+        // calloc creates an array and initilises to 0
+        // malloc returns unitialised array - diffrent syntax
+        index_array = (int *)calloc(n, sizeof (int));
+        value_array = (float *)calloc(n, sizeof (float));
+
+        int i=0;
+        rewind(fp); // 'scrolled' to end of file, so go back to beginning
+        serial.printf("Reading into arrays...\n");
+        while (fscanf(fp, "%d,%f",&index_array[i],&value_array[i]) != EOF) {
+            i++;  // read data into array and increment index
+        }
+        serial.printf("Done.\n");
+        fclose(fp);  // ensure you close the file after reading
+    }
+    
+    // we should now have the data in the arrays, will print to serial to check
+    for(int i=0; i<n ; i++) {
+        serial.printf("[%d] %d,%f\n",i,index_array[i],value_array[i]);
+    } 
+
+    ///////////////////////////////////////////////////
+    serial.printf("End of SD card example\n");
+}
+
+void delete_file(char filename[])
+{
+    serial.printf("Deleting file '%s'...",filename);
+    FILE *fp = fopen(filename, "r");  // try and open file
+    if (fp != NULL) {  // if it does open...
+        fclose(fp);    // close it
+        remove(filename);  // and then delete
+        serial.printf("Done!\n");
+    }
+    // if we can't open it, it doesn't exist and so we can't delete it
+}