Connecting an SD Card to a Microcontroller.
In one of my previous articles we displayed an image from an SD card on a display, but a few points were left out: first, connecting the card itself; second, only some of the Petit FatFs library functions were covered. Let's look at these points in more detail.
Communication with the card is possible over one of two interfaces, SPI or SD.




I should say that the SD interface can work in one-bit and four-bit modes.
The SPI wiring diagram for the card is standard and looks like this; unused card pins should be pulled up to the supply with 10K resistors.

But in hobby projects the pull-up resistors are often omitted, simplifying the wiring.
It should be noted that when connected via SPI, the card is very sensitive to the supply voltage, and even a small sag in the supply voltage makes the card stop working; I've verified this from personal experience. I can't say anything about the SD interface, as I haven't tried it yet. I'm writing all this to say that you must put capacitors on the power supply. As for the inductor, it should be rated for up to 100mA, but it's optional.
The diagrams above show that the card needs 3.3 volts, so the voltage on the data lines must not go outside the 0 – 3.3 volt range, and here the question arises: what if the MCU runs on 5 volts?
The answer is simple: the data lines need level matching, and this can be done with an ordinary resistive divider.

The diagram shows that the MISO line doesn't need level matching, since data on this line is transmitted from the card to the MCU.
In reality, few people connect the card directly to the MCU; it's much more convenient to connect a card socket to the MCU or buy a shield with a socket and all the necessary components.

We've dealt with the connection; now let's look at how to use the Petit FatFs library, designed for 8-bit microcontrollers with little memory.
The library consists of 5 files:
integer.h - a header file that describes the basic data types.
diskio.h - a header file that declares the prototypes of the low-level disk functions and the status codes they return.
diskio.c - the low-level functions must be implemented in this file; initially it contains "stubs".
pffconf.h - the configuration file.
pff.h - a header file that declares the prototypes of the functions for interacting with the disk's file system.
pff.c - the file contains the implementations of the functions for interacting with the disk's file system.
You can see that for the library to work, the low-level functions must be implemented. But if we're talking about AVR or PIC, you can download an example of using the library for them from the website; it contains an mmc file in which the low-level functions are already implemented. You also need to set the library configuration in the pff.h file and write the functions needed for SPI to work.
Petit FatFs functions.
FRESULT pf_mount (FATFS*) — the function mounts/unmounts a disk. This function must be called before starting to work with the disk; if the function is called with a null pointer, the disk is unmounted. The function can be called at any time.
Parameters
FATFS* fs — a pointer to an object of type FATFS; the description of this structure can be found in pff.h. We just need to declare a variable of this type.
Return values:
FR_OK (0) — returned if the function succeeds
FR_NOT_READY — the device could not be initialized
FR_DISK_ERR — an error occurred while reading from the disk
FR_NO_FILESYSTEM — there is no valid FAT partition on the disk
FRESULT pf_open (const char* path) — the function opens an existing file. Once a file is open, you can work with it, i.e. read from and write to it. You can work with an open file until another file is opened. The function can be called at any time.
Parameters
const char* path — a pointer to a string specifying the path to the file. The path must be specified in full relative to the root directory, with directories separated by slashes.
Return values:
FR_OK (0) — returned if the function succeeds
FR_NO_FILE — file not found
FR_DISK_ERR — disk error
FR_NOT_ENABLED — the disk was not mounted
FRESULT pf_read(void* buff, WORD btr, WORD* br) — the function reads the specified number of bytes from a file and stores them in a buffer. If the number of bytes read is less than specified, the end of the file has been reached. For the function to work, you need to write the following in pffconf.h
#define _USE_READ 1
Parameters:
void* buff — a pointer to the buffer where the read data is stored
WORD btr — the number of bytes to read
WORD* br — a pointer to a variable that stores the number of bytes read.
Return values:
FR_OK (0) — returned if the function succeeds
FR_DISK_ERR — disk error
FR_NOT_OPENED — the file was not opened
FR_NOT_ENABLED — the disk was not mounted
FRESULT pf_write(const void* buff, WORD btw, WORD* bw) — the function lets you write data to an open file. For the function to work, you need to write the following in pffconf.h
#define _USE_WRITE 1
Parameters:
void* buff — a pointer to the buffer we want to write; a null value finalizes the write
WORD btw — the number of bytes we want to write
WORD* bw — a pointer to a variable that stores the number of bytes actually written. By analyzing this variable, you can find out whether the end of the file has been reached.
Return values:
FR_OK (0) — returned if the function succeeds
FR_DISK_ERR — disk error
FR_NOT_OPENED — the file was not opened
FR_NOT_ENABLED — the disk was not mounted
Because the library is designed for microcontrollers with little memory, this function has a number of limitations:
To understand the second-to-last point, you need to know that the card's memory is divided into 512-byte blocks (sectors), and writing can only start at the beginning of a sector. So if we want to write 1000 bytes, the first sector will be written completely, while only 488 bytes will be written to the second, and the remaining 24 bytes will be filled with zeros.
To write to an open file, you need to do the following:
To give an example of how the write function works, we need to look at one more function.
FRESULT pf_lseek(DWORD offset) - sets the read/write pointer in an open file. The pointer can be set with an absolute or relative offset; for an absolute offset, pass a number to the function
for a relative offset, pass the value of the pointer to the current position fs.fptr plus the offset
For the function to work, you need to write the following in pffconf.h
#define _USE_LSEEK 1
Parameters:
DWORD offset - the number of bytes by which to move the pointer.
Return values:
FR_OK (0) — returned if the function succeeds
FR_DISK_ERR — disk error
FR_NOT_OPENED — the file was not opened
Data can be written to a file as follows.
I'm also leaving here a piece of actually working code that uses all the functions described above.
FRESULT pf_opendir(DIR* dp, const char * path) — the function opens an existing directory and creates a pointer to an object of type DIR, which will be used to get the list of files in the open directory.
For the function to work, you need to write the following in pffconf.h
#define _USE_DIR 1
Parameters:
DIR *dp — a pointer to a variable of type DIR.
const char * path — a pointer to a string containing the path to the directory; directories are separated by slashes
Return values:
FR_OK (0) — returned if the function succeeds
FR_NO_PATH — the path could not be found
FR_NOT_READY — the disk could not be initialized
FR_DISK_ERR — disk error
FR_NOT_ENABLED — the disk was not mounted
FRESULT pf_readdir(DIR* dp, FILINFO* fno) — the function lets you read the contents of a directory. To do this, open the directory with pf_opendir() and call pf_readdir(). Each time it's called, the function returns the name of an object (folder/file) located in the specified directory. When it has gone through all the objects, it returns an empty string in the fno.fname[] array.
For the function to work, you need to write the following in pffconf.h
#define _USE_DIR 1
Parameters:
DIR *dp — a pointer to a variable of type DIR, which must be declared beforehand
FILINFO *fno — a pointer to a variable of type FILINFO, which must be declared beforehand.
Return values:
FR_OK - the function completed successfully
FR_DISK_ERR - disk error
FR_NOT_OPENED - the directory is not open
And finally, I'll leave a working project here sd_card_example.rar.
I bought the shield here.
Communication with the card is possible over one of two interfaces, SPI or SD.




