Reading and Writing to SD Card with PIC Microcontroller using MPLAB Code Configurator

Curiosity Development board with microSD

Reading and Writing to SD Card with PIC Microcontroller using MPLAB Code Configurator

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.

In the article, Interfacing SD Card With PIC Microcontroller – XC8, we learned how to interface and SD card with PIC microcontroller and how to use Chan’s FatFs Library to Read/write data to an SD/SDHC cards. The SPI configuration of the PIC was done with MPLAB Code Configurator (MCC), however adapted the Chan’s FatFs library files to work with our MCC project which is a tedious job and could break when using a new Chan’s FatFs library version.

Microchip has released the File System library for MCC Device Libraries that configures the Chan’s FatFs library with MCC, thus no need to manually configure all the individual files like the ffconfig.h, diskio.c, diskio.h etc.

In this article we are going to learn how to use MCC File System library to write/read text to SD/SDHC cards with PIC Microcontroller. We are going to use the PIC16F18346 with Curiosity development board and microSD Click, but any PIC with enough memory supported by MCC could also do the job.

To learn the different types of SD cards and how to interface them with a PIC microcontroller, please watch the video below or refer to this article:

Interfacing SD Card With PIC Microcontroller – XC8

Watch the video Tutorial: Connection

Project Setup

Microchip File System Library 

The File System library provides access to the FatFs file system library and SD Card library. In this tutorial we are using File System library v1.00
FatFS is basically Chan’s FatFs a generic FAT file system available through an open source license. It provides functions to writing to physical media devices that use the FAT file system, a common file system used on removable media devices like multi-media cards or USB memory sticks.

For more information regarding FatFs including module settings documentation, FatFs application notes, and file system API documentation please visit the FatFs Home page: http://elm-chan.org/fsw/ff/00index_e.html

System Requirements

  • MPLAB® X IDE v5.15 or later
  • XC8 compiler v2.05 or later
  • XC16 compiler v1.36b or later
  • XC32 compiler v2.15 or later
  • MCC Plugin Version 3.75 or later
  • Foundation Services Library v0.1.32 or later

We’re gonna start a new MPLAB Project and select the PIC16F18346, in the Hardware Tool, we are going to select Microchip Starter Kits (PKOB) to use the the Curiosity development board  

Start MCC  and do the following configurations:

System Module:

We selected the Internal Oscillator and set it to 16MHz and enabled the Low-Voltage programming mode, this is important as the curiosity development board works only in Low-Voltage programming mode.

FatFs

In the Device Resources, ad the FatFs library, it will also add automatically the SD Card (SPI) under the Foundation Services library

Click on Insert Driver to create a physical driver and set its label name. You can click on the Help button on the FatFs to get more information on how to configure this section.

The rest of the setting are more or less left to their default values. You can play around with these settings to disable the features you don’t need to optimize the code.

SD Card (SPI)

Here we are going to Enable the Chip Select (CS) pin only. Once enabled, you will have to define this pin in Pin manager as well.

Map the SPI pins to the correct pins of your PIC microcontroller, using the Curiosity development board SPI SDI1 is set to RB4, SDO1 to RC7, SCK1 to RB6 and CS to RC6.

SPIMASTER

With our current clock settings, it has given us the SPI speed SDSLOW of 400KHz to initialize the SD card and SDFAST of 2MHz for normal operation.

Click Generate to generate the MCC files.

Description of Some FatFs functions

f_mount
This function Register/Unregister a work area (mount SD Card). This function must always be called before any other file functions except for f_fdisk function
Parameters:
File system object: Pointer to the file system object to be registered and cleared. Null pointer unregisters the registered file system object. example: FATFS FatFs
Logical drive number: Pointer to the null-terminated string that specifies the logical drive. The string without drive number means the default drive. example: “” for default driver.
Initialization option: 0: Do not mount now (to be mounted later), 1: Force mounted the volume to check if the FAT volume is ready to work.
Return Values: When a function succeeded, it returns zero, otherwise returns non-zero value that indicates type of error. FR_OK (0: The function succeeded.), FR_INVALID_DRIVE, FR_DISK_ERR, FR_NOT_READY, FR_NO_FILESYSTEM
Example:

