SPI, SD cards, FatFs, part 2 of 2 Part 1: SPI on the PIC32MZPart 2: FATFS on the PIC32MZ

FATFS on the PIC32MZ

All 2 posts in SPI, SD cards, FatFs
  1. SPI on the PIC32MZ
  2. FATFS on the PIC32MZ
On this page

Code for this post

How to use FATFS with the PIC32MZ

Update 29/10/2018: At the request of user Malte I'm uploading a sample project, using the older mmcpic32.c file. You need to modify both mmcpic32.c and also the PPS setup in main.c to make it work for your project. Please note this isn't by any means for fast transfers, it's just to get the SD card connection working :)
Here's my project

Update 26/10/2018: Endless problems with this stuff! :) Here's the old mmcpic32.c file. Remove mmcpic32.c and replace it with this oldmmcpic32.c:
Here's my oldmmcpic32.c

Update 16/10/2018: It seems my diskio.h is a bit different so I'm adding it here:
Here's my diskio.h

Update 06/09/2018: I haven't implemented the writing part yet so there may still be some compatibility issues with the latest FatFs. You may need to make the following changes to ffconf.h:

#define FF_FS_NORTC     1
#define FF_NORTC_MON    9
#define FF_NORTC_MDAY   6
#define FF_NORTC_YEAR   2018
#define FF_FS_READONLY  0
#define FF_FS_RPATH     1

This is part 2 of 2 of the article on SPI on the PIC32MZ. Last time I discussed how to set up SPI and all the tricks and traps involved therein. Today I will be discussing how to use the FATFS library with our code in order to give us access to the files on the SD card. I'm only covering reading of the files today, maybe at some point in the future I'll cover writing.

TL;DR

A bit of background and an explanation of what I'll cover today

The problem I set out to solve was that I needed to read 320x240 30fps 16-bit video data from an SD card and show it on an LCD. This is a huge amount of data and the built-in Harmony SD library is far too slow for this. I needed about 4.5MB/s and at the time it was giving me reads of 2MB/s. I came across some code by Riccardo Leonardi and Aiden Morrison (who can be found on the Microchip forums). They'd ported the FatFs interface to PIC32 for the old MX series in a file titled mmcpic32.c. The problem with this was it was also far too slow (it's 7 years old so I can understand that!). After examination of the file I realised I could use a combination of Enhanced Buffers mode and 32-bit SPI reads to speed up the reading section.

I bought a good SD card (Samsung Evo 32GB) and formatted it at 32kB/cluster. After implementing these changes I can get read rates of 4.6MB/s when using 32kB read buffers. Today I'll be discussing these changes. Please bear in mind that SD cards vary wildly in terms of speeds and your results will vary.

Before we get down to business, credit where credit is due:
- Most of the work was done by Riccardo Leonardi and Aiden Morrison from the Microchip forums, so thanks to them for their mmcpic32.c file.
- My friend Bryn Thomas did a lot of work in finding out the root cause of why SD transfers were so slow and in using 32-bit SPI and Enhanced Buffers modes
- The FatFs library by ChaN is what made this all possible, so huge thanks to ChaN and all their hard work. The project is being updated to this day (last update was September 3 2018, yesterday at the time of writing).

STEP 1

OK, before we get started you will need to download the FATFS library and extract the contents to your project folder. I'm using version R0.13b for reference.

STEP 2

The next step is to include the header files needed:

#include "ff.h"
#include "diskio.h"

STEP 3

Next, download the mmcpic32.c file and copy it into your project folder.

STEP 4

Open mmcpic32.c and modify the following to make it work with your project:

/* Port Controls  (Platform dependent) */
#define CS_SETOUT() TRISBbits.TRISB4 = 0 
#define CS_LOW()  LATBbits.LATB4 = 0    //MMC CS = L
#define CS_HIGH() LATBbits.LATB4 = 1    //MMC CS = H
//Change the SPI port number as needed on the following 4 lines
#define SPIBRG  SPI2BRG
#define SPIBUF  SPI2BUF
#define SPISTATbits SPI2STATbits
#define SPICONbits SPI2CONbits

For my example, I'm using SPI2 and I have CS on pin RB4.

STEP 5

In your main C file, you need to add the following code:

// Global variables
FIL file; // File handle for the file we open
DIR dir; // Directory information for the current directory
FATFS fso; // File System Object for the file system we are reading from
FILINFO fileInfo; // Information for the file we have opened (not really necessary to have this)

void init_disk()
{
    // Wait for the disk to initialise
    while(disk_initialize(0));
    // Mount the disk
    f_mount(&fso, "", 0);
    // Change dir to the root directory
    f_chdir("/");
    // Open the directory
    f_opendir(&dir, ".");
}

STEP 6

Finally, in main() or setup() or whatever you use, call:

init_disk();

And... that's that! Now using files can be done just like you would on any other platform. For example, to open a file called "test.txt" in the root directory, you'd do this:

f_open(&file, "/test.txt", FA_READ);

Now you have the file handle stored in file and can use it as you please. For example, to read 32768 bytes into an array, do this:

unsigned char buffer[32768]; // buffer stores the data read from the file
int bytes_read; // bytes_read stores how many bytes were actually read

f_read(&file, buffer, 32768, &bytes_read);

If count has a different number of bytes to 32768 that means the end of the file was reached before it could read 32768 bytes or an error occurred.

Here's the code

