Watch the video Tutorial part 1:

                        Memory Cards

A memory card (also called a flash memory card) is a solid-state electronic data storage device used for storing digital information. They are commonly used in many electronic devices, including digital cameras, mobile phones, laptop computers, MP3 players etc.
They are small, re-writable and are able to retain data without power.
This ability to retain data and the ability to re-write many times is the key for flash memory card applications, for example, in digital cameras, where the saved pictures are not lost after the memory card is removed from the camera.

There are many different types of memory cards available in the market today. Some of the most commonly known memory cards are:
–> Smart media (SM) card
–> Multimedia card (MMC)
–> Compact flash (CF) card
–> Memory stick (MS) card
–> Microdrive
–> xD card
–> Secure digital (SD) card: SD cards are the most widely used memory cards today. They are based on MMC and in terms of functionality they are the same ( except that the SD has an optional encryption feature). The SD are physically thicker than MMCs and would not fit into MMC slots. The MMC, on the other hand, can be easily inserted into SD card slots.
SD cards are available in three different sizes: normal SD, miniSD, and microSD as shown on figure 1 below:

SD Cards                    

SD Card                            MiniSD                      MicroSD
Figure 1: SD Cards

Table 1: Technical Properties of Memory Cards

Note: The new SDXC Cards have capacity up to 2TB.

Most SD cards and MMCs particularly those sized below 2 gigabytes (GBs), use the FAT16 standard. In this article we will use the FAT32 standard to address memory sized between 2 gigabytes and 2 terabytes.

SD Card Pin Configuration

The card has nine pins, as shown in the figure 2 below, and a write-protect switch to enable/disable writing onto the card.

SD Card pins

Figure 2: SD Card pins

A standard SD card can be operated in two modes: the SD Bus mode and the SPI Bus mode.
In SD Bus mode, all the pins of the card are used, data is transferred using four pins (D0–D3), a clock (CLK) pin, and a command line (CMD).
In SPI Bus mode using a chip select (CS) and a CLK line. The following pins are used in SPI Bus mode:
–> Chip select:   Pin 1
–> Data in:        Pin 2
–> Clock:           Pin 5
–> Data out:      Pin 7
–> Positive:        Pin 4
–> Ground:        Pin 3 and 6

The Card operates with 3.3V supply voltage and these are the logic levels:
Maximum logic 0 output voltage, VOL = 0.4125 V
Minimum required logic 1 input voltage, VIH = 2.0625 V
Maximum logic 1 input voltage = 3.6 V
Maximum required logic 0 input voltage, VIL = 0.825 V
When connected to a PIC microcontroller, the output voltage (2.475 V) of the SD card to the PIC is enough to drive the input circuit of the microcontroller, but the typical logic 1 output voltage of a PIC microcontroller pin is 4.3 V, and this is too to apply to the card, where the maximum voltage should not exceed 3.6 V. As a result of this, it is required to use resistors at the inputs of the SD card to lower the input voltage.
Figure 3 below shows a typical SD card interface to a PIC microcontroller in SPI mode. In this figure, 2.2K and 3.3K resistors are used as a potential divider circuit to lower the SD card input voltage to approximately 2.48 V, as shown below.

SD card input voltage = 4.3 V × 3.3 K / (2.2 K + 3.3 K) = 2.48 V.

SD card connected in SPI mode to Port C of PIC Microcontroller

Figure 3: SD card connected in SPI mode to Port C of PIC Microcontroller.

SD cards can consume up to 100–200 mA while reading or writing onto the card. This is usually a high current, and an appropriate voltage regulator capable of supplying the required current must be used in the design.
The card consumes approximately 150 μA in sleep (the card goes automatically in sleep mode if it doesn’t receive any command in 5ms).

Watch the video Tutorial part 2:

    mikroC Pro for PIC FAT32 Library

Reading and writing onto SD cards is very complex and requires some complex functions and procedures to handle the card I/O operations correctly. The great news is that MikroC Pro for PIC compiler provides all these for free in mikroC FAT32 library. This library is not included in the mikroC Pro for PIC compiler at the moment (mikroC version 6.5.0) but it can be downloaded from LibStock.

The file you are going to download has an .mpkg extension. You need the package manager to integrate this FAT32 library into the MikroElekronika compilers. You can download the latest package manager from MikroElekronika website.

Once you have installed the package manager, Open the desired package file (*.mpkg) and it’s content will be displayed in Navigation and Information sections.

Click on File->Install option and the installation will begin. Installer will copy your package content into destination folders and update your definition files.

Figure 4: Installing a library into mikroC compiler

New installed library will appear in Library Manager of your compiler, and only for those chips that are compatible with installed library.

Figure 5: New installed library (FAT32) in mikroC library manager

For SD Cards size below 2 GB, you may consider to use the already include in the compiler, the Multi Media Card Library. To learn more, read our article: Interfacing SD Card with PIC Microcontroller.

FAT32 lifts many constraints imposed by FAT16 file system. The key benefits is more addressable space(>2GB) and less wasted space due to smaller cluster size.

This library is designed to simplify handling of the underlying hardware (SD/MMC cards), but also to be hardware independent. This library should work on any microcontroller with more than 1.5kB of RAM