f_open
This function Open/Create a file.
Parameters:
File object structure:Pointer to the blank file object structure. Example: FIL Fil
File name: Pointer to the null-terminated string that specifies the file name to open or create. Example: “test.txt”
Mode flags: specifies the type of access and open method for the file. It is specified by a combination of following flags:

  • FA_OPEN_ALWAYS: Opens the file if it is existing. If not, a new file will be created.
  • FA_READ: Data can be read from the file.
  • FA_WRITE: Data can be written to the file. Combine with FA_READ for read-write access.
  • FA_CREATE_NEW: Creates a new file. The function fails if the file is existing.
  • FA_CREATE_ALWAYS: Creates a new file. If the file is existing, it will be truncated and overwritten.
  • FA_OPEN_EXISTING: Opens the file. The function fails if the file is not existing. (Default)

Return Values: When a function succeeded, it returns zero, otherwise returns non-zero value that indicates type of error. FR_OK (0: The function succeeded.)
Example:

f_read
This function reads data from a file
Parameters: FRESULT f_read (FIL* fp, void* buff, UINT btr, UINT* br);
File object: Pointer to the open file object.
buffer: Pointer to the buffer to store read data.
btr: Number of bytes to read in range of UINT type.
br: Pointer to the UINT variable to return number of bytes read. The value is always valid after the function call regardless of the result.
Return Values: When a function succeeded, it returns zero, otherwise returns non-zero value that indicates type of error. FR_OK (0: The function succeeded.)
f_write
This function writes data to a file.
Parameters: FRESULT f_write (FIL* fp, const void* buff, UINT btw, UINT* bw);
fp: Pointer to the open file object structure.
buff: Pointer to the data to be written.
btw: Specifies number of bytes to write in range of UINT type.
bw: Pointer to the UINT variable to return the number of bytes written. The value is always valid after the function call regardless of the result.
Example:

f_lseek
This function moves the file read/write pointer of an open file object. It can also be used to expand the file size (cluster pre-allocation).
Parameters: FRESULT f_lseek (FIL* fp, DWORD ofs);
fp: Pointer to the open file object.
ofs: Byte offset from top of the file.
f_gets
This function reads a string from the file.
TCHAR* f_gets (
TCHAR* buff, /* [OUT] Read buffer */
int len, /* [IN] Size of the read buffer */
FIL* fp /* [IN] File object */
);
f_putc
This funciton puts a character to the file.
int f_putc (
TCHAR chr, /* [IN] A character to put */
FIL* fp /* [IN] File object */
);
f_puts
This function writes a string to the file.
int f_puts (
const TCHAR* str, /* [IN] String */
FIL* fp /* [IN] File object */
);
f_printf
This function writes formatted string to the file.
int f_printf (
FIL* fp, /* [IN] File object */
const TCHAR* fmt, /* [IN] Format stirng */

);
f_size
This function gets the size of a file.
DWORD f_size (
FIL* fp /* [IN] File object */
);
f_close
This function closes an open file.
FRESULT f_close (
FIL* fp /* [IN] Pointer to the file object */
);
More details can be obtained from the  popular Chan’s FatFs Generic FAT File System Module. website.

Project Example

The code below is main.c file, we are going to open the file “TEST.TXT” if it exists if it doesn’t exist it will be created, then open and write: “Hello world! This is text message written to sd card” on the first line and on the second line write: “For more information, please visit www.studentcompanion.co.za”

You can download the full project files (MPLAB XC8 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 Mplab X Project: SD-Card-Microchip-File

Share this post


You've just added this product to the cart:

Select your currency
EUR Euro
USD United States (US) dollar