FreeRTOS, fatfs, and spi. interrupt issues?

sjkklein wrote on Friday, July 01, 2016:

Hello all!

This is my first time using freertos. I am using a SAM4 chip and trying to configure it so that it can write to an sd card.

I currently have it setup for one task to simply write to the sd. When I read back the file it is all good except for at extremely regular intervals I get a segment of extended ascii garbage inside my file, but mostly I just see the good data. My first instinct was that the tick interrupt was causing an error in my spi communications.

The first thing I tried was a lazy approach that I thought was garaunteed to work. I surrounded each call to a fatfs function with portENTER_CRITICAL and portEXIT_CRITICAL. I realize that is not a good way to do it and it was really just a diagnostic measure. But anyways… No dice, identacle behavior to before.

The next thing I tried was to write one thing and then wait for the next tic in order to write again. I know that the write fits in between ticks. I get the same data corruption in (weirdly) the exact same spot.

I know that this is RTOS related because when I run very similar code without the rtos it writes perfectly.

Any ideas? I don’t even know what to try next. I seem to get corrupt data every 400 characters or so.

rtel wrote on Saturday, July 02, 2016:

Are you 100% sure the SPI to SD card interface is working solidly when
you are not using FreeRTOS?

How is the SPI driver functioning, is it using interrupts or just polling?

Are you sure the SPI is not accessed by any other tasks.

If you share the fatfs file system between tasks then you have to set a
constant in the file system’s configuration file, but as you are only
using it from one task that should not be necessary.

(by the way, we have our own file system working on Atmel Cortex-M chips
too - see

sjkklein wrote on Tuesday, July 05, 2016:

I am 100% sure that the interfaces works without FreeRTOS.

Currently it is configured for polling, but ultimately I want to use the DMA and change it to interrupt based.

I have only been running one task because I can’t get it to work, so it is certainly the only one accessing SPI.

Thanks for posting that link! That is some good stuff. I may try to just implement it with that FAT filesystem used in those demo examples. I am really at a loss, I cannot trace down my error.

sjkklein wrote on Tuesday, July 05, 2016:

I’m posting here for the people that inevitably run into the same problem. The above comment made me realize I was mounting the SD in the main, so I guess sharing the filesystem between main and the task caused an issue. When I ran the code without free rtos I was just calling the task function and it worked perfectly. When I used FreeRTOS it did not work until I mounted it once within the function. I don’t know why that worked, but I think I don’t understand mounting very well…