USB device, part 1 of 10 Part 1: USBPart 2: Initialising the USB peripheralPart 3: USB descriptors and how to send and receive data on endpoint 0Part 4: Finishing the USB CDC devicePart 5: USB progress updatePart 6: USB MSD codePart 7: How to make a USB Mass Storage Device part 1Part 8: How to make a USB Mass Storage Device part 2Part 9: USB HID joystick: it worksPart 10: USB HID joystick: schematic, code and KiCad files

USB

All 10 posts in USB device
  1. USB
  2. Initialising the USB peripheral
  3. USB descriptors and how to send and receive data on endpoint 0
  4. Finishing the USB CDC device
  5. USB progress update
  6. USB MSD code
  7. How to make a USB Mass Storage Device part 1
  8. How to make a USB Mass Storage Device part 2
  9. USB HID joystick: it works
  10. USB HID joystick: schematic, code and KiCad files

Code for this post

USB on the PIC32MZ

UPDATE: ERROR IN CODE FIXED

In the USB_device_description, change the line called /* bDeviceClass */ from 0x00 to 0x02 otherwise enumeration won't complete

Hello again all, he said to no one. Great news! I've finally gotten the USB port on the PIC32MZ working without Harmony. It's been a multi-year on-again-off-again project but this time I managed to get it done. Well, it works on all my development boards anyway.
What I've gotten to work so far is USB CDC (virtual COM port), which means I no longer have to use a USB-UART chip on my PIC32MZ development boards. From here I want to move on to getting HID working and then the ultimate goal of MSD. But for now, I'm uploading the CDC code and hopefully if anyone reads this they can see if it works on their boards :)

The documentation is severely lacking on USB-related stuff and to give credit where credit is due, here are all the sites I referenced when making my code:
* Microchip's own OTG datasheet
* Microchip's AN1166 on USB CDC
* The massively long USB.org CDC spec 1.2
* MARKDINGST.BLOGSPOT.COM that helped me understand the get/set line coding better
* WWW.XMOS.AI that helped me understand what the various endpoints were
* AIJU.DE that really helped explain some of the intricacies of the flags I needed to set
* WWW.BEYONDLOGIC.ORG for their simple explanation of the USB setup packets
* WWW.SILABS.COM for a better explanation of USB-CDC

And then the big ones. Actual examples of USB-CDC for the PIC32MZ. I couldn't get either of these to work on my dev board but I used them as skeletons to base my own code off of (with a fair bit of copy and pasting!). Thanks to both of these people without whom I'd never have had any hope of getting this done:

What you will notice missing there is MPLAB Harmony, because it continues to be a bloated, slow, useless mess that is so cryptic that it is useless and provides no hints of how to do anything yourself. The Harmony approach of one library for all devices may be great for corporations who don't care about how anything works but it is atrocious for a hobbyist like me trying to understand how to use the PIC32MZ series.

Anyway, I will go into a brief explanation of USB and CDC in a future post but for now I just wanted to share the code.

Please note that while I have started splitting up the code into a few different files the work isn't done yet. I also have a lot more to learn about USB so some of the naming or things I'm doing may well be wrong :) Point is, it works on my board and I think having the code out there is better than not having it out there. As always, YMMV!

Here's the code. I hope it works on your boards and, if not, leave a comment and I'll try and help out.

