Skip to content

Community.Hardware.USBHost

NicolasG3 edited this page Sep 3, 2014 · 3 revisions

Community.Hardware.USBHost class provide access to an USB mass storage device. No other device implemented.

Implementation note
The code is base on CMSIS implementation. This is intended to work for Cerbuino, the Default USB controller is the second one.
This code is far from a clean implementation but it works on Cerbuino.

Warning
The NETMF FAT implementation is not fully compatible with Windows. You can not rely on create or write files when the mass storage device contains files from another source than NETMF. Sometimes, another existing file will be corrupted. Reading is OK as far as I know.
This is also true for SDCard.

Sample code
Once the USB controller is started (UsbController.DefaultController.Start()), USB device insertion/ejection is handled by Microsoft.SPOT.IO.RemovableMedia and files are accessed with Microsoft.SPOT.IO.VolumeInfo

using System;
using System.Threading;
using Community.Hardware;
using Community.Hardware.UsbHost;
using GHI.OSHW.Hardware;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.IO;
using System.IO;
using System.Text;

namespace UsbHostTest
    {
    public class Program
        {
        public static void Main() {
            Debug.Print("UsbHost test");
            RemovableMedia.Insert += RemovableMedia_Insert;
            //compare to a SD Card (insertion is not detected for SD)
            //StorageDev.MountSD();

            bool res = UsbController.DefaultController.Start();
            Debug.Print("UsbController started, ready to detect USB key");
            for (int i = 0; i < 60 * 3; i++) {
                //wait for USB Device insertion
                Thread.Sleep(1000);
                }
            UsbController.DefaultController.Stop();
            Debug.Print("UsbController stop");
            }

        static void RemovableMedia_Insert(object sender, MediaEventArgs e) {
            VolumeInfo[] volumes = VolumeInfo.GetVolumes();
            if (volumes.Length > 0) {
                //assume the USB volume is the last one
                VolumeInfo media = volumes[volumes.Length - 1];
                Debug.Print("GetDirectories " + media.Name);
                String[] usbdirs = Directory.GetDirectories(media.RootDirectory);
                Debug.Print("Dir count = " + usbdirs.Length.ToString());
                for (int i = 0; i < usbdirs.Length; i++)
                    Debug.Print(usbdirs[i]);
                Debug.Print("-------------------------------------------");
                String[] usbfiles = Directory.GetFiles(media.RootDirectory);
                Debug.Print("File count = " + usbfiles.Length.ToString());
                for (int i = 0; i < usbfiles.Length; i++)
                    Debug.Print(usbfiles[i]);
                }
            }

        }
    }