FatFS for PIC32MX/MZ

Skill level: Intermediate, with knowledge of C and 32-bit microcontrollers.

Hello there again! 🙂

Want to write stuff into an SD-Card? Or maybe reading a file inside and then display it onto an LCD screen? Then this is the tutorial for you!

In this tutorial, you are using the FatFS library, which allows you to create, edit and read files in the SD-Card.

What will you need?

  • Cytron sk1632 w/ PIC32MX250F128B
  • 8MHz crystal
  • Cytron BB-uSD
  • Breadboard
  • Some jumper wires
  • PICKit 3
  • USB-to-UART module
  • a spare SD-Card formatted in FAT16/32! (not your SD-card where you store your homework/assignments or your personal stuff!)

For the software:

  • MPLAB X IDE 3.xx
  • MPLAB XC32 v1.40 and above
  • MPLAB Harmony v.1.0.7 or v.1.1.1

This is the basic wiring diagram of the sk1632 to the Cytron BB-uSD:

The blue “RXD” means you must connect this to the RXD of the USB-to-UART adapter. You need to connect the GND of the adapter to the Vss too!

Meanwhile, the requirement for the SD-card interface to work properly is to add the pull-ups in between the CS, SDI, SDO and SCK lines. Here’s a little trick for you: you don’t have to rummage your drawers for the 10K resistors – the PIC32MX on your hands has weak pull-ups to accomodate this situation.

The letters A and B in the CNPUAbits and CNPUBbits correspond to the port number. So if you want to have a pull-up enabled on PORTA’s RA1 for example, you simply type in “CNPUAbits.CNPUA1 = 1“.

In the sample program, you will know how to:

  1. Initalize the SD-card
  2. Initialize the file system inside
  3. Create file for reading and writing
  4. Write some text into a file
  5. Read the text from the file you have written and display to the terminal through UART
  6. Close the file

You are now reading the flow of the sample program:

1.) This initializes the disk. If it returns more than 0, it shows you an error, and the firmware stays waiting here with the LED blinking at a rate of 250ms. Also prints out the error.

// Initialize disk. If SD-card not present or faulty, wait there
    // and blink LED.
    if(disk_initialize(0)) {
        printf("No card or card error!\r");
        while(1) { 
            LATAbits.LATA0 ^= 1;

2.) Then, you mount the file system. If the SD-card is not formatted, or not formatted in FAT16/32, it will stay there and display the error too. Else, the program can proceed.

// Mounting the file system. If file system invalid, wait there and blink LED.
    if(f_mount(&Fatfs,"",0) == FR_INVALID_DRIVE) {
        printf("Invalid file system!\r");
        while(1) { 
            LATAbits.LATA0 ^= 1;

3.) After all the initalization, you create a file named “hello123.txt” with the mode “FA_CREATE_ALWAYS”, “FA_WRITE” and “FA_READ”. This mean the file is created if it does not exist, and if it is, the file is read or being overwritten if you are writing to it.

// Create a file here named "hello123.txt":
    // (File is created if it does not exist, and if it is, file is opened instead).
    printf("Creating a file inside for reading and writing!\r");
    f_open(&file1, "hello123.txt", FA_CREATE_ALWAYS | FA_WRITE | FA_READ);

4.) This is self-explanatory. Writes a block of text into the file.

// Write a text (contents inside text1[]) into the file.
    f_write(&file1, &text1, sizeof(text1), &numWrite);
char buffer[256] = { 0 };
    const char text1[] = "Hello World sk1632!\r This file is created with FatFs driver!\r Have a great day!\r\r";
    unsigned int numWrite = 0;   // number of bytes written to file.
    unsigned int numRead = 0;    // number of bytes read from file.

Scrolling up to near the beginning of the main() function, you see a couple of arrays and variables declared. These are used for the f_write and f_read functions.

The contents of text1[] = “…..” is written to the file, with the amount of bytes sizeof(text1) and numWrite stores the number of bytes written to file after the writing.

5.) To read the contents in the file, you call up the f_read function. Now, the function reads the contents in the file and places them into the buffer array. The function requires the amount of bytes read from the file, so on the third parameter, the sample code shows “sizeof(text1)“. Similarly, the numRead stores the number of bytes read from the file after the reading.

The file pointer (position of the ‘cursor’ in the opened file) has gone to the end of the text after writing in (4), so you have to rewind it to the beginning if you want the function to read the whole text:

// Rewind the file pointer to the start!
    f_lseek(&file1, 0);

Whatever is in the buffer is printed out to the terminal program through UART.

// Read the text and store them into the buffer.
    printf("Reading the file inside...\r");
    f_read(&file1, &buffer, sizeof(text1), &numRead);
    // Print the buffer contents to the terminal:
    printf("Printing contents: %s\r", &buffer);

6.) Finally, you close the file.

// Close the file after it is done!
    printf("Closing file!\r");

If there are no errors, the program stays in the loop with the LED blinking at the rate of 1/2 second.

Here is the output from the terminal:

And as a proof, you can see the created file Hello123.txt when you check the SD-card in the computer:

Open the file and you should be seeing this text which is the same as the terminal’s output (between “Printing contents” and the “Closing file”) :

Hello World sk1632! This file is created with FatFs driver!  Have a great day!

Grab the sample program from there, now! >>>>>> SK1632 FatFs tutorial!

For more information, you can read the user manual for extra information on the FatFS.

Extra note: Long File Name (LFN) support is not supported – so you have to make do with the 8-character (8.3) format for now.

What fancy ideas you can come up after you learned about the FatFs? 🙂


1.) FatFs – Generic FAT Filesystem Module





, , , , ,

Related Post

I2S for PIC32MX/MZ – Mikroelektronika Audio Codec Proto Board (Cirrus Logic WM8731 codec)

I2S for PIC32MX/MZ – Application: Music Box

I2S for PIC32MX/MZ – Direct Memory Access (DMA)

I2S for PIC32MX/MZ – Sine wave generation using DDS

Leave a Reply

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