OS 6 SD Card filesystem gets corrupted when written to

Hello, I am using the DISCO-L475VG IoT board and this code:

#include "mbed.h"
#include "SDBlockDevice.h"
#include "FATFileSystem.h"

// Instantiate the SDBlockDevice by specifying the SPI pins connected to the SDCard
// socket. The PINS are:
//     MOSI (Master Out Slave In)
//     MISO (Master In Slave Out)
//     SCLK (Serial Clock)
//     CS (Chip Select)
uint8_t block[512] = "Hello World!\n";

int main()
    // Call the SDBlockDevice instance initialisation method
    if (0 != sd.init()) {
        printf("Init failed \n");
        return -1;
    printf("sd size: %llu\n",         sd.size());
    printf("sd read size: %llu\n",    sd.get_read_size());
    printf("sd program size: %llu\n", sd.get_program_size());
    printf("sd erase size: %llu\n",   sd.get_erase_size());

    // Set the frequency
    if (0 != sd.frequency(5000000)) {
        printf("Error setting frequency \n");

    if (0 != sd.erase(0, sd.get_erase_size())) {
        printf("Error Erasing block \n");

    // Write data block to the device
    if (0 == sd.program(block, 0, 512)) {
        // Read the data block from the device
        if (0 == sd.read(block, 0, 512)) {
            // Print the contents of the block
            printf("%s", block);

    // Call the SDBlockDevice instance de-initialisation method

When the code runs and writes to the card, it successfully outputs the contents of the block to the terminal using sd.read(). However, the card is unreadable when inserted to a windows pc and I have to reformat it. I have double, triple checked my wiring, and have run through a few different example codes, forum posts etc. I formatted the SD card as FAT32, and am powering the SD card reader off of 5V from the mbed. (I tried 3.3V also)

Hardware connections between SPI SD Card reader (left) and DISCO board (right).


you need combinate the SDblockdevice with a FileSystem, in context of Windows - FATFileSystem - API references and tutorials | Mbed OS 6 Documentation

BR, Jan

This Mbed OS5 example appears to also work for me in OS6. Thanks so much! This is a massive headache that you have helped me overcome. I can only hope that the documentation for mbed’s API’s improves over time.