DMA, part 1 of 4 Part 1: Working on DMAPart 2: Direct Memory Access on the PIC32MZPart 3: DMA SD card reads on the PIC32MZPart 4: Updated SPI SD DMA code and DMA Pattern Matching

Working on DMA

All 4 posts in DMA
  1. Working on DMA
  2. Direct Memory Access on the PIC32MZ
  3. DMA SD card reads on the PIC32MZ
  4. Updated SPI SD DMA code and DMA Pattern Matching

Code for this post

What I've been doing and progress on DMA

These last few weeks I've been working on a project for work which is basically putting the DAC-based MP3 player onto a PIC32MX250F256B chip, attaching some serial flash memory and having it attach to the PC via USB in vendor mode, which meant I had to write an app to do that too. Harmony works fine for this and you can still open up their examples and modify them to get them to work. I'm really not a fan of how Harmony splits up everything into its own little file and then needs the Harmony library too, it makes working on the project on multiple machines - which I do - a pain. Personal preference I guess.

Anyway, I'm back to working on trying to get SD card reads to work in DMA mode. With my previous code, the maximum speed I saw was about 3302kB/s, even with huge sustained block reads of 64kB. I'm happy to report that I'm currently getting a bit over 5000kB/s with 64kB sustained block reads. Please note: I am not currently working on DMA mode to get background reads working, I am doing this solely for the speed increase it provides.

I know the SD card spec is for 25MHz but everything seems to work fine at 50MHz. I'm not putting my code into hospital equipment, it's all hobbyist / personal stuff so I just want speed. There are some reliability issues that I'm working on but I hope to upload the code in a few days. Even if it doesn't work, I'll upload it and someone smarter than me can hopefully show me where I've gone wrong. Until then, good luck with the PIC32!

Update (2019-01-07): Here are some results from my tests, comparing the original SD SPI code that I got 8 years ago, my newer 32-bit enhanced buffers code and my new 8-bit enhanced buffers DMA code. The results are fantastic at bigger block sizes!

PIC32MZ - SPI SD transfer speed comparison

HERE BE DRAGONS

There may well still be issues with this code!

I'm uploading this code for anyone who cares to test but be warned. You have to make the following changes to your code:

  • Add this line PRISS = 0x76543210; after you've set up TRIS registers, to enable the SRS registers I use in the DMA interrupt
  • Set SCK as an input (in my case, SPI2 needs TRISG6 set to 1). I have no idea why this is but it refuses to work without it and caused untold hours of debugging!
  • Change your read buffer declaration from unsigned char read_buffer[8192] to __attribute__((coherent)) unsigned char read_buffer[8192];
  • Pray

This code is provided as is and you should fully expect it to have issues. I'm providing it because it works for me, on my own board and in my own programs and I thought someone might like to get their hands on it while I slowly write the post on DMA. Good luck! Now to write that post on DMA...

Here's the code

