SD Card 1

Dependencies:   mbed SDFileSystem

main.cpp

Committer:
devananda
Date:
2020-12-06
Revision:
1:36503ac7a3ba
Parent:
0:fad6683294f8

File content as of revision 1:36503ac7a3ba:

#include "mbed.h"
#include "SDFileSystem.h"
#include "errno.h"

SDFileSystem    fs(D11, D12, D13, D7, "sd");  // mosi, miso, sck, cs
FILE*           fp;

/**
 * @brief
 * @note
 * @param
 * @retval
 */
int main()
{
    printf("Mounting file system...\r\n");

    int err = fs.mount();
    printf("%s\r\n", (err ? "Failed :(\r\n" : "OK\r\n"));
    if (err)
        return err;

    // Open the file.
    printf("Opening file '/sd/mytest/sdtest.txt'... ");
    fp = fopen("/sd/mytest/sdtest.txt", "w+");
    printf("%s\r\n", (!fp ? "Failed :(\r\n" : "OK\r\n"));

    if (!fp)
    {
        // Check whether directory '/sd/mytest' exists.
        printf("\r\nChecking directory '/sd/mytest'...\r\n");

        struct stat info;
        err = stat("/sd/mytest", &info);
        if (err)
        {
            printf("Directory '/sd/mytest' does not exist.\r\n");
            printf("Trying to create it...");
            err = mkdir("/sd/mytest", 0777);
            printf("%s\r\n", (err ? "Failed :(\r\n" : "OK\r\n"));
            if (err)
                return err;
        }

        // Create a new 'sdtest.txt' file.
        printf("File not found, creating a new one...\r\n");
        fp = fopen("/sd/mytest/sdtest.txt", "w+");
        printf("%s\r\n", (!fp ? "Failed :(" : "OK"));
        if (!fp)
        {
            error("error: %s (%d)\r\n", strerror(errno), -errno);
            return errno;
        }
    }

    for (int i = 0; i < 10; i++)
    {
        printf("Writing numbers (%d/%d)... ", i, 10);
        err = fprintf(fp, "    %d\r\n", i);
        if (err < 0)
        {
            printf("Fail :(\r\n");
            error("error: %s (%d)\r\n", strerror(errno), -errno);
        }
        else
            printf("OK\r\n");
    }

    printf("Writing numbers (%d/%d)... OK\r\n\r\n", 10, 10);
    err = fclose(fp);
    printf("Closing file '/sd/mytest/sdtest.txt'... ");
    printf("%s\r\n", (err ? "Failed :(\r\n" : "OK\r\n"));
    if (err)
        return err;

    return 0;
}