I should say that the SD interface can work in one-bit and four-bit modes.
The SPI wiring diagram for the card is standard and looks like this; unused card pins should be pulled up to the supply with 10K resistors.

But in hobby projects the pull-up resistors are often omitted, simplifying the wiring.
It should be noted that when connected via SPI, the card is very sensitive to the supply voltage, and even a small sag in the supply voltage makes the card stop working; I've verified this from personal experience. I can't say anything about the SD interface, as I haven't tried it yet. I'm writing all this to say that you must put capacitors on the power supply. As for the inductor, it should be rated for up to 100mA, but it's optional.
The diagrams above show that the card needs 3.3 volts, so the voltage on the data lines must not go outside the 0 – 3.3 volt range, and here the question arises: what if the MCU runs on 5 volts?
The answer is simple: the data lines need level matching, and this can be done with an ordinary resistive divider.

The diagram shows that the MISO line doesn't need level matching, since data on this line is transmitted from the card to the MCU.
In reality, few people connect the card directly to the MCU; it's much more convenient to connect a card socket to the MCU or buy a shield with a socket and all the necessary components.

We've dealt with the connection; now let's look at how to use the Petit FatFs library, designed for 8-bit microcontrollers with little memory.
The library consists of 5 files:
integer.h - a header file that describes the basic data types.
diskio.h - a header file that declares the prototypes of the low-level disk functions and the status codes they return.
diskio.c - the low-level functions must be implemented in this file; initially it contains "stubs".
pffconf.h - the configuration file.
pff.h - a header file that declares the prototypes of the functions for interacting with the disk's file system.
pff.c - the file contains the implementations of the functions for interacting with the disk's file system.
You can see that for the library to work, the low-level functions must be implemented. But if we're talking about AVR or PIC, you can download an example of using the library for them from the website; it contains an mmc file in which the low-level functions are already implemented. You also need to set the library configuration in the pff.h file and write the functions needed for SPI to work.
Petit FatFs functions.
FRESULT pf_mount (FATFS*) — the function mounts/unmounts a disk. This function must be called before starting to work with the disk; if the function is called with a null pointer, the disk is unmounted. The function can be called at any time.
Parameters
FATFS* fs — a pointer to an object of type FATFS; the description of this structure can be found in pff.h. We just need to declare a variable of this type.
Return values:
FR_OK (0) — returned if the function succeeds
FR_NOT_READY — the device could not be initialized
FR_DISK_ERR — an error occurred while reading from the disk
FR_NO_FILESYSTEM — there is no valid FAT partition on the disk
FATFS fs;//declare an object of type FATFS
//mount the disk
if (pf_mount(&fs) == FR_OK )
{
//the disk is mounted, work with it
//unmount the disk
pf_mount(NULL);
}
else
{
//failed to mount the disk
}
FRESULT pf_open (const char* path) — the function opens an existing file. Once a file is open, you can work with it, i.e. read from and write to it. You can work with an open file until another file is opened. The function can be called at any time.
Parameters
const char* path — a pointer to a string specifying the path to the file. The path must be specified in full relative to the root directory, with directories separated by slashes.
Return values:
FR_OK (0) — returned if the function succeeds
FR_NO_FILE — file not found
FR_DISK_ERR — disk error
FR_NOT_ENABLED — the disk was not mounted
FATFS fs;//declare an object of type FATFS
//mount the disk
if (pf_mount(&fs) == FR_OK )
{
//open a file located in the root directory
if(pf_open("hello.txt") == FR_OK)
{
//do something
}
//open a file located in the new folder
if(pf_open("new/hello.txt") == FR_OK)
{
//do something
}
//unmount the disk
pf_mount(NULL);
}
else
{
//failed to mount the disk
}
FRESULT pf_read(void* buff, WORD btr, WORD* br) — the function reads the specified number of bytes from a file and stores them in a buffer. If the number of bytes read is less than specified, the end of the file has been reached. For the function to work, you need to write the following in pffconf.h
#define _USE_READ 1
Parameters:
void* buff — a pointer to the buffer where the read data is stored
WORD btr — the number of bytes to read
WORD* br — a pointer to a variable that stores the number of bytes read.
Return values:
FR_OK (0) — returned if the function succeeds
FR_DISK_ERR — disk error
FR_NOT_OPENED — the file was not opened
FR_NOT_ENABLED — the disk was not mounted
FATFS fs;//declare an object of type FATFS
BYTE buff[10];//buffer for reading the file
WORD br; //counter of bytes read
//mount the disk
if (pf_mount(&fs) == FR_OK )
{
//open a file located in the root directory
if(pf_open("hello.txt") == FR_OK)
{
//read 10 bytes from it
pf_read(buff, 10, &br);
if(br != 10)
{
//if br is not equal to 10
//it means we've reached the end of the file
}
}
}
FRESULT pf_write(const void* buff, WORD btw, WORD* bw) — the function lets you write data to an open file. For the function to work, you need to write the following in pffconf.h
#define _USE_WRITE 1
Parameters:
void* buff — a pointer to the buffer we want to write; a null value finalizes the write
WORD btw — the number of bytes we want to write
WORD* bw — a pointer to a variable that stores the number of bytes actually written. By analyzing this variable, you can find out whether the end of the file has been reached.
Return values:
FR_OK (0) — returned if the function succeeds
FR_DISK_ERR — disk error
FR_NOT_OPENED — the file was not opened
FR_NOT_ENABLED — the disk was not mounted
Because the library is designed for microcontrollers with little memory, this function has a number of limitations:
- you can't create new files; you can only write to existing ones
- you can't increase the file size
- you can't update the timestamp
- a write operation can only be started/stopped on a sector boundary
- the "read-only" file attribute can't prevent writing
To understand the second-to-last point, you need to know that the card's memory is divided into 512-byte blocks (sectors), and writing can only start at the beginning of a sector. So if we want to write 1000 bytes, the first sector will be written completely, while only 488 bytes will be written to the second, and the remaining 24 bytes will be filled with zeros.
To write to an open file, you need to do the following:
- set the pointer to a sector boundary; if it's not set to a boundary, the pointer will be rounded down to the lower sector boundary
- call the write function the required number of times
- finalize the write by calling the function with a null pointer
To give an example of how the write function works, we need to look at one more function.
FRESULT pf_lseek(DWORD offset) - sets the read/write pointer in an open file. The pointer can be set with an absolute or relative offset; for an absolute offset, pass a number to the function
pf_lseek(5000);for a relative offset, pass the value of the pointer to the current position fs.fptr plus the offset
pf_lseek(fs.fptr + 3000);For the function to work, you need to write the following in pffconf.h
#define _USE_LSEEK 1
Parameters:
DWORD offset - the number of bytes by which to move the pointer.
Return values:
FR_OK (0) — returned if the function succeeds
FR_DISK_ERR — disk error
FR_NOT_OPENED — the file was not opened
Data can be written to a file as follows.
FATFS fs;//declare an object of type FATFS
BYTE buff[10];//buffer for reading the file
WORD br; //counter of bytes read
//mount the disk
if (pf_mount(&fs) == FR_OK )
{
//open a file located in the root directory
if(pf_open("hello.txt") == FR_OK)
{
//set the pointer to the first sector
pf_lseek(0);
//write
pf_write(buff, 10, &br);
//finalize the write
pf_write(0, 0, &br);
}
}
I'm also leaving here a piece of actually working code that uses all the functions described above.
#define F_CPU 8000000UL
#define buff_size 10
#include <stdlib.h>
#include <avr/io.h>
#include "diskio.h"
#include "pff.h"
#include "spi.h"
FATFS fs;//declare an object of type FATFS
BYTE read_buff[buff_size];//buffer for reading the file
BYTE write_buff[buff_size] = "hello word";////buffer for writing to the file
UINT br; //counter of bytes read
int main(void)
{
//mount the disk
if (pf_mount(&fs) == FR_OK )
{
//open a file located in the new folder
if(pf_open("new/hello.txt") == FR_OK)
{
//set the write pointer
pf_lseek(0);
//write
pf_write(write_buff, buff_size, &br);
//finalize the write
pf_write(0, 0, &br);
//set the read pointer
pf_lseek(0);
//read what we wrote
pf_read(read_buff, buff_size, &br);
if(br != buff_size)
{
//if br is not equal to buff_size
//it means we've reached the end of the file
}
}
//unmount the disk
pf_mount(NULL);
}
while(1)
{
}
}
FRESULT pf_opendir(DIR* dp, const char * path) — the function opens an existing directory and creates a pointer to an object of type DIR, which will be used to get the list of files in the open directory.
For the function to work, you need to write the following in pffconf.h
#define _USE_DIR 1
Parameters:
DIR *dp — a pointer to a variable of type DIR.
const char * path — a pointer to a string containing the path to the directory; directories are separated by slashes
Return values:
FR_OK (0) — returned if the function succeeds
FR_NO_PATH — the path could not be found
FR_NOT_READY — the disk could not be initialized
FR_DISK_ERR — disk error
FR_NOT_ENABLED — the disk was not mounted
//declare the variables
FATFS fs;
DIR dir;
//mount the disk
pf_mount(&fs);
//open the directory
pf_opendir(&dir, "MY_FOLDER");
FRESULT pf_readdir(DIR* dp, FILINFO* fno) — the function lets you read the contents of a directory. To do this, open the directory with pf_opendir() and call pf_readdir(). Each time it's called, the function returns the name of an object (folder/file) located in the specified directory. When it has gone through all the objects, it returns an empty string in the fno.fname[] array.
For the function to work, you need to write the following in pffconf.h
#define _USE_DIR 1
Parameters:
DIR *dp — a pointer to a variable of type DIR, which must be declared beforehand
FILINFO *fno — a pointer to a variable of type FILINFO, which must be declared beforehand.
Return values:
FR_OK - the function completed successfully
FR_DISK_ERR - disk error
FR_NOT_OPENED - the directory is not open
FATFS fs;
FRESULT res;
FILINFO fno;
DIR dir;
//mount the disk
pf_mount(&fs);
//open the directory
res = pf_opendir(&dir, MY_FOLDER);
//read the contents of the directory
for(;;){
res = pf_readdir(&dir, &fno);
//check whether any errors occurred while reading
// and whether there are more files in the specified directory
if ((res != FR_OK) || (fno.fname[0] == 0)){
break;
}
//output fno.fname in a convenient way
usart_sendStr(fno.name);
usart_sendStr(/r);
}
And finally, I'll leave a working project here sd_card_example.rar.
I bought the shield here.