51 comments
  1. colle

    very intresting speed!!!
    how did you measure the kb/s transfer speed? and.. i suppose is kbyte/s right?

    1. Aidan Author

      Yes, it is kilobytes (1024 bytes) not kilobits. I wrote a simple benchmark program to read 100MB from a huge file on the SD card. This code may still have problems but it works in my mp3 player so who knows. Good luck :)

      1. colle

        if i'm doing right the math these are my results for reading 100MB from SD:
        Block = 512B
        Timer Read 100MB: 80,965 S -> 1235,106 kB/s
        Block = 1024B
        Timer Read 100MB: 56,878 S -> 1758,149 kB/s
        Block = 2048B
        Timer Read 100MB: 44,524 S -> 2245,979 kB/s
        Block = 4096B
        Timer Read 100MB: 38,524 S -> 2595.784 kB/s
        Block = 8192B
        Timer Read 100MB: 38,795 S -> 2577,652 kB/s
        Block = 16384B
        Timer Read 100MB: 38,792 S -> 2577,851 kB/s
        Block = 35768B
        Timer Read 100MB: 39,998 S -> 2500,125 kB/s
        Block = 65536B
        Timer Read 100MB: 38,774 S -> 2579,048 kB/s
        Block = 131072B
        Timer Read 100MB: 38,748 S -> 2580,778 kB/s
        Block = 262144B
        Timer Read 100MB: 38,750 S -> 2580,645 kB/s

        here is the code I wrote for this test.. can you check if I did it right? basically, I seated up a 32bit timer, at the end of the SD reading I read the value of the TMR register and calc the seconds and the kB/s..
        the values are in line with your 8bit basic test.

        https://www.dropbox.com/sh/...

        1. Aidan Author

          Hi, yes it looks good. I made a millisecond timer (with interrupt) like Arduino millis() and counted how many milliseconds it took.

          Which code does that use for f_read? Is it yours or is it mine, and is it dma or not?

          I'm also using a Samsung UHS-I 32GB microSD card formatted as FAT32 with 32,768 cluster size, so maybe that's making a difference too. The SD standard is for max 25MHz in SPI mode so I don't expect all cards will work with it running at 50MHz.

          1. colle

            it uses the code from ff.c file. I think is the original from the fatfs library... fastseek is disabled by now, should I enable it?
            for sure I'm not using DMA now.

            1. Aidan Author

              Sorry, I don't mean f_read, I mean the block read in diskio.c or mmcpic32.c.

              No I don't think fastseek will help you. I have it disabled. 2.5MB/s seems right for the old code. Is SPI 25MHz or 50MHz?

              1. colle

                50MHz but i'm using an old sd card... late today i'll try a new one..
                it seems i'm using the rcvr_datablock funcition in mmcpic32.c is this the old one? how can i use the new ?

                1. Aidan Author

                  Try replacing your mmcpic32.c file with the one from the code found at:

                  http://www.aidanmocke.com/b...

                  (By "here's the code" at the bottom of the post, it's inside a ZIP file).

                  Be sure to backup first in case it doesn't work :) And remember you need to change SPI settings at the top (in the #define section).

                  1. colle

                    ok, your mmcpic32 is faster!!!

                    https://uploads.disquscdn.c...

                    And in DMA i have your result as well!! like 5600KBps!!! many thanks!!!
                    but it's hard to understand how dma works

                    1. Aidan Author

                      That's excellent news! I'm glad it works. Yes, DMA is a bit hard to understand, I'll write a post on it today or tomorrow. It takes a long time to write these posts :)

                      1. colle

                        I'm looking at your mmcpic32_dma code and, thanks to your today posts, now is a little more easy to understand what's going on.
                        just a question.. the MAX_TOKEN_WAIT_BYTES constant has to be the same as the receive buffer length? or it can be different?

                        1. Aidan Author

                          Hi there,

                          No, it is indepedent. You can set it to whatever value you like but I recommend setting it to at least 4096, maybe even higher.

                          1. colle

                            thanks.. and another question... in the comments you type all the interrupt referred tu DMA1 channel but the code set or reset the DMA0 bits.. for example
                            IFS4CLR = 1 << 6; // Clear DMA1IF
                            IEC4SET = 1 << 6; // Set DMA1IE

                            is only the comment wrong isn't it?

                            1. Aidan Author

                              Oops... yes you're right. When I was trying to get it working I was using DMA 1 but I changed it to DMA 0. That's why I don't like using things like IFS4CLR = 1 << 6 because mistakes like this happen.

                              I will edit the code, thank you.

                              1. colle

                                I never use the clr, set inv function.. i think thet at asm level is better use REGISTERbits.xxx = 1.

                                I asked for that because I edited your code to make the setup simple by declare Wich spi module and DMA channels to use without edit the code changing the registers every time.

                                1. Aidan Author

                                  Hi colle,

                                  I think the SET, CLR and INV are actually faster, they're called "atomic" instructions.

                                  I read somewhere that if you say LATAbits.LATA0 = 1, the PIC32MZ actually reads the value of the port, modifies it and then writes it back to the port, which takes a few cycles.

                                  They seem to recommend using SET, CLR and INV in ISRs because there's a chance that the value of LATA might change after you read it and when you write back the new value the change will be lost. But it does lead to silly mistakes and it's not very easy to read, especially when the comments are wrong like in my code :)

                                  I'd be interested in seeing your code when you're done editing. I'm glad someone else is working on this!

                                  1. colle

                                    I know about the "atomic" properties but.. we type the code in XC32, why the compiler doesn't take care of that?? if I use LATAbits.LATA0 = 1 it's obvious that I want to modify the register atomically..
                                    I read the disassembly instruction for LATAbits.LATA0 = 1 and LATASET = 1 and to me the ASM results seem similar.. but I'm not really into MIPS ASM..

                                    here are the mmcpic32 files modified, but now I'm thinking if I have to modify all and use SET/CLR instructions.. let me know what you think
                                    https://www.dropbox.com/s/b...

                                    1. Aidan Author

                                      Yes, I saw that in the assembler too. There is a lot of discussion about it in the Microchip forums but a lot of people say that only SET, CLR and INV are atomic and if we do "LATAbits.LATA1 = x", the compiler can't know if that needs to be a SET, CLR or INV because the value of x changes at runtime so it doesn't use the atomic instruction. So maybe it's safer to just use them.

                                      Microchip talks about them here: http://microchipdeveloper.c...
                                      And on the forums: https://www.microchip.com/f...

                                      I looked at your code, it's great. It makes it much more flexible.

                                      1. colle

                                        different thinking in some book...
                                        https://uploads.disquscdn.c...

                                        1. Aidan Author

                                          Yes, that's why I use it, because it's very easy to get confused. So OK, only SET, CLR and INV are atomic. Thanks for confirming that.

                                          1. colle

                                            ok.. I did some test last night with set/clr registers. atomic or not atomic they are definitely faster than bits struct access. at least for changing the output value of a single pin on a port. I modify my LCD 320*240 ILI9235 library to use SET/CLR on RS/WR/CS pins and I doubled the speed write on the display. Now I can achieve 20fps in 8bit data communication (reading 320*240 RGB565 from SD in DMA, store into a buffer and write the buffer on display). Now I want to try 16bit mode and then PMP.
                                            of course I'm going to remodify your mmcpic32 to use SET/CLR. The files I send to you yesterday I had changed your set/clr register access with bits struct access to make them flexible..

                                            1. Aidan Author

                                              That's good to know, I suspected they might be faster but I didn't know for sure.

                                              I'm sure you will find PMP *much* faster for LCD :)

                                              Whenever you finish that code please send it and I'll add it to the post. Thanks again!

                                              1. colle

                                                Here you can download the new files. dma version is not tested yet..
                                                https://www.dropbox.com/s/3...

                                                I have a couple of questions about the DMA code you wrote in function SPI_DMA_wait_token
                                                - can i change DCH0DAT = 'รพ' to DCH0DAT = 0xFF ?
                                                - there are 2 lines that we have already set in SPI_DMA_init function (CHAEN = 0 and CHPRI = 3) can we delete those?

                                                can I get rid of diskio.c right??

                                                1. Aidan Author

                                                  Hi colle,

                                                  1) No, that needs to be 0xFE. I can't remember why I wrote it like that but there might have been a reason. If it works with 0xFE you can change it to that.

                                                  2) Yes, my code wasn't 100% finished so there's still some stuff I wanted to clean up. Maybe even more repetition here and there.

                                                  3) Yes :)

                                                  I will look at the code in the morning thanks. Need to get to bed!

                                                  1. colle

                                                    new files, dma tested and working. little speed improvements
                                                    https://www.dropbox.com/s/e...

                                                    1. Aidan Author

                                                      Hi colle,

                                                      That's great work, thank you! I think there might be a way to make all those defines shorter, will see if I can do something about that today.

                                                      It's really cool to have someone working on this with me, thanks again.

                                                      I have one question. Do you also have to set SCK as an input?

                                                      1. colle

                                                        Yes, i set sck as input but didn't tried as output. Will try it tomorrow.. need some sleep now :)

                                                        1. Aidan Author

                                                          Good night colle. Time for me to get up:)

                                                          1. colle

                                                            Hi Aidan,
                                                            for me is working also with SCK tris setted to 0. I also removed the line PRISS = 0x76543210 because i allready setted the shadow registers for the interrupts. i also changed SPICONbits.SRXISEL = 0 in 8 bit and 32 bit mode.
                                                            i tried to use SPI at 25Mhz but i have some reading errors in dma mode (can't open file, or transmission closed)

                                                            1. Aidan Author

                                                              Hi colle,

                                                              Why did you change RXISEL to 0?

                                                              If you want to use 32-bit mode DMA you'd have to change my code a bit.

                                                              How did you set shadow registers for the interrupts?

                                                              I've gotten busy with work again but I'm glad to hear you're finding this stuff out.

                                                              1. colle

                                                                I changed it in 8 bit mode and 32 bit mode not dma... I think it's not necessary right?

                                                                1. Aidan Author

                                                                  Ah right, yes. It's not necessary with DMA. I'm working on the DMA code a bit today and I found some bugs that may lead to the SPI buffer overflowing, which could make it stop working. Not finished yet but it may explain why the code didn't work at 25MHz.

                                                                2. Aidan Author

                                                                  I've fixed the bugs and tested it at multiple spi speeds, cpu speeds and system clock speeds, it seems to be working fine. I'll upload it when I finish cleaning it up.

                                                                  1. colle

                                                                    Many thanks. Looking forward to try the new code!

                                                                    1. Aidan Author

                                                                      Hi there colle,

                                                                      Mostly done cleaning up, if you want to check it out it's here. I'll make a post on it when I have some time.

                                                                      Please be aware that, for now, your read buffer needs to be 2 bytes bigger than your biggest read (I read crc straight into it).

                                                                      There may still be some mistakes or errors, but it's getting better. I tested it with many different SPIBRG (down to 256 and 2kB/s) with many different PB7DIV and SYSCLKs so hopefully it works. Thanks a lot for your help with this.

                                                                      1. colle

                                                                        Many thanks. I'm reading the code but i can't try it now. nice touch the #define in that way!!!
                                                                        personally, I think that changing the CD and SDO to use SET/CLR registers would be "safer" if the pins are on the same port with some other devices.

                                                                        1. Aidan Author

                                                                          Oops, I meant to do that. Will update the code. No rush to test it, just letting you know :)

                                                                          1. colle

                                                                            code tested and working!! maybe a little slower than the previous one (5901KB/S to 5743KB/S for 100MB at 262144B buffer)

                                                                            1. Aidan Author

                                                                              Thanks colle, and that's great news. It is a little bit slower but the bugs are hopefully gone. Something seems to be wrong with comments on this page, they're really slow to edit. Anyway, thanks again!

                                                                              1. colle

                                                                                YES, now it works also at 25Mhz.. thanks to you!!!
                                                                                do you plan to make one file for 32bit dma mode?

                                                                                1. Aidan Author

                                                                                  Excellent I'm glad it works at 25MHz now, thanks for checking that. I checked it on my board down to 200kHz and it worked.

                                                                                  I actually got 32-bit to work but because waiting for 0xFE can be any number of bytes it created a lot of overhead and ended up being 10kB/s slower than 8-bit mode and less reliable.

                                                                                  The next thing I want to do when I have some time is get SQI working with an 8MB PSRAM I have (because it can expand available PIC32MZ RAM by 8MB) or maybe start working on DMA file writing to SD card.

  2. colle

    hi Aidan, how you doing?
    can you upload a simple example in harmony for test my USB? I tried the built-in example but I can't get it to compile with PIC32MZ2048EFH. I just want to verify that my USB onboard works fine before send the PCB v2 to get manufactured. thanks

    1. Aidan Author

      Hi colle, I'm fine thanks and you?

      Sure, here is my modified cdc_com_port_dual example from Harmony v2.03b. You need to copy it into
      C:\microchip\harmony\v2_03b\apps\usb\device and overwrite the existing folder.

      If it works, you should be able to see two new COM ports in Device Manager in Windows but that's all. I don't think the program does anything else.

      1. colle

        hi, thanks for the files, I can compile it and load into my PIC32MZ2048EFH100 but nothing happens when I plug the usb into the PC.. no new com port. I think that the "hardware" is fine.. is just D+ PIC into D+ USB and D- into D-.. and GND.. any ideas?

        1. Aidan Author

          Hi colle,

          Did you connect vbus to 5V and vusb3v3 to 3.3v too? Also, are you using a crystal or external clock?

          1. colle

            vusb3V3 connected to 3.3, vbus not connected to 5v. should I?

            1. Aidan Author

              Yes I usually connect it to the 5V from the USB connector or even my 5V regulator. Seems to work fine. You are using a crystal right, not the internal FRC?

              1. colle

                Ok, it works with vbus conneccted do 5v, probably there sort of usb connected detection.

                many thanks

                1. Aidan Author

                  Yes I think that's what it is in device mode. Glad it works, you're welcome.

  3. Marc Brussieux

    (sorry for my english : i'm french !) well : all your posts are really usefull , congrats ! i use MIKROE's compilers and... so sorry... am not using 'harmony' . I am developing various gadgets (sonars, robots) with PIC32 and all of these lines are a great fun. Thank you for bringing joy into firmware development. So far, i could achieve signal generation with a 20ns sample resolution (PIC32MZ), synchronize external peripherals with the PIC's 50MHz reference clock. I am currently trying to interface the PIC32MZ with an external TI's FIFO and couple that with an ultrasound system. If i can help this enthusistic community, let me know. Kindest regards. Marc

    1. Aidan Author

      Hi Marc,

      It's great to hear someone offering to help others. Thank you for your comment and for stopping by!

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