Using SDCard with STM32F103C8T6 board.

Dependencies:   mbed SDFileSystem

Using SD Card with STM32F103C8T6 board

Schematic

/media/uploads/hudakz/stm32f103c8t6_sdcard.png

Wiring
STM32F103C8T6SDCard slot
GND<=>VSS
+3.3V<=>VDD
PB_5<=>CMD/DI
PB_4<=>DO/DAT0
PB_3<=>CLK
PA_10<=>CS/DAT3

main.cpp

Committer:
hudakz
Date:
2019-02-05
Revision:
2:cb349fd2a36a
Parent:
1:e8699d7ca61a

File content as of revision 2:cb349fd2a36a:

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

Serial         pc(PA_2, PA_3);
SDFileSystem*  fs;
FILE*          fp;

int main()
{
    pc.baud(9600);
    
    // Create and mount SDFileSystem
    fs = new SDFileSystem(PB_5, PB_4, PB_3, PA_10, "sd"); // mosi, miso, sck, cs
    pc.printf("Mounting file system...\r\n");
    int err = fs->mount();
    pc.printf("%s\r\n", (err ? "Failed :(\r\n" : "OK\r\n"));
    if (err)
        return err;

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

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

        // Create a new 'sdtest.txt' file.
        pc.printf("File not found, creating a new one...\r\n");
        fp = fopen("/sd/mytest/sdtest.txt", "w+");
        pc.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++) {
        pc.printf("Writing numbers (%d/%d)... ", i, 10);
        err = fprintf(fp, "    %d\r\n", i);
        if (err < 0) {
            pc.printf("Fail :(\r\n");
            error("error: %s (%d)\r\n", strerror(errno), -errno);
        } else
            pc.printf("OK\r\n");
    }

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

    return 0;
}