This FAT32 Library supports:

  • SD/MMC cards.
  • Files and folders operation.
  • Multiple files read/write operation.


  • If the storage device has Master Boot Record (MBR), the library will work with the first available primary (logical) partition that has non-zero size. If the device has Volume Boot Record (i.e. there is only one logical partition and no MBRs), the library works with entire device as a single partition.
  • Before write operation, make sure you don’t overwrite Boot, FSI, or FAT sectors as it could make your card on PC or digital camera unreadable.
  • It is necessary to setup communication with the storage device properly. For example – if SD/MMC cards are used, SPI module for communication is required by the library.

FAT32 Library External Dependencies
The following variable must be defined in all projects using FAT32 library:

const unsigned short FAT32_MAX_FILES and __FILE fat32_fdesc[FAT32_MAX_FILES.
Example : 

Below is a quick descriptions of the FAT32 library routines as described in the FAT32 library help file:

Library Routines

This function Initializes the SD card, reads FAT32 boot sector and extract necessary data required by the library. The SD card has to be formatted to FAT32 file system. This routine will return ‘0’ if the initialization was successfully or ‘-1’ if there was an error during the initialization (Boot Record not found, storage device read/write error, etc). You must call this function before and the initialization must be successful before doing any other thing.

This function initializes the storage device and formats it to FAT32. This routine will return ‘0’ if the initialization was successfully or ‘-1’ if there was an error during the initialization (Boot Record not found, storage device read/write error, etc). This routine can be used instead or in conjunction with FAT32_Init routine.

“DEVICE” is the volume label (up to 11 characters in length). If less than 11 characters are provided, the label will be padded with spaces. If null string is passed volume will not be labeled.

This routine is used to create new directory with the name you specify. The SD card needs to be initialized first before calling this routine. This routine will return ‘0’ if the directory creation was successful and ‘-1’ if there was an error during function call (not enough space, directory name already exists, read/write error, etc.).

Figure 6: create directory (folder) and name it: DIR_A

This routine is used to change current directory to another directory that you specify. The SD card needs to be initialized first before calling this routine. This routine will return ‘0’ if the directory creation was successful and ‘-1’ if there was an error during function call (not enough space, directory name already exists, read/write error, etc.).

This routine is used to open a file for reading, writing, or appending via FILE_READ, FILE_WRITE, or FILE_APPEND operation, respectively.
In read mode only, the file must already exist. In write/append mode, the file is created if it did not exist.
In read/write mode, file cursor is reset to 0 on file open. In append mode, file cursor is moved at the end of the file.
There can be as many as FAT32_MAX_FILES files opened at the same time.
Prototype: int8 FAT32_Open(char *fn, uint8 mode);
fn: name of the file to be opened
mode: mode of operation: Read, Write or Append.
The SD card needs to be initialized first before calling this routine.

This routine is used to close an already opened file selected by fHandle. If the file selected is not opened (or due to any other error), the routine will return ‘-1’. The routine is responsible for file size and modified time update.
Parameters: fHandle: file handle index. Valid values are 0..FAT32_MAX_FILES-1. File pointed by fHandle needs to be opened first before calling this routine

This routine Writes requested number of bytes to the currently opened file.
Prototype: int8 FAT32_Write(short fHandle, char *wrBuf, uint16 len);
fHandle: file handle index. Valid values are 0..FAT32_MAX_FILES-1.
wrBuf: write buffer.
len: number of bytes to be written. it should not be greater then length of .
This routine will return ‘0’ if the write operation was completed successfully or ‘-1’ if there was an error during function call.
Before using this routine, the file pointed by fHandle needs to be opened first.

You can read the FAT32 library help file to learn more about all the routines.

This program creates a folder called DIR_A inside the SD Card and creates two files inside that folder called TEST.TXT and TEST2.TXT . The following text will be written in TEST.TXT file: “Hello, this is text written in TEST.TXT” and the following in the other file: Hello, and this one is text written in TEST2.TXT”. All these processes and feedback will be sent to PC via the PIC UART including the initialization feedback as shown on figure 7 below.

Figure 7: Display messages on PC on a successful operation

Figure 8 below shows the creation of two files inside the DIR_A folder.

Figure 8: Creation of two files

Figure 9 below shows the content written on the two files.

Figure 9: Content written on the two files

Figure 10 below shows the circuit diagram of the project.

Interfacing SD Card to PIC18F45K22

Figure 10: Interfacing SD Card to PIC18F45K22

Circuit diagram

The circuit diagram above on figure 5 shows an SD Card interfaced to PIC18F45K22.
The CS pin of the card is connected to RC2 of the PIC, Din of card to Do1 (RC5) of PIC, Do of card to Di1 (RC4) of card and CLK of card to CLK1 of PIC (RC3).
The power connections of the card are not shown here, but should be connected to the 3.3V variable regulator (U2). VDD and VSS of the pic microcontroller are not shown in the circuit diagram. VDD should be connected to +5V and VSS to GND. A reset circuit is connect to the MCLR pin. An 8MHz crystal oscillator is connected OSC1 and OSC2 of the PIC but this frequency is raised to 32MHz internally with the PLL. A voltage level converter, the MAX232 is used to interface the PIC to a PC COM port.

mikroC Source Code  

You can download the full project files (MikroC source code and Proteus Schematic design) below here.
All the files are zipped, you will need to unzip them (Download a free version of the Winzip utility to unzip files).

Download mikroC source code: SD_Card_FAT32
Download Proteus Schematic: Interfacing SD Card FAT32