The on board USB module on the PIC microcontroller is very powerful able to function as both a device and host and is excellent for data logging applications. However sometimes you require a little higher transfer speed in your embedded application. For that reason we may need to use an SD card. SD cards are used to store data for your embedded system and are compact and robust little devices that function at very high speed. In this post we look at writing a text file to an SD card.

The SD Card

Secure Digital Cards or SD cards are memory devices use flash to store data that will be used in your end application. SD Cards are a non-volatile type of storage device and can maintain the data that is written to them even after the power is removed.

SD cards are made from a special type of Flash known as NAND flash. This type of memory is very robust and can withstand hundreds of thousands of read/write cycles. There are also older Multimedia Cards or MMCs that are slowly fading out but is compatible with SD cards.

SD cards can be either Standard SD cards that typically have storage capacities up to 4 GB or High Capacity cards (SDHC) that reach up to about 64 GB capacity as well as Extended Capacity (SDXC) that reach into the terabyte range.

SD Cards also have different sizes or form factors including the standard SD, mini SD and micro SD cards.

SD cards have speed classes that for SDHC ranges from class 2 which runs at speeds of  2 MB/s, class 4 which runs at 4MB/s, class 6 which runs at up to 6 MB/s and class 10 which runs at up to 10 MB/s. SDXC cards run in the Ultra High Speed class and run at up to 30 Mb/s. There is also the Video Speed Class and have data transfer rates of up to 90MB/s.

SD cards can be operated in SD bus mode or SPI bus mode. Since the PIC32MX270F256D lacks a SDIO bus, we will use the SD card in SPI bus mode.

SD cards have a maximum working voltage of 3.6 volts, and since the PIC32MX270F256D operates at a voltage of 3.3v we should have no problem interfacing to the card.

In order to read and write to the SD card and then view the files on a computer, we need a file system. The robust and time tested Microchip’s Memory Disk Drive File System  or Microchip MDDFS will be used as the file system for reading and writing to the SD card.


Connections

SD Card is connected as shown above. You MUST include the capacitor as these cards draw a lot of power during power up and initialization, make sure it is a low ESR cap like tantalum or ceramic.


C Program

/*
 * File: Main.c
 * Author: Armstrong Subero
 * Processor: PIC32MX270F256D w/Ext OSC @ 4MHz, PLL to 48 MHz, 3.3v
 * Program: 17_SD_Card_FS
 * Compiler: XC32 (v1.44, MPLAX X v4.00)
 * Program Version: 1.0
 *                             
 * Program Description: This Program Allows PIC32MX270F256D to use an SD card 
 *                      with a file system. This is dependent on the legacy PLIB 
 *                      libraries.
 * 
 * Hardware Description: An MH SD card breakout module is connected as follows:
 *                        GND  -> GND
 *                        3.3V -> 3.3v
 *                        CS   -> RC6 
 *                        MOSI -> RB2
 *                        SCK  -> RB14
 *                        MISO -> RB1
 *                        GND  -> GND
 * 
 * A Sparkfun SD/MMC breakout was also tested and was connected as follows:
*                     
*                    D2         --> NC
*                    D3(SS)     --> (pullup to VCC) RC6
*                    CMD(MOSI)  --> (pullup to VCC) RB2
*                    CD         --> NC
*                    CLK(SCK)   --> RB14
*                    VCC        --> 3.3V (Decoupled, cap, tantalum)(10uF)
*                    GND        --> GND  (Decoupled, cap, tantalum)
*                    D0(MISO)   --> (pullup to VCC)RB1
*                    D1         --> NC
*                    WP         --> NC
* 
 * Change History:
 *
 * Author             Rev     Date          Description
 * Armstrong Subero   1.0     09/04/2018    Initial Release.
 * 
 *                      
 * Created April 9th, 2018, 12:43 AM
 * 
 * 
 */

#define _SUPPRESS_PLIB_WARNING     //Remove warnings
#include <stdio.h>
#include <GenericTypeDefs.h>
#include "PIC32MX270_STD.h"
#include "Delay.h"
#include "plib.h"
#include "MDD_includes/FSIO.h"
#include "MDD_includes/FSIO.h"


/*******************************************************************************
* Function Name: void initMain (void)
*
* Specification: initializes main
*
*******************************************************************************/
void initMain(void){ 
    
    // unlock PPS
    systemReg_Unlock();
    CFGCONbits.IOLOCK = 0;
    
    RPB2Rbits.RPB2R = 0x0003;               //RB2->SDO1;
    SDI1Rbits.SDI1R = 0x0002;               //RB1->SDI1;
    
    // lock PPS
    CFGCONbits.IOLOCK = 1; 
    systemReg_Lock();
    
    ANSELA = 0; ANSELB = 0;                 // Disable analog inputs
    CM1CON = 0; CM2CON = 0; CM3CON = 0;     // Disable analog comparators
}

/*******************************************************************************
* Function Name: void main (void)
*
* Specification: Program entry point
*
*******************************************************************************/
void main(void) {
    // SD Card Variables
    char myData[15] = "ThisIsSomeText";
    int bytesWritten;
    char newFile[] = "MyTest.txt";

    FSFILE *fPointer, *pNewFile;
    SearchRec rec;
    UINT8 attributes = ATTR_MASK;
     
    initMain();    
   
    // Initialize the library
    while (!FSInit());
    
    //Open file
    pNewFile = FSfopen (newFile, "w");
    
    //Write data
    bytesWritten = FSfwrite ((void *) myData, sizeof(myData), 1, pNewFile);
    FSfclose (pNewFile);
    
    /*
     //Show current text files
     if (FindFirst("*.TXT", attributes, &rec) == 0) { // file found
        printf("%s\t%u KB\n\r", rec.filename, rec.filesize/1000);   
        delay_ms(3000);
        int x = 0;
        while (FindNext(&rec) == 0) { // more files found
            printf("%s\t%u KB\n\r", rec.filename, rec.filesize/1000);    
            delay_ms(3000);
        }
    }
    */
 }  

The code is very simply and relies on the legacy PLIB libraries. It is very robust and has been tested with SD cards with up to 32GB capacity and it works well. The MDDFS can address devices for up to 2 TB capacity. Though it is legacy it can serve your needs for many projects.

The code above demonstrates initializing an SD card and reading and writing to it.


Link to Project

You can download the entire project here!

SD Card Project

Leave a Reply

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