The more we know the harder it is to defeat us!

Recently I have written a short post about the HAL library created by STM32. The HAL is gaining popularity among hobbyists and is more and more frequently used. However, when you would like to use it for something else than just basic stuff like generating PWM on digital output you have to write it by yourself. Not so long ago I had to use SD card in one of my projects. It turned out that there is no driver for FatFS based on HAL – at least there was not. I decided to write the driver and here you can read about it…

FatFS delivers you with a template which you have to fill up so you can communicate with the SD card. In my case I needed something simple and straightforward. I decided to implement hardware layer for SPI based on HAL. There is no DMA transfer, it is just a simple implementation that works pretty well with not very frequent transfers. It is well-suited for log purposes.

You need to write definition for a few functions:

  • void SELECT(void),
  • void DESELECT(void),
  • void xmit_spi(BYTE Data),
  • BYTE rcvr_spi(void).

Below are definitions of those four functions:

As you can see I am using SPI2 but you can use whatever SPI you want. For details about the HAL functions look up the documentation.

Final remark.

If you do not use chip select pin you can simply pull-down CS input port of SD card and leave SELECT and DESELECT functions empty or create empty macros which would be a bit more efficient.

Update

Below you can find my full implementation of diskio.c based on ChaN original file with some tweaks.

sd_stm32.c

sd_stm32.h

Update 2

I have forgotten to mention that this is non standart implementation in terms of timing. The function disk_timerproc() is required to be called every 10 ms (100 Hz). Since this implementation was using in a project where I was using FreeRTOS with finer grain (0.1 ms) I  had to modify the sdcard_systick_timerproc() function.

If you want it to be standard implementation you have to modify the code above. Simply instead of 100 place 10 and call this function every 1 ms i.e. in SysTick handler. Thanks lauba for pointing this out!

10 Responses to Using FatFS with HAL

Leave a Reply

Your email address will not be published. Required fields are marked *

Donate

If you like my blog please consider a small donation.

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 227 other subscribers