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

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /* 2545_SD_Card Example
00002 
00003 Example of writing data to SD card.
00004 
00005 Based on FTF2014_lab4 Example
00006 
00007 https://developer.mbed.org/teams/Freescale/wiki/FTF2014_workshop
00008 
00009 Craig A. Evans, University of Leeds, Mar 2016
00010 
00011 */
00012 
00013 #include "mbed.h"
00014 #include "SDFileSystem.h"
00015 
00016 // Connections to SD card holder on K64F (SPI interface)
00017 SDFileSystem sd(PTE3, PTE1, PTE2, PTE4, "sd"); // MOSI, MISO, SCK, CS
00018 
00019 void delete_file(char filename[]);
00020 
00021 int main()
00022 {
00023     printf("#### SD Card Example #####\n");
00024     FILE *fp; // this is our file pointer
00025     wait(1);
00026 
00027     // Various examples below - can comment out ones you don't need
00028 
00029     /////////////////////// Deleting file example ////////////////////////
00030 
00031     // comment this line out if you don't want to delete the file!
00032     delete_file("/sd/test.txt");
00033 
00034     ////////////////////// Simple writing example //////////////////////////
00035 
00036     // open file for writing ('w') - creates file if it doesn't exist and overwrites
00037     // if it does. If you wish to add a score onto a list, then you can
00038     // append instead 'a'. This will open the file if it exists and start
00039     // writing at the end. It will create the file if it doesn't exist.
00040     fp = fopen("/sd/topscore.txt", "w");
00041     int top_score = 56;  // random example
00042 
00043     if (fp == NULL) {  // if it can't open the file then print error message
00044         printf("Error! Unable to open file!\n");
00045     } else {  // opened file so can write
00046         printf("Writing to file....");
00047         fprintf(fp, "%d",top_score); // ensure data type matches
00048         printf("Done.\n");
00049         fclose(fp);  // ensure you close the file after writing
00050     }
00051 
00052     ////////////////////// Simple reading example //////////////////////////
00053 
00054     // now open file for reading
00055     fp = fopen("/sd/topscore.txt", "r");
00056     int stored_top_score = -1;  // -1 to demonstrate it has changed after reading
00057 
00058     if (fp == NULL) {  // if it can't open the file then print error message
00059         printf("Error! Unable to open file!\n");
00060     } else {  // opened file so can write
00061         fscanf(fp, "%d",&stored_top_score); // ensure data type matches - note address operator (&)
00062         printf("Read %d from file.\n",stored_top_score);
00063         fclose(fp);  // ensure you close the file after reading
00064     }
00065 
00066     ///////////////////// Writing list to file example //////////////////////
00067     
00068     // for this example, I'll create some numbers to write to file in a big list
00069     // a data logger for example will usually append to a file - at a reading
00070     // at the end rather than creating a new file
00071     fp = fopen("/sd/test.txt", "a");
00072 
00073     if (fp == NULL) {  // if it can't open the file then print error message
00074         printf("Error! Unable to open file!\n");
00075     } else {  // opened file so can write
00076         printf("Writing to file....");
00077         for(int i = 1; i <= 50; i++) {
00078             float dummy = 1000.0F/i;  // dummy variable
00079             fprintf(fp, "%d,%f\n",i,dummy);  // print formatted string to file (CSV)
00080         }
00081         printf("Done.\n");
00082         fclose(fp);  // ensure you close the file after writing
00083     }
00084     
00085     // you can comment out the writing example to check that the writing has
00086     // worked - when you run it after commenting, it should still open the
00087     // file that exists on the SD card - assuming you didn't delete it!
00088 
00089     /////////////////////// Reading from file example ////////////////////////
00090 
00091     // now open file for reading...note the 'r'
00092     fp = fopen("/sd/test.txt", "r");
00093     if (fp == NULL) {  // if it can't open the file then print error message
00094         printf("Error! Unable to open file!\n");
00095     } else {
00096         printf("Reading file....\n");
00097         int i;    // create suitable variables to store the data in the file
00098         float value;
00099 
00100         // in this example, we keep reading (using fscanf) until we reach
00101         // the 'end of file'. Note we use the address operator & to write
00102         // to the variables. Also the format of the string must match what
00103         // is in the file
00104         while (fscanf(fp, "%d,%f", &i, &value) != EOF) {
00105             printf("%d,%f\n",i,value);
00106         }
00107         printf("Done.\n");
00108         fclose(fp);  // ensure you close the file after reading
00109     }
00110 
00111     ///////////////// Advanced Reading from file example ///////////////////
00112 
00113     // the previous example just read the values into variables and printed to
00114     // serial, we'll now read files into an array.
00115 
00116     // now open file for reading...note the 'r'
00117     fp = fopen("/sd/test.txt", "r");
00118 
00119     int n=0;  // going to store the number of lines in the file
00120     int *index_array;  // pointers to create dynamic arrays later
00121     float *value_array; // note memory will be in heap rather than on the stack
00122 
00123     if (fp == NULL) {  // if it can't open the file then print error message
00124         printf("Error! Unable to open file!\n");
00125     } else {
00126         printf("Counting lines in file....\n");
00127         //Since we may not know the
00128         // number of lines in the files ahead of time, we'll first count them
00129         // * means scan but don't save
00130         while (fscanf(fp, "%*d,%*f") != EOF) {
00131             n++;  // increment counter when read a line
00132         }
00133 
00134 
00135         printf("Read %d lines\n",n);
00136         printf("Creating dynamic arrays...\n");
00137         // calloc creates an array and initilises to 0
00138         // malloc returns unitialised array - diffrent syntax
00139         index_array = (int *)calloc(n, sizeof (int));
00140         value_array = (float *)calloc(n, sizeof (float));
00141 
00142         int i=0;
00143         rewind(fp); // 'scrolled' to end of file, so go back to beginning
00144         printf("Reading into arrays...\n");
00145         while (fscanf(fp, "%d,%f",&index_array[i],&value_array[i]) != EOF) {
00146             i++;  // read data into array and increment index
00147         }
00148         printf("Done.\n");
00149         fclose(fp);  // ensure you close the file after reading
00150     }
00151     
00152     // we should now have the data in the arrays, will print to serial to check
00153     for(int i=0; i<n ; i++) {
00154         printf("[%d] %d,%f\n",i,index_array[i],value_array[i]);
00155     } 
00156 
00157     ///////////////////////////////////////////////////
00158     printf("End of SD card example\n");
00159 }
00160 
00161 void delete_file(char filename[])
00162 {
00163     printf("Deleting file '%s'...",filename);
00164     FILE *fp = fopen(filename, "r");  // try and open file
00165     if (fp != NULL) {  // if it does open...
00166         fclose(fp);    // close it
00167         remove(filename);  // and then delete
00168         printf("Done!\n");
00169     }
00170     // if we can't open it, it doesn't exist and so we can't delete it
00171 }