USB is a ubiquitous protocol in modern computing. There are many applications where we may need to use a USB Flash drive to store and read data. The PIC32MX270F256D includes an embedded USB host and in this example we interface the PIC32 to a USB flash drive and write a text file to it. This can be used for embedded data logging applications.

USB and PIC32

The Universal Serial Bus or USB is a protocol for serial bus communications between computing devices. USB is a very complex protocol and covering it in its entirety is not possible in this post. In this post we will cover the basics you will need to know to use a USB host.

USB consists of 4 lines which are GND, VCC, D+ and D-.

USB works by using something known as differential signalling. By using a differential pair USB can provides a robust, high-speed interface that is not susceptible to interference. The data signals are sent going positive on the D+ line and going negative on the D- line.

USB also internally has devices known as serializers and deserializers. The serializer is responsible for generating data to be transmitted on the transmit end and the derserializer decodes the information transmitted.

The data in USB is known as non-return-to-zero Inverted or NZRI data to communicate between a master device called the host and another device is simply called the device.

The PIC32 microcontroller includes a module known as USB On the Go or USB OTG which allows it to be used as a host or a device.

The rate at which data is transferred over USB is called the bus speed. USB speeds can be: USB 1.0 Low Speed transferring at 1.5 Mbit/s, USB 1.1 Full Speed tranferring data at 12 Mbit/s, USB 2.0 Hi Speed with a data rate of 480 Mbit/s. There is also USB 3.0 SuperSpeed which goes up to 10 Gbit/s speed.

USb devices belong to particular classes which is used to specify the functionality of the device. For example there are classes that will identify the device as either an audio device, a mouse, keyboard or some type of storage device. there are many storage classes available which can be used by a developer based on their needs.

USB includes many connectors which includes:

Type A connectors:

Type B connectors:

and Type C connectors:

There are also mini and micro connectors used by a lot of embedded and portable devices. USB type C connectors are special because they allow for reversible plugging.

USB is used for its ability for plug and play. What this means is that the USB device will automatically discover when a device has been added to the bus and will interact with it.

The USB module on the PIC32MX270F256D has low and full speed embedded host capabilities.

Flash Drives

Flash drives are devices which have flash memory build in flash memory that will range in memory from as low as 128 MB all the way up to Terabytes of storage. These devices belong to the Mass Storage Device class.

The common flash drives are USB 2.0 and USB 3.0 type flash drives that will have type A or type C connectors. In our example we assume you are using a USB 2.0 type flash drive with a type A connector that will have a pin-out as shown above.

In order to use the Flash Drive with the PIC32MX270f256D you may use an adapter board for prototyping or you may use a makeshift connector for prototyping.

 

This adapter made with header pins and a USB type A connector is useful for prototypes involving USB hosts.

 


Connections

The connections consist of a USB drive connected to the PIC32MX270F256D as depicted. It is important to connect the USB ID pin to ground as this will ensure that the PIC32 is used in host mode.


C Program

        /*
 * File: Main.c
 * Author: Armstrong Subero
 * Processor: PIC32MX270F256D w/Ext OSC @ 4MHz, PLL to 48 MHz, 3.3v
 * Program: 18_USB_Host
 * Compiler: XC32 (v1.44, MPLAX X v5.05)
 * Program Version: 1.0
 *                             
 * Program Description: This Program Allows PIC32MX270F256D to use the USB OTG
 *                      module in USB host mode to read a USB drive. The program
 *                      was tested with various Drives from size 2 GB to 32 GB
 *                      from different manufacturers. 
 * 
 *                      NOTE: This file is dependent on the legacy PLIB 
 *                      libraries.  
 * 
 * Hardware Description: A USB Flash Drive is connected to the microcontroller
 *                       as follows:
 *                       
 *                       VBUS -> Vcc (5v)
 *                    VUSB3V3 -> 3.3v                    
 *                         D+ -> D+
 *                         D- -> D-
 *                     VBUSON -> 3.3v    
 *                      USBID -> GND   
 * 
 * Change History:
 *
 * Author             Rev     Date          Description
 * Armstrong Subero   1.0     23/09/2018    Initial Release.
 *                      
 * Created September 23st, 2018, 01:26 PM
 */

////////////////////////////////////////////////////////////////////////////////
// Includes and Defines
////////////////////////////////////////////////////////////////////////////////
#include "usb.h"
#include "usb_host_msd.h"
#include "usb_host_msd_scsi.h"
#include "FSIO.h"
#include "PIC32MX270_USB.h"
#include "usb_event_handler.h"

FSFILE *myFile;                // FSFILE pointer for file we are working with 

int main(void)
{ 
    // Enable the cache for the best performance
    CheKseg0CacheOn();
    
    // Enable interrupts
    INTEnableSystemMultiVectoredInt();
    
    // Initially the device is not attached
    deviceAttached = FALSE;

    //Initialize the stack
    USBInitialize(0);

    while(1)
    {
        //USB stack process function
        USBTasks();

        //if flash drive is plugged in
        if(USBHostMSDSCSIMediaDetect())
        {
            // device is now attached
            deviceAttached = TRUE;   
    
            // after device is attached try to initialize the file system
            if(FSInit())
            {
                // Opening a file in mode "w" will create the file if it doesn't
                // exist.  If the file does exist it will delete the old file
                // and create a new one.
                myFile = FSfopen("text.txt","w");
                PORTBbits.RB0 = 1;

                // Write some data to the new file.
                FSfwrite("Some Text",1,11,myFile);
                
                // Make sure to close the file so that the data is written
                FSfclose(myFile);

                // Just sit here until the device is removed.
                while(deviceAttached == TRUE)
                {
                    USBTasks();
                }
            }
        }
    }
    return 0;
}


The code in the main program is very simple. Despite the underlying thousands of lines of code, the main program has been made as simple as possible to allow writing to a flash drive with a file system.

A pointer is created to the file we are working with, after which we set the initial USB device connected state to unattached. After we initialize the USB stack and once the device is initialized we initialize the file system and create a file and write some data to it.

In less than 100 lines of code we can interface a USB flash drive and write some data to it!

*Note that I used the legacy peripheral libraries  with this example as the Harmony Framework has been demonstrated to have problems with the USB code as when implemented it has not worked with some flash drives. The problem is very difficult to debug due to the complexity of the framework.

Therefore you will need to download and install the PLIB libraries provided by Microchip Technology to compile this example. do not worry though, even if the code is legacy, it can serve your project needs well for many years to come.


Results

The code runs well and is very robust. I have previously used this code in a product that has been running for many years without any complaints from customers.


Link to Project

You can download the entire project here!

USB Host Project

Leave a Reply

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