fatfs sample: file close error (-5)

Hi, I'm running the fatfs sample using an Actinius Icarus board (nrf9160) and a microSD card, connected via SPI. The original sample works as it should (it mounts and opens the SD card and then lists the files on it), but when adding some lines to write a file, I'm having the following issue:

  • If the string I'm trying to write has more than 11 characters, it writes well but then I get the message: "<err> fs: file close error (-5)". When opening the file on the SD card using a USB reader, sometimes I can see the file with the string I wrote, but sometimes It has different characters. I already tried to synchronize the file first using fs_sync() and it returned "file sync error (-5)". I also checked this ticket: https://devzone.nordicsemi.com/f/nordic-q-a/92166/fs-file-write-error--5  but deleting the line does not solve my issue, since it doesn't print the error message but the writing still fails.
  • If the string I'm trying to write has less than 11 characters, the system starts rebooting repeatedly and never writes anything.

This is the .overlay I'm using:

&spi3{
    status = "okay";
    cs-gpios = <&gpio0 03 GPIO_ACTIVE_LOW>;
    sdhc0: sdhc@0 {
        compatible = "zephyr,sdhc-spi-slot";
        reg = <0>;
        status = "okay";
        label = "SDHC0";
       mmc {
            compatible = "zephyr,sdmmc-disk";
            status = "okay";
        };
        spi-max-frequency = <24000000>;
    };
};


This is the additional .config file I added (I'm aware that some of these lines might be unnecessary since they seem to be repeated):

CONFIG_SPI=y
CONFIG_GPIO=y
CONFIG_DISK_ACCESS=y
CONFIG_DISK_DRIVER_SDMMC=y
CONFIG_DISK_DRIVERS=y
CONFIG_FS_FATFS_EXFAT=y
CONFIG_SDHC=y
CONFIG_LOG=y
CONFIG_FILE_SYSTEM=y
CONFIG_FAT_FILESYSTEM_ELM=y
CONFIG_PRINTK=y
CONFIG_MAIN_STACK_SIZE=4096
CONFIG_SPI_NRFX_RAM_BUFFER_SIZE=8


And these are the lines I added to main.c:
struct fs_file_t file;
int err;
char data[] = "aaaaaaaaaaaa";                          //This is the string whose length determines how the system works

err = fs_open(&file, "/SD:/test.txt",FS_O_WRITE | FS_O_CREATE);
if (err) {
    printk("Error al abrir el archivo: %d\n" ,err);
}
err = fs_write(&file, data, sizeof(data));
if (err < 0) {
    printk("Error al escribir en el archivo: %d\n", err);
}
printk("Escrito correctamente %d bytes.\n", err);
err = fs_close(&file);

I'm working with SDK version 2.1.0.
Thanks in advance,
Rocío
Related