STM32 SD Card (SPI) is not writing in an interrupt

168 views Asked by At

I am working on STM32F103 aka Bluepill. I will be using my project on human body so it should be compact (i.e. not connected to computer by cables).

I have an external interrupt by a chip at every 10ms. I am getting four 28bit values. I concatenate them in a string and send them over UART at the speed of 115200 bps. It works this way but i need it to be compact as I said before. I used HC05 bluetooth module to send my data wirelessly but it misses data no matter how much I tried. So decided to save them in an SD Card using SPI (like a data logger). I used FatFs library.

Firstly, I did a simple example. I used ADC in polling mode took 10000 data and save them immediately in a loop to see how quickly it saves using led toggle and it was pretty quick (Quicker then 10ms).

I am using this piece of code to write to SD Card:

      res= f_mount(&fs, "", 0);
      res= f_open(&fil, "write.txt", FA_OPEN_ALWAYS | FA_WRITE | FA_READ);
      res= f_lseek(&fil, fil.fsize);
      res= f_write(&fil, adc1char , strlen(adc1char), (void *)&bw);
      res= f_close(&fil);

Then tried to implement it to my original code. Wrote it in the external interrupt. But it does not work. It is not writing. If I write it in the main loop while(1) it writes some data but less than the original one and it repeats(re-writes) a lot of them.

What do you think is the problem? How can I solve it? Thanks in advance.

1

There are 1 answers

1
wek On

My guess is, that those functions - f_mount(), f_open() etc. - rely on some interrupt, too, and it's blocked by your interrupt from where you're calling being of higher or equal priority.

So, a quick fix would be to find that interrupt and set it higher priority than your interrupt is.

However, generally it's a bad idea to call lengthy functions from ISR. The usual pattern is to use interrupts only to move necessary data and set up signals/flags, which are then handled in main(). You need to take care of atomicity, i.e. variables which have to form a consistent group must be changed in a way that at any point an interrupt happens it does not "see" an inconsistent state. A common way to deal with this is to use ring buffers.

Also, you cannot rely on an SD card storing data consistently below 10ms just because you "tested" it in one particular setting. Using file system may result in a need to perform a series of writes internally in the file system library, and also the SD card itself may decide to perform lengthy maintenance operations.