Bukit Mertajam, Penang

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 read the file contents and display it onto an LCD screen? This is the tutorial for you!

In this tutorial, you will be 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!

For the SD-card interface to work properly, we have to add 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 internal pull-ups to accommodate this situation.

The letters A and B in the CNPUAbits and CNPUBbits correspond to the port number. Since we want all four pull-ups enabled, change code according to the diagram above.

 

With this sample program, you will learn 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

 

1.) Initializing the SD-card. 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;
            delay_ms(250);
        }
    }

2.) Initialize and mount the file system. If the SD-card is not formatted, or not formatted in FAT16/32, it will wait and display the error message 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;
            delay_ms(250);
        }        
    }

3.) 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.) 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");
    f_close(&file1);

If there are no errors, the program stays in the loop with the LED blinking every 0.5 seconds.

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. The following text should be written in the file as well 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 here, 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? 🙂

References:

1.) FatFs – Generic FAT Filesystem Module

 

 

 

 

Related Posts

Comments (3)

Hi NGYH,

Your article are among the very few examples using PIC32MX250F128B, …, thank you so much for your work.

I am very interested in using FatFs, but I see you are using also Harmony framework. I tried to follow your example but without using Harmony Framework, unfortunately I didn’t succeed. I used the fatfs library files from your source code and added in the diskio.c in the power_on function the PPS definitions for SDI1 and SDO1 pins, but I cannot make it work so far.

If I want to make FATFS work without Harmony Framework, can you please advise me on the additionals modifications needed?

Is there any chance that you publish this guide but without using Harmony Framework?

Thanks in advance.

Hello Leo,

Good to have a look at your code fragment – I can help to suggest there? It is very possible to run it without using any Harmony Framework – there is one similar example such as: https://www.codeproject.com/Articles/1198462/King-MM-The-joys-of-a-Harmony-less-life-Part-PIC-M.

Thanks for reading the tutorial too.

Hi NGYH,

Thank you very much for replying and suggesting me the article. I will try it out.

Your articles are really interesting; the DMA one caught my attention and I look forward to experiment with it.

Cheers.

Leave a comment

Loading...