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

Dependencies:   mbed

main.cpp

Committer:
eencae
Date:
2020-02-03
Revision:
1:caceb9d9d17a
Parent:
0:5448330e1a33

File content as of revision 1:caceb9d9d17a:

/* 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

void delete_file(char filename[]);

int main()
{
    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
        printf("Error! Unable to open file!\n");
    } else {  // opened file so can write
        printf("Writing to file....");
        fprintf(fp, "%d",top_score); // ensure data type matches
        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
        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 (&)
        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
        printf("Error! Unable to open file!\n");
    } else {  // opened file so can write
        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)
        }
        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
        printf("Error! Unable to open file!\n");
    } else {
        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) {
            printf("%d,%f\n",i,value);
        }
        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
        printf("Error! Unable to open file!\n");
    } else {
        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
        }


        printf("Read %d lines\n",n);
        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
        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
        }
        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++) {
        printf("[%d] %d,%f\n",i,index_array[i],value_array[i]);
    } 

    ///////////////////////////////////////////////////
    printf("End of SD card example\n");
}

void delete_file(char filename[])
{
    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
        printf("Done!\n");
    }
    // if we can't open it, it doesn't exist and so we can't delete it
}