21 comments
  1. Aidan Author

    Thanks for stopping by. I'm afraid there's just so much information to write about that it's going to take some time and it won't be an exciting read :)

  2. colle

    great!!!!
    many thanks

    1. Aidan Author

      Hey colle,

      Good to see you again. I've gotten a lot more USB working, will post in a few days.

  3. HRISHIKESH E B

    Even I'm working on the same project with pic32mx but no progress till now tried many examples but I cant get the pic32mx to get detected by my computer
    please help

    1. Aidan Author

      Hi there, disqus didn't notify me about your comment so sorry for the late reply.
      Please note my code is for pic32mz not pic32mx so it may not work for you.

      In the USB_device_description, change the line called /* bDeviceClass */ from 0x00 to 0x02

      I hope this fixes your issue.

      1. HRISHIKESH E B

        The build failed with a lot of errors. Do you have any other ideas.

      2. Carlos789

        Hi Aidan:
        I have the following errors and I cannot find the reason for them.
        I would very much appreciate any ideas.
        Many greetings
        Carlos

        "C:\Program Files (x86)\Microchip\xc32\v2.30\bin\xc32-gcc.exe" -mprocessor=32MZ2048EFH144 -o dist/default/production/PIC32MZ_USB_CDC.X.production.elf build/default/production/USB.o build/default/production/USB_CDC.o build/default/production/main.o -DXPRJ_default=default -legacy-libc -Wl,--defsym=__MPLAB_BUILD=1,--no-code-in-dinit,--no-dinit-in-serial-mem,-Map="dist/default/production/PIC32MZ_USB_CDC.X.productio...",--memorysummary,dist/default/production/memoryfile.xml -mdfp="C:/Program Files/Microchip/MPLABX/v5.50/packs/Microchip/PIC32MZ-EF_DFP/1.3.58"
        nbproject/Makefile-default.mk:164: recipe for target 'dist/default/production/PIC32MZ_USB_CDC.X.production.hex' failed
        make[2]: Leaving directory 'C:/PC Nueva/cec/OLIMEX/USB sinMHC/PIC32MZ_USB_CDC.X'
        nbproject/Makefile-default.mk:91: recipe for target '.build-conf' failed
        make[1]: Leaving directory 'C:/PC Nueva/cec/OLIMEX/USB sinMHC/PIC32MZ_USB_CDC.X'
        nbproject/Makefile-impl.mk:39: recipe for target '.build-impl' failed
        build/default/production/USB_CDC.o:(.data+0x0): multiple definition of `USB_device_description'
        build/default/production/USB.o:(.data+0x0): first defined here
        build/default/production/USB_CDC.o: In function `USB_EP0_handle_transaction':
        c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/usb_cdc.c:129: multiple definition of `USB_address'
        build/default/production/USB.o:c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/usb.c:5: first defined here
        build/default/production/USB_CDC.o: In function `USB_EP0_handle_transaction':
        c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/usb_cdc.c:129: multiple definition of `USB_set_address'
        build/default/production/USB.o:c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/usb.c:5: first defined here
        build/default/production/USB_CDC.o: In function `USB_EP0_handle_transaction':
        c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/usb_cdc.c:129: multiple definition of `USB_line_control_state'
        build/default/production/USB.o:c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/usb.c:5: first defined here
        build/default/production/main.o:(.data+0x0): multiple definition of `USB_device_description'
        build/default/production/USB.o:(.data+0x0): first defined here
        build/default/production/main.o: In function `set_performance_mode':
        c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/main.c:79: multiple definition of `USB_address'
        build/default/production/USB.o:c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/usb.c:5: first defined here
        build/default/production/main.o: In function `set_performance_mode':
        c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/main.c:79: multiple definition of `USB_set_address'
        build/default/production/USB.o:c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/usb.c:5: first defined here
        build/default/production/main.o: In function `set_performance_mode':
        c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/main.c:79: multiple definition of `USB_line_control_state'
        build/default/production/USB.o:c:/pc nueva/cec/olimex/usb sinmhc/pic32mz_usb_cdc.x/usb.c:5: first defined here
        c:\program files (x86)\microchip\xc32\v2.30\bin\bin\gcc\pic32mx\4.8.3\..\..\..\..\bin/pic32m-ld.exe: Link terminated due to previous error(s).
        collect2.exe: error: ld returned 255 exit status
        make[2]: *** [dist/default/production/PIC32MZ_USB_CDC.X.production.hex] Error 255
        make[1]: *** [.build-conf] Error 2
        make: *** [.build-impl] Error 2

        BUILD FAILED (exit value 2, total time: 3s)

  4. Dale Rodgers

    Hi, Thank you for this code - its certainly more lightweight and easy to understand than the Harmony mess.

    This code worked fine for me with compiler optimisations turned off (-O0). The free compiler does allow -O1 to be used and this is where I think I've found an issue

    With Putty I started getting errors and also with custom Windows code. Whenever I tried SetCommState() from my Windows code I would get error 87 (ERROR_INVALID_PARAMETER). It seems the USB_LINE_CODING struct was getting corrupted.

    I tracked this down to the set line coding transaction on endpoint 0. The interrupt is generated for the the setup part (about to follow is the set line coding data). In decoding this we clear USBE0CSR0bits.RXRDYC in the initial call to USB_receive_EP0().

    We then call USB_receive_EP0() again to get the actual line coding parameters. However, I believe in some cases the second part of the command (the actual line coding data) has not yet been received in HW. With -O0 optimisation, there is an inherent delay that allows the second part to come into HW okay. With -O1 optimisation, this delay is reduced and there's a bit of race. Emptying the EP0 fifo gives gibberish and corrupts the line coding parameters. If the host then asks for the line coding parameters to modify, they are given corrupted values that cause error 87.

    I've added this simple fix to USB_CDC.c around line 228 where the Set Line Coding command is handled (surrounded by START and END!):

    case 0x20:
    {
    if (USB_transaction.bmRequestType == 0x21)
    {
    // Set line coding
    // Read (wLength) bytes from USB Endpoint 0


    // START START START START START START START START START START
    // ensure data part has been received following command
    while( !USBE0CSR0bits.RXRDY )
    {
    _nop();
    }

    // END END END END END END END END END END END END END END END


    USB_receive_EP0(USB_transaction.wLength);


    USB_line_coding.baud = ((int)EP[0].rx_buffer[3] << 24) | ((int)EP[0].rx_buffer[2] << 16) | ((int)EP[0].rx_buffer[1] << 8) | EP[0].rx_buffer[0];
    USB_line_coding.parity_bits = EP[0].rx_buffer[4];
    USB_line_coding.stop_bits = EP[0].rx_buffer[5];
    USB_line_coding.data_bits = EP[0].rx_buffer[6];
    }
    break;
    }

    There are probably better ways of doing this then a blocking wait but the time is very, very small.

    1. Aidan Author

      Hi Dale,

      Many thanks for the reply and the updated code. I haven’t updated my site in quite some time due to the covid-19 situation keeping me quite busy at work, and general fatigue in trying to get the USB host mode to work properly with absolutely no usable documentation :) I haven’t been getting notifications about comments so I’m glad I saw this. Thanks again!

  5. Dale Rodgers

    Again, thanks for the code.

    Is this code freely useable and modifyable?

    1. Aidan Author

      Hi Dale,

      Yeah you’re free to use it as you see fit, I just ask that you mention where it came from in the source file :) Modify away, this is a non-profit site I started because I was frustrated with how bad Harmony was and the elitist attitudes of people on the Microchip forums. I’m glad it’s of use to someone, it tooks me a lot of trial and error to get this stuff to work (and some mostly working code from a user I credited in the post). Thanks for stopping by!

      1. Dale Rodgers

        Excellent!

  6. Father of ten

    Hi Aidan. Thanks for this. It works on my Olimex PIC32-EMZ with a 32MZ2048EFH064 but not on my custom 32MZ2048EFH144. There's a little activity on D-D+, but the computer keeps flashing USB device not recognized. Same code. Maybe the lack of .1uf on Host power? Also Olimex is micro and mine is mini B.
    Another issue - do you know of a TCPIP stack without Harmony?

    1. Aidan Author

      Hi there,

      Glad the code works, thanks for leaving a comment to say so.

      Does your custom board have a crystal on-board? If I recall correctly it needs to be 12MHz or 24MHz for the USB clock divider to work correctly.

      1. Father of ten

        Yes, it's 24Mhz

        1. Aidan Author

          Hmmm… is your VUSB (not VBUS) pin tied to 3.3V and USB_ID pin tied to 3.3V too?

      2. Father of ten

        Works. Config oscillator setup was not correct.

        1. Aidan Author

          Well, glad it worked out. I haven’t heard anything about a TCP/IP stack no.

  7. Chris Eagleton

    Hello,
    Thank you for putting this USB project together.
    I have just attempted to use it and i get quite a few errors. Most related to multiple definitions.
    I am using your code as is with no changes. I simply imported the project into MPLAB 6.
    I cant see any reason why it would be creating multiple definitions.

    Are you able to help me to compile the project please.
    Thanks

    1. Aidan Author

      Thanks for commenting, most people don't :)

  8. Aubrey Champagne

    I see you are using a pic32mz, will this work for a pic32mx?

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