44 comments
  1. colle

    I used this library on an 8 bit pic with some limitation in one of my last project. It's a very complete and usefull one. I expect this to be more powerful with a 32 bit MCU running at 200Mhz. I'm looking forward to trying it.

    1. Aidan Author

      I haven't gotten round to doing file writing yet, so there may be a few errors when you compile with the newest FatFs. I'll update this post later today with some things to change if you get errors.

  2. Malte

    Hi, first thanks a lot for you blog, its really helpfull!!!

    But i just got a problem by working with FatFS and my microcontroller. I am using a chipkit Wifire Dev. (REV C) Board with a PIC32MZ2048EFG100, but everytime i am trying to compile your code, i got the following errors:

    build/default/production/diskio.o: In function `disk_status':
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:31: undefined reference to `RAM_disk_status'
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:38: undefined reference to `MMC_disk_status'
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:45: undefined reference to `USB_disk_status'
    build/default/production/diskio.o: In function `disk_initialize':
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:69: undefined reference to `RAM_disk_initialize'
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:76: undefined reference to `MMC_disk_initialize'
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:83: undefined reference to `USB_disk_initialize'
    build/default/production/diskio.o: In function `disk_read':
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:112: undefined reference to `RAM_disk_read'
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:121: undefined reference to `MMC_disk_read'
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:130: undefined reference to `USB_disk_read'
    build/default/production/diskio.o: In function `disk_write':
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:160: undefined reference to `RAM_disk_write'
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:169: undefined reference to `MMC_disk_write'
    c:/users/malte/mplabxprojects/08.10 v2.x/diskio.c:178: undefined reference to `USB_disk_write'

    Perhaps you got a solution for this problem? It´s really frustraing, i don´t find an answer. Thank you!

    1. Malte

      Hi, it´s me again, i think i figoured out, that we are using mmcpic32.c file to enable our functions out of diskio.h , so I stopped including diskio.c file.
      Now I get the next problems, the Variable CT_BLOCK, CT_SDC, CT_SD2 and CT_SD1 are undeclared. I think i habe to define my CardType, but it didn´t know how. Perhaps you can post an example how you did it with your Card? That would be really Helpfull
      Best Regards
      Malte

      1. Aidan Author

        Hi there, sorry for the super late reply been busy with work! Yes, mmcpic32.c replaces the diskio.c, you can just include mmcpic32.c or rename it to diskio.c, whichever you prefer.

        I've updated the post with my diskio.h, I forgot there were some things to modify in there, sorry :)

        Or, to fix those issues, add the following to your diskio.h:

        /* MMC card type flags (MMC_GET_TYPE) */
        #define CT_MMC0x01/* MMC ver 3 */
        #define CT_SD10x02/* SD ver 1 */
        #define CT_SD20x04/* SD ver 2 */
        #define CT_SDC(CT_SD1|CT_SD2)/* SD */
        #define CT_BLOCK0x08/* Block addressing */

        If you have any other problems, let me know and I'll do my best to help.

        1. Malte

          Hi, Thanks for the Help and don´t be sorry :)

          So now I got another problem, the Program is runnig without any failures but i am hanging in a loop, by diskio.c/mmcpic32.c

          static
          BYTE xchg_spi (BYTE dat)
          {
          SPIBUF = dat;
          while (SPISTATbits.SPIRBE);
          return (BYTE)SPIBUF;
          }

          The Programm isn´t running out of the "while (SPISTATbits.SPIRBE);" loop. I know it have something to do with the enhanced buffer mode, but doesn´t know really what. If you also got a solution for this problem, this would be great. Thank You!!!

          1. Aidan Author

            That sounds like the SD card isn't sending you any data back. Maybe you need to check the following:

            /* Port Controls (Platform dependent) */
            #define CS_SETOUT() TRISBbits.TRISB4 = 0
            #define CS_LOW() LATBbits.LATB4 = 0//MMC CS = L
            #define CS_HIGH() LATBbits.LATB4 = 1//MMC CS = H
            //Change the SPI port number as needed on the following 5 lines
            #define SPIBRG SPI2BRG
            #define SPIBUF SPI2BUF
            #define SPISTATbits SPI2STATbits
            #define SPICONbits SPI2CONbits

            You need to specify which port has the SD card's CS bit and which SPI channel you're using. I used SPI2 so all of those #defines are set up for that.

            1. Malte

              Im using an oboard SD-Card, which is communicating over the SPI3 slot with this following:

              /* Port Controls (Platform dependent) */
              #define CS_SETOUT() TRISCbits.TRISC3 = 0
              #define CS_LOW() LATCbits.LATC3 = 0 //MMC CS = L
              #define CS_HIGH() LATCbits.LATC3 = 1 //MMC CS = H
              //Change the SPI port number as needed on the following 5 lines
              #define SPIBRG SPI3BRG
              #define SPIBUF SPI3BUF
              #define SPISTATbits SPI3STATbits
              #define SPICONbits SPI3CONbits

              this should also be configured correct

              // Set up PPS for SPI3 on RB10 and RC4
              SDI3R = 0b0110; // RB10 = SDI3
              RPC4R = 0b0111; // RC4 = SDO3
              TRISBbits.TRISB3 = 1; // Set RB10 as input because it's SDI3

              I also tested it with other SD-Card = same problem.

              while(disk_initialize(1));

              never ends because, i get there "Initialization failed" and the value of Stat (return from this function) is 1.

              My Board: chipkit Wifire Dev. (REV C)

              I also got a Problem with your delay function, when i copy your code and load it on my Board my LED is blinking with 2s and not 1s, how it is supposed to be. Could there be a context?

              Also thanks a lot for the previous advices.

              1. Aidan Author

                Hi there,

                I'm not sure why the delay wouldn't work. Did you copy my initialise code? I'll have a look at my code, maybe I did something dumb. You can remove SPI_Init() and SPI_send() from the PIC32MZ_6.c file, they're useless.

                I see there's a mistake in your code. The line should be:
                TRISBbits.TRISB10 = 1; // Set RB10 as input because it's SDI3

                It usually gets stuck at disk_initialize() when there's a communication problem or the SD card isn't present. Let me know if this works, it's really hard to debug that without having the same board or having your code :)

                1. Malte

                  Hi Aidan,

                  there was a Typing error from me I do set RB10 as input, so this wasn´t the problem.

                  I did copy your complete code from the "delay post", just changed my ports where I connected my LED and the #include <proc p32mz2048efg100.h=""> to my processor specifics.

                  while (1)
                  {
                  LATGbits.LATG6 = 0;
                  LATAINV = 1 << 0; // Toggle LAT A bit 0
                  delay_ms(1000); // Delay 1 second
                  LATGbits.LATG6 = 1;
                  delay_ms(1000); // Delay 1 second
                  }

                  For the SD-Card, I will start to connect a exernal sd-card module, perhaps something with the on-Board sd-card module doens´t work.

                  EDIT:
                  Just solved the delay failure, haven´t to do anything with the sd-card :(

                  Thanks a lot for you time and your help, if I am getting it worked I will share it with you :)

                  Best Regards
                  Malte

                  1. Malte

                    Hello Aidan,

                    I just checked to connect a exernal sd-card module, but it wouldn´t work also, in disk_initalize, i am entering the idle Status and i can´t get out of it. Perhaps you got any advices left, what else could be possible wrong. It can´t explain why it works on your controller but don´t on mine, because the SPI module, where the SD Card is connected is just the same... I also tried to configure it with harmony, but also don´t with success, and it´s just more confussing :(
                    Perhaps I will find the mistake by your next SD-Card example :) When are you thinking you gone continue your blog? Can´t await :)

                    1. Aidan Author

                      Hi Malte,

                      I've just now tried this same code with the latest fatfs on a really old dev board of mine and it works fine. One thing that might be different is on my dev board I have a pullup resistor on MOSI/SDO (I have one wire going from MOSI to the PIC32 and then also a 10k resistor going to 3.3V). Other than that, I really can't imagine what the problem might be :/ Maybe try another SD card or make sure you are using the FAT or FAT32 filesystem? Can you post your whole main C file? I'll try your C file with my board and see if it works. In the meantime, I've uploaded a mmcpic32.c file without enhanced buffers (at the top of the post), I hope that one will work for you!

                      I'm actually writing a few posts on I2C and I2S right now but I'm waiting for my new prototype PCB to get made. I've been waiting almost 3 weeks so far but the company (seeedstudio) is being really slow. I need to test the stuff before I upload it :) Thanks for all your posts and for fixing my broken delay code.

                      1. Malte

                        Hi Aidan,

                        So this is my C:

                        #include "ff.h"
                        #include "diskio.h"

                        /** CONFIGURATION *************************************************************/

                        // DEVCFG2
                        //Define SYSCLK = 200 MHz
                        #pragma config FPLLIDIV = DIV_3 // System PLL Input Divider (3x Divider)
                        #pragma config FPLLRNG = RANGE_5_10_MHZ // System PLL Input Range (5-10 MHz Input)
                        #pragma config FPLLICLK = PLL_POSC // System PLL Input Clock Selection (POSC is input to the System PLL)
                        #pragma config FPLLMULT = MUL_50 // System PLL Multiplier (PLL Multiply by 50)
                        #pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider)
                        #pragma config UPLLFSEL = FREQ_24MHZ // USB PLL Input Frequency Selection (USB PLL input is 24 MHz)

                        // DEVCFG1
                        #pragma config FNOSC = SPLL // Oscillator Selection Bits (System PLL)
                        #pragma config POSCMOD = EC // Primary Oscillator Configuration (External clock mode)
                        #pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648))
                        #pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled)

                        // DEVCFG0
                        #pragma config ICESEL = ICS_PGx2 // ICE/ICD Comm Channel Select (Communicate on PGEC2/PGED2)

                        #include <xc.h>
                        #include <stdio.h>
                        #include <stdlib.h>
                        #include <stdbool.h>
                        #include <proc p32mz2048efg100.h="">

                        #define SYS_FREQ 200000000 // Running at 200MHz

                        void set_performance_mode()
                        {
                        unsigned int cp0;

                        // Unlock Sequence
                        asm volatile("di"); // Disable all interrupts
                        SYSKEY = 0xAA996655;
                        SYSKEY = 0x556699AA;

                        // PB1DIV
                        // Peripheral Bus 1 cannot be turned off, so there's no need to turn it on
                        PB1DIVbits.PBDIV = 1; // Peripheral Bus 1 Clock Divisor Control

                        // PB2DIV
                        PB2DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
                        PB2DIVbits.PBDIV = 1; // Peripheral Bus 2 Clock Divisor Control

                        // PB3DIV
                        PB3DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
                        PB3DIVbits.PBDIV = 1; // Peripheral Bus 3 Clock Divisor Control

                        // PB4DIV
                        PB4DIVbits.ON = 1; // Peripheral Bus 4 Output Clock Enable (Output clock is enabled)
                        while (!PB4DIVbits.PBDIVRDY); // Wait until it is ready to write to
                        PB4DIVbits.PBDIV = 0; // Peripheral Bus 4 Clock Divisor Control

                        // PB5DIV
                        PB5DIVbits.ON = 1; // Peripheral Bus 5 Output Clock Enable (Output clock is enabled)
                        PB5DIVbits.PBDIV = 1; // Peripheral Bus 5 Clock Divisor Control

                        // PB7DIV
                        PB7DIVbits.ON = 1; // Peripheral Bus 7 Output Clock Enable (Output clock is enabled)
                        PB7DIVbits.PBDIV = 1; // Peripheral Bus 7 Clock Divisor Control

                        // PB8DIV
                        PB8DIVbits.ON = 1; // Peripheral Bus 8 Output Clock Enable (Output clock is enabled)
                        PB8DIVbits.PBDIV = 1; // Peripheral Bus 8 Clock Divisor Control

                        // PRECON - Set up prefetch
                        PRECONbits.PFMSECEN = 0; // Flash SEC Interrupt Enable (Do not generate an interrupt when the PFMSEC bit is set)
                        PRECONbits.PREFEN = 0b11; // Predictive Prefetch Enable (Enable predictive prefetch for any address)
                        PRECONbits.PFMWS = 0b010; // PFM Access Time Defined in Terms of SYSCLK Wait States (Two wait states)

                        // Set up caching
                        cp0 = _mfc0(16, 0);
                        cp0 &= ~0x07;
                        cp0 |= 0b011; // K0 = Cacheable, non-coherent, write-back, write allocate
                        _mtc0(16, 0, cp0);

                        // Lock Sequence
                        SYSKEY = 0x33333333;
                        asm volatile("ei"); // Enable all interrupts
                        }

                        // Global variables
                        FIL file; // File handle for the file we open
                        DIR dir; // Directory information for the current directory
                        FATFS fso; // File System Object for the file system we are reading from
                        FILINFO fileInfo; // Information for the file we have opened (not really necessary to have this)

                        void init_disk()
                        {
                        // Wait for the disk to initialise
                        while(disk_initialize(0));
                        // Mount the disk
                        f_mount(&fso, "", 0);
                        // Change dir to the root directory
                        f_chdir("/");
                        // Open the directory
                        f_opendir(&dir, ".");
                        }

                        void main()
                        {
                        int bytes_read;
                        unsigned char buffer[32768];

                        // Set up all ports to be digital and not analog
                        ANSELA = 0;
                        ANSELB = 0;
                        ANSELC = 0;
                        ANSELD = 0;
                        ANSELE = 0;
                        ANSELF = 0;
                        ANSELG = 0;

                        // Set up PPS for SPI3 on RB10 and RC4
                        SDI3R = 0b0110; // RB10 = SDI3
                        RPC4R = 0b0111; // RC4 = SDO3
                        TRISBbits.TRISB10 = 1; // Set RB10 as input because it's SDI3

                        // Set max performance mode
                        //set_performance_mode();

                        // Initialise the SD card
                        init_disk();

                        // Open the file test.txt
                        f_open(&file, "/test.txt", FA_WRITE);

                        while (1);
                        }

                        Im hanging in diskio.c by,

                        static
                        BYTE wait_ready (void)
                        {
                        BYTE res;

                        Timer2 = 500;/* Wait for ready in timeout of 500ms */
                        rcvr_spi();
                        do
                        res = rcvr_spi();
                        while ((res != 0xFF) && Timer2);

                        return res;
                        }

                        my Pic isn´t getting out of this do while loop (while ((res != 0xFF) && Timer2);)

                        In debbuging i checked res. Its 0x00 and Timer2 is 500 so the condition should ok, so the questions is, why isn´t ,my Controller leaving this loop? By the way my filesystem is FAT32 and i just checked it with two sd-cards, tomorrow i will check it out with another.

                        Regards
                        Malte

                        1. Максим Голуб

                          Hi, Malte.
                          I was faced with similar problem on PIC32MZ2048ECG100. The problem has been solved by adding pull-up resistor on pins of SPI3 (to SDcard). For example, CNPUBbits.CNPUB15 (adding pull-up resistor on pin 15 port B). Now this code is working fine:)
                          Have a nice day!
                          Faithfully yours Maks!

                          1. Malte

                            Hi Mark,
                            thanks for you tipp, just figured out 2 week ago, but this was it. Have taked a lot of time^^ but now everything works. Thanks at all lot to Aidan, who tried to help me and share his whole code with me. Really helpfull blog and also a friendly comunity :)))
                            Best Regards
                            Malte

                            1. Aidan Author

                              That's great news Malte, I'm really glad it works for you. As I said above I have a hardware pullup resistor on SDO, I thought your board might have one too but I guess not? Regardless, excellent news!

                          2. Aidan Author

                            Thank you Maks, I didn't put that in my post but I have a hardware pullup resistor. Thank you for taking the time to help out!

                    2. Aidan Author

                      This whole post seems to be a mess, sorry about that. Hopefully we can get it all sorted out!

                      I'll try to ensure future posts are less jumbled :)

                      1. Malte

                        Don´t know why disqus thinks that it was probably spam^^
                        So here is my main:
                        #include "ff.h"
                        #include "diskio.h"

                        /** CONFIGURATION *************************************************************/

                        // DEVCFG2
                        //Define SYSCLK = 200 MHz
                        #pragma config FPLLIDIV = DIV_3 // System PLL Input Divider (3x Divider)
                        #pragma config FPLLRNG = RANGE_5_10_MHZ // System PLL Input Range (5-10 MHz Input)
                        #pragma config FPLLICLK = PLL_POSC // System PLL Input Clock Selection (POSC is input to the System PLL)
                        #pragma config FPLLMULT = MUL_50 // System PLL Multiplier (PLL Multiply by 50)
                        #pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider)
                        #pragma config UPLLFSEL = FREQ_24MHZ // USB PLL Input Frequency Selection (USB PLL input is 24 MHz)

                        // DEVCFG1
                        #pragma config FNOSC = SPLL // Oscillator Selection Bits (System PLL)
                        #pragma config POSCMOD = EC // Primary Oscillator Configuration (External clock mode)
                        #pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648))
                        #pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled)

                        // DEVCFG0
                        #pragma config ICESEL = ICS_PGx2 // ICE/ICD Comm Channel Select (Communicate on PGEC2/PGED2)

                        #include <xc.h>
                        #include <stdio.h>
                        #include <stdlib.h>
                        #include <stdbool.h>
                        #include <proc p32mz2048efg100.h="">

                        #define SYS_FREQ 200000000 // Running at 200MHz

                        void set_performance_mode()
                        {
                        unsigned int cp0;

                        // Unlock Sequence
                        asm volatile("di"); // Disable all interrupts
                        SYSKEY = 0xAA996655;
                        SYSKEY = 0x556699AA;

                        // PB1DIV
                        // Peripheral Bus 1 cannot be turned off, so there's no need to turn it on
                        PB1DIVbits.PBDIV = 1; // Peripheral Bus 1 Clock Divisor Control (PBCLK1 is SYSCLK divided by 2)

                        // PB2DIV
                        PB2DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
                        PB2DIVbits.PBDIV = 1; // Peripheral Bus 2 Clock Divisor Control (PBCLK2 is SYSCLK divided by 2)

                        // PB3DIV
                        PB3DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
                        PB3DIVbits.PBDIV = 1; // Peripheral Bus 3 Clock Divisor Control (PBCLK3 is SYSCLK divided by 2)

                        // PB4DIV
                        PB4DIVbits.ON = 1; // Peripheral Bus 4 Output Clock Enable (Output clock is enabled)
                        while (!PB4DIVbits.PBDIVRDY); // Wait until it is ready to write to
                        PB4DIVbits.PBDIV = 0; // Peripheral Bus 4 Clock Divisor Control (PBCLK4 is SYSCLK divided by 1)

                        // PB5DIV
                        PB5DIVbits.ON = 1; // Peripheral Bus 5 Output Clock Enable (Output clock is enabled)
                        PB5DIVbits.PBDIV = 1; // Peripheral Bus 5 Clock Divisor Control (PBCLK5 is SYSCLK divided by 2)

                        // PB7DIV
                        PB7DIVbits.ON = 1; // Peripheral Bus 7 Output Clock Enable (Output clock is enabled)
                        PB7DIVbits.PBDIV = 1; // Peripheral Bus 7 Clock Divisor Control (PBCLK7 is SYSCLK divided by 1)

                        // PB8DIV
                        PB8DIVbits.ON = 1; // Peripheral Bus 8 Output Clock Enable (Output clock is enabled)
                        PB8DIVbits.PBDIV = 1; // Peripheral Bus 8 Clock Divisor Control (PBCLK8 is SYSCLK divided by 2)

                        // PRECON - Set up prefetch
                        PRECONbits.PFMSECEN = 0; // Flash SEC Interrupt Enable (Do not generate an interrupt when the PFMSEC bit is set)
                        PRECONbits.PREFEN = 0b11; // Predictive Prefetch Enable (Enable predictive prefetch for any address)
                        PRECONbits.PFMWS = 0b010; // PFM Access Time Defined in Terms of SYSCLK Wait States (Two wait states)

                        // Set up caching
                        cp0 = _mfc0(16, 0);
                        cp0 &= ~0x07;
                        cp0 |= 0b011; // K0 = Cacheable, non-coherent, write-back, write allocate
                        _mtc0(16, 0, cp0);

                        // Lock Sequence
                        SYSKEY = 0x33333333;
                        asm volatile("ei"); // Enable all interrupts
                        }

                        // Global variables
                        FIL file; // File handle for the file we open
                        DIR dir; // Directory information for the current directory
                        FATFS fso; // File System Object for the file system we are reading from
                        FILINFO fileInfo; // Information for the file we have opened (not really necessary to have this)

                        void init_disk()
                        {
                        // Wait for the disk to initialise
                        while(disk_initialize(0));
                        // Mount the disk
                        f_mount(&fso, "", 0);
                        // Change dir to the root directory
                        f_chdir("/");
                        // Open the directory
                        f_opendir(&dir, ".");
                        }

                        void main()
                        {
                        int bytes_read;
                        unsigned char buffer[32768];

                        // Set up all ports to be digital and not analog
                        ANSELA = 0;
                        ANSELB = 0;
                        ANSELC = 0;
                        ANSELD = 0;
                        ANSELE = 0;
                        ANSELF = 0;
                        ANSELG = 0;

                        // Set up PPS for SPI3 on RB10 and RC4
                        SDI3R = 0b0110; // RB10 = SDI3
                        RPC4R = 0b0111; // RC4 = SDO3
                        TRISBbits.TRISB10 = 1; // Set RB10 as input because it's SDI3

                        // Set max performance mode
                        //set_performance_mode();

                        // Initialise the SD card
                        init_disk();

                        // Open the file test.txt
                        f_open(&file, "/test.txt", FA_WRITE);

                        while (1);
                        }

                        Just got another question by the diskio.c function:
                        How does Timer1 and Timer2 are working? I do not see that they are open any functions, it looks for me they just got declared. I belive that my timer functions doesn´t really work, there is also nothing standing in the void disk_timerproc function. But you also do it so, so confussing.

                        Can you perhaps just Upload your complete Project, so that i can import this directly in mplab x? Perhaps your Project will run in my microcontroller. Thx Aidan for everything

                        1. Aidan Author

                          Hi Malte,

                          Timer1 and Timer2 were put in there by whoever originally made mmcpic32.c. They're supposed to time out when there is an error but they are not needed so I never implemented them.

                          Your program is hanging because the SD card controller is not returning the value 0xFF which means there's a problem. If Timer1 and Timer2 were working, init_disk() would return but the SD card would not be initialised. So I decided to let it hang there because if the SD card isn't working there's no point carrying on with the program.

                          I will upload my project files tomorrow. All my PIC32 stuff is at work because I was testing the FatFS code :)

  3. Ciaran Watters

    I'm only getting started with PIC32 and it is helpful to find you, given the jump from PIC 16/18 to 32. I'm impressed & grateful. Thanks Aidan for the hosting this information online.

    1. Aidan Author

      Hi Ciaran, you're welcome. Thanks for visiting.

      1. Ciaran Watters

        Hi Aidan,
        I had no luck when I tried your code to start a PIC32 without Harmony.

        I'm using the MZ2048EFG064, I got the code to build, compile and program the processor but the uP didn't seem to respond. My main while loop was just to simply turn a PORT pin high, which I successfully done with Harmony code, infarct using Harmony I managed to toggle that same pin at 8 MHz. I had to make slight modifications to your code for example #include <proc p32mz2048efg064.h=""> and also it was not happy with the delay loop but I don't think that I strayed to far from what should work to activate a port pin. I can sent you the code and or the project, but maybe you know why know why my processor is not firing given your experience.
        Any tips are welcome, in advance THANKS Ciaran.

        1. Aidan Author

          Hi there Ciaran, sounds like there are a lot of problems there. If you post your code here I'll take a look at it as soon as I can.

          1. Ciaran Watters

            // PIC32MZ_2.c - A simple PIC32MZ skeleton
            // by Aidan Mocke 2018-04-09
            //
            // PIC32MZ2048EFH144 Configuration Bit Settings

            // DEVCFG3
            // USERID = No Setting
            #pragma config FMIIEN = ON // Ethernet RMII/MII Enable (MII Enabled)
            #pragma config FETHIO = ON // Ethernet I/O Pin Select (Default Ethernet I/O)
            #pragma config PGL1WAY = OFF // Permission Group Lock One Way Configuration (Allow multiple reconfigurations)
            #pragma config PMDL1WAY = OFF // Peripheral Module Disable Configuration (Allow multiple reconfigurations)
            #pragma config IOL1WAY = OFF // Peripheral Pin Select Configuration (Allow multiple reconfigurations)
            #pragma config FUSBIDIO = OFF // USB USBID Selection (Controlled by Port Function)

            // DEVCFG2
            #pragma config FPLLIDIV = DIV_3 // System PLL Input Divider (3x Divider)
            #pragma config FPLLRNG = RANGE_5_10_MHZ // System PLL Input Range (5-10 MHz Input)
            #pragma config FPLLICLK = PLL_POSC // System PLL Input Clock Selection (POSC is input to the System PLL)
            #pragma config FPLLMULT = MUL_50 // System PLL Multiplier (PLL Multiply by 50)
            #pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider (2x Divider)
            #pragma config UPLLFSEL = FREQ_24MHZ // USB PLL Input Frequency Selection (USB PLL input is 24 MHz)

            // DEVCFG1
            #pragma config FNOSC = SPLL // Oscillator Selection Bits (System PLL)
            #pragma config DMTINTV = WIN_127_128 // DMT Count Window Interval (Window/Interval value is 127/128 counter value)
            #pragma config FSOSCEN = OFF // Secondary Oscillator Enable (Disable SOSC)
            #pragma config IESO = OFF // Internal/External Switch Over (Disabled)
            #pragma config POSCMOD = EC // Primary Oscillator Configuration (External clock mode)
            #pragma config OSCIOFNC = OFF // CLKO Output Signal Active on the OSCO Pin (Disabled)
            #pragma config FCKSM = CSECME // Clock Switching and Monitor Selection (Clock Switch Enabled, FSCM Enabled)
            #pragma config WDTPS = PS1048576 // Watchdog Timer Postscaler (1:1048576)
            #pragma config WDTSPGM = STOP // Watchdog Timer Stop During Flash Programming (WDT stops during Flash programming)
            #pragma config WINDIS = NORMAL // Watchdog Timer Window Mode (Watchdog Timer is in non-Window mode)
            #pragma config FWDTEN = OFF // Watchdog Timer Enable (WDT Disabled)
            #pragma config FWDTWINSZ = WINSZ_25 // Watchdog Timer Window Size (Window size is 25%)
            #pragma config DMTCNT = DMT31 // Deadman Timer Count Selection (2^31 (2147483648))
            #pragma config FDMTEN = OFF // Deadman Timer Enable (Deadman Timer is disabled)

            // DEVCFG0
            #pragma config DEBUG = OFF // Background Debugger Enable (Debugger is disabled)
            #pragma config JTAGEN = OFF // JTAG Enable (JTAG Disabled)
            #pragma config ICESEL = ICS_PGx1 // ICE/ICD Comm Channel Select (Communicate on PGEC1/PGED1)
            #pragma config TRCEN = OFF // Trace Enable (Trace features in the CPU are disabled)
            #pragma config BOOTISA = MIPS32 // Boot ISA Selection (Boot code and Exception code is MIPS32)
            #pragma config FECCCON = OFF_UNLOCKED // Dynamic Flash ECC Configuration (ECC and Dynamic ECC are disabled (ECCCON bits are writable))
            #pragma config FSLEEP = OFF // Flash Sleep Mode (Flash is powered down when the device is in Sleep mode)
            #pragma config DBGPER = PG_ALL // Debug Mode CPU Access Permission (Allow CPU access to all permission regions)
            #pragma config SMCLR = MCLR_NORM // Soft Master Clear Enable bit (MCLR pin generates a normal system Reset)
            #pragma config SOSCGAIN = GAIN_2X // Secondary Oscillator Gain Control bits (2x gain setting)
            #pragma config SOSCBOOST = OFF // Secondary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
            #pragma config POSCGAIN = GAIN_2X // Primary Oscillator Gain Control bits (2x gain setting)
            #pragma config POSCBOOST = OFF // Primary Oscillator Boost Kick Start Enable bit (Boost the kick start of the oscillator)
            #pragma config EJTAGBEN = NORMAL // EJTAG Boot (Normal EJTAG functionality)
            #pragma config CP = OFF // Code Protect (Protection Disabled)

            #include <xc.h>
            #include <stdio.h>
            #include <stdlib.h>
            #include <stdbool.h>
            #include <proc p32mz2048efg064.h="">

            void set_performance_mode()
            {
            unsigned int cp0;

            // Unlock Sequence
            asm volatile("di"); // Disable all interrupts
            SYSKEY = 0xAA996655;
            SYSKEY = 0x556699AA;

            // PB1DIV
            // Peripheral Bus 1 cannot be turned off, so there's no need to turn it on
            PB1DIVbits.PBDIV = 1; // Peripheral Bus 1 Clock Divisor Control (PBCLK1 is SYSCLK divided by 2)

            // PB2DIV
            PB2DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
            PB2DIVbits.PBDIV = 1; // Peripheral Bus 2 Clock Divisor Control (PBCLK2 is SYSCLK divided by 2)

            // PB3DIV
            PB3DIVbits.ON = 1; // Peripheral Bus 2 Output Clock Enable (Output clock is enabled)
            PB3DIVbits.PBDIV = 1; // Peripheral Bus 3 Clock Divisor Control (PBCLK3 is SYSCLK divided by 2)

            // PB4DIV
            PB4DIVbits.ON = 1; // Peripheral Bus 4 Output Clock Enable (Output clock is enabled)
            while (!PB4DIVbits.PBDIVRDY); // Wait until it is ready to write to
            PB4DIVbits.PBDIV = 0; // Peripheral Bus 4 Clock Divisor Control (PBCLK4 is SYSCLK divided by 1)

            // PB5DIV
            PB5DIVbits.ON = 1; // Peripheral Bus 5 Output Clock Enable (Output clock is enabled)
            PB5DIVbits.PBDIV = 1; // Peripheral Bus 5 Clock Divisor Control (PBCLK5 is SYSCLK divided by 2)

            // PB7DIV
            PB7DIVbits.ON = 1; // Peripheral Bus 7 Output Clock Enable (Output clock is enabled)
            PB7DIVbits.PBDIV = 1; // Peripheral Bus 7 Clock Divisor Control (PBCLK7 is SYSCLK divided by 1)

            // PB8DIV
            PB8DIVbits.ON = 1; // Peripheral Bus 8 Output Clock Enable (Output clock is enabled)
            PB8DIVbits.PBDIV = 1; // Peripheral Bus 8 Clock Divisor Control (PBCLK8 is SYSCLK divided by 2)

            // PRECON - Set up prefetch
            PRECONbits.PFMSECEN = 0; // Flash SEC Interrupt Enable (Do not generate an interrupt when the PFMSEC bit is set)
            PRECONbits.PREFEN = 0b11; // Predictive Prefetch Enable (Enable predictive prefetch for any address)
            PRECONbits.PFMWS = 0b010; // PFM Access Time Defined in Terms of SYSCLK Wait States (Two wait states)

            // Set up caching
            cp0 = _mfc0(16, 0);
            cp0 &= ~0x07;
            cp0 |= 0b011; // K0 = Cacheable, non-coherent, write-back, write allocate
            _mtc0(16, 0, cp0);

            // Lock Sequence
            SYSKEY = 0x33333333;
            asm volatile("ei"); // Enable all interrupts
            }

            void delay_ms(int ms)
            {
            ms *= (200000000 / 1000 / 2 / 32); // /2 due to PB_clock being DIV_2

            T8CON = 0;
            T9CON = 0;
            // PR8 = (delay & 0xFFFF); // Low word in PR8
            //PR9 = (delay >> 16); // High word in PR9
            T8CON = 0x8008; // Bit 15 = timer enable, bit 3 = 32-bit mode on

            TMR8 = 0;
            TMR9 = 0;
            // while (TMR9 < (delay >> 16)); // Delay ms milliseconds
            }

            void main()
            {
            // Set up all ports to be digital and not analog
            //ANSELA = 0;
            ANSELB = 0;
            //ANSELC = 0;
            //ANSELD = 0;
            ANSELE = 0;
            //ANSELF = 0;
            ANSELG = 0;
            //ANSELH = 0;
            //ANSELJ = 0;

            // Set max performance mode
            set_performance_mode();

            TRISECLR = 1 << 0; // Clear bit 0 of TRISA. which makes PORT A bit 0 an output

            LATESET = 1 << 0; // Set bit 0 of PORT A to 1

            // Main loop
            while (1)
            {
            LATEbits.LATE5 = 1; // I was experimenting here with
            // all these similar instructions
            // to turn RE5 high and or toggle RE5
            // but I had no luck.

            PORTEbits.RE5 = 1;

            //LATEINV = 1 << 5;

            LATESET = 1 << 5;

            LATECLR = 1 << 5;

            // Insert code here
            }
            }

            1. Aidan Author

              OK two things.

              First, I didn't intend to include that old delay_ms() routine, please get the one from the post on Delays and use that instead.

              Second, are you wanting to toggle pin E5? It looks like you didn't clear TRISE bit 5 so it's still set as an input and will not change.

              Change this line:
              TRISECLR = 1 << 0;
              to
              TRISE = 0;
              or
              TRISEbits.TRISE5 = 0;

              Also, inside that main loop:
              LATEINV = 1 << 5;
              should be enough. Good luck!

            2. Aidan Author

              What dev board are you using Ciaran? Does it use the same clock as mine or does it maybe use a crystal? Just trying to think of reasons why something so simple wouldn't work.

              1. Ciaran Watters

                To save money I didn't buy a dev. board, I bought the actual I.C. (PIC32MX20148EFG064) and soldered it to a footprint to break out the Surface Mount to DIL Headers Through Hole pins 2.54mm spacing.. I then connected up all the Power & Grounds, the Programming connections with a pull up on the MCLR and some 100nF close by the chip. and Hey Presto it worked. I'm using the internal Fast RC with Harmony, I don't know if your code is configured to activate an external crystal? Yesterday I was happy when I included your delay functions into my skeletal Harmony built code and the timing was accurate. Your delay routines bult / compiled and worked, so that was some progress. I didn't get back to running your Non-Harmony-Config code yet but I will try it again asap. Thanks for your concern Aidan and please don't hesitate to ask me any further questions as I would like to really get to know as much s possible about these awesome PIC's and help build up the knowledge base on your HOBBYIST forum

                1. Aidan Author

                  I also don't buy the official dev boards, they're too expensive. I usually make my own. They're probably breaking a lot of design rules but they work fine so I don't care too much :)

                  Yes, the code I uploaded is designed to be used with an External Crystal, so that might be why it didn't work for you. You need to change the following lines to work with the internal oscillator:

                  #pragma config FPLLIDIV = DIV_1 // System PLL Input Divider (1x Divider) 8 / 1=8
                  #pragma config FPLLRNG = RANGE_5_10_MHZ // System PLL Input Range
                  #pragma config FPLLICLK = PLL_FRC // System PLL Input Clock Selection
                  #pragma config FPLLMULT = MUL_50 // System PLL Multiplier 8 * 50 = 400Mhz
                  #pragma config FPLLODIV = DIV_2 // System PLL Output Clock Divider 400 / 2 = 200Mhz
                  #pragma config FNOSC = SPLL

                  Please note that with the internal FRC oscillator stuff that requires tight timing like USB doesn't work (or I've never been able to get it to work at least).

                  Good luck!

                  1. Ciaran Watters

                    Whow! this is a great forum Aidan with great communication. I will try this RC code this week, and let you know how I get on. I have a fondness for the Microchip PIC and I would like to see how far I can go in terms of cutting edge projects. I like external crystals but in the last few years I have being amazed by the Fast RC speed and the idea of having everything self contained within the Chip is just as appealing. This week I had a 25 MHz square wave on PORTE5, which is formed by 20ns high & 20ns low, not bad given the while loop code required to invert the pin. I also learned that ST have a 400 Mhz uP, so I'm also interested to know how well the PIC can rival this. Finally I learned that PIC have an ARM core device now, I don't know the significance of this but it sure sounds good. Last comment for the week, I was truly satisfied by how simple it was to run the UART at 1 MHz (1us for a bit), because NXP use this unusual speed to communicate with their Zigbee module and I'm interested to read the communication lines. I will get back to you soon Aidan, thanks for all your all help. Enjoy the weekend & new week. Ciaran.keep well!

                    1. Aidan Author

                      Hi there Ciaran,

                      It's easy to reply when there's so few people reading but I'm glad at least someone finds the information useful. That's why I put it up in the first place.

                      I forgot a line that you need, it's:
                      #pragma config POSCMOD = OFF // Primary Oscillator Configuration

                      Hope you have a great week and keep well too.

  4. colle

    hi,
    i'm now experimenting with sd cards and i'm getting nice results.. only 2 qustion.
    in your project do you use the mmcpic32 routines to initialize and use spi module, right? not the routine in the previous post.
    second. qhy do you use the funcion disk_initialize? the fatFs doc says this:
    Remarks: This function needs to be under control of FatFs module. Application program MUST NOT call this function, or FAT structure on the volume can be broken. To re-initialize the filesystem, use f_mount function instead.

    infact i use the f_mount function and all works fine!

    1. Aidan Author

      Hi Colle,

      I'm glad to hear it's working for you.

      Yes I put all the spi sd card related stuff into mmcpic32.c, including the initialisation which is handled by power_on(). It was more convenient to do than having an SPI_init() in each new program I write and mmcpic32.c needs to be aware of which SPI port is in use anyway. You could put it in main if you prefer, makes no difference in the end.

      As to why I use disk_initialize, that's a good question. I've been using it for a few years now, probably got some example code from the internet using it. I've never had an issue with FAT corruption but I'll definitely look into that, thanks for pointing that out!

      1. colle

        hi, I just did a couple of tests: write/read txt, read bmp and display on a little 320*240 TFT. the speed with the spi at 50MHz is shocking compared to the PIC18F. I found that the best solution is to create a 200K ram buffer or more, read into it the image and then write the buffer on the display.

        at the moment I'm using FatFs 0.13b with your disk io and mmcpic32 modified to use my SPI routines, I tried also the new version 0.13c but I have some compiling errors.

        https://www.youtube.com/wat...

        and some speed comparision for read and write 320x240 bmp
        SPI 1 MHz 250K buffer: 1,6202318668 S
        SPI 1 MHz no buffer: 1,6028388977 S
        SPI 25MHz no buffer: 0,2186146259 S
        SPI 50MHz no buffer: 0,1894090271 S
        SPI 25MHz 250K buffer: 0,1310590982 S
        SPI 50MHz 250K buffer: 0,1023453116 S

        1. Aidan Author

          Hi colle,

          Is "shocking" good or bad? :) I haven't updated that code for writing so it's really, really old. Something like 8 years old. It's also not my code. The reading code I changed a little bit to use 32-bit SPI transfers for the 512-byte sector read so it's reasonably fast but not super fast. I am working on DMA mode which is faster but it has many problems for the moment.

          Thanks for sharing your result. The video doesn't work though?

          1. colle

            for me is shocking good.. i know that i'ts not super fast.. is only 1.5MB/s but compared to my old project with SPI running at 1MHz it's very fast.
            can you see the video now?

            1. Aidan Author

              If the files are big then try formatting your SD card with block size 32kB, it might make reads faster. Also, read at least 32kB at a time in f_read(). Good luck, glad the code is working for you. Thanks for your results and your video!

        2. Aidan Author

          OK, video is working now. For reference, I was able to get a 320x240 video (30fps, uncompressed 320x240 RGB565 frames) streaming off an SD card while streaming a uncompressed 44.1khz stereo WAV file working with some combined 32-bit and DMA code, so it's also pretty fast. When it's stable I'll upload it. If that ever happens :/

          1. colle

            for sure is faster than mine.. if my calculations are correct with my actual speed I should be able to get 320x240 RGB565 at 10fps.. looking forward to see your code!!

  5. Harpreet Singh

    Hi Aidan,

    Nice Blog !! .I have not tried your code yet. I have few doubts .
    Will it possible to Interface two microSDCards with Single SPI Module with different select lines as above ?
    How to mount to different ? two SDCards ?
    According to my requirement I have to copy data from one microsdcard to another ?

    --
    HK

    1. Aidan Author

      Hi Harpeet, I've been on vacation so sorry for the really late reply. It would be possible to interface two microSD cards but you would have to edit the mmcpic32.c to support multiple drives. It may be quite a lot of work but not impossible.

  6. Mark Lewis

    Any updates? I've tried using this and others posted on the Microchip forum but have had problems.
    It seems I can mount the card but trying to read anything just causes it to freeze indefinitely.

    I make my own boards too but none with an SC card socket so for testing purposes i'm just using the Curiosity PIC MZ EF development board.

    I'm trying to figure out what's going on but hard to tell since it's blocking code and doesn't report any error, it just simply freezes.

    1. Aidan Author

      Hi Mark, I've been on vacation so the replies are really late.

      Where is it locking up? It may be that you either haven't set up the SPI channel correctly or you are missing a pullup resistor on SDO.

  7. Manel Cristovao

    Hi for all,

    I have problem to implement this code in PIC32MX795F512L. When i start to initialize disk with function disk_initialize(0), in line "if (send_cmd(CMD0, 0) == 1)", never return 1. Do you have this problem before?

    I found this (https://www.microchip.com/f..., and one guy ave a same problem but i can't solve it like him.

    I try with two SD CARDS:
    -MICRO SDHC 4GB C4,
    -MICRO SDXC 64GB U3,

    I have system clock at 80 MHz with peripheral clock 40MHz and SPI CLK at 10MHz.

    Best Regards,

    Luis Emanuel

Comments are hosted by Disqus, which loads only when you ask for it.