mass trailing whitespace cleanup
authorMichael Moon <triffid.hunter@gmail.com>
Sun, 11 Nov 2012 02:24:34 +0000 (13:24 +1100)
committerMichael Moon <triffid.hunter@gmail.com>
Sun, 11 Nov 2012 02:24:34 +0000 (13:24 +1100)
106 files changed:
src/libs/ADC/adc.cpp
src/libs/ADC/adc.h
src/libs/Adc.h
src/libs/ChaNFS/CHAN_FS/diskio.cpp
src/libs/ChaNFS/CHAN_FS/diskio.h
src/libs/ChaNFS/CHAN_FS/ff.cpp
src/libs/ChaNFS/CHAN_FS/ff.h
src/libs/ChaNFS/CHAN_FS/ffconf.h
src/libs/ChaNFS/CHAN_FS/integer.h
src/libs/ChaNFS/CHAN_FS/option/ccsbcs.c
src/libs/ChaNFS/FATDirHandle.h
src/libs/ChaNFS/FATFileHandle.cpp
src/libs/ChaNFS/FATFileHandle.h
src/libs/ChaNFS/FATFileSystem.cpp
src/libs/ChaNFS/FATFileSystem.h
src/libs/ChaNFSSD/SDFileSystem.cpp
src/libs/ChaNFSSD/SDFileSystem.h
src/libs/Config.cpp
src/libs/Config.h
src/libs/ConfigCache.h
src/libs/ConfigSource.h
src/libs/ConfigSources/FileConfigSource.h
src/libs/ConfigValue.h
src/libs/Digipot.h
src/libs/Kernel.cpp
src/libs/Kernel.h
src/libs/LPC17xx/sLPC17xx.h
src/libs/LPC17xx/score_cm3.h
src/libs/Module.cpp
src/libs/Module.h
src/libs/Pin.h
src/libs/RingBuffer.h
src/libs/SlowTicker.cpp
src/libs/SlowTicker.h
src/libs/StepTicker.h
src/libs/StreamOutput.h
src/libs/USBCDCMSC/USBCDCMSC.cpp
src/libs/USBCDCMSC/USBCDCMSC.h
src/libs/USBDevice/USBAudio/USBAudio.cpp
src/libs/USBDevice/USBAudio/USBAudio.h
src/libs/USBDevice/USBAudio/USBAudio_Types.h
src/libs/USBDevice/USBDevice/USBBusInterface.h
src/libs/USBDevice/USBDevice/USBBusInterface_LPC11U.cpp
src/libs/USBDevice/USBDevice/USBBusInterface_LPC17_LPC23.cpp
src/libs/USBDevice/USBDevice/USBDescriptor.h
src/libs/USBDevice/USBDevice/USBDevice.cpp
src/libs/USBDevice/USBDevice/USBDevice.h
src/libs/USBDevice/USBDevice/USBDevice_Types.h
src/libs/USBDevice/USBDevice/USBEndpoints.h
src/libs/USBDevice/USBDevice/USBEndpoints_LPC11U.h
src/libs/USBDevice/USBDevice/USBEndpoints_LPC17_LPC23.h
src/libs/USBDevice/USBHID/USBHID.cpp
src/libs/USBDevice/USBHID/USBHID.h
src/libs/USBDevice/USBHID/USBHID_Types.h
src/libs/USBDevice/USBHID/USBKeyboard.cpp
src/libs/USBDevice/USBHID/USBKeyboard.h
src/libs/USBDevice/USBHID/USBMouse.cpp
src/libs/USBDevice/USBHID/USBMouse.h
src/libs/USBDevice/USBHID/USBMouseKeyboard.cpp
src/libs/USBDevice/USBHID/USBMouseKeyboard.h
src/libs/USBDevice/USBMIDI/MIDIMessage.h
src/libs/USBDevice/USBMIDI/USBMIDI.cpp
src/libs/USBDevice/USBMIDI/USBMIDI.h
src/libs/USBDevice/USBMSD/USBMSD.cpp
src/libs/USBDevice/USBMSD/USBMSD.h
src/libs/USBDevice/USBSERIAL/USBCDC.cpp
src/libs/USBDevice/USBSERIAL/USBCDC.h
src/libs/USBDevice/USBSERIAL/USBSerial.cpp
src/libs/USBDevice/USBSERIAL/USBSerial.h
src/libs/nuts_bolts.h
src/libs/utils.cpp
src/main.cpp
src/modules/communication/GcodeDispatch.h
src/modules/communication/SerialConsole.cpp
src/modules/communication/SerialConsole.h
src/modules/communication/utils/Gcode.cpp
src/modules/communication/utils/Gcode.h
src/modules/robot/Block.h
src/modules/robot/Planner.cpp
src/modules/robot/Planner.h
src/modules/robot/Player.cpp
src/modules/robot/Player.h
src/modules/robot/Robot.cpp
src/modules/robot/Robot.h
src/modules/robot/Stepper.h
src/modules/robot/arm_solutions/BaseSolution.cpp
src/modules/robot/arm_solutions/BaseSolution.h
src/modules/robot/arm_solutions/CartesianSolution.cpp
src/modules/robot/arm_solutions/CartesianSolution.h
src/modules/tools/endstops/Endstops.cpp
src/modules/tools/endstops/Endstops.h
src/modules/tools/switch/Switch.cpp
src/modules/tools/switch/Switch.h
src/modules/tools/switch/SwitchPool.cpp
src/modules/tools/switch/SwitchPool.h
src/modules/tools/temperaturecontrol/TemperatureControl.cpp
src/modules/tools/temperaturecontrol/TemperatureControl.h
src/modules/tools/temperaturecontrol/TemperatureControlPool.cpp
src/modules/tools/temperaturecontrol/TemperatureControlPool.h
src/modules/utils/configurator/Configurator.cpp
src/modules/utils/configurator/Configurator.h
src/modules/utils/currentcontrol/CurrentControl.cpp
src/modules/utils/currentcontrol/CurrentControl.h
src/modules/utils/pausebutton/PauseButton.cpp
src/modules/utils/pausebutton/PauseButton.h
src/modules/utils/simpleshell/SimpleShell.h

index 1e2ca13..a6fc701 100644 (file)
-/* mbed Library - ADC\r
- * Copyright (c) 2010, sblandford\r
- * released under MIT license http://mbed.org/licence/mit\r
- */\r
-#include "mbed.h"\r
-#include "adc.h"\r
-\r
-\r
-ADC *ADC::instance;\r
-\r
-ADC::ADC(int sample_rate, int cclk_div)\r
-    {\r
-\r
-    int i, adc_clk_freq, pclk, clock_div, max_div=1;\r
-\r
-    //Work out CCLK\r
-    adc_clk_freq=CLKS_PER_SAMPLE*sample_rate;\r
-    int m = (LPC_SC->PLL0CFG & 0xFFFF) + 1;\r
-    int n = (LPC_SC->PLL0CFG >> 16) + 1;\r
-    int cclkdiv = LPC_SC->CCLKCFG + 1;\r
-    int Fcco = (2 * m * XTAL_FREQ) / n;\r
-    int cclk = Fcco / cclkdiv;\r
-\r
-    //Power up the ADC        \r
-    LPC_SC->PCONP |= (1 << 12);\r
-    //Set clock at cclk / 1.\r
-    LPC_SC->PCLKSEL0 &= ~(0x3 << 24);    \r
-    switch (cclk_div) {\r
-        case 1:\r
-            LPC_SC->PCLKSEL0 |= 0x1 << 24;\r
-            break;\r
-        case 2:\r
-            LPC_SC->PCLKSEL0 |= 0x2 << 24;\r
-            break;\r
-        case 4:\r
-            LPC_SC->PCLKSEL0 |= 0x0 << 24;\r
-            break;\r
-        case 8:\r
-            LPC_SC->PCLKSEL0 |= 0x3 << 24;\r
-            break;\r
-        default:\r
-            printf("Warning: ADC CCLK clock divider must be 1, 2, 4 or 8. %u supplied.\n",\r
-                cclk_div);\r
-            printf("Defaulting to 1.\n");\r
-            LPC_SC->PCLKSEL0 |= 0x1 << 24;\r
-            break;\r
-    }\r
-    pclk = cclk / cclk_div;\r
-    clock_div=pclk / adc_clk_freq;\r
-\r
-    if (clock_div > 0xFF) {\r
-        //printf("Warning: Clock division is %u which is above 255 limit. Re-Setting at limit.\n",\r
-        //    clock_div);\r
-        clock_div=0xFF;\r
-    }\r
-    if (clock_div == 0) {\r
-        printf("Warning: Clock division is 0. Re-Setting to 1.\n");\r
-        clock_div=1;\r
-    }\r
-\r
-    _adc_clk_freq=pclk / clock_div;\r
-    if (_adc_clk_freq > MAX_ADC_CLOCK) {\r
-        printf("Warning: Actual ADC sample rate of %u which is above %u limit\n",\r
-            _adc_clk_freq / CLKS_PER_SAMPLE, MAX_ADC_CLOCK / CLKS_PER_SAMPLE);\r
-        while ((pclk / max_div) > MAX_ADC_CLOCK) max_div++;\r
-        printf("Maximum recommended sample rate is %u\n", (pclk / max_div) / CLKS_PER_SAMPLE);\r
-    }\r
-\r
-    LPC_ADC->ADCR =\r
-        ((clock_div - 1 ) << 8 ) |    //Clkdiv\r
-        ( 1 << 21 );                  //A/D operational\r
-\r
-    //Default no channels enabled\r
-    LPC_ADC->ADCR &= ~0xFF;\r
-    //Default NULL global custom isr\r
-    _adc_g_isr = NULL;\r
-    //Initialize arrays\r
-    for (i=7; i>=0; i--) {\r
-        _adc_data[i] = 0;\r
-        _adc_isr[i] = NULL;\r
-    }\r
-\r
-\r
-    //* Attach IRQ\r
-    instance = this;\r
-    NVIC_SetVector(ADC_IRQn, (uint32_t)&_adcisr);\r
-\r
-    //Disable global interrupt\r
-    LPC_ADC->ADINTEN &= ~0x100;\r
-\r
-};\r
-\r
-void ADC::_adcisr(void)\r
-{\r
-    instance->adcisr();\r
-}\r
-\r
-\r
-void ADC::adcisr(void)  \r
-{\r
-    uint32_t stat;\r
-    int chan;\r
-\r
-    // Read status\r
-    stat = LPC_ADC->ADSTAT;\r
-    //Scan channels for over-run or done and update array\r
-    if (stat & 0x0101) _adc_data[0] = LPC_ADC->ADDR0;\r
-    if (stat & 0x0202) _adc_data[1] = LPC_ADC->ADDR1;\r
-    if (stat & 0x0404) _adc_data[2] = LPC_ADC->ADDR2;\r
-    if (stat & 0x0808) _adc_data[3] = LPC_ADC->ADDR3;\r
-    if (stat & 0x1010) _adc_data[4] = LPC_ADC->ADDR4;\r
-    if (stat & 0x2020) _adc_data[5] = LPC_ADC->ADDR5;\r
-    if (stat & 0x4040) _adc_data[6] = LPC_ADC->ADDR6;\r
-    if (stat & 0x8080) _adc_data[7] = LPC_ADC->ADDR7;\r
-\r
-    // Channel that triggered interrupt\r
-    chan = (LPC_ADC->ADGDR >> 24) & 0x07;\r
-    //User defined interrupt handlers\r
-    if (_adc_isr[chan] != NULL)\r
-        _adc_isr[chan](_adc_data[chan]);\r
-    if (_adc_g_isr != NULL)\r
-        _adc_g_isr(chan, _adc_data[chan]); \r
-    return;\r
-}\r
-\r
-int ADC::_pin_to_channel(PinName pin) {\r
-    int chan;\r
-    switch (pin) {\r
-        case p15://=p0.23 of LPC1768\r
-        default:\r
-            chan=0;\r
-            break;\r
-        case p16://=p0.24 of LPC1768\r
-            chan=1;\r
-            break;\r
-        case p17://=p0.25 of LPC1768\r
-            chan=2;\r
-            break;\r
-        case p18://=p0.26 of LPC1768\r
-            chan=3;\r
-            break;\r
-        case p19://=p1.30 of LPC1768\r
-            chan=4;\r
-            break;\r
-        case p20://=p1.31 of LPC1768\r
-            chan=5;\r
-            break;\r
-    }\r
-    return(chan);\r
-}\r
-\r
-PinName ADC::channel_to_pin(int chan) {\r
-    const PinName pin[8]={p15, p16, p17, p18, p19, p20, p15, p15};\r
+/* mbed Library - ADC
+ * Copyright (c) 2010, sblandford
+ * released under MIT license http://mbed.org/licence/mit
+ */
+#include "mbed.h"
+#include "adc.h"
+\r
+\r
+ADC *ADC::instance;
+\r
+ADC::ADC(int sample_rate, int cclk_div)
+    {
+\r
+    int i, adc_clk_freq, pclk, clock_div, max_div=1;
+\r
+    //Work out CCLK
+    adc_clk_freq=CLKS_PER_SAMPLE*sample_rate;
+    int m = (LPC_SC->PLL0CFG & 0xFFFF) + 1;
+    int n = (LPC_SC->PLL0CFG >> 16) + 1;
+    int cclkdiv = LPC_SC->CCLKCFG + 1;
+    int Fcco = (2 * m * XTAL_FREQ) / n;
+    int cclk = Fcco / cclkdiv;
+\r
+    //Power up the ADC
+    LPC_SC->PCONP |= (1 << 12);
+    //Set clock at cclk / 1.
+    LPC_SC->PCLKSEL0 &= ~(0x3 << 24);
+    switch (cclk_div) {
+        case 1:
+            LPC_SC->PCLKSEL0 |= 0x1 << 24;
+            break;
+        case 2:
+            LPC_SC->PCLKSEL0 |= 0x2 << 24;
+            break;
+        case 4:
+            LPC_SC->PCLKSEL0 |= 0x0 << 24;
+            break;
+        case 8:
+            LPC_SC->PCLKSEL0 |= 0x3 << 24;
+            break;
+        default:
+            printf("Warning: ADC CCLK clock divider must be 1, 2, 4 or 8. %u supplied.\n",
+                cclk_div);
+            printf("Defaulting to 1.\n");
+            LPC_SC->PCLKSEL0 |= 0x1 << 24;
+            break;
+    }
+    pclk = cclk / cclk_div;
+    clock_div=pclk / adc_clk_freq;
+\r
+    if (clock_div > 0xFF) {
+        //printf("Warning: Clock division is %u which is above 255 limit. Re-Setting at limit.\n",
+        //    clock_div);
+        clock_div=0xFF;
+    }
+    if (clock_div == 0) {
+        printf("Warning: Clock division is 0. Re-Setting to 1.\n");
+        clock_div=1;
+    }
+\r
+    _adc_clk_freq=pclk / clock_div;
+    if (_adc_clk_freq > MAX_ADC_CLOCK) {
+        printf("Warning: Actual ADC sample rate of %u which is above %u limit\n",
+            _adc_clk_freq / CLKS_PER_SAMPLE, MAX_ADC_CLOCK / CLKS_PER_SAMPLE);
+        while ((pclk / max_div) > MAX_ADC_CLOCK) max_div++;
+        printf("Maximum recommended sample rate is %u\n", (pclk / max_div) / CLKS_PER_SAMPLE);
+    }
+\r
+    LPC_ADC->ADCR =
+        ((clock_div - 1 ) << 8 ) |    //Clkdiv
+        ( 1 << 21 );                  //A/D operational
+\r
+    //Default no channels enabled
+    LPC_ADC->ADCR &= ~0xFF;
+    //Default NULL global custom isr
+    _adc_g_isr = NULL;
+    //Initialize arrays
+    for (i=7; i>=0; i--) {
+        _adc_data[i] = 0;
+        _adc_isr[i] = NULL;
+    }
+\r
+\r
+    //* Attach IRQ
+    instance = this;
+    NVIC_SetVector(ADC_IRQn, (uint32_t)&_adcisr);
+\r
+    //Disable global interrupt
+    LPC_ADC->ADINTEN &= ~0x100;
+\r
+};
+\r
+void ADC::_adcisr(void)
+{
+    instance->adcisr();
+}
+\r
+\r
+void ADC::adcisr(void)
+{
+    uint32_t stat;
+    int chan;
+\r
+    // Read status
+    stat = LPC_ADC->ADSTAT;
+    //Scan channels for over-run or done and update array
+    if (stat & 0x0101) _adc_data[0] = LPC_ADC->ADDR0;
+    if (stat & 0x0202) _adc_data[1] = LPC_ADC->ADDR1;
+    if (stat & 0x0404) _adc_data[2] = LPC_ADC->ADDR2;
+    if (stat & 0x0808) _adc_data[3] = LPC_ADC->ADDR3;
+    if (stat & 0x1010) _adc_data[4] = LPC_ADC->ADDR4;
+    if (stat & 0x2020) _adc_data[5] = LPC_ADC->ADDR5;
+    if (stat & 0x4040) _adc_data[6] = LPC_ADC->ADDR6;
+    if (stat & 0x8080) _adc_data[7] = LPC_ADC->ADDR7;
+\r
+    // Channel that triggered interrupt
+    chan = (LPC_ADC->ADGDR >> 24) & 0x07;
+    //User defined interrupt handlers
+    if (_adc_isr[chan] != NULL)
+        _adc_isr[chan](_adc_data[chan]);
+    if (_adc_g_isr != NULL)
+        _adc_g_isr(chan, _adc_data[chan]);
+    return;
+}
+\r
+int ADC::_pin_to_channel(PinName pin) {
+    int chan;
+    switch (pin) {
+        case p15://=p0.23 of LPC1768
+        default:
+            chan=0;
+            break;
+        case p16://=p0.24 of LPC1768
+            chan=1;
+            break;
+        case p17://=p0.25 of LPC1768
+            chan=2;
+            break;
+        case p18://=p0.26 of LPC1768
+            chan=3;
+            break;
+        case p19://=p1.30 of LPC1768
+            chan=4;
+            break;
+        case p20://=p1.31 of LPC1768
+            chan=5;
+            break;
+    }
+    return(chan);
+}
+\r
+PinName ADC::channel_to_pin(int chan) {
+    const PinName pin[8]={p15, p16, p17, p18, p19, p20, p15, p15};
     \r
-    if ((chan < 0) || (chan > 5))\r
-        fprintf(stderr, "ADC channel %u is outside range available to MBED pins.\n", chan);\r
-    return(pin[chan & 0x07]);\r
-} \r
+    if ((chan < 0) || (chan > 5))
+        fprintf(stderr, "ADC channel %u is outside range available to MBED pins.\n", chan);
+    return(pin[chan & 0x07]);
+}
 \r
 \r
-int ADC::channel_to_pin_number(int chan) {\r
-    const int pin[8]={15, 16, 17, 18, 19, 20, 0, 0};\r
+int ADC::channel_to_pin_number(int chan) {
+    const int pin[8]={15, 16, 17, 18, 19, 20, 0, 0};
     \r
-    if ((chan < 0) || (chan > 5))\r
-        fprintf(stderr, "ADC channel %u is outside range available to MBED pins.\n", chan);\r
-    return(pin[chan & 0x07]);\r
-} \r
-\r
-\r
-uint32_t ADC::_data_of_pin(PinName pin) {\r
-    //If in burst mode and at least one interrupt enabled then\r
-    //take all values from _adc_data\r
-    if (burst() && (LPC_ADC->ADINTEN & 0x3F)) {\r
-        return(_adc_data[_pin_to_channel(pin)]);\r
-    } else {\r
-        //Return current register value or last value from interrupt\r
-        switch (pin) {\r
-            case p15://=p0.23 of LPC1768\r
-            default:\r
-                return(LPC_ADC->ADINTEN & 0x01?_adc_data[0]:LPC_ADC->ADDR0);\r
-            case p16://=p0.24 of LPC1768\r
-                return(LPC_ADC->ADINTEN & 0x02?_adc_data[1]:LPC_ADC->ADDR1);\r
-            case p17://=p0.25 of LPC1768\r
-                return(LPC_ADC->ADINTEN & 0x04?_adc_data[2]:LPC_ADC->ADDR2);\r
-            case p18://=p0.26 of LPC1768:\r
-                return(LPC_ADC->ADINTEN & 0x08?_adc_data[3]:LPC_ADC->ADDR3);\r
-            case p19://=p1.30 of LPC1768\r
-                return(LPC_ADC->ADINTEN & 0x10?_adc_data[4]:LPC_ADC->ADDR4);\r
-            case p20://=p1.31 of LPC1768\r
-                return(LPC_ADC->ADINTEN & 0x20?_adc_data[5]:LPC_ADC->ADDR5);\r
-        }\r
-    }\r
-}\r
-\r
-//Enable or disable an ADC pin\r
-void ADC::setup(PinName pin, int state) {\r
-    int chan;    \r
-    chan=_pin_to_channel(pin);\r
-    if ((state & 1) == 1) {\r
-        switch(pin) {\r
-            case p15://=p0.23 of LPC1768\r
-            default:\r
-                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 14);\r
-                LPC_PINCON->PINSEL1 |= (unsigned int)0x1 << 14;\r
-                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 14);\r
-                LPC_PINCON->PINMODE1 |= (unsigned int)0x2 << 14;\r
-                break;\r
-            case p16://=p0.24 of LPC1768\r
-                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 16);\r
-                LPC_PINCON->PINSEL1 |= (unsigned int)0x1 << 16;\r
-                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 16);\r
-                LPC_PINCON->PINMODE1 |= (unsigned int)0x2 << 16;\r
-                break;\r
-            case p17://=p0.25 of LPC1768\r
-                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 18);\r
-                LPC_PINCON->PINSEL1 |= (unsigned int)0x1 << 18;\r
-                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 18);\r
-                LPC_PINCON->PINMODE1 |= (unsigned int)0x2 << 18;\r
-                break;\r
-            case p18://=p0.26 of LPC1768:\r
-                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 20);\r
-                LPC_PINCON->PINSEL1 |= (unsigned int)0x1 << 20;\r
-                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 20);\r
-                LPC_PINCON->PINMODE1 |= (unsigned int)0x2 << 20;\r
-                break;\r
-            case p19://=p1.30 of LPC1768\r
-                LPC_PINCON->PINSEL3 &= ~((unsigned int)0x3 << 28);\r
-                LPC_PINCON->PINSEL3 |= (unsigned int)0x3 << 28;\r
-                LPC_PINCON->PINMODE3 &= ~((unsigned int)0x3 << 28);\r
-                LPC_PINCON->PINMODE3 |= (unsigned int)0x2 << 28;\r
-                break;\r
-            case p20://=p1.31 of LPC1768\r
-                LPC_PINCON->PINSEL3 &= ~((unsigned int)0x3 << 30);\r
-                LPC_PINCON->PINSEL3 |= (unsigned int)0x3 << 30;\r
-                LPC_PINCON->PINMODE3 &= ~((unsigned int)0x3 << 30);\r
-                LPC_PINCON->PINMODE3 |= (unsigned int)0x2 << 30;\r
-               break;\r
-        }\r
-        //Only one channel can be selected at a time if not in burst mode\r
-        if (!burst()) LPC_ADC->ADCR &= ~0xFF;\r
-        //Select channel\r
-        LPC_ADC->ADCR |= (1 << chan);\r
-    }\r
-    else {\r
-        switch(pin) {\r
-            case p15://=p0.23 of LPC1768\r
-            default:\r
-                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 14);\r
-                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 14);\r
-                break;\r
-            case p16://=p0.24 of LPC1768\r
-                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 16);\r
-                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 16);\r
-                break;\r
-            case p17://=p0.25 of LPC1768\r
-                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 18);\r
-                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 18);\r
-                break;\r
-            case p18://=p0.26 of LPC1768:\r
-                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 20);\r
-                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 20);\r
-                break;\r
-            case p19://=p1.30 of LPC1768\r
-                LPC_PINCON->PINSEL3 &= ~((unsigned int)0x3 << 28);\r
-                LPC_PINCON->PINMODE3 &= ~((unsigned int)0x3 << 28);\r
-                break;\r
-            case p20://=p1.31 of LPC1768\r
-                LPC_PINCON->PINSEL3 &= ~((unsigned int)0x3 << 30);\r
-                LPC_PINCON->PINMODE3 &= ~((unsigned int)0x3 << 30);\r
-                break;\r
-        }\r
-        LPC_ADC->ADCR &= ~(1 << chan);\r
-    }\r
-}\r
-//Return channel enabled/disabled state\r
-int ADC::setup(PinName pin) {\r
-    int chan;\r
+    if ((chan < 0) || (chan > 5))
+        fprintf(stderr, "ADC channel %u is outside range available to MBED pins.\n", chan);
+    return(pin[chan & 0x07]);
+}
+\r
+\r
+uint32_t ADC::_data_of_pin(PinName pin) {
+    //If in burst mode and at least one interrupt enabled then
+    //take all values from _adc_data
+    if (burst() && (LPC_ADC->ADINTEN & 0x3F)) {
+        return(_adc_data[_pin_to_channel(pin)]);
+    } else {
+        //Return current register value or last value from interrupt
+        switch (pin) {
+            case p15://=p0.23 of LPC1768
+            default:
+                return(LPC_ADC->ADINTEN & 0x01?_adc_data[0]:LPC_ADC->ADDR0);
+            case p16://=p0.24 of LPC1768
+                return(LPC_ADC->ADINTEN & 0x02?_adc_data[1]:LPC_ADC->ADDR1);
+            case p17://=p0.25 of LPC1768
+                return(LPC_ADC->ADINTEN & 0x04?_adc_data[2]:LPC_ADC->ADDR2);
+            case p18://=p0.26 of LPC1768:
+                return(LPC_ADC->ADINTEN & 0x08?_adc_data[3]:LPC_ADC->ADDR3);
+            case p19://=p1.30 of LPC1768
+                return(LPC_ADC->ADINTEN & 0x10?_adc_data[4]:LPC_ADC->ADDR4);
+            case p20://=p1.31 of LPC1768
+                return(LPC_ADC->ADINTEN & 0x20?_adc_data[5]:LPC_ADC->ADDR5);
+        }
+    }
+}
+\r
+//Enable or disable an ADC pin
+void ADC::setup(PinName pin, int state) {
+    int chan;
+    chan=_pin_to_channel(pin);
+    if ((state & 1) == 1) {
+        switch(pin) {
+            case p15://=p0.23 of LPC1768
+            default:
+                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 14);
+                LPC_PINCON->PINSEL1 |= (unsigned int)0x1 << 14;
+                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 14);
+                LPC_PINCON->PINMODE1 |= (unsigned int)0x2 << 14;
+                break;
+            case p16://=p0.24 of LPC1768
+                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 16);
+                LPC_PINCON->PINSEL1 |= (unsigned int)0x1 << 16;
+                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 16);
+                LPC_PINCON->PINMODE1 |= (unsigned int)0x2 << 16;
+                break;
+            case p17://=p0.25 of LPC1768
+                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 18);
+                LPC_PINCON->PINSEL1 |= (unsigned int)0x1 << 18;
+                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 18);
+                LPC_PINCON->PINMODE1 |= (unsigned int)0x2 << 18;
+                break;
+            case p18://=p0.26 of LPC1768:
+                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 20);
+                LPC_PINCON->PINSEL1 |= (unsigned int)0x1 << 20;
+                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 20);
+                LPC_PINCON->PINMODE1 |= (unsigned int)0x2 << 20;
+                break;
+            case p19://=p1.30 of LPC1768
+                LPC_PINCON->PINSEL3 &= ~((unsigned int)0x3 << 28);
+                LPC_PINCON->PINSEL3 |= (unsigned int)0x3 << 28;
+                LPC_PINCON->PINMODE3 &= ~((unsigned int)0x3 << 28);
+                LPC_PINCON->PINMODE3 |= (unsigned int)0x2 << 28;
+                break;
+            case p20://=p1.31 of LPC1768
+                LPC_PINCON->PINSEL3 &= ~((unsigned int)0x3 << 30);
+                LPC_PINCON->PINSEL3 |= (unsigned int)0x3 << 30;
+                LPC_PINCON->PINMODE3 &= ~((unsigned int)0x3 << 30);
+                LPC_PINCON->PINMODE3 |= (unsigned int)0x2 << 30;
+               break;
+        }
+        //Only one channel can be selected at a time if not in burst mode
+        if (!burst()) LPC_ADC->ADCR &= ~0xFF;
+        //Select channel
+        LPC_ADC->ADCR |= (1 << chan);
+    }
+    else {
+        switch(pin) {
+            case p15://=p0.23 of LPC1768
+            default:
+                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 14);
+                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 14);
+                break;
+            case p16://=p0.24 of LPC1768
+                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 16);
+                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 16);
+                break;
+            case p17://=p0.25 of LPC1768
+                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 18);
+                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 18);
+                break;
+            case p18://=p0.26 of LPC1768:
+                LPC_PINCON->PINSEL1 &= ~((unsigned int)0x3 << 20);
+                LPC_PINCON->PINMODE1 &= ~((unsigned int)0x3 << 20);
+                break;
+            case p19://=p1.30 of LPC1768
+                LPC_PINCON->PINSEL3 &= ~((unsigned int)0x3 << 28);
+                LPC_PINCON->PINMODE3 &= ~((unsigned int)0x3 << 28);
+                break;
+            case p20://=p1.31 of LPC1768
+                LPC_PINCON->PINSEL3 &= ~((unsigned int)0x3 << 30);
+                LPC_PINCON->PINMODE3 &= ~((unsigned int)0x3 << 30);
+                break;
+        }
+        LPC_ADC->ADCR &= ~(1 << chan);
+    }
+}
+//Return channel enabled/disabled state
+int ADC::setup(PinName pin) {
+    int chan;
     \r
-    chan = _pin_to_channel(pin);\r
-    return((LPC_ADC->ADCR & (1 << chan)) >> chan);\r
-}\r
+    chan = _pin_to_channel(pin);
+    return((LPC_ADC->ADCR & (1 << chan)) >> chan);
+}
 \r
-//Select channel already setup\r
-void ADC::select(PinName pin) {\r
-    int chan;\r
+//Select channel already setup
+void ADC::select(PinName pin) {
+    int chan;
     \r
-    //Only one channel can be selected at a time if not in burst mode\r
-    if (!burst()) LPC_ADC->ADCR &= ~0xFF;\r
-    //Select channel\r
-    chan = _pin_to_channel(pin);\r
-    LPC_ADC->ADCR |= (1 << chan);\r
-}\r
-\r
-//Enable or disable burst mode\r
-void ADC::burst(int state) {\r
-    if ((state & 1) == 1) {\r
-        if (startmode(0) != 0)\r
-            fprintf(stderr, "Warning. startmode is %u. Must be 0 for burst mode.\n", startmode(0));\r
-        LPC_ADC->ADCR |= (1 << 16);\r
-    }\r
-    else \r
-        LPC_ADC->ADCR &= ~(1 << 16);\r
-}\r
-//Return burst mode state\r
-int  ADC::burst(void) {\r
-    return((LPC_ADC->ADCR & (1 << 16)) >> 16);\r
-}\r
-\r
-//Set startmode and edge\r
-void ADC::startmode(int mode, int edge) {\r
-    int lpc_adc_temp;\r
+    //Only one channel can be selected at a time if not in burst mode
+    if (!burst()) LPC_ADC->ADCR &= ~0xFF;
+    //Select channel
+    chan = _pin_to_channel(pin);
+    LPC_ADC->ADCR |= (1 << chan);
+}
+\r
+//Enable or disable burst mode
+void ADC::burst(int state) {
+    if ((state & 1) == 1) {
+        if (startmode(0) != 0)
+            fprintf(stderr, "Warning. startmode is %u. Must be 0 for burst mode.\n", startmode(0));
+        LPC_ADC->ADCR |= (1 << 16);
+    }
+    else
+        LPC_ADC->ADCR &= ~(1 << 16);
+}
+//Return burst mode state
+int  ADC::burst(void) {
+    return((LPC_ADC->ADCR & (1 << 16)) >> 16);
+}
+\r
+//Set startmode and edge
+void ADC::startmode(int mode, int edge) {
+    int lpc_adc_temp;
     \r
-    //Reset start mode and edge bit, \r
-    lpc_adc_temp = LPC_ADC->ADCR & ~(0x0F << 24);\r
-    //Write with new values\r
-    lpc_adc_temp |= ((mode & 7) << 24) | ((edge & 1) << 27);\r
-    LPC_ADC->ADCR = lpc_adc_temp;\r
-}\r
-\r
-//Return startmode state according to mode_edge=0: mode and mode_edge=1: edge\r
-int ADC::startmode(int mode_edge){\r
-    switch (mode_edge) {\r
-        case 0:\r
-        default:\r
-            return((LPC_ADC->ADCR >> 24) & 0x07);\r
-        case 1:\r
-            return((LPC_ADC->ADCR >> 27) & 0x01);\r
-    }\r
-}\r
-\r
-//Start ADC conversion\r
-void ADC::start(void) {\r
-    startmode(1,0);\r
-}\r
-\r
-\r
-//Set interrupt enable/disable for pin to state\r
-void ADC::interrupt_state(PinName pin, int state) {\r
-    int chan;\r
+    //Reset start mode and edge bit,
+    lpc_adc_temp = LPC_ADC->ADCR & ~(0x0F << 24);
+    //Write with new values
+    lpc_adc_temp |= ((mode & 7) << 24) | ((edge & 1) << 27);
+    LPC_ADC->ADCR = lpc_adc_temp;
+}
+\r
+//Return startmode state according to mode_edge=0: mode and mode_edge=1: edge
+int ADC::startmode(int mode_edge){
+    switch (mode_edge) {
+        case 0:
+        default:
+            return((LPC_ADC->ADCR >> 24) & 0x07);
+        case 1:
+            return((LPC_ADC->ADCR >> 27) & 0x01);
+    }
+}
+\r
+//Start ADC conversion
+void ADC::start(void) {
+    startmode(1,0);
+}
+\r
+\r
+//Set interrupt enable/disable for pin to state
+void ADC::interrupt_state(PinName pin, int state) {
+    int chan;
     \r
-    chan = _pin_to_channel(pin);\r
-    if (state == 1) {\r
-        LPC_ADC->ADINTEN &= ~0x100;\r
-        LPC_ADC->ADINTEN |= 1 << chan;\r
-        /* Enable the ADC Interrupt */\r
-        NVIC_EnableIRQ(ADC_IRQn);\r
-    } else {\r
-        LPC_ADC->ADINTEN &= ~( 1 << chan );\r
-        //Disable interrrupt if no active pins left\r
-        if ((LPC_ADC->ADINTEN & 0xFF) == 0)\r
-            NVIC_DisableIRQ(ADC_IRQn);\r
-    }\r
-}\r
-\r
-//Return enable/disable state of interrupt for pin\r
-int ADC::interrupt_state(PinName pin) {\r
-    int chan;\r
+    chan = _pin_to_channel(pin);
+    if (state == 1) {
+        LPC_ADC->ADINTEN &= ~0x100;
+        LPC_ADC->ADINTEN |= 1 << chan;
+        /* Enable the ADC Interrupt */
+        NVIC_EnableIRQ(ADC_IRQn);
+    } else {
+        LPC_ADC->ADINTEN &= ~( 1 << chan );
+        //Disable interrrupt if no active pins left
+        if ((LPC_ADC->ADINTEN & 0xFF) == 0)
+            NVIC_DisableIRQ(ADC_IRQn);
+    }
+}
+\r
+//Return enable/disable state of interrupt for pin
+int ADC::interrupt_state(PinName pin) {
+    int chan;
         \r
-    chan = _pin_to_channel(pin);\r
-    return((LPC_ADC->ADINTEN >> chan) & 0x01);\r
-}\r
+    chan = _pin_to_channel(pin);
+    return((LPC_ADC->ADINTEN >> chan) & 0x01);
+}
 \r
 \r
-//Attach custom interrupt handler replacing default\r
-void ADC::attach(void(*fptr)(void)) {\r
-    //* Attach IRQ\r
-    NVIC_SetVector(ADC_IRQn, (uint32_t)fptr);\r
-}\r
+//Attach custom interrupt handler replacing default
+void ADC::attach(void(*fptr)(void)) {
+    //* Attach IRQ
+    NVIC_SetVector(ADC_IRQn, (uint32_t)fptr);
+}
 \r
-//Restore default interrupt handler\r
-void ADC::detach(void) {\r
-    //* Attach IRQ\r
-    instance = this;\r
-    NVIC_SetVector(ADC_IRQn, (uint32_t)&_adcisr);\r
-}\r
+//Restore default interrupt handler
+void ADC::detach(void) {
+    //* Attach IRQ
+    instance = this;
+    NVIC_SetVector(ADC_IRQn, (uint32_t)&_adcisr);
+}
 \r
 \r
-//Append interrupt handler for pin to function isr\r
-void ADC::append(PinName pin, void(*fptr)(uint32_t value)) {\r
-    int chan;\r
+//Append interrupt handler for pin to function isr
+void ADC::append(PinName pin, void(*fptr)(uint32_t value)) {
+    int chan;
         \r
-    chan = _pin_to_channel(pin);\r
-    _adc_isr[chan] = fptr;\r
-}\r
+    chan = _pin_to_channel(pin);
+    _adc_isr[chan] = fptr;
+}
 \r
-//Append interrupt handler for pin to function isr\r
-void ADC::unappend(PinName pin) {\r
-    int chan;\r
+//Append interrupt handler for pin to function isr
+void ADC::unappend(PinName pin) {
+    int chan;
         \r
-    chan = _pin_to_channel(pin);\r
-    _adc_isr[chan] = NULL;\r
-}\r
-\r
-//Unappend global interrupt handler to function isr\r
-void ADC::append(void(*fptr)(int chan, uint32_t value)) {\r
-    _adc_g_isr = fptr;\r
-}\r
-\r
-//Detach global interrupt handler to function isr\r
-void ADC::unappend() {\r
-    _adc_g_isr = NULL;\r
-}\r
-\r
-//Set ADC offset\r
-void offset(int offset) {\r
-    LPC_ADC->ADTRM &= ~(0x07 << 4);\r
-    LPC_ADC->ADTRM |= (offset & 0x07) << 4;\r
-}\r
-\r
-//Return current ADC offset\r
-int offset(void) {\r
-    return((LPC_ADC->ADTRM >> 4) & 0x07);\r
-}\r
-\r
-//Return value of ADC on pin\r
-int ADC::read(PinName pin) {\r
-    //Reset DONE and OVERRUN flags of interrupt handled ADC data\r
-    _adc_data[_pin_to_channel(pin)] &= ~(((uint32_t)0x01 << 31) | ((uint32_t)0x01 << 30));\r
-    //Return value\r
-    return((_data_of_pin(pin) >> 4) & 0xFFF);\r
-}\r
-\r
-//Return DONE flag of ADC on pin\r
-int ADC::done(PinName pin) {\r
-    return((_data_of_pin(pin) >> 31) & 0x01);\r
-}\r
-\r
-//Return OVERRUN flag of ADC on pin\r
-int ADC::overrun(PinName pin) {\r
-    return((_data_of_pin(pin) >> 30) & 0x01);\r
-}\r
-\r
-int ADC::actual_adc_clock(void) {\r
-    return(_adc_clk_freq);\r
-}\r
-\r
-int ADC::actual_sample_rate(void) {\r
-    return(_adc_clk_freq / CLKS_PER_SAMPLE);\r
-}\r
+    chan = _pin_to_channel(pin);
+    _adc_isr[chan] = NULL;
+}
+\r
+//Unappend global interrupt handler to function isr
+void ADC::append(void(*fptr)(int chan, uint32_t value)) {
+    _adc_g_isr = fptr;
+}
+\r
+//Detach global interrupt handler to function isr
+void ADC::unappend() {
+    _adc_g_isr = NULL;
+}
+\r
+//Set ADC offset
+void offset(int offset) {
+    LPC_ADC->ADTRM &= ~(0x07 << 4);
+    LPC_ADC->ADTRM |= (offset & 0x07) << 4;
+}
+\r
+//Return current ADC offset
+int offset(void) {
+    return((LPC_ADC->ADTRM >> 4) & 0x07);
+}
+\r
+//Return value of ADC on pin
+int ADC::read(PinName pin) {
+    //Reset DONE and OVERRUN flags of interrupt handled ADC data
+    _adc_data[_pin_to_channel(pin)] &= ~(((uint32_t)0x01 << 31) | ((uint32_t)0x01 << 30));
+    //Return value
+    return((_data_of_pin(pin) >> 4) & 0xFFF);
+}
+\r
+//Return DONE flag of ADC on pin
+int ADC::done(PinName pin) {
+    return((_data_of_pin(pin) >> 31) & 0x01);
+}
+\r
+//Return OVERRUN flag of ADC on pin
+int ADC::overrun(PinName pin) {
+    return((_data_of_pin(pin) >> 30) & 0x01);
+}
+\r
+int ADC::actual_adc_clock(void) {
+    return(_adc_clk_freq);
+}
+\r
+int ADC::actual_sample_rate(void) {
+    return(_adc_clk_freq / CLKS_PER_SAMPLE);
+}
index cd6e309..9ff7248 100644 (file)
-/* mbed Library - ADC\r
- * Copyright (c) 2010, sblandford\r
- * released under MIT license http://mbed.org/licence/mit\r
- */\r
+/* mbed Library - ADC
+ * Copyright (c) 2010, sblandford
+ * released under MIT license http://mbed.org/licence/mit
+ */
 \r
-#ifndef MBED_ADC_H\r
-#define MBED_ADC_H\r
+#ifndef MBED_ADC_H
+#define MBED_ADC_H
  \r
-#include "PinNames.h" // mbed.h lib\r
-#define XTAL_FREQ       12000000\r
-#define MAX_ADC_CLOCK   13000000\r
-#define CLKS_PER_SAMPLE 64\r
-\r
-class ADC {\r
-public:\r
-\r
-    //Initialize ADC with ADC maximum sample rate of\r
-    //sample_rate and system clock divider of cclk_div\r
-    //Maximum recommened sample rate is 184000\r
-    ADC(int sample_rate, int cclk_div);\r
-\r
-    //Enable/disable ADC on pin according to state\r
-    //and also select/de-select for next conversion\r
-    void setup(PinName pin, int state);\r
-\r
-    //Return enabled/disabled state of ADC on pin\r
-    int setup(PinName pin);\r
-\r
-    //Enable/disable burst mode according to state\r
-    void burst(int state);\r
-\r
-    //Select channel already setup\r
-    void select(PinName pin);\r
-\r
-    //Return burst mode enabled/disabled\r
-    int burst(void);\r
-\r
-    /*Set start condition and edge according to mode:\r
-    0 - No start (this value should be used when clearing PDN to 0).\r
-    1 - Start conversion now.\r
-    2 - Start conversion when the edge selected by bit 27 occurs on the P2.10 / EINT0 / NMI pin.\r
-    3 - Start conversion when the edge selected by bit 27 occurs on the P1.27 / CLKOUT /\r
-        USB_OVRCRn / CAP0.1 pin.\r
-    4 - Start conversion when the edge selected by bit 27 occurs on MAT0.1. Note that this does\r
-        not require that the MAT0.1 function appear on a device pin.\r
-    5 - Start conversion when the edge selected by bit 27 occurs on MAT0.3. Note that it is not\r
-        possible to cause the MAT0.3 function to appear on a device pin.\r
-    6 - Start conversion when the edge selected by bit 27 occurs on MAT1.0. Note that this does\r
-        not require that the MAT1.0 function appear on a device pin.\r
-    7 - Start conversion when the edge selected by bit 27 occurs on MAT1.1. Note that this does\r
-        not require that the MAT1.1 function appear on a device pin.\r
-    When mode >= 2, conversion is triggered by edge:\r
-    0 - Rising edge\r
-    1 - Falling edge\r
-    */\r
-    void startmode(int mode, int edge);\r
+#include "PinNames.h" // mbed.h lib
+#define XTAL_FREQ       12000000
+#define MAX_ADC_CLOCK   13000000
+#define CLKS_PER_SAMPLE 64
+\r
+class ADC {
+public:
+\r
+    //Initialize ADC with ADC maximum sample rate of
+    //sample_rate and system clock divider of cclk_div
+    //Maximum recommened sample rate is 184000
+    ADC(int sample_rate, int cclk_div);
+\r
+    //Enable/disable ADC on pin according to state
+    //and also select/de-select for next conversion
+    void setup(PinName pin, int state);
+\r
+    //Return enabled/disabled state of ADC on pin
+    int setup(PinName pin);
+\r
+    //Enable/disable burst mode according to state
+    void burst(int state);
+\r
+    //Select channel already setup
+    void select(PinName pin);
+\r
+    //Return burst mode enabled/disabled
+    int burst(void);
+\r
+    /*Set start condition and edge according to mode:
+    0 - No start (this value should be used when clearing PDN to 0).
+    1 - Start conversion now.
+    2 - Start conversion when the edge selected by bit 27 occurs on the P2.10 / EINT0 / NMI pin.
+    3 - Start conversion when the edge selected by bit 27 occurs on the P1.27 / CLKOUT /
+        USB_OVRCRn / CAP0.1 pin.
+    4 - Start conversion when the edge selected by bit 27 occurs on MAT0.1. Note that this does
+        not require that the MAT0.1 function appear on a device pin.
+    5 - Start conversion when the edge selected by bit 27 occurs on MAT0.3. Note that it is not
+        possible to cause the MAT0.3 function to appear on a device pin.
+    6 - Start conversion when the edge selected by bit 27 occurs on MAT1.0. Note that this does
+        not require that the MAT1.0 function appear on a device pin.
+    7 - Start conversion when the edge selected by bit 27 occurs on MAT1.1. Note that this does
+        not require that the MAT1.1 function appear on a device pin.
+    When mode >= 2, conversion is triggered by edge:
+    0 - Rising edge
+    1 - Falling edge
+    */
+    void startmode(int mode, int edge);
     \r
-    //Return startmode state according to mode_edge=0: mode and mode_edge=1: edge\r
-    int startmode(int mode_edge);\r
+    //Return startmode state according to mode_edge=0: mode and mode_edge=1: edge
+    int startmode(int mode_edge);
     \r
-    //Start ADC conversion\r
-    void start(void);\r
+    //Start ADC conversion
+    void start(void);
 \r
-    //Set interrupt enable/disable for pin to state\r
-    void interrupt_state(PinName pin, int state);\r
+    //Set interrupt enable/disable for pin to state
+    void interrupt_state(PinName pin, int state);
     \r
-    //Return enable/disable state of interrupt for pin\r
-    int interrupt_state(PinName pin);\r
+    //Return enable/disable state of interrupt for pin
+    int interrupt_state(PinName pin);
 \r
-    //Attach custom interrupt handler replacing default\r
-    void attach(void(*fptr)(void));\r
+    //Attach custom interrupt handler replacing default
+    void attach(void(*fptr)(void));
 \r
-    //Restore default interrupt handler\r
-    void detach(void);\r
+    //Restore default interrupt handler
+    void detach(void);
 \r
-    //Append custom interrupt handler for pin\r
-    void append(PinName pin, void(*fptr)(uint32_t value));\r
+    //Append custom interrupt handler for pin
+    void append(PinName pin, void(*fptr)(uint32_t value));
 \r
-    //Unappend custom interrupt handler for pin\r
-    void unappend(PinName pin);\r
+    //Unappend custom interrupt handler for pin
+    void unappend(PinName pin);
 \r
-    //Append custom global interrupt handler\r
-    void append(void(*fptr)(int chan, uint32_t value));\r
+    //Append custom global interrupt handler
+    void append(void(*fptr)(int chan, uint32_t value));
 \r
-    //Unappend custom global interrupt handler\r
-    void unappend(void);\r
+    //Unappend custom global interrupt handler
+    void unappend(void);
 \r
-    //Set ADC offset to a value 0-7\r
-    void offset(int offset);\r
+    //Set ADC offset to a value 0-7
+    void offset(int offset);
     \r
-    //Return current ADC offset\r
-    int offset(void);\r
+    //Return current ADC offset
+    int offset(void);
 \r
-    //Return value of ADC on pin\r
-    int read(PinName pin);\r
+    //Return value of ADC on pin
+    int read(PinName pin);
 \r
-    //Return DONE flag of ADC on pin\r
-    int done(PinName pin);\r
+    //Return DONE flag of ADC on pin
+    int done(PinName pin);
     \r
-    //Return OVERRUN flag of ADC on pin\r
-    int overrun(PinName pin);\r
+    //Return OVERRUN flag of ADC on pin
+    int overrun(PinName pin);
 \r
-    //Return actual ADC clock\r
-    int actual_adc_clock(void);\r
+    //Return actual ADC clock
+    int actual_adc_clock(void);
     \r
-    //Return actual maximum sample rate\r
-    int actual_sample_rate(void);\r
+    //Return actual maximum sample rate
+    int actual_sample_rate(void);
 \r
-    //Return pin ID of ADC channel\r
-    PinName channel_to_pin(int chan);\r
+    //Return pin ID of ADC channel
+    PinName channel_to_pin(int chan);
 \r
-    //Return pin number of ADC channel\r
-    int channel_to_pin_number(int chan);\r
+    //Return pin number of ADC channel
+    int channel_to_pin_number(int chan);
 \r
 \r
-private:\r
-    int _pin_to_channel(PinName pin);\r
-    uint32_t _data_of_pin(PinName pin);\r
+private:
+    int _pin_to_channel(PinName pin);
+    uint32_t _data_of_pin(PinName pin);
 \r
-    int _adc_clk_freq;\r
-    void adcisr(void);\r
-    static void _adcisr(void);\r
-    static ADC *instance;\r
+    int _adc_clk_freq;
+    void adcisr(void);
+    static void _adcisr(void);
+    static ADC *instance;
     \r
-    uint32_t _adc_data[8];\r
-    void(*_adc_isr[8])(uint32_t value);\r
-    void(*_adc_g_isr)(int chan, uint32_t value);\r
-    void(*_adc_m_isr)(void);\r
-};\r
+    uint32_t _adc_data[8];
+    void(*_adc_isr[8])(uint32_t value);
+    void(*_adc_g_isr)(int chan, uint32_t value);
+    void(*_adc_m_isr)(void);
+};
 \r
-#endif\r
+#endif
index fd7ca79..e3630d1 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 
index a371f49..40a8c99 100644 (file)
-/*-----------------------------------------------------------------------*/\r
-/* Low level disk I/O module skeleton for FatFs     (C)ChaN, 2007        */\r
-/*-----------------------------------------------------------------------*/\r
-/* This is a stub disk I/O module that acts as front end of the existing */\r
-/* disk I/O modules and attach it to FatFs module with common interface. */\r
-/*-----------------------------------------------------------------------*/\r
+/*-----------------------------------------------------------------------*/
+/* Low level disk I/O module skeleton for FatFs     (C)ChaN, 2007        */
+/*-----------------------------------------------------------------------*/
+/* This is a stub disk I/O module that acts as front end of the existing */
+/* disk I/O modules and attach it to FatFs module with common interface. */
+/*-----------------------------------------------------------------------*/
 \r
-#include "diskio.h"\r
-#include <stdio.h>\r
-#include <string.h>\r
-#include "FATFileSystem.h"\r
+#include "diskio.h"
+#include <stdio.h>
+#include <string.h>
+#include "FATFileSystem.h"
 \r
-#include "mbed.h"\r
+#include "mbed.h"
 \r
-DSTATUS disk_initialize (\r
-       BYTE drv                                /* Physical drive nmuber (0..) */\r
-) \r
-{\r
-       FFSDEBUG("disk_initialize on drv [%d]\n", drv);\r
-       return (DSTATUS)FATFileSystem::_ffs[drv]->disk_initialize();\r
-}\r
+DSTATUS disk_initialize (
+       BYTE drv                                /* Physical drive nmuber (0..) */
+)
+{
+       FFSDEBUG("disk_initialize on drv [%d]\n", drv);
+       return (DSTATUS)FATFileSystem::_ffs[drv]->disk_initialize();
+}
 \r
-DSTATUS disk_status (\r
-       BYTE drv                /* Physical drive nmuber (0..) */\r
-) \r
-{\r
-       FFSDEBUG("disk_status on drv [%d]\n", drv);\r
-       return (DSTATUS)FATFileSystem::_ffs[drv]->disk_status();\r
-}\r
+DSTATUS disk_status (
+       BYTE drv                /* Physical drive nmuber (0..) */
+)
+{
+       FFSDEBUG("disk_status on drv [%d]\n", drv);
+       return (DSTATUS)FATFileSystem::_ffs[drv]->disk_status();
+}
 \r
-DRESULT disk_read (\r
-       BYTE drv,               /* Physical drive nmuber (0..) */\r
-       BYTE *buff,             /* Data buffer to store read data */\r
-       DWORD sector,   /* Sector address (LBA) */\r
-       BYTE count              /* Number of sectors to read (1..255) */\r
-)\r
-{\r
-       FFSDEBUG("disk_read(sector %d, count %d) on drv [%d]\n", sector, count, drv);\r
-       for(unsigned int s=sector; s<sector+count; s++) {\r
-               FFSDEBUG(" disk_read(sector %d)\n", s);\r
-               int res = FATFileSystem::_ffs[drv]->disk_read((char*)buff, s);\r
-               if(res) {\r
-                       return RES_PARERR;\r
-               }\r
-               buff += 512;\r
-       }\r
-       return RES_OK;\r
-}\r
+DRESULT disk_read (
+       BYTE drv,               /* Physical drive nmuber (0..) */
+       BYTE *buff,             /* Data buffer to store read data */
+       DWORD sector,   /* Sector address (LBA) */
+       BYTE count              /* Number of sectors to read (1..255) */
+)
+{
+       FFSDEBUG("disk_read(sector %d, count %d) on drv [%d]\n", sector, count, drv);
+       for(unsigned int s=sector; s<sector+count; s++) {
+               FFSDEBUG(" disk_read(sector %d)\n", s);
+               int res = FATFileSystem::_ffs[drv]->disk_read((char*)buff, s);
+               if(res) {
+                       return RES_PARERR;
+               }
+               buff += 512;
+       }
+       return RES_OK;
+}
 \r
-#if _READONLY == 0\r
-DRESULT disk_write (\r
-       BYTE drv,                       /* Physical drive nmuber (0..) */\r
-       const BYTE *buff,       /* Data to be written */\r
-       DWORD sector,           /* Sector address (LBA) */\r
-       BYTE count                      /* Number of sectors to write (1..255) */\r
-)\r
-{\r
-       FFSDEBUG("disk_write(sector %d, count %d) on drv [%d]\n", sector, count, drv);\r
-       for(unsigned int s=sector; s<sector+count; s++) {\r
-               FFSDEBUG(" disk_write(sector %d)\n", s);\r
-               int res = FATFileSystem::_ffs[drv]->disk_write((char*)buff, sector);\r
-               if(res) {\r
-                       return RES_PARERR;\r
-               }\r
-               buff += 512;\r
-       }\r
-       return RES_OK;\r
-}\r
-#endif /* _READONLY */\r
+#if _READONLY == 0
+DRESULT disk_write (
+       BYTE drv,                       /* Physical drive nmuber (0..) */
+       const BYTE *buff,       /* Data to be written */
+       DWORD sector,           /* Sector address (LBA) */
+       BYTE count                      /* Number of sectors to write (1..255) */
+)
+{
+       FFSDEBUG("disk_write(sector %d, count %d) on drv [%d]\n", sector, count, drv);
+       for(unsigned int s=sector; s<sector+count; s++) {
+               FFSDEBUG(" disk_write(sector %d)\n", s);
+               int res = FATFileSystem::_ffs[drv]->disk_write((char*)buff, sector);
+               if(res) {
+                       return RES_PARERR;
+               }
+               buff += 512;
+       }
+       return RES_OK;
+}
+#endif /* _READONLY */
 \r
-DRESULT disk_ioctl (\r
-       BYTE drv,               /* Physical drive nmuber (0..) */\r
-       BYTE ctrl,              /* Control code */\r
-       void *buff              /* Buffer to send/receive control data */\r
-)\r
-{\r
-       FFSDEBUG("disk_ioctl(%d)\n", ctrl);\r
-       switch(ctrl) {\r
-               case CTRL_SYNC:\r
-                       if(FATFileSystem::_ffs[drv] == NULL) {\r
-                               return RES_NOTRDY;\r
-                       } else if(FATFileSystem::_ffs[drv]->disk_sync()) {\r
-                               return RES_ERROR;\r
-                       } \r
-                       return RES_OK;\r
-               case GET_SECTOR_COUNT:\r
-                       if(FATFileSystem::_ffs[drv] == NULL) {\r
-                               return RES_NOTRDY;\r
-                       } else {\r
-                               int res = FATFileSystem::_ffs[drv]->disk_sectors();\r
-                               if(res > 0) {\r
-                                       *((DWORD*)buff) = res; // minimum allowed\r
-                                       return RES_OK;\r
-                               } else {\r
-                                       return RES_ERROR;\r
-                               }\r
-                       }\r
-               case GET_BLOCK_SIZE:\r
-                       *((DWORD*)buff) = 1; // default when not known\r
-                       return RES_OK;\r
+DRESULT disk_ioctl (
+       BYTE drv,               /* Physical drive nmuber (0..) */
+       BYTE ctrl,              /* Control code */
+       void *buff              /* Buffer to send/receive control data */
+)
+{
+       FFSDEBUG("disk_ioctl(%d)\n", ctrl);
+       switch(ctrl) {
+               case CTRL_SYNC:
+                       if(FATFileSystem::_ffs[drv] == NULL) {
+                               return RES_NOTRDY;
+                       } else if(FATFileSystem::_ffs[drv]->disk_sync()) {
+                               return RES_ERROR;
+                       }
+                       return RES_OK;
+               case GET_SECTOR_COUNT:
+                       if(FATFileSystem::_ffs[drv] == NULL) {
+                               return RES_NOTRDY;
+                       } else {
+                               int res = FATFileSystem::_ffs[drv]->disk_sectors();
+                               if(res > 0) {
+                                       *((DWORD*)buff) = res; // minimum allowed
+                                       return RES_OK;
+                               } else {
+                                       return RES_ERROR;
+                               }
+                       }
+               case GET_BLOCK_SIZE:
+                       *((DWORD*)buff) = 1; // default when not known
+                       return RES_OK;
 \r
-       }\r
-       return RES_PARERR;\r
-}\r
+       }
+       return RES_PARERR;
+}
 \r
index 67ccc1e..e1f92e3 100644 (file)
@@ -1,80 +1,80 @@
-/*-----------------------------------------------------------------------\r
-/  Low level disk interface modlue include file\r
-/-----------------------------------------------------------------------*/\r
+/*-----------------------------------------------------------------------
+/  Low level disk interface modlue include file
+/-----------------------------------------------------------------------*/
 \r
-#ifndef _DISKIO\r
+#ifndef _DISKIO
 \r
-#define _READONLY      0       /* 1: Remove write functions */\r
-#define _USE_IOCTL     1       /* 1: Use disk_ioctl fucntion */\r
+#define _READONLY      0       /* 1: Remove write functions */
+#define _USE_IOCTL     1       /* 1: Use disk_ioctl fucntion */
 \r
-#include "integer.h"\r
+#include "integer.h"
 \r
 \r
-/* Status of Disk Functions */\r
-typedef BYTE   DSTATUS;\r
+/* Status of Disk Functions */
+typedef BYTE   DSTATUS;
 \r
-/* Results of Disk Functions */\r
-typedef enum {\r
-       RES_OK = 0,             /* 0: Successful */\r
-       RES_ERROR,              /* 1: R/W Error */\r
-       RES_WRPRT,              /* 2: Write Protected */\r
-       RES_NOTRDY,             /* 3: Not Ready */\r
-       RES_PARERR              /* 4: Invalid Parameter */\r
-} DRESULT;\r
+/* Results of Disk Functions */
+typedef enum {
+       RES_OK = 0,             /* 0: Successful */
+       RES_ERROR,              /* 1: R/W Error */
+       RES_WRPRT,              /* 2: Write Protected */
+       RES_NOTRDY,             /* 3: Not Ready */
+       RES_PARERR              /* 4: Invalid Parameter */
+} DRESULT;
 \r
 \r
-/*---------------------------------------*/\r
-/* Prototypes for disk control functions */\r
+/*---------------------------------------*/
+/* Prototypes for disk control functions */
 \r
-int assign_drives (int, int);\r
-DSTATUS disk_initialize (BYTE);\r
-DSTATUS disk_status (BYTE);\r
-DRESULT disk_read (BYTE, BYTE*, DWORD, BYTE);\r
-#if    _READONLY == 0\r
-DRESULT disk_write (BYTE, const BYTE*, DWORD, BYTE);\r
-#endif\r
-DRESULT disk_ioctl (BYTE, BYTE, void*);\r
-void   disk_timerproc (void);\r
+int assign_drives (int, int);
+DSTATUS disk_initialize (BYTE);
+DSTATUS disk_status (BYTE);
+DRESULT disk_read (BYTE, BYTE*, DWORD, BYTE);
+#if    _READONLY == 0
+DRESULT disk_write (BYTE, const BYTE*, DWORD, BYTE);
+#endif
+DRESULT disk_ioctl (BYTE, BYTE, void*);
+void   disk_timerproc (void);
 \r
 \r
 \r
 \r
-/* Disk Status Bits (DSTATUS) */\r
+/* Disk Status Bits (DSTATUS) */
 \r
-#define STA_NOINIT             0x01    /* Drive not initialized */\r
-#define STA_NODISK             0x02    /* No medium in the drive */\r
-#define STA_PROTECT            0x04    /* Write protected */\r
+#define STA_NOINIT             0x01    /* Drive not initialized */
+#define STA_NODISK             0x02    /* No medium in the drive */
+#define STA_PROTECT            0x04    /* Write protected */
 \r
 \r
-/* Command code for disk_ioctrl fucntion */\r
+/* Command code for disk_ioctrl fucntion */
 \r
-/* Generic command (defined for FatFs) */\r
-#define CTRL_SYNC                      0       /* Flush disk cache (for write functions) */\r
-#define GET_SECTOR_COUNT       1       /* Get media size (for only f_mkfs()) */\r
-#define GET_SECTOR_SIZE                2       /* Get sector size (for multiple sector size (_MAX_SS >= 1024)) */\r
-#define GET_BLOCK_SIZE         3       /* Get erase block size (for only f_mkfs()) */\r
-#define CTRL_ERASE_SECTOR      4       /* Force erased a block of sectors (for only _USE_ERASE) */\r
+/* Generic command (defined for FatFs) */
+#define CTRL_SYNC                      0       /* Flush disk cache (for write functions) */
+#define GET_SECTOR_COUNT       1       /* Get media size (for only f_mkfs()) */
+#define GET_SECTOR_SIZE                2       /* Get sector size (for multiple sector size (_MAX_SS >= 1024)) */
+#define GET_BLOCK_SIZE         3       /* Get erase block size (for only f_mkfs()) */
+#define CTRL_ERASE_SECTOR      4       /* Force erased a block of sectors (for only _USE_ERASE) */
 \r
-/* Generic command */\r
-#define CTRL_POWER                     5       /* Get/Set power status */\r
-#define CTRL_LOCK                      6       /* Lock/Unlock media removal */\r
-#define CTRL_EJECT                     7       /* Eject media */\r
+/* Generic command */
+#define CTRL_POWER                     5       /* Get/Set power status */
+#define CTRL_LOCK                      6       /* Lock/Unlock media removal */
+#define CTRL_EJECT                     7       /* Eject media */
 \r
-/* MMC/SDC specific ioctl command */\r
-#define MMC_GET_TYPE           10      /* Get card type */\r
-#define MMC_GET_CSD                    11      /* Get CSD */\r
-#define MMC_GET_CID                    12      /* Get CID */\r
-#define MMC_GET_OCR                    13      /* Get OCR */\r
-#define MMC_GET_SDSTAT         14      /* Get SD status */\r
+/* MMC/SDC specific ioctl command */
+#define MMC_GET_TYPE           10      /* Get card type */
+#define MMC_GET_CSD                    11      /* Get CSD */
+#define MMC_GET_CID                    12      /* Get CID */
+#define MMC_GET_OCR                    13      /* Get OCR */
+#define MMC_GET_SDSTAT         14      /* Get SD status */
 \r
-/* ATA/CF specific ioctl command */\r
-#define ATA_GET_REV                    20      /* Get F/W revision */\r
-#define ATA_GET_MODEL          21      /* Get model name */\r
-#define ATA_GET_SN                     22      /* Get serial number */\r
+/* ATA/CF specific ioctl command */
+#define ATA_GET_REV                    20      /* Get F/W revision */
+#define ATA_GET_MODEL          21      /* Get model name */
+#define ATA_GET_SN                     22      /* Get serial number */
 \r
-/* NAND specific ioctl command */\r
-#define NAND_FORMAT                    30      /* Create physical format */\r
+/* NAND specific ioctl command */
+#define NAND_FORMAT                    30      /* Create physical format */
 \r
 \r
-#define _DISKIO\r
-#endif\r
+#define _DISKIO
+#endif
index dfe4c7c..3deafb6 100644 (file)
-/*----------------------------------------------------------------------------/\r
-/  FatFs - FAT file system module  R0.08b                 (C)ChaN, 2011\r
-/-----------------------------------------------------------------------------/\r
-/ FatFs module is a generic FAT file system module for small embedded systems.\r
-/ This is a free software that opened for education, research and commercial\r
-/ developments under license policy of following terms.\r
-/\r
-/  Copyright (C) 2011, ChaN, all right reserved.\r
-/\r
-/ * The FatFs module is a free software and there is NO WARRANTY.\r
-/ * No restriction on use. You can use, modify and redistribute it for\r
-/   personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.\r
-/ * Redistributions of source code must retain the above copyright notice.\r
-/\r
-/-----------------------------------------------------------------------------/\r
-/ Feb 26,'06 R0.00  Prototype.\r
-/\r
-/ Apr 29,'06 R0.01  First stable version.\r
-/\r
-/ Jun 01,'06 R0.02  Added FAT12 support.\r
-/                   Removed unbuffered mode.\r
-/                   Fixed a problem on small (<32M) partition.\r
-/ Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).\r
-/\r
-/ Sep 22,'06 R0.03  Added f_rename().\r
-/                   Changed option _FS_MINIMUM to _FS_MINIMIZE.\r
-/ Dec 11,'06 R0.03a Improved cluster scan algorithm to write files fast.\r
-/                   Fixed f_mkdir() creates incorrect directory on FAT32.\r
-/\r
-/ Feb 04,'07 R0.04  Supported multiple drive system.\r
-/                   Changed some interfaces for multiple drive system.\r
-/                   Changed f_mountdrv() to f_mount().\r
-/                   Added f_mkfs().\r
-/ Apr 01,'07 R0.04a Supported multiple partitions on a physical drive.\r
-/                   Added a capability of extending file size to f_lseek().\r
-/                   Added minimization level 3.\r
-/                   Fixed an endian sensitive code in f_mkfs().\r
-/ May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.\r
-/                   Added FSInfo support.\r
-/                   Fixed DBCS name can result FR_INVALID_NAME.\r
-/                   Fixed short seek (<= csize) collapses the file object.\r
-/\r
-/ Aug 25,'07 R0.05  Changed arguments of f_read(), f_write() and f_mkfs().\r
-/                   Fixed f_mkfs() on FAT32 creates incorrect FSInfo.\r
-/                   Fixed f_mkdir() on FAT32 creates incorrect directory.\r
-/ Feb 03,'08 R0.05a Added f_truncate() and f_utime().\r
-/                   Fixed off by one error at FAT sub-type determination.\r
-/                   Fixed btr in f_read() can be mistruncated.\r
-/                   Fixed cached sector is not flushed when create and close without write.\r
-/\r
-/ Apr 01,'08 R0.06  Added fputc(), fputs(), fprintf() and fgets().\r
-/                   Improved performance of f_lseek() on moving to the same or following cluster.\r
-/\r
-/ Apr 01,'09 R0.07  Merged Tiny-FatFs as a configuration option. (_FS_TINY)\r
-/                   Added long file name feature.\r
-/                   Added multiple code page feature.\r
-/                   Added re-entrancy for multitask operation.\r
-/                   Added auto cluster size selection to f_mkfs().\r
-/                   Added rewind option to f_readdir().\r
-/                   Changed result code of critical errors.\r
-/                   Renamed string functions to avoid name collision.\r
-/ Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.\r
-/                   Added multiple sector size feature.\r
-/ Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.\r
-/                   Fixed wrong cache control in f_lseek().\r
-/                   Added relative path feature.\r
-/                   Added f_chdir() and f_chdrive().\r
-/                   Added proper case conversion to extended char.\r
-/ Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.\r
-/                   Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.\r
-/                   Fixed name matching error on the 13 char boundary.\r
-/                   Added a configuration option, _LFN_UNICODE.\r
-/                   Changed f_readdir() to return the SFN with always upper case on non-LFN cfg.\r
-/\r
-/ May 15,'10 R0.08  Added a memory configuration option. (_USE_LFN = 3)\r
-/                   Added file lock feature. (_FS_SHARE)\r
-/                   Added fast seek feature. (_USE_FASTSEEK)\r
-/                   Changed some types on the API, XCHAR->TCHAR.\r
-/                   Changed fname member in the FILINFO structure on Unicode cfg.\r
-/                   String functions support UTF-8 encoding files on Unicode cfg.\r
-/ Aug 16,'10 R0.08a Added f_getcwd(). (_FS_RPATH = 2)\r
-/                   Added sector erase feature. (_USE_ERASE)\r
-/                   Moved file lock semaphore table from fs object to the bss.\r
-/                   Fixed a wrong directory entry is created on non-LFN cfg when the given name contains ';'.\r
-/                   Fixed f_mkfs() creates wrong FAT32 volume.\r
-/ Jan 15,'11 R0.08b Fast seek feature is also applied to f_read() and f_write().\r
-/                   f_lseek() reports required table size on creating CLMP.\r
-/                   Extended format syntax of f_printf function.\r
-/                   Ignores duplicated directory separators in given path names.\r
-/---------------------------------------------------------------------------*/\r
-\r
-#include "ff.h"            /* FatFs configurations and declarations */\r
-#include "diskio.h"        /* Declarations of low level disk I/O functions */\r
-#include "mbed.h"\r
-\r
-\r
-/*--------------------------------------------------------------------------\r
-\r
-   Module Private Definitions\r
-\r
----------------------------------------------------------------------------*/\r
-\r
-#if _FATFS != 8237\r
-#error Wrong include file (ff.h).\r
-#endif\r
-\r
-\r
-/* Definitions on sector size */\r
-#if _MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096\r
-#error Wrong sector size.\r
-#endif\r
-#if _MAX_SS != 512\r
-#define    SS(fs)    ((fs)->ssize)    /* Multiple sector size */\r
-#else\r
-#define    SS(fs)    512U            /* Fixed sector size */\r
-#endif\r
-\r
-\r
-/* Reentrancy related */\r
-#if _FS_REENTRANT\r
-#if _USE_LFN == 1\r
-#error Static LFN work area must not be used in re-entrant configuration.\r
-#endif\r
-#define    ENTER_FF(fs)        { if (!lock_fs(fs)) return FR_TIMEOUT; }\r
-#define    LEAVE_FF(fs, res)    { unlock_fs(fs, res); return res; }\r
-#else\r
-#define    ENTER_FF(fs)\r
-#define LEAVE_FF(fs, res)    return res\r
-#endif\r
-\r
-#define    ABORT(fs, res)        { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }\r
-\r
-\r
-/* File shareing feature */\r
-#if _FS_SHARE\r
-#if _FS_READONLY\r
-#error _FS_SHARE must be 0 on read-only cfg.\r
-#endif\r
-typedef struct {\r
-    FATFS *fs;                /* File ID 1, volume (NULL:blank entry) */\r
-    DWORD clu;                /* File ID 2, directory */\r
-    WORD idx;                /* File ID 3, directory index */\r
-    WORD ctr;                /* File open counter, 0:none, 0x01..0xFF:read open count, 0x100:write mode */\r
-} FILESEM;\r
-#endif\r
-\r
-\r
-/* Misc definitions */\r
-#define LD_CLUST(dir)    (((DWORD)LD_WORD(dir+DIR_FstClusHI)<<16) | LD_WORD(dir+DIR_FstClusLO))\r
-#define ST_CLUST(dir,cl) {ST_WORD(dir+DIR_FstClusLO, cl); ST_WORD(dir+DIR_FstClusHI, (DWORD)cl>>16);}\r
-\r
-\r
-/* DBCS code ranges and SBCS extend char conversion table */\r
-\r
-#if _CODE_PAGE == 932    /* Japanese Shift-JIS */\r
-#define _DF1S    0x81    /* DBC 1st byte range 1 start */\r
-#define _DF1E    0x9F    /* DBC 1st byte range 1 end */\r
-#define _DF2S    0xE0    /* DBC 1st byte range 2 start */\r
-#define _DF2E    0xFC    /* DBC 1st byte range 2 end */\r
-#define _DS1S    0x40    /* DBC 2nd byte range 1 start */\r
-#define _DS1E    0x7E    /* DBC 2nd byte range 1 end */\r
-#define _DS2S    0x80    /* DBC 2nd byte range 2 start */\r
-#define _DS2E    0xFC    /* DBC 2nd byte range 2 end */\r
-\r
-#elif _CODE_PAGE == 936    /* Simplified Chinese GBK */\r
-#define _DF1S    0x81\r
-#define _DF1E    0xFE\r
-#define _DS1S    0x40\r
-#define _DS1E    0x7E\r
-#define _DS2S    0x80\r
-#define _DS2E    0xFE\r
-\r
-#elif _CODE_PAGE == 949    /* Korean */\r
-#define _DF1S    0x81\r
-#define _DF1E    0xFE\r
-#define _DS1S    0x41\r
-#define _DS1E    0x5A\r
-#define _DS2S    0x61\r
-#define _DS2E    0x7A\r
-#define _DS3S    0x81\r
-#define _DS3E    0xFE\r
-\r
-#elif _CODE_PAGE == 950    /* Traditional Chinese Big5 */\r
-#define _DF1S    0x81\r
-#define _DF1E    0xFE\r
-#define _DS1S    0x40\r
-#define _DS1E    0x7E\r
-#define _DS2S    0xA1\r
-#define _DS2E    0xFE\r
-\r
-#elif _CODE_PAGE == 437    /* U.S. (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F,0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \\r
-                0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 720    /* Arabic (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x45,0x41,0x84,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x49,0x49,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \\r
-                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 737    /* Greek (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \\r
-                0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xE7,0xE8,0xF1,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 775    /* Baltic (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \\r
-                0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 850    /* Multilingual Latin 1 (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \\r
-                0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 852    /* Latin 2 (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F,0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0x9F, \\r
-                0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 855    /* Cyrillic (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F,0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \\r
-                0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \\r
-                0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 857    /* Turkish (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x98,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \\r
-                0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0x59,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 858    /* Multilingual Latin 1 + Euro (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \\r
-                0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 862    /* Hebrew (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \\r
-                0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 866    /* Russian (OEM) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \\r
-                0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 874    /* Thai (OEM, Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \\r
-                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 1250 /* Central Europe (Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \\r
-                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xA3,0xB4,0xB5,0xB6,0xB7,0xB8,0xA5,0xAA,0xBB,0xBC,0xBD,0xBC,0xAF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}\r
-\r
-#elif _CODE_PAGE == 1251 /* Cyrillic (Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x80,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \\r
-                0xA0,0xA2,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB2,0xA5,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xA3,0xBD,0xBD,0xAF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF}\r
-\r
-#elif _CODE_PAGE == 1252 /* Latin 1 (Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0xAd,0x9B,0x8C,0x9D,0xAE,0x9F, \\r
-                0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}\r
-\r
-#elif _CODE_PAGE == 1253 /* Greek (Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \\r
-                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xA2,0xB8,0xB9,0xBA, \\r
-                0xE0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xFB,0xBC,0xFD,0xBF,0xFF}\r
-\r
-#elif _CODE_PAGE == 1254 /* Turkish (Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x9D,0x9E,0x9F, \\r
-                0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}\r
-\r
-#elif _CODE_PAGE == 1255 /* Hebrew (Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \\r
-                0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 1256 /* Arabic (Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x8C,0x9D,0x9E,0x9F, \\r
-                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0x41,0xE1,0x41,0xE3,0xE4,0xE5,0xE6,0x43,0x45,0x45,0x45,0x45,0xEC,0xED,0x49,0x49,0xF0,0xF1,0xF2,0xF3,0x4F,0xF5,0xF6,0xF7,0xF8,0x55,0xFA,0x55,0x55,0xFD,0xFE,0xFF}\r
-\r
-#elif _CODE_PAGE == 1257 /* Baltic (Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \\r
-                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xBC,0xBD,0xBE,0xAF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}\r
-\r
-#elif _CODE_PAGE == 1258 /* Vietnam (OEM, Windows) */\r
-#define _DF1S    0\r
-#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0xAC,0x9D,0x9E,0x9F, \\r
-                0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \\r
-                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xEC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xFE,0x9F}\r
-\r
-#elif _CODE_PAGE == 1    /* ASCII (for only non-LFN cfg) */\r
-#if _USE_LFN\r
-#error Cannot use LFN feature without valid code page.\r
-#endif\r
-#define _DF1S    0\r
-\r
-#else\r
-#error Unknown code page\r
-\r
-#endif\r
-\r
-\r
-/* Character code support macros */\r
-#define IsUpper(c)    (((c)>='A')&&((c)<='Z'))\r
-#define IsLower(c)    (((c)>='a')&&((c)<='z'))\r
-#define IsDigit(c)    (((c)>='0')&&((c)<='9'))\r
-\r
-#if _DF1S        /* Code page is DBCS */\r
-\r
-#ifdef _DF2S    /* Two 1st byte areas */\r
-#define IsDBCS1(c)    (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))\r
-#else            /* One 1st byte area */\r
-#define IsDBCS1(c)    ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)\r
-#endif\r
-\r
-#ifdef _DS3S    /* Three 2nd byte areas */\r
-#define IsDBCS2(c)    (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))\r
-#else            /* Two 2nd byte areas */\r
-#define IsDBCS2(c)    (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))\r
-#endif\r
-\r
-#else            /* Code page is SBCS */\r
-\r
-#define IsDBCS1(c)    0\r
-#define IsDBCS2(c)    0\r
-\r
-#endif /* _DF1S */\r
-\r
-\r
-/* Name status flags */\r
-#define NS            11        /* Index of name status byte in fn[] */\r
-#define NS_LOSS        0x01    /* Out of 8.3 format */\r
-#define NS_LFN        0x02    /* Force to create LFN entry */\r
-#define NS_LAST        0x04    /* Last segment */\r
-#define NS_BODY        0x08    /* Lower case flag (body) */\r
-#define NS_EXT        0x10    /* Lower case flag (ext) */\r
-#define NS_DOT        0x20    /* Dot entry */\r
-\r
-\r
-/* FAT sub-type boundaries */\r
-/* Note that the FAT spec by Microsoft says 4085 but Windows works with 4087! */\r
-#define MIN_FAT16    4086    /* Minimum number of clusters for FAT16 */\r
-#define    MIN_FAT32    65526    /* Minimum number of clusters for FAT32 */\r
-\r
-\r
-/* FatFs refers the members in the FAT structures as byte array instead of\r
-/ structure member because the structure is not binary compatible between\r
-/ different platforms */\r
-\r
-#define BS_jmpBoot            0    /* Jump instruction (3) */\r
-#define BS_OEMName            3    /* OEM name (8) */\r
-#define BPB_BytsPerSec        11    /* Sector size [byte] (2) */\r
-#define BPB_SecPerClus        13    /* Cluster size [sector] (1) */\r
-#define BPB_RsvdSecCnt        14    /* Size of reserved area [sector] (2) */\r
-#define BPB_NumFATs            16    /* Number of FAT copies (1) */\r
-#define BPB_RootEntCnt        17    /* Number of root dir entries for FAT12/16 (2) */\r
-#define BPB_TotSec16        19    /* Volume size [sector] (2) */\r
-#define BPB_Media            21    /* Media descriptor (1) */\r
-#define BPB_FATSz16            22    /* FAT size [sector] (2) */\r
-#define BPB_SecPerTrk        24    /* Track size [sector] (2) */\r
-#define BPB_NumHeads        26    /* Number of heads (2) */\r
-#define BPB_HiddSec            28    /* Number of special hidden sectors (4) */\r
-#define BPB_TotSec32        32    /* Volume size [sector] (4) */\r
-#define BS_DrvNum            36    /* Physical drive number (2) */\r
-#define BS_BootSig            38    /* Extended boot signature (1) */\r
-#define BS_VolID            39    /* Volume serial number (4) */\r
-#define BS_VolLab            43    /* Volume label (8) */\r
-#define BS_FilSysType        54    /* File system type (1) */\r
-#define BPB_FATSz32            36    /* FAT size [sector] (4) */\r
-#define BPB_ExtFlags        40    /* Extended flags (2) */\r
-#define BPB_FSVer            42    /* File system version (2) */\r
-#define BPB_RootClus        44    /* Root dir first cluster (4) */\r
-#define BPB_FSInfo            48    /* Offset of FSInfo sector (2) */\r
-#define BPB_BkBootSec        50    /* Offset of backup boot sectot (2) */\r
-#define BS_DrvNum32            64    /* Physical drive number (2) */\r
-#define BS_BootSig32        66    /* Extended boot signature (1) */\r
-#define BS_VolID32            67    /* Volume serial number (4) */\r
-#define BS_VolLab32            71    /* Volume label (8) */\r
-#define BS_FilSysType32        82    /* File system type (1) */\r
-#define    FSI_LeadSig            0    /* FSI: Leading signature (4) */\r
-#define    FSI_StrucSig        484    /* FSI: Structure signature (4) */\r
-#define    FSI_Free_Count        488    /* FSI: Number of free clusters (4) */\r
-#define    FSI_Nxt_Free        492    /* FSI: Last allocated cluster (4) */\r
-#define MBR_Table            446    /* MBR: Partition table offset (2) */\r
-#define    SZ_PTE                16    /* MBR: Size of a partition table entry */\r
-#define BS_55AA                510    /* Boot sector signature (2) */\r
-\r
-#define    DIR_Name            0    /* Short file name (11) */\r
-#define    DIR_Attr            11    /* Attribute (1) */\r
-#define    DIR_NTres            12    /* NT flag (1) */\r
-#define    DIR_CrtTime            14    /* Created time (2) */\r
-#define    DIR_CrtDate            16    /* Created date (2) */\r
-#define    DIR_FstClusHI        20    /* Higher 16-bit of first cluster (2) */\r
-#define    DIR_WrtTime            22    /* Modified time (2) */\r
-#define    DIR_WrtDate            24    /* Modified date (2) */\r
-#define    DIR_FstClusLO        26    /* Lower 16-bit of first cluster (2) */\r
-#define    DIR_FileSize        28    /* File size (4) */\r
-#define    LDIR_Ord            0    /* LFN entry order and LLE flag (1) */\r
-#define    LDIR_Attr            11    /* LFN attribute (1) */\r
-#define    LDIR_Type            12    /* LFN type (1) */\r
-#define    LDIR_Chksum            13    /* Sum of corresponding SFN entry */\r
-#define    LDIR_FstClusLO        26    /* Filled by zero (0) */\r
-#define    SZ_DIR                32        /* Size of a directory entry */\r
-#define    LLE                    0x40    /* Last long entry flag in LDIR_Ord */\r
-#define    DDE                    0xE5    /* Deleted directory enrty mark in DIR_Name[0] */\r
-#define    NDDE                0x05    /* Replacement of a character collides with DDE */\r
-\r
-\r
-/*------------------------------------------------------------*/\r
-/* Work area                                                  */\r
-\r
-#if _VOLUMES\r
-static\r
-FATFS *FatFs[_VOLUMES];    /* Pointer to the file system objects (logical drives) */\r
-#else\r
-#error Number of drives must not be 0.\r
-#endif\r
-\r
-static\r
-WORD Fsid;                /* File system mount ID */\r
-\r
-#if _FS_RPATH\r
-static\r
-BYTE CurrVol;            /* Current drive */\r
-#endif\r
-\r
-#if _FS_SHARE\r
-static\r
-FILESEM    Files[_FS_SHARE];    /* File lock semaphores */\r
-#endif\r
-\r
-#if _USE_LFN == 0            /* No LFN */\r
-#define    DEF_NAMEBUF            BYTE sfn[12]\r
-#define INIT_BUF(dobj)        (dobj).fn = sfn\r
-#define    FREE_BUF()\r
-\r
-#elif _USE_LFN == 1            /* LFN with static LFN working buffer */\r
-static WCHAR LfnBuf[_MAX_LFN+1];\r
-#define    DEF_NAMEBUF            BYTE sfn[12]\r
-#define INIT_BUF(dobj)        { (dobj).fn = sfn; (dobj).lfn = LfnBuf; }\r
-#define    FREE_BUF()\r
-\r
-#elif _USE_LFN == 2         /* LFN with dynamic LFN working buffer on the stack */\r
-#define    DEF_NAMEBUF            BYTE sfn[12]; WCHAR lbuf[_MAX_LFN+1]\r
-#define INIT_BUF(dobj)        { (dobj).fn = sfn; (dobj).lfn = lbuf; }\r
-#define    FREE_BUF()\r
-\r
-#elif _USE_LFN == 3         /* LFN with dynamic LFN working buffer on the heap */\r
-#define    DEF_NAMEBUF            BYTE sfn[12]; WCHAR *lfn\r
-#define INIT_BUF(dobj)        { lfn = ff_memalloc((_MAX_LFN + 1) * 2); \\r
-                              if (!lfn) LEAVE_FF((dobj).fs, FR_NOT_ENOUGH_CORE); \\r
-                              (dobj).lfn = lfn;    (dobj).fn = sfn; }\r
-#define    FREE_BUF()            ff_memfree(lfn)\r
-\r
-#else\r
-#error Wrong LFN configuration.\r
-#endif\r
-\r
-\r
-\r
-\r
-/*--------------------------------------------------------------------------\r
-\r
-   Module Private Functions\r
-\r
----------------------------------------------------------------------------*/\r
-\r
-//static FATFS *FatFs[_DRIVES];    /* Pointer to the file system objects (logical drives) */\r
-//static WORD fsid;                /* File system mount ID */\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* String functions                                                      */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-/* Copy memory to memory */\r
-static\r
-void mem_cpy (void* dst, const void* src, UINT cnt) {\r
-    BYTE *d = (BYTE*)dst;\r
-    const BYTE *s = (const BYTE*)src;\r
-\r
-#if _WORD_ACCESS == 1\r
-    while (cnt >= sizeof(int)) {\r
-        *(int*)d = *(int*)s;\r
-        d += sizeof(int); s += sizeof(int);\r
-        cnt -= sizeof(int);\r
-    }\r
-#endif\r
-    while (cnt--)\r
-        *d++ = *s++;\r
-}\r
-\r
-/* Fill memory */\r
-static\r
-void mem_set (void* dst, int val, UINT cnt) {\r
-    BYTE *d = (BYTE*)dst;\r
-\r
-    while (cnt--)\r
-        *d++ = (BYTE)val;\r
-}\r
-\r
-/* Compare memory to memory */\r
-static\r
-int mem_cmp (const void* dst, const void* src, UINT cnt) {\r
-    const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;\r
-    int r = 0;\r
-\r
-    while (cnt-- && (r = *d++ - *s++) == 0) ;\r
-    return r;\r
-}\r
-\r
-/* Check if chr is contained in the string */\r
-static\r
-int chk_chr (const char* str, int chr) {\r
-    while (*str && *str != chr) str++;\r
-    return *str;\r
-}\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Request/Release grant to access the volume                            */\r
-/*-----------------------------------------------------------------------*/\r
-#if _FS_REENTRANT\r
-\r
-static\r
-int lock_fs (\r
-    FATFS *fs        /* File system object */\r
-)\r
-{\r
-    return ff_req_grant(fs->sobj);\r
-}\r
-\r
-\r
-static\r
-void unlock_fs (\r
-    FATFS *fs,        /* File system object */\r
-    FRESULT res        /* Result code to be returned */\r
-)\r
-{\r
-    if (res != FR_NOT_ENABLED &&\r
-        res != FR_INVALID_DRIVE &&\r
-        res != FR_INVALID_OBJECT &&\r
-        res != FR_TIMEOUT) {\r
-        ff_rel_grant(fs->sobj);\r
-    }\r
-}\r
-#endif\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* File shareing control functions                                       */\r
-/*-----------------------------------------------------------------------*/\r
-#if _FS_SHARE\r
-\r
-static\r
-FRESULT chk_lock (    /* Check if the file can be accessed */\r
-    DIR* dj,        /* Directory object pointing the file to be checked */\r
-    int acc            /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */\r
-)\r
-{\r
-    UINT i, be;\r
-\r
-    /* Search file semaphore table */\r
-    for (i = be = 0; i < _FS_SHARE; i++) {\r
-        if (Files[i].fs) {    /* Existing entry */\r
-            if (Files[i].fs == dj->fs &&         /* Check if the file matched with an open file */\r
-                Files[i].clu == dj->sclust &&\r
-                Files[i].idx == dj->index) break;\r
-        } else {            /* Blank entry */\r
-            be++;\r
-        }\r
-    }\r
-    if (i == _FS_SHARE)    /* The file is not opened */\r
-        return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES;    /* Is there a blank entry for new file? */\r
-\r
-    /* The file has been opened. Reject any open against writing file and all write mode open */\r
-    return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;\r
-}\r
-\r
-\r
-static\r
-int enq_lock (    /* Check if an entry is available for a new file */\r
-    FATFS* fs    /* File system object */\r
-)\r
-{\r
-    UINT i;\r
-\r
-    for (i = 0; i < _FS_SHARE && Files[i].fs; i++) ;\r
-    return (i == _FS_SHARE) ? 0 : 1;\r
-}\r
-\r
-\r
-static\r
-UINT inc_lock (    /* Increment file open counter and returns its index (0:int error) */\r
-    DIR* dj,    /* Directory object pointing the file to register or increment */\r
-    int acc        /* Desired access mode (0:Read, !0:Write) */\r
-)\r
-{\r
-    UINT i;\r
-\r
-\r
-    for (i = 0; i < _FS_SHARE; i++) {    /* Find the file */\r
-        if (Files[i].fs == dj->fs &&\r
-            Files[i].clu == dj->sclust &&\r
-            Files[i].idx == dj->index) break;\r
-    }\r
-\r
-    if (i == _FS_SHARE) {                /* Not opened. Register it as new. */\r
-        for (i = 0; i < _FS_SHARE && Files[i].fs; i++) ;\r
-        if (i == _FS_SHARE) return 0;    /* No space to register (int err) */\r
-        Files[i].fs = dj->fs;\r
-        Files[i].clu = dj->sclust;\r
-        Files[i].idx = dj->index;\r
-        Files[i].ctr = 0;\r
-    }\r
-\r
-    if (acc && Files[i].ctr) return 0;    /* Access violation (int err) */\r
-\r
-    Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1;    /* Set semaphore value */\r
-\r
-    return i + 1;\r
-}\r
-\r
-\r
-static\r
-FRESULT dec_lock (    /* Decrement file open counter */\r
-    UINT i            /* Semaphore index */\r
-)\r
-{\r
-    WORD n;\r
-    FRESULT res;\r
-\r
-\r
-    if (--i < _FS_SHARE) {\r
-        n = Files[i].ctr;\r
-        if (n == 0x100) n = 0;\r
-        if (n) n--;\r
-        Files[i].ctr = n;\r
-        if (!n) Files[i].fs = 0;\r
-        res = FR_OK;\r
-    } else {\r
-        res = FR_INT_ERR;\r
-    }\r
-    return res;\r
-}\r
-\r
-\r
-static\r
-void clear_lock (    /* Clear lock entries of the volume */\r
-    FATFS *fs\r
-)\r
-{\r
-    UINT i;\r
-\r
-    for (i = 0; i < _FS_SHARE; i++) {\r
-        if (Files[i].fs == fs) Files[i].fs = 0;\r
-    }\r
-}\r
-#endif\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Change window offset                                                  */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-static\r
-FRESULT move_window (\r
-    FATFS *fs,        /* File system object */\r
-    DWORD sector    /* Sector number to make appearance in the fs->win[] */\r
-)                    /* Move to zero only writes back dirty window */\r
-{\r
-    DWORD wsect;\r
-\r
-\r
-    wsect = fs->winsect;\r
-    if (wsect != sector) {    /* Changed current window */\r
-#if !_FS_READONLY\r
-        if (fs->wflag) {    /* Write back dirty window if needed */\r
-            if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK)\r
-                return FR_DISK_ERR;\r
-            fs->wflag = 0;\r
-            if (wsect < (fs->fatbase + fs->fsize)) {    /* In FAT area */\r
-                BYTE nf;\r
-                for (nf = fs->n_fats; nf > 1; nf--) {    /* Reflect the change to all FAT copies */\r
-                    wsect += fs->fsize;\r
-                    disk_write(fs->drv, fs->win, wsect, 1);\r
-                }\r
-            }\r
-        }\r
-#endif\r
-        if (sector) {\r
-            if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK)\r
-                return FR_DISK_ERR;\r
-            fs->winsect = sector;\r
-        }\r
-    }\r
-\r
-    return FR_OK;\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Clean-up cached data                                                  */\r
-/*-----------------------------------------------------------------------*/\r
-#if !_FS_READONLY\r
-static\r
-FRESULT sync (    /* FR_OK: successful, FR_DISK_ERR: failed */\r
-    FATFS *fs    /* File system object */\r
-)\r
-{\r
-    FRESULT res;\r
-\r
-\r
-    res = move_window(fs, 0);\r
-    if (res == FR_OK) {\r
-    /* Update FSInfo sector if needed */\r
-    if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {\r
-        fs->winsect = 0;\r
-            /* Create FSInfo structure */\r
-            mem_set(fs->win, 0, 512);\r
-            ST_WORD(fs->win+BS_55AA, 0xAA55);\r
-            ST_DWORD(fs->win+FSI_LeadSig, 0x41615252);\r
-            ST_DWORD(fs->win+FSI_StrucSig, 0x61417272);\r
-            ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust);\r
-            ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust);\r
-            /* Write it into the FSInfo sector */\r
-            disk_write(fs->drv, fs->win, fs->fsi_sector, 1);\r
-        fs->fsi_flag = 0;\r
-    }\r
-    /* Make sure that no pending write process in the physical drive */\r
-        if (disk_ioctl(fs->drv, CTRL_SYNC, (void*)0) != RES_OK)\r
-            res = FR_DISK_ERR;\r
-    }\r
-\r
-    return res;\r
-}\r
-#endif\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Get sector# from cluster#                                             */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-\r
-DWORD clust2sect (    /* !=0: Sector number, 0: Failed - invalid cluster# */\r
-    FATFS *fs,        /* File system object */\r
-    DWORD clst        /* Cluster# to be converted */\r
-)\r
-{\r
-    clst -= 2;\r
-    if (clst >= (fs->n_fatent - 2)) return 0;        /* Invalid cluster# */\r
-    return clst * fs->csize + fs->database;\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* FAT access - Read value of a FAT entry                                */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-\r
-DWORD get_fat (    /* 0xFFFFFFFF:Disk error, 1:Internal error, Else:Cluster status */\r
-    FATFS *fs,        /* File system object */\r
-    DWORD clst    /* Cluster# to get the link information */\r
-)\r
-{\r
-    UINT wc, bc;\r
-    BYTE *p;\r
-\r
-\r
-    if (clst < 2 || clst >= fs->n_fatent)    /* Chack range */\r
-        return 1;\r
-\r
-        switch (fs->fs_type) {\r
-        case FS_FAT12 :\r
-        bc = (UINT)clst; bc += bc / 2;\r
-        if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;\r
-        wc = fs->win[bc % SS(fs)]; bc++;\r
-        if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;\r
-        wc |= fs->win[bc % SS(fs)] << 8;\r
-        return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);\r
-\r
-        case FS_FAT16 :\r
-        if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)))) break;\r
-        p = &fs->win[clst * 2 % SS(fs)];\r
-        return LD_WORD(p);\r
-\r
-        case FS_FAT32 :\r
-        if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)))) break;\r
-        p = &fs->win[clst * 4 % SS(fs)];\r
-        return LD_DWORD(p) & 0x0FFFFFFF;\r
-    }\r
-\r
-    return 0xFFFFFFFF;    /* An error occurred at the disk I/O layer */\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* FAT access - Change value of a FAT entry                              */\r
-/*-----------------------------------------------------------------------*/\r
-#if !_FS_READONLY\r
-\r
-FRESULT put_fat (\r
-    FATFS *fs,        /* File system object */\r
-    DWORD clst,    /* Cluster# to be changed in range of 2 to fs->n_fatent - 1 */\r
-    DWORD val        /* New value to mark the cluster */\r
-)\r
-{\r
-    UINT bc;\r
-    BYTE *p;\r
-    FRESULT res;\r
-\r
-\r
-    if (clst < 2 || clst >= fs->n_fatent) {    /* Check range */\r
-        res = FR_INT_ERR;\r
-\r
-    } else {\r
-    switch (fs->fs_type) {\r
-    case FS_FAT12 :\r
-            bc = clst; bc += bc / 2;\r
-            res = move_window(fs, fs->fatbase + (bc / SS(fs)));\r
-            if (res != FR_OK) break;\r
-            p = &fs->win[bc % SS(fs)];\r
-            *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;\r
-        bc++;\r
-            fs->wflag = 1;\r
-            res = move_window(fs, fs->fatbase + (bc / SS(fs)));\r
-            if (res != FR_OK) break;\r
-            p = &fs->win[bc % SS(fs)];\r
-            *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));\r
-        break;\r
-\r
-    case FS_FAT16 :\r
-            res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));\r
-            if (res != FR_OK) break;\r
-            p = &fs->win[clst * 2 % SS(fs)];\r
-            ST_WORD(p, (WORD)val);\r
-        break;\r
-\r
-    case FS_FAT32 :\r
-            res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));\r
-            if (res != FR_OK) break;\r
-            p = &fs->win[clst * 4 % SS(fs)];\r
-            val |= LD_DWORD(p) & 0xF0000000;\r
-            ST_DWORD(p, val);\r
-        break;\r
-\r
-    default :\r
-            res = FR_INT_ERR;\r
-    }\r
-        fs->wflag = 1;\r
-    }\r
-\r
-    return res;\r
-}\r
-#endif /* !_FS_READONLY */\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* FAT handling - Remove a cluster chain                                 */\r
-/*-----------------------------------------------------------------------*/\r
-#if !_FS_READONLY\r
-static\r
-FRESULT remove_chain (\r
-    FATFS *fs,        /* File system object */\r
-    DWORD clst            /* Cluster# to remove a chain from */\r
-)\r
-{\r
-    FRESULT res;\r
-    DWORD nxt;\r
-#if _USE_ERASE\r
-    DWORD scl = clst, ecl = clst, resion[2];\r
-#endif\r
-\r
-    if (clst < 2 || clst >= fs->n_fatent) {    /* Check range */\r
-        res = FR_INT_ERR;\r
-\r
-    } else {\r
-        res = FR_OK;\r
-        while (clst < fs->n_fatent) {            /* Not a last link? */\r
-            nxt = get_fat(fs, clst);            /* Get cluster status */\r
-            if (nxt == 0) break;                /* Empty cluster? */\r
-            if (nxt == 1) { res = FR_INT_ERR; break; }    /* Internal error? */\r
-            if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }    /* Disk error? */\r
-            res = put_fat(fs, clst, 0);            /* Mark the cluster "empty" */\r
-            if (res != FR_OK) break;\r
-            if (fs->free_clust != 0xFFFFFFFF) {    /* Update FSInfo */\r
-            fs->free_clust++;\r
-            fs->fsi_flag = 1;\r
-            }\r
-#if _USE_ERASE\r
-            if (ecl + 1 == nxt) {    /* Next cluster is contiguous */\r
-                ecl = nxt;\r
-            } else {                /* End of contiguous clusters */ \r
-                resion[0] = clust2sect(fs, scl);                    /* Start sector */\r
-                resion[1] = clust2sect(fs, ecl) + fs->csize - 1;    /* End sector */\r
-                disk_ioctl(fs->drv, CTRL_ERASE_SECTOR, resion);        /* Erase the block */\r
-                scl = ecl = nxt;\r
-            }\r
-#endif\r
-            clst = nxt;    /* Next cluster */\r
-        }\r
-    }\r
-\r
-    return res;\r
-}\r
-#endif\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* FAT handling - Stretch or Create a cluster chain                      */\r
-/*-----------------------------------------------------------------------*/\r
-#if !_FS_READONLY\r
-static\r
-DWORD create_chain (    /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */\r
-    FATFS *fs,            /* File system object */\r
-    DWORD clst            /* Cluster# to stretch. 0 means create a new chain. */\r
-)\r
-{\r
-    DWORD cs, ncl, scl;\r
-    FRESULT res;\r
-\r
-\r
-    if (clst == 0) {        /* Create a new chain */\r
-        scl = fs->last_clust;            /* Get suggested start point */\r
-        if (!scl || scl >= fs->n_fatent) scl = 1;\r
-    }\r
-    else {                    /* Stretch the current chain */\r
-        cs = get_fat(fs, clst);            /* Check the cluster status */\r
-        if (cs < 2) return 1;            /* It is an invalid cluster */\r
-        if (cs < fs->n_fatent) return cs;    /* It is already followed by next cluster */\r
-        scl = clst;\r
-    }\r
-\r
-    ncl = scl;                /* Start cluster */\r
-    for (;;) {\r
-        ncl++;                            /* Next cluster */\r
-        if (ncl >= fs->n_fatent) {        /* Wrap around */\r
-            ncl = 2;\r
-            if (ncl > scl) return 0;    /* No free cluster */\r
-        }\r
-        cs = get_fat(fs, ncl);            /* Get the cluster status */\r
-        if (cs == 0) break;                /* Found a free cluster */\r
-        if (cs == 0xFFFFFFFF || cs == 1)/* An error occurred */\r
-            return cs;\r
-        if (ncl == scl) return 0;        /* No free cluster */\r
-    }\r
-\r
-    res = put_fat(fs, ncl, 0x0FFFFFFF);    /* Mark the new cluster "last link" */\r
-    if (res == FR_OK && clst != 0) {\r
-        res = put_fat(fs, clst, ncl);    /* Link it to the previous one if needed */\r
-    }\r
-    if (res == FR_OK) {\r
-        fs->last_clust = ncl;            /* Update FSINFO */\r
-    if (fs->free_clust != 0xFFFFFFFF) {\r
-        fs->free_clust--;\r
-        fs->fsi_flag = 1;\r
-        }\r
-    } else {\r
-        ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1;\r
-    }\r
-\r
-    return ncl;        /* Return new cluster number or error code */\r
-}\r
-#endif /* !_FS_READONLY */\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* FAT handling - Convert offset into cluster with link map table        */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-#if _USE_FASTSEEK\r
-static\r
-DWORD clmt_clust (    /* <2:Error, >=2:Cluster number */\r
-    FIL* fp,        /* Pointer to the file object */\r
-    DWORD ofs        /* File offset to be converted to cluster# */\r
-)\r
-{\r
-    DWORD cl, ncl, *tbl;\r
-\r
-\r
-    tbl = fp->cltbl + 1;    /* Top of CLMT */\r
-    cl = ofs / SS(fp->fs) / fp->fs->csize;    /* Cluster order from top of the file */\r
-    for (;;) {\r
-        ncl = *tbl++;            /* Number of cluters in the fragment */\r
-        if (!ncl) return 0;        /* End of table? (error) */\r
-        if (cl < ncl) break;    /* In this fragment? */\r
-        cl -= ncl; tbl++;        /* Next fragment */\r
-    }\r
-    return cl + *tbl;    /* Return the cluster number */\r
-}\r
-#endif    /* _USE_FASTSEEK */\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Directory handling - Set directory index                              */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-static\r
-FRESULT dir_sdi (\r
-    DIR_t *dj,        /* Pointer to directory object */\r
-    WORD idx        /* Directory index number */\r
-)\r
-{\r
-    DWORD clst;\r
-    WORD ic;\r
-\r
-\r
-    dj->index = idx;\r
-    clst = dj->sclust;\r
-    if (clst == 1 || clst >= dj->fs->n_fatent)    /* Check start cluster range */\r
-        return FR_INT_ERR;\r
-    if (!clst && dj->fs->fs_type == FS_FAT32)    /* Replace cluster# 0 with root cluster# if in FAT32 */\r
-        clst = dj->fs->dirbase;\r
-\r
-    if (clst == 0) {    /* Static table (root-dir in FAT12/16) */\r
-        dj->clust = clst;\r
-        if (idx >= dj->fs->n_rootdir)        /* Index is out of range */\r
-            return FR_INT_ERR;\r
-        dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / SZ_DIR);    /* Sector# */\r
-    }\r
-    else {                /* Dynamic table (sub-dirs or root-dir in FAT32) */\r
-        ic = SS(dj->fs) / SZ_DIR * dj->fs->csize;    /* Entries per cluster */\r
-        while (idx >= ic) {    /* Follow cluster chain */\r
-            clst = get_fat(dj->fs, clst);                /* Get next cluster */\r
-            if (clst == 0xFFFFFFFF) return FR_DISK_ERR;    /* Disk error */\r
-            if (clst < 2 || clst >= dj->fs->n_fatent)    /* Reached to end of table or int error */\r
-                return FR_INT_ERR;\r
-            idx -= ic;\r
-        }\r
-        dj->clust = clst;\r
-        dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / SZ_DIR);    /* Sector# */\r
-    }\r
-\r
-    dj->dir = dj->fs->win + (idx % (SS(dj->fs) / SZ_DIR)) * SZ_DIR;    /* Ptr to the entry in the sector */\r
-\r
-    return FR_OK;    /* Seek succeeded */\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Directory handling - Move directory index next                        */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-static\r
-FRESULT dir_next (    /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not stretch */\r
-    DIR_t *dj,        /* Pointer to directory object */\r
-    int stretch        /* 0: Do not stretch table, 1: Stretch table if needed */\r
-)\r
-{\r
-    DWORD clst;\r
-    WORD i;\r
-\r
-\r
-    i = dj->index + 1;\r
-    if (!i || !dj->sect)    /* Report EOT when index has reached 65535 */\r
-        return FR_NO_FILE;\r
-\r
-    if (!(i % (SS(dj->fs) / SZ_DIR))) {    /* Sector changed? */\r
-        dj->sect++;                /* Next sector */\r
-\r
-        if (dj->clust == 0) {    /* Static table */\r
-            if (i >= dj->fs->n_rootdir)    /* Report EOT when end of table */\r
-                return FR_NO_FILE;\r
-        }\r
-        else {                    /* Dynamic table */\r
-            if (((i / (SS(dj->fs) / SZ_DIR)) & (dj->fs->csize - 1)) == 0) {    /* Cluster changed? */\r
-                clst = get_fat(dj->fs, dj->clust);                /* Get next cluster */\r
-                if (clst <= 1) return FR_INT_ERR;\r
-                if (clst == 0xFFFFFFFF) return FR_DISK_ERR;\r
-                if (clst >= dj->fs->n_fatent) {                    /* When it reached end of dynamic table */\r
-#if !_FS_READONLY\r
-                    BYTE c;\r
-                    if (!stretch) return FR_NO_FILE;            /* When do not stretch, report EOT */\r
-                    clst = create_chain(dj->fs, dj->clust);        /* Stretch cluster chain */\r
-                    if (clst == 0) return FR_DENIED;            /* No free cluster */\r
-                    if (clst == 1) return FR_INT_ERR;\r
-                    if (clst == 0xFFFFFFFF) return FR_DISK_ERR;\r
-                    /* Clean-up stretched table */\r
-                    if (move_window(dj->fs, 0)) return FR_DISK_ERR;    /* Flush active window */\r
-                    mem_set(dj->fs->win, 0, SS(dj->fs));            /* Clear window buffer */\r
-                    dj->fs->winsect = clust2sect(dj->fs, clst);    /* Cluster start sector */\r
-                    for (c = 0; c < dj->fs->csize; c++) {        /* Fill the new cluster with 0 */\r
-                        dj->fs->wflag = 1;\r
-                        if (move_window(dj->fs, 0)) return FR_DISK_ERR;\r
-                        dj->fs->winsect++;\r
-                    }\r
-                    dj->fs->winsect -= c;                        /* Rewind window address */\r
-#else\r
-                    return FR_NO_FILE;            /* Report EOT */\r
-#endif\r
-            }\r
-                dj->clust = clst;                /* Initialize data for new cluster */\r
-                dj->sect = clust2sect(dj->fs, clst);\r
-        }\r
-    }\r
-    }\r
-\r
-    dj->index = i;\r
-    dj->dir = dj->fs->win + (i % (SS(dj->fs) / SZ_DIR)) * SZ_DIR;\r
-\r
-    return FR_OK;\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry   */\r
-/*-----------------------------------------------------------------------*/\r
-#if _USE_LFN\r
-static\r
-const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30};    /* Offset of LFN chars in the directory entry */\r
-\r
-\r
-static\r
-int cmp_lfn (            /* 1:Matched, 0:Not matched */\r
-    WCHAR *lfnbuf,        /* Pointer to the LFN to be compared */\r
-    BYTE *dir            /* Pointer to the directory entry containing a part of LFN */\r
-)\r
-{\r
-    UINT i, s;\r
-    WCHAR wc, uc;\r
-\r
-\r
-    i = ((dir[LDIR_Ord] & ~LLE) - 1) * 13;    /* Get offset in the LFN buffer */\r
-    s = 0; wc = 1;\r
-    do {\r
-        uc = LD_WORD(dir+LfnOfs[s]);    /* Pick an LFN character from the entry */\r
-        if (wc) {    /* Last char has not been processed */\r
-            wc = ff_wtoupper(uc);        /* Convert it to upper case */\r
-            if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++]))    /* Compare it */\r
-                return 0;                /* Not matched */\r
-        } else {\r
-            if (uc != 0xFFFF) return 0;    /* Check filler */\r
-    }\r
-    } while (++s < 13);                /* Repeat until all chars in the entry are checked */\r
-\r
-    if ((dir[LDIR_Ord] & LLE) && wc && lfnbuf[i])    /* Last segment matched but different length */\r
-        return 0;\r
-\r
-    return 1;                        /* The part of LFN matched */\r
-        }\r
-\r
-\r
-\r
-static\r
-int pick_lfn (            /* 1:Succeeded, 0:Buffer overflow */\r
-    WCHAR *lfnbuf,        /* Pointer to the Unicode-LFN buffer */\r
-    BYTE *dir            /* Pointer to the directory entry */\r
-)\r
-{\r
-    UINT i, s;\r
-    WCHAR wc, uc;\r
-\r
-\r
-    i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13;    /* Offset in the LFN buffer */\r
-\r
-    s = 0; wc = 1;\r
-    do {\r
-        uc = LD_WORD(dir+LfnOfs[s]);        /* Pick an LFN character from the entry */\r
-        if (wc) {    /* Last char has not been processed */\r
-            if (i >= _MAX_LFN) return 0;    /* Buffer overflow? */\r
-            lfnbuf[i++] = wc = uc;            /* Store it */\r
-        } else {\r
-            if (uc != 0xFFFF) return 0;        /* Check filler */\r
-    }\r
-    } while (++s < 13);                        /* Read all character in the entry */\r
-\r
-    if (dir[LDIR_Ord] & LLE) {                /* Put terminator if it is the last LFN part */\r
-        if (i >= _MAX_LFN) return 0;        /* Buffer overflow? */\r
-        lfnbuf[i] = 0;\r
-}\r
-\r
-    return 1;\r
-}\r
-\r
-\r
-#if !_FS_READONLY\r
-static\r
-void fit_lfn (\r
-    const WCHAR *lfnbuf,    /* Pointer to the LFN buffer */\r
-    BYTE *dir,                /* Pointer to the directory entry */\r
-    BYTE ord,                /* LFN order (1-20) */\r
-    BYTE sum                /* SFN sum */\r
-)\r
-{\r
-    UINT i, s;\r
-    WCHAR wc;\r
-\r
-\r
-    dir[LDIR_Chksum] = sum;            /* Set check sum */\r
-    dir[LDIR_Attr] = AM_LFN;        /* Set attribute. LFN entry */\r
-    dir[LDIR_Type] = 0;\r
-    ST_WORD(dir+LDIR_FstClusLO, 0);\r
-\r
-    i = (ord - 1) * 13;                /* Get offset in the LFN buffer */\r
-    s = wc = 0;\r
-    do {\r
-        if (wc != 0xFFFF) wc = lfnbuf[i++];    /* Get an effective char */\r
-        ST_WORD(dir+LfnOfs[s], wc);    /* Put it */\r
-        if (!wc) wc = 0xFFFF;        /* Padding chars following last char */\r
-    } while (++s < 13);\r
-    if (wc == 0xFFFF || !lfnbuf[i]) ord |= LLE;    /* Bottom LFN part is the start of LFN sequence */\r
-    dir[LDIR_Ord] = ord;            /* Set the LFN order */\r
-}\r
-\r
-#endif\r
-#endif\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Create numbered name                                                  */\r
-/*-----------------------------------------------------------------------*/\r
-#if _USE_LFN\r
-void gen_numname (\r
-    BYTE *dst,            /* Pointer to generated SFN */\r
-    const BYTE *src,    /* Pointer to source SFN to be modified */\r
-    const WCHAR *lfn,    /* Pointer to LFN */\r
-    WORD seq            /* Sequence number */\r
-)\r
-{\r
-    BYTE ns[8], c;\r
-    UINT i, j;\r
-\r
-\r
-    mem_cpy(dst, src, 11);\r
-\r
-    if (seq > 5) {    /* On many collisions, generate a hash number instead of sequential number */\r
-        do seq = (seq >> 1) + (seq << 15) + (WORD)*lfn++; while (*lfn);\r
-    }\r
-\r
-    /* itoa (hexdecimal) */\r
-    i = 7;\r
-    do {\r
-        c = (seq % 16) + '0';\r
-        if (c > '9') c += 7;\r
-        ns[i--] = c;\r
-        seq /= 16;\r
-    } while (seq);\r
-    ns[i] = '~';\r
-\r
-    /* Append the number */\r
-    for (j = 0; j < i && dst[j] != ' '; j++) {\r
-        if (IsDBCS1(dst[j])) {\r
-            if (j == i - 1) break;\r
-            j++;\r
-        }\r
-    }\r
-    do {\r
-        dst[j++] = (i < 8) ? ns[i++] : ' ';\r
-    } while (j < 8);\r
-}\r
-#endif\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Calculate sum of an SFN                                               */\r
-/*-----------------------------------------------------------------------*/\r
-#if _USE_LFN\r
-static\r
-BYTE sum_sfn (\r
-    const BYTE *dir        /* Ptr to directory entry */\r
-)\r
-{\r
-    BYTE sum = 0;\r
-    UINT n = 11;\r
-\r
-    do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);\r
-    return sum;\r
-}\r
-#endif\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Directory handling - Find an object in the directory                  */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-static\r
-FRESULT dir_find (\r
-    DIR_t *dj            /* Pointer to the directory object linked to the file name */\r
-)\r
-{\r
-    FRESULT res;\r
-    BYTE c, *dir;\r
-#if _USE_LFN\r
-    BYTE a, ord, sum;\r
-#endif\r
-\r
-    res = dir_sdi(dj, 0);            /* Rewind directory object */\r
-    if (res != FR_OK) return res;\r
-\r
-#if _USE_LFN\r
-    ord = sum = 0xFF;\r
-#endif\r
-    do {\r
-        res = move_window(dj->fs, dj->sect);\r
-        if (res != FR_OK) break;\r
-        dir = dj->dir;                    /* Ptr to the directory entry of current index */\r
-        c = dir[DIR_Name];\r
-        if (c == 0) { res = FR_NO_FILE; break; }    /* Reached to end of table */\r
-#if _USE_LFN    /* LFN configuration */\r
-        a = dir[DIR_Attr] & AM_MASK;\r
-        if (c == DDE || ((a & AM_VOL) && a != AM_LFN)) {    /* An entry without valid data */\r
-            ord = 0xFF;\r
-        } else {\r
-            if (a == AM_LFN) {            /* An LFN entry is found */\r
-                if (dj->lfn) {\r
-                    if (c & LLE) {        /* Is it start of LFN sequence? */\r
-                        sum = dir[LDIR_Chksum];\r
-                        c &= ~LLE; ord = c;    /* LFN start order */\r
-                        dj->lfn_idx = dj->index;\r
-        }\r
-                    /* Check validity of the LFN entry and compare it with given name */\r
-                    ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;\r
-            }\r
-            } else {                    /* An SFN entry is found */\r
-                if (!ord && sum == sum_sfn(dir)) break;    /* LFN matched? */\r
-                ord = 0xFF; dj->lfn_idx = 0xFFFF;    /* Reset LFN sequence */\r
-                if (!(dj->fn[NS] & NS_LOSS) && !mem_cmp(dir, dj->fn, 11)) break;    /* SFN matched? */\r
-            }\r
-        }\r
-#else        /* Non LFN configuration */\r
-        if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */\r
-            break;\r
-#endif\r
-        res = dir_next(dj, 0);        /* Next entry */\r
-    } while (res == FR_OK);\r
-\r
-    return res;\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Read an object from the directory                                     */\r
-/*-----------------------------------------------------------------------*/\r
-#if _FS_MINIMIZE <= 1\r
-static\r
-FRESULT dir_read (\r
-    DIR_t *dj            /* Pointer to the directory object that pointing the entry to be read */\r
-)\r
-{\r
-    FRESULT res;\r
-    BYTE c, *dir;\r
-#if _USE_LFN\r
-    BYTE a, ord = 0xFF, sum = 0xFF;\r
-#endif\r
-\r
-    res = FR_NO_FILE;\r
-    while (dj->sect) {\r
-        res = move_window(dj->fs, dj->sect);\r
-        if (res != FR_OK) break;\r
-        dir = dj->dir;                    /* Ptr to the directory entry of current index */\r
-        c = dir[DIR_Name];\r
-        if (c == 0) { res = FR_NO_FILE; break; }    /* Reached to end of table */\r
-#if _USE_LFN    /* LFN configuration */\r
-        a = dir[DIR_Attr] & AM_MASK;\r
-        if (c == DDE || (!_FS_RPATH && c == '.') || ((a & AM_VOL) && a != AM_LFN)) {    /* An entry without valid data */\r
-            ord = 0xFF;\r
-        } else {\r
-            if (a == AM_LFN) {            /* An LFN entry is found */\r
-                if (c & LLE) {            /* Is it start of LFN sequence? */\r
-                    sum = dir[LDIR_Chksum];\r
-                    c &= ~LLE; ord = c;\r
-                    dj->lfn_idx = dj->index;\r
-        }\r
-                /* Check LFN validity and capture it */\r
-                ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;\r
-            } else {                    /* An SFN entry is found */\r
-                if (ord || sum != sum_sfn(dir))    /* Is there a valid LFN? */\r
-                    dj->lfn_idx = 0xFFFF;        /* It has no LFN. */\r
-                break;\r
-        }\r
-            }\r
-#else        /* Non LFN configuration */\r
-        if (c != DDE && (_FS_RPATH || c != '.') && !(dir[DIR_Attr] & AM_VOL))    /* Is it a valid entry? */\r
-            break;\r
-#endif\r
-        res = dir_next(dj, 0);                /* Next entry */\r
-        if (res != FR_OK) break;\r
-        }\r
-\r
-    if (res != FR_OK) dj->sect = 0;\r
-\r
-    return res;\r
-    }\r
-#endif\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Register an object to the directory                                   */\r
-/*-----------------------------------------------------------------------*/\r
-#if !_FS_READONLY\r
-static\r
-FRESULT dir_register (    /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */\r
-    DIR_t *dj                /* Target directory with object name to be created */\r
-)\r
-{\r
-    FRESULT res;\r
-    BYTE c, *dir;\r
-#if _USE_LFN    /* LFN configuration */\r
-    WORD n, ne, is;\r
-    BYTE sn[12], *fn, sum;\r
-    WCHAR *lfn;\r
-\r
-\r
-    fn = dj->fn; lfn = dj->lfn;\r
-    mem_cpy(sn, fn, 12);\r
-\r
-    if (_FS_RPATH && (sn[NS] & NS_DOT))        /* Cannot create dot entry */\r
-        return FR_INVALID_NAME;\r
-\r
-    if (sn[NS] & NS_LOSS) {            /* When LFN is out of 8.3 format, generate a numbered name */\r
-        fn[NS] = 0; dj->lfn = 0;            /* Find only SFN */\r
-        for (n = 1; n < 100; n++) {\r
-            gen_numname(fn, sn, lfn, n);    /* Generate a numbered name */\r
-            res = dir_find(dj);                /* Check if the name collides with existing SFN */\r
-            if (res != FR_OK) break;\r
-        }\r
-        if (n == 100) return FR_DENIED;        /* Abort if too many collisions */\r
-        if (res != FR_NO_FILE) return res;    /* Abort if the result is other than 'not collided' */\r
-        fn[NS] = sn[NS]; dj->lfn = lfn;\r
-}\r
-\r
-    if (sn[NS] & NS_LFN) {            /* When LFN is to be created, reserve an SFN + LFN entries. */\r
-        for (ne = 0; lfn[ne]; ne++) ;\r
-        ne = (ne + 25) / 13;\r
-    } else {                        /* Otherwise reserve only an SFN entry. */\r
-        ne = 1;\r
-    }\r
-\r
-    /* Reserve contiguous entries */\r
-    res = dir_sdi(dj, 0);\r
-    if (res != FR_OK) return res;\r
-    n = is = 0;\r
-    do {\r
-        res = move_window(dj->fs, dj->sect);\r
-        if (res != FR_OK) break;\r
-        c = *dj->dir;                /* Check the entry status */\r
-        if (c == DDE || c == 0) {    /* Is it a blank entry? */\r
-            if (n == 0) is = dj->index;    /* First index of the contiguous entry */\r
-            if (++n == ne) break;    /* A contiguous entry that required count is found */\r
-        } else {\r
-            n = 0;                    /* Not a blank entry. Restart to search */\r
-        }\r
-        res = dir_next(dj, 1);        /* Next entry with table stretch */\r
-    } while (res == FR_OK);\r
-\r
-    if (res == FR_OK && ne > 1) {    /* Initialize LFN entry if needed */\r
-        res = dir_sdi(dj, is);\r
-        if (res == FR_OK) {\r
-            sum = sum_sfn(dj->fn);    /* Sum of the SFN tied to the LFN */\r
-            ne--;\r
-            do {                    /* Store LFN entries in bottom first */\r
-                res = move_window(dj->fs, dj->sect);\r
-                if (res != FR_OK) break;\r
-                fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum);\r
-                dj->fs->wflag = 1;\r
-                res = dir_next(dj, 0);    /* Next entry */\r
-            } while (res == FR_OK && --ne);\r
-        }\r
-    }\r
-\r
-#else    /* Non LFN configuration */\r
-    res = dir_sdi(dj, 0);\r
-    if (res == FR_OK) {\r
-        do {    /* Find a blank entry for the SFN */\r
-            res = move_window(dj->fs, dj->sect);\r
-            if (res != FR_OK) break;\r
-            c = *dj->dir;\r
-            if (c == DDE || c == 0) break;    /* Is it a blank entry? */\r
-            res = dir_next(dj, 1);            /* Next entry with table stretch */\r
-        } while (res == FR_OK);\r
-    }\r
-#endif\r
-\r
-    if (res == FR_OK) {        /* Initialize the SFN entry */\r
-        res = move_window(dj->fs, dj->sect);\r
-        if (res == FR_OK) {\r
-            dir = dj->dir;\r
-            mem_set(dir, 0, SZ_DIR);    /* Clean the entry */\r
-            mem_cpy(dir, dj->fn, 11);    /* Put SFN */\r
-#if _USE_LFN\r
-            dir[DIR_NTres] = *(dj->fn+NS) & (NS_BODY | NS_EXT);    /* Put NT flag */\r
-#endif\r
-            dj->fs->wflag = 1;\r
-        }\r
-    }\r
-\r
-    return res;\r
-}\r
-#endif /* !_FS_READONLY */\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Remove an object from the directory                                   */\r
-/*-----------------------------------------------------------------------*/\r
-#if !_FS_READONLY && !_FS_MINIMIZE\r
-static\r
-FRESULT dir_remove (    /* FR_OK: Successful, FR_DISK_ERR: A disk error */\r
-    DIR_t *dj                /* Directory object pointing the entry to be removed */\r
-)\r
-{\r
-    FRESULT res;\r
-#if _USE_LFN    /* LFN configuration */\r
-    WORD i;\r
-\r
-    i = dj->index;    /* SFN index */\r
-    res = dir_sdi(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx));    /* Goto the SFN or top of the LFN entries */\r
-    if (res == FR_OK) {\r
-        do {\r
-            res = move_window(dj->fs, dj->sect);\r
-            if (res != FR_OK) break;\r
-            *dj->dir = DDE;            /* Mark the entry "deleted" */\r
-            dj->fs->wflag = 1;\r
-            if (dj->index >= i) break;    /* When reached SFN, all entries of the object has been deleted. */\r
-            res = dir_next(dj, 0);        /* Next entry */\r
-        } while (res == FR_OK);\r
-        if (res == FR_NO_FILE) res = FR_INT_ERR;\r
-    }\r
-\r
-#else            /* Non LFN configuration */\r
-    res = dir_sdi(dj, dj->index);\r
-    if (res == FR_OK) {\r
-        res = move_window(dj->fs, dj->sect);\r
-        if (res == FR_OK) {\r
-            *dj->dir = DDE;            /* Mark the entry "deleted" */\r
-            dj->fs->wflag = 1;\r
-        }\r
-    }\r
-#endif\r
-\r
-    return res;\r
-}\r
-#endif /* !_FS_READONLY */\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Pick a segment and create the object name in directory form           */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-static\r
-FRESULT create_name (\r
-    DIR_t *dj,            /* Pointer to the directory object */\r
-    const TCHAR **path    /* Pointer to pointer to the segment in the path string */\r
-)\r
-{\r
-#ifdef _EXCVT\r
-    static const BYTE excvt[] = _EXCVT;    /* Upper conversion table for extended chars */\r
-#endif\r
-\r
-#if _USE_LFN    /* LFN configuration */\r
-    BYTE b, cf;\r
-    WCHAR w, *lfn;\r
-    UINT i, ni, si, di;\r
-    const TCHAR *p;\r
-\r
-    /* Create LFN in Unicode */\r
-    for (p = *path; *p == '/' || *p == '\\'; p++) ;    /* Strip duplicated separator */\r
-    lfn = dj->lfn;\r
-    si = di = 0;\r
-    for (;;) {\r
-        w = p[si++];                    /* Get a character */\r
-        if (w < ' ' || w == '/' || w == '\\') break;    /* Break on end of segment */\r
-        if (di >= _MAX_LFN)                /* Reject too long name */\r
-            return FR_INVALID_NAME;\r
-#if !_LFN_UNICODE\r
-        w &= 0xFF;\r
-        if (IsDBCS1(w)) {                /* Check if it is a DBC 1st byte (always false on SBCS cfg) */\r
-            b = (BYTE)p[si++];            /* Get 2nd byte */\r
-            if (!IsDBCS2(b))\r
-                return FR_INVALID_NAME;    /* Reject invalid sequence */\r
-            w = (w << 8) + b;            /* Create a DBC */\r
-        }\r
-        w = ff_convert(w, 1);            /* Convert ANSI/OEM to Unicode */\r
-        if (!w) return FR_INVALID_NAME;    /* Reject invalid code */\r
-#endif\r
-        if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal chars for LFN */\r
-            return FR_INVALID_NAME;\r
-        lfn[di++] = w;                    /* Store the Unicode char */\r
-    }\r
-    *path = &p[si];                        /* Return pointer to the next segment */\r
-    cf = (w < ' ') ? NS_LAST : 0;        /* Set last segment flag if end of path */\r
-#if _FS_RPATH\r
-    if ((di == 1 && lfn[di-1] == '.') || /* Is this a dot entry? */\r
-        (di == 2 && lfn[di-1] == '.' && lfn[di-2] == '.')) {\r
-        lfn[di] = 0;\r
-        for (i = 0; i < 11; i++)\r
-            dj->fn[i] = (i < di) ? '.' : ' ';\r
-        dj->fn[i] = cf | NS_DOT;        /* This is a dot entry */\r
-        return FR_OK;\r
-    }\r
-#endif\r
-    while (di) {                        /* Strip trailing spaces and dots */\r
-        w = lfn[di-1];\r
-        if (w != ' ' && w != '.') break;\r
-        di--;\r
-    }\r
-    if (!di) return FR_INVALID_NAME;    /* Reject nul string */\r
-\r
-    lfn[di] = 0;                        /* LFN is created */\r
-\r
-    /* Create SFN in directory form */\r
-    mem_set(dj->fn, ' ', 11);\r
-    for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ;    /* Strip leading spaces and dots */\r
-    if (si) cf |= NS_LOSS | NS_LFN;\r
-    while (di && lfn[di - 1] != '.') di--;    /* Find extension (di<=si: no extension) */\r
-\r
-    b = i = 0; ni = 8;\r
-    for (;;) {\r
-        w = lfn[si++];                    /* Get an LFN char */\r
-        if (!w) break;                    /* Break on end of the LFN */\r
-        if (w == ' ' || (w == '.' && si != di)) {    /* Remove spaces and dots */\r
-            cf |= NS_LOSS | NS_LFN; continue;\r
-        }\r
-\r
-        if (i >= ni || si == di) {        /* Extension or end of SFN */\r
-            if (ni == 11) {                /* Long extension */\r
-                cf |= NS_LOSS | NS_LFN; break;\r
-            }\r
-            if (si != di) cf |= NS_LOSS | NS_LFN;    /* Out of 8.3 format */\r
-            if (si > di) break;            /* No extension */\r
-            si = di; i = 8; ni = 11;    /* Enter extension section */\r
-            b <<= 2; continue;\r
-        }\r
-\r
-        if (w >= 0x80) {                /* Non ASCII char */\r
-#ifdef _EXCVT\r
-            w = ff_convert(w, 0);        /* Unicode -> OEM code */\r
-            if (w) w = excvt[w - 0x80];    /* Convert extended char to upper (SBCS) */\r
-#else\r
-            w = ff_convert(ff_wtoupper(w), 0);    /* Upper converted Unicode -> OEM code */\r
-#endif\r
-            cf |= NS_LFN;                /* Force create LFN entry */\r
-        }\r
-\r
-        if (_DF1S && w >= 0x100) {        /* Double byte char (always false on SBCS cfg) */\r
-            if (i >= ni - 1) {\r
-                cf |= NS_LOSS | NS_LFN; i = ni; continue;\r
-            }\r
-            dj->fn[i++] = (BYTE)(w >> 8);\r
-        } else {                        /* Single byte char */\r
-            if (!w || chk_chr("+,;=[]", w)) {    /* Replace illegal chars for SFN */\r
-                w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */\r
-            } else {\r
-                if (IsUpper(w)) {        /* ASCII large capital */\r
-                    b |= 2;\r
-    } else {\r
-                    if (IsLower(w)) {    /* ASCII small capital */\r
-                        b |= 1; w -= 0x20;\r
-    }\r
-                }\r
-            }\r
-        }\r
-        dj->fn[i++] = (BYTE)w;\r
-    }\r
-\r
-    if (dj->fn[0] == DDE) dj->fn[0] = NDDE;    /* If the first char collides with deleted mark, replace it with 0x05 */\r
-\r
-    if (ni == 8) b <<= 2;\r
-    if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03)    /* Create LFN entry when there are composite capitals */\r
-        cf |= NS_LFN;\r
-    if (!(cf & NS_LFN)) {                        /* When LFN is in 8.3 format without extended char, NT flags are created */\r
-        if ((b & 0x03) == 0x01) cf |= NS_EXT;    /* NT flag (Extension has only small capital) */\r
-        if ((b & 0x0C) == 0x04) cf |= NS_BODY;    /* NT flag (Filename has only small capital) */\r
-    }\r
-\r
-    dj->fn[NS] = cf;    /* SFN is created */\r
-\r
-    return FR_OK;\r
-\r
-\r
-#else    /* Non-LFN configuration */\r
-    BYTE b, c, d, *sfn;\r
-    UINT ni, si, i;\r
-    const char *p;\r
-\r
-    /* Create file name in directory form */\r
-    for (p = *path; *p == '/' || *p == '\\'; p++) ;    /* Strip duplicated separator */\r
-    sfn = dj->fn;\r
-    mem_set(sfn, ' ', 11);\r
-    si = i = b = 0; ni = 8;\r
-#if _FS_RPATH\r
-    if (p[si] == '.') { /* Is this a dot entry? */\r
-    for (;;) {\r
-            c = (BYTE)p[si++];\r
-            if (c != '.' || si >= 3) break;\r
-            sfn[i++] = c;\r
-        }\r
-        if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;\r
-        *path = &p[si];                                    /* Return pointer to the next segment */\r
-        sfn[NS] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT;    /* Set last segment flag if end of path */\r
-        return FR_OK;\r
-    }\r
-#endif\r
-        for (;;) {\r
-        c = (BYTE)p[si++];\r
-        if (c <= ' ' || c == '/' || c == '\\') break;    /* Break on end of segment */\r
-        if (c == '.' || i >= ni) {\r
-            if (ni != 8 || c != '.') return FR_INVALID_NAME;\r
-            i = 8; ni = 11;\r
-            b <<= 2; continue;\r
-        }\r
-        if (c >= 0x80) {                /* Extended char? */\r
-            b |= 3;                        /* Eliminate NT flag */\r
-#ifdef _EXCVT\r
-            c = excvt[c-0x80];            /* Upper conversion (SBCS) */\r
-#else\r
-#if !_DF1S    /* ASCII only cfg */\r
-            return FR_INVALID_NAME;\r
-#endif\r
-#endif\r
-        }\r
-        if (IsDBCS1(c)) {                /* Check if it is a DBC 1st byte (always false on SBCS cfg) */\r
-            d = (BYTE)p[si++];            /* Get 2nd byte */\r
-            if (!IsDBCS2(d) || i >= ni - 1)    /* Reject invalid DBC */\r
-                return FR_INVALID_NAME;\r
-            sfn[i++] = c;\r
-            sfn[i++] = d;\r
-        } else {                        /* Single byte code */\r
-            if (chk_chr("\"*+,:;<=>\?[]|\x7F", c))    /* Reject illegal chrs for SFN */\r
-                return FR_INVALID_NAME;\r
-            if (IsUpper(c)) {            /* ASCII large capital? */\r
-                b |= 2;\r
-            } else {\r
-                if (IsLower(c)) {        /* ASCII small capital? */\r
-                    b |= 1; c -= 0x20;\r
-                }\r
-            }\r
-            sfn[i++] = c;\r
-        }\r
-    }\r
-    *path = &p[si];                        /* Return pointer to the next segment */\r
-    c = (c <= ' ') ? NS_LAST : 0;        /* Set last segment flag if end of path */\r
-\r
-    if (!i) return FR_INVALID_NAME;        /* Reject nul string */\r
-    if (sfn[0] == DDE) sfn[0] = NDDE;    /* When first char collides with DDE, replace it with 0x05 */\r
-\r
-    if (ni == 8) b <<= 2;\r
-    if ((b & 0x03) == 0x01) c |= NS_EXT;    /* NT flag (Name extension has only small capital) */\r
-    if ((b & 0x0C) == 0x04) c |= NS_BODY;    /* NT flag (Name body has only small capital) */\r
-\r
-    sfn[NS] = c;        /* Store NT flag, File name is created */\r
-\r
-    return FR_OK;\r
-#endif\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Get file information from directory entry                             */\r
-/*-----------------------------------------------------------------------*/\r
-#if _FS_MINIMIZE <= 1\r
-static\r
-void get_fileinfo (        /* No return code */\r
-    DIR_t *dj,            /* Pointer to the directory object */\r
-    FILINFO *fno         /* Pointer to the file information to be filled */\r
-)\r
-{\r
-    UINT i;\r
-    BYTE nt, *dir;\r
-    TCHAR *p, c;\r
-    p = fno->fname;\r
+/*----------------------------------------------------------------------------/
+/  FatFs - FAT file system module  R0.08b                 (C)ChaN, 2011
+/-----------------------------------------------------------------------------/
+/ FatFs module is a generic FAT file system module for small embedded systems.
+/ This is a free software that opened for education, research and commercial
+/ developments under license policy of following terms.
+/
+/  Copyright (C) 2011, ChaN, all right reserved.
+/
+/ * The FatFs module is a free software and there is NO WARRANTY.
+/ * No restriction on use. You can use, modify and redistribute it for
+/   personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY.
+/ * Redistributions of source code must retain the above copyright notice.
+/
+/-----------------------------------------------------------------------------/
+/ Feb 26,'06 R0.00  Prototype.
+/
+/ Apr 29,'06 R0.01  First stable version.
+/
+/ Jun 01,'06 R0.02  Added FAT12 support.
+/                   Removed unbuffered mode.
+/                   Fixed a problem on small (<32M) partition.
+/ Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM).
+/
+/ Sep 22,'06 R0.03  Added f_rename().
+/                   Changed option _FS_MINIMUM to _FS_MINIMIZE.
+/ Dec 11,'06 R0.03a Improved cluster scan algorithm to write files fast.
+/                   Fixed f_mkdir() creates incorrect directory on FAT32.
+/
+/ Feb 04,'07 R0.04  Supported multiple drive system.
+/                   Changed some interfaces for multiple drive system.
+/                   Changed f_mountdrv() to f_mount().
+/                   Added f_mkfs().
+/ Apr 01,'07 R0.04a Supported multiple partitions on a physical drive.
+/                   Added a capability of extending file size to f_lseek().
+/                   Added minimization level 3.
+/                   Fixed an endian sensitive code in f_mkfs().
+/ May 05,'07 R0.04b Added a configuration option _USE_NTFLAG.
+/                   Added FSInfo support.
+/                   Fixed DBCS name can result FR_INVALID_NAME.
+/                   Fixed short seek (<= csize) collapses the file object.
+/
+/ Aug 25,'07 R0.05  Changed arguments of f_read(), f_write() and f_mkfs().
+/                   Fixed f_mkfs() on FAT32 creates incorrect FSInfo.
+/                   Fixed f_mkdir() on FAT32 creates incorrect directory.
+/ Feb 03,'08 R0.05a Added f_truncate() and f_utime().
+/                   Fixed off by one error at FAT sub-type determination.
+/                   Fixed btr in f_read() can be mistruncated.
+/                   Fixed cached sector is not flushed when create and close without write.
+/
+/ Apr 01,'08 R0.06  Added fputc(), fputs(), fprintf() and fgets().
+/                   Improved performance of f_lseek() on moving to the same or following cluster.
+/
+/ Apr 01,'09 R0.07  Merged Tiny-FatFs as a configuration option. (_FS_TINY)
+/                   Added long file name feature.
+/                   Added multiple code page feature.
+/                   Added re-entrancy for multitask operation.
+/                   Added auto cluster size selection to f_mkfs().
+/                   Added rewind option to f_readdir().
+/                   Changed result code of critical errors.
+/                   Renamed string functions to avoid name collision.
+/ Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg.
+/                   Added multiple sector size feature.
+/ Jun 21,'09 R0.07c Fixed f_unlink() can return FR_OK on error.
+/                   Fixed wrong cache control in f_lseek().
+/                   Added relative path feature.
+/                   Added f_chdir() and f_chdrive().
+/                   Added proper case conversion to extended char.
+/ Nov 03,'09 R0.07e Separated out configuration options from ff.h to ffconf.h.
+/                   Fixed f_unlink() fails to remove a sub-dir on _FS_RPATH.
+/                   Fixed name matching error on the 13 char boundary.
+/                   Added a configuration option, _LFN_UNICODE.
+/                   Changed f_readdir() to return the SFN with always upper case on non-LFN cfg.
+/
+/ May 15,'10 R0.08  Added a memory configuration option. (_USE_LFN = 3)
+/                   Added file lock feature. (_FS_SHARE)
+/                   Added fast seek feature. (_USE_FASTSEEK)
+/                   Changed some types on the API, XCHAR->TCHAR.
+/                   Changed fname member in the FILINFO structure on Unicode cfg.
+/                   String functions support UTF-8 encoding files on Unicode cfg.
+/ Aug 16,'10 R0.08a Added f_getcwd(). (_FS_RPATH = 2)
+/                   Added sector erase feature. (_USE_ERASE)
+/                   Moved file lock semaphore table from fs object to the bss.
+/                   Fixed a wrong directory entry is created on non-LFN cfg when the given name contains ';'.
+/                   Fixed f_mkfs() creates wrong FAT32 volume.
+/ Jan 15,'11 R0.08b Fast seek feature is also applied to f_read() and f_write().
+/                   f_lseek() reports required table size on creating CLMP.
+/                   Extended format syntax of f_printf function.
+/                   Ignores duplicated directory separators in given path names.
+/---------------------------------------------------------------------------*/
+\r
+#include "ff.h"            /* FatFs configurations and declarations */
+#include "diskio.h"        /* Declarations of low level disk I/O functions */
+#include "mbed.h"
+\r
+\r
+/*--------------------------------------------------------------------------
+\r
+   Module Private Definitions
+\r
+---------------------------------------------------------------------------*/
+\r
+#if _FATFS != 8237
+#error Wrong include file (ff.h).
+#endif
+\r
+\r
+/* Definitions on sector size */
+#if _MAX_SS != 512 && _MAX_SS != 1024 && _MAX_SS != 2048 && _MAX_SS != 4096
+#error Wrong sector size.
+#endif
+#if _MAX_SS != 512
+#define    SS(fs)    ((fs)->ssize)    /* Multiple sector size */
+#else
+#define    SS(fs)    512U            /* Fixed sector size */
+#endif
+\r
+\r
+/* Reentrancy related */
+#if _FS_REENTRANT
+#if _USE_LFN == 1
+#error Static LFN work area must not be used in re-entrant configuration.
+#endif
+#define    ENTER_FF(fs)        { if (!lock_fs(fs)) return FR_TIMEOUT; }
+#define    LEAVE_FF(fs, res)    { unlock_fs(fs, res); return res; }
+#else
+#define    ENTER_FF(fs)
+#define LEAVE_FF(fs, res)    return res
+#endif
+\r
+#define    ABORT(fs, res)        { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); }
+\r
+\r
+/* File shareing feature */
+#if _FS_SHARE
+#if _FS_READONLY
+#error _FS_SHARE must be 0 on read-only cfg.
+#endif
+typedef struct {
+    FATFS *fs;                /* File ID 1, volume (NULL:blank entry) */
+    DWORD clu;                /* File ID 2, directory */
+    WORD idx;                /* File ID 3, directory index */
+    WORD ctr;                /* File open counter, 0:none, 0x01..0xFF:read open count, 0x100:write mode */
+} FILESEM;
+#endif
+\r
+\r
+/* Misc definitions */
+#define LD_CLUST(dir)    (((DWORD)LD_WORD(dir+DIR_FstClusHI)<<16) | LD_WORD(dir+DIR_FstClusLO))
+#define ST_CLUST(dir,cl) {ST_WORD(dir+DIR_FstClusLO, cl); ST_WORD(dir+DIR_FstClusHI, (DWORD)cl>>16);}
+\r
+\r
+/* DBCS code ranges and SBCS extend char conversion table */
+\r
+#if _CODE_PAGE == 932    /* Japanese Shift-JIS */
+#define _DF1S    0x81    /* DBC 1st byte range 1 start */
+#define _DF1E    0x9F    /* DBC 1st byte range 1 end */
+#define _DF2S    0xE0    /* DBC 1st byte range 2 start */
+#define _DF2E    0xFC    /* DBC 1st byte range 2 end */
+#define _DS1S    0x40    /* DBC 2nd byte range 1 start */
+#define _DS1E    0x7E    /* DBC 2nd byte range 1 end */
+#define _DS2S    0x80    /* DBC 2nd byte range 2 start */
+#define _DS2E    0xFC    /* DBC 2nd byte range 2 end */
+\r
+#elif _CODE_PAGE == 936    /* Simplified Chinese GBK */
+#define _DF1S    0x81
+#define _DF1E    0xFE
+#define _DS1S    0x40
+#define _DS1E    0x7E
+#define _DS2S    0x80
+#define _DS2E    0xFE
+\r
+#elif _CODE_PAGE == 949    /* Korean */
+#define _DF1S    0x81
+#define _DF1E    0xFE
+#define _DS1S    0x41
+#define _DS1E    0x5A
+#define _DS2S    0x61
+#define _DS2E    0x7A
+#define _DS3S    0x81
+#define _DS3E    0xFE
+\r
+#elif _CODE_PAGE == 950    /* Traditional Chinese Big5 */
+#define _DF1S    0x81
+#define _DF1E    0xFE
+#define _DS1S    0x40
+#define _DS1E    0x7E
+#define _DS2S    0xA1
+#define _DS2E    0xFE
+\r
+#elif _CODE_PAGE == 437    /* U.S. (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F,0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
+                0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 720    /* Arabic (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x45,0x41,0x84,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x49,0x49,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
+                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 737    /* Greek (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \
+                0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xE7,0xE8,0xF1,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 775    /* Baltic (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
+                0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 850    /* Multilingual Latin 1 (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
+                0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 852    /* Latin 2 (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F,0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0x9F, \
+                0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 855    /* Cyrillic (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F,0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \
+                0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \
+                0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 857    /* Turkish (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x98,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \
+                0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0x59,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 858    /* Multilingual Latin 1 + Euro (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \
+                0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 862    /* Hebrew (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
+                0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 866    /* Russian (OEM) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
+                0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 874    /* Thai (OEM, Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
+                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 1250 /* Central Europe (Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
+                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xA3,0xB4,0xB5,0xB6,0xB7,0xB8,0xA5,0xAA,0xBB,0xBC,0xBD,0xBC,0xAF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
+\r
+#elif _CODE_PAGE == 1251 /* Cyrillic (Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x80,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \
+                0xA0,0xA2,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB2,0xA5,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xA3,0xBD,0xBD,0xAF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF}
+\r
+#elif _CODE_PAGE == 1252 /* Latin 1 (Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0xAd,0x9B,0x8C,0x9D,0xAE,0x9F, \
+                0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
+\r
+#elif _CODE_PAGE == 1253 /* Greek (Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
+                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xA2,0xB8,0xB9,0xBA, \
+                0xE0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xFB,0xBC,0xFD,0xBF,0xFF}
+\r
+#elif _CODE_PAGE == 1254 /* Turkish (Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x9D,0x9E,0x9F, \
+                0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F}
+\r
+#elif _CODE_PAGE == 1255 /* Hebrew (Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
+                0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 1256 /* Arabic (Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x8C,0x9D,0x9E,0x9F, \
+                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0x41,0xE1,0x41,0xE3,0xE4,0xE5,0xE6,0x43,0x45,0x45,0x45,0x45,0xEC,0xED,0x49,0x49,0xF0,0xF1,0xF2,0xF3,0x4F,0xF5,0xF6,0xF7,0xF8,0x55,0xFA,0x55,0x55,0xFD,0xFE,0xFF}
+\r
+#elif _CODE_PAGE == 1257 /* Baltic (Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \
+                0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xBC,0xBD,0xBE,0xAF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF}
+\r
+#elif _CODE_PAGE == 1258 /* Vietnam (OEM, Windows) */
+#define _DF1S    0
+#define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0xAC,0x9D,0x9E,0x9F, \
+                0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \
+                0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xEC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xFE,0x9F}
+\r
+#elif _CODE_PAGE == 1    /* ASCII (for only non-LFN cfg) */
+#if _USE_LFN
+#error Cannot use LFN feature without valid code page.
+#endif
+#define _DF1S    0
+\r
+#else
+#error Unknown code page
+\r
+#endif
+\r
+\r
+/* Character code support macros */
+#define IsUpper(c)    (((c)>='A')&&((c)<='Z'))
+#define IsLower(c)    (((c)>='a')&&((c)<='z'))
+#define IsDigit(c)    (((c)>='0')&&((c)<='9'))
+\r
+#if _DF1S        /* Code page is DBCS */
+\r
+#ifdef _DF2S    /* Two 1st byte areas */
+#define IsDBCS1(c)    (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E))
+#else            /* One 1st byte area */
+#define IsDBCS1(c)    ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E)
+#endif
+\r
+#ifdef _DS3S    /* Three 2nd byte areas */
+#define IsDBCS2(c)    (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E))
+#else            /* Two 2nd byte areas */
+#define IsDBCS2(c)    (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E))
+#endif
+\r
+#else            /* Code page is SBCS */
+\r
+#define IsDBCS1(c)    0
+#define IsDBCS2(c)    0
+\r
+#endif /* _DF1S */
+\r
+\r
+/* Name status flags */
+#define NS            11        /* Index of name status byte in fn[] */
+#define NS_LOSS        0x01    /* Out of 8.3 format */
+#define NS_LFN        0x02    /* Force to create LFN entry */
+#define NS_LAST        0x04    /* Last segment */
+#define NS_BODY        0x08    /* Lower case flag (body) */
+#define NS_EXT        0x10    /* Lower case flag (ext) */
+#define NS_DOT        0x20    /* Dot entry */
+\r
+\r
+/* FAT sub-type boundaries */
+/* Note that the FAT spec by Microsoft says 4085 but Windows works with 4087! */
+#define MIN_FAT16    4086    /* Minimum number of clusters for FAT16 */
+#define    MIN_FAT32    65526    /* Minimum number of clusters for FAT32 */
+\r
+\r
+/* FatFs refers the members in the FAT structures as byte array instead of
+/ structure member because the structure is not binary compatible between
+/ different platforms */
+\r
+#define BS_jmpBoot            0    /* Jump instruction (3) */
+#define BS_OEMName            3    /* OEM name (8) */
+#define BPB_BytsPerSec        11    /* Sector size [byte] (2) */
+#define BPB_SecPerClus        13    /* Cluster size [sector] (1) */
+#define BPB_RsvdSecCnt        14    /* Size of reserved area [sector] (2) */
+#define BPB_NumFATs            16    /* Number of FAT copies (1) */
+#define BPB_RootEntCnt        17    /* Number of root dir entries for FAT12/16 (2) */
+#define BPB_TotSec16        19    /* Volume size [sector] (2) */
+#define BPB_Media            21    /* Media descriptor (1) */
+#define BPB_FATSz16            22    /* FAT size [sector] (2) */
+#define BPB_SecPerTrk        24    /* Track size [sector] (2) */
+#define BPB_NumHeads        26    /* Number of heads (2) */
+#define BPB_HiddSec            28    /* Number of special hidden sectors (4) */
+#define BPB_TotSec32        32    /* Volume size [sector] (4) */
+#define BS_DrvNum            36    /* Physical drive number (2) */
+#define BS_BootSig            38    /* Extended boot signature (1) */
+#define BS_VolID            39    /* Volume serial number (4) */
+#define BS_VolLab            43    /* Volume label (8) */
+#define BS_FilSysType        54    /* File system type (1) */
+#define BPB_FATSz32            36    /* FAT size [sector] (4) */
+#define BPB_ExtFlags        40    /* Extended flags (2) */
+#define BPB_FSVer            42    /* File system version (2) */
+#define BPB_RootClus        44    /* Root dir first cluster (4) */
+#define BPB_FSInfo            48    /* Offset of FSInfo sector (2) */
+#define BPB_BkBootSec        50    /* Offset of backup boot sectot (2) */
+#define BS_DrvNum32            64    /* Physical drive number (2) */
+#define BS_BootSig32        66    /* Extended boot signature (1) */
+#define BS_VolID32            67    /* Volume serial number (4) */
+#define BS_VolLab32            71    /* Volume label (8) */
+#define BS_FilSysType32        82    /* File system type (1) */
+#define    FSI_LeadSig            0    /* FSI: Leading signature (4) */
+#define    FSI_StrucSig        484    /* FSI: Structure signature (4) */
+#define    FSI_Free_Count        488    /* FSI: Number of free clusters (4) */
+#define    FSI_Nxt_Free        492    /* FSI: Last allocated cluster (4) */
+#define MBR_Table            446    /* MBR: Partition table offset (2) */
+#define    SZ_PTE                16    /* MBR: Size of a partition table entry */
+#define BS_55AA                510    /* Boot sector signature (2) */
+\r
+#define    DIR_Name            0    /* Short file name (11) */
+#define    DIR_Attr            11    /* Attribute (1) */
+#define    DIR_NTres            12    /* NT flag (1) */
+#define    DIR_CrtTime            14    /* Created time (2) */
+#define    DIR_CrtDate            16    /* Created date (2) */
+#define    DIR_FstClusHI        20    /* Higher 16-bit of first cluster (2) */
+#define    DIR_WrtTime            22    /* Modified time (2) */
+#define    DIR_WrtDate            24    /* Modified date (2) */
+#define    DIR_FstClusLO        26    /* Lower 16-bit of first cluster (2) */
+#define    DIR_FileSize        28    /* File size (4) */
+#define    LDIR_Ord            0    /* LFN entry order and LLE flag (1) */
+#define    LDIR_Attr            11    /* LFN attribute (1) */
+#define    LDIR_Type            12    /* LFN type (1) */
+#define    LDIR_Chksum            13    /* Sum of corresponding SFN entry */
+#define    LDIR_FstClusLO        26    /* Filled by zero (0) */
+#define    SZ_DIR                32        /* Size of a directory entry */
+#define    LLE                    0x40    /* Last long entry flag in LDIR_Ord */
+#define    DDE                    0xE5    /* Deleted directory enrty mark in DIR_Name[0] */
+#define    NDDE                0x05    /* Replacement of a character collides with DDE */
+\r
+\r
+/*------------------------------------------------------------*/
+/* Work area                                                  */
+\r
+#if _VOLUMES
+static
+FATFS *FatFs[_VOLUMES];    /* Pointer to the file system objects (logical drives) */
+#else
+#error Number of drives must not be 0.
+#endif
+\r
+static
+WORD Fsid;                /* File system mount ID */
+\r
+#if _FS_RPATH
+static
+BYTE CurrVol;            /* Current drive */
+#endif
+\r
+#if _FS_SHARE
+static
+FILESEM    Files[_FS_SHARE];    /* File lock semaphores */
+#endif
+\r
+#if _USE_LFN == 0            /* No LFN */
+#define    DEF_NAMEBUF            BYTE sfn[12]
+#define INIT_BUF(dobj)        (dobj).fn = sfn
+#define    FREE_BUF()
+\r
+#elif _USE_LFN == 1            /* LFN with static LFN working buffer */
+static WCHAR LfnBuf[_MAX_LFN+1];
+#define    DEF_NAMEBUF            BYTE sfn[12]
+#define INIT_BUF(dobj)        { (dobj).fn = sfn; (dobj).lfn = LfnBuf; }
+#define    FREE_BUF()
+\r
+#elif _USE_LFN == 2         /* LFN with dynamic LFN working buffer on the stack */
+#define    DEF_NAMEBUF            BYTE sfn[12]; WCHAR lbuf[_MAX_LFN+1]
+#define INIT_BUF(dobj)        { (dobj).fn = sfn; (dobj).lfn = lbuf; }
+#define    FREE_BUF()
+\r
+#elif _USE_LFN == 3         /* LFN with dynamic LFN working buffer on the heap */
+#define    DEF_NAMEBUF            BYTE sfn[12]; WCHAR *lfn
+#define INIT_BUF(dobj)        { lfn = ff_memalloc((_MAX_LFN + 1) * 2); \
+                              if (!lfn) LEAVE_FF((dobj).fs, FR_NOT_ENOUGH_CORE); \
+                              (dobj).lfn = lfn;    (dobj).fn = sfn; }
+#define    FREE_BUF()            ff_memfree(lfn)
+\r
+#else
+#error Wrong LFN configuration.
+#endif
+\r
+\r
+\r
+\r
+/*--------------------------------------------------------------------------
+\r
+   Module Private Functions
+\r
+---------------------------------------------------------------------------*/
+\r
+//static FATFS *FatFs[_DRIVES];    /* Pointer to the file system objects (logical drives) */
+//static WORD fsid;                /* File system mount ID */
+\r
+/*-----------------------------------------------------------------------*/
+/* String functions                                                      */
+/*-----------------------------------------------------------------------*/
+\r
+/* Copy memory to memory */
+static
+void mem_cpy (void* dst, const void* src, UINT cnt) {
+    BYTE *d = (BYTE*)dst;
+    const BYTE *s = (const BYTE*)src;
+\r
+#if _WORD_ACCESS == 1
+    while (cnt >= sizeof(int)) {
+        *(int*)d = *(int*)s;
+        d += sizeof(int); s += sizeof(int);
+        cnt -= sizeof(int);
+    }
+#endif
+    while (cnt--)
+        *d++ = *s++;
+}
+\r
+/* Fill memory */
+static
+void mem_set (void* dst, int val, UINT cnt) {
+    BYTE *d = (BYTE*)dst;
+\r
+    while (cnt--)
+        *d++ = (BYTE)val;
+}
+\r
+/* Compare memory to memory */
+static
+int mem_cmp (const void* dst, const void* src, UINT cnt) {
+    const BYTE *d = (const BYTE *)dst, *s = (const BYTE *)src;
+    int r = 0;
+\r
+    while (cnt-- && (r = *d++ - *s++) == 0) ;
+    return r;
+}
+\r
+/* Check if chr is contained in the string */
+static
+int chk_chr (const char* str, int chr) {
+    while (*str && *str != chr) str++;
+    return *str;
+}
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Request/Release grant to access the volume                            */
+/*-----------------------------------------------------------------------*/
+#if _FS_REENTRANT
+\r
+static
+int lock_fs (
+    FATFS *fs        /* File system object */
+)
+{
+    return ff_req_grant(fs->sobj);
+}
+\r
+\r
+static
+void unlock_fs (
+    FATFS *fs,        /* File system object */
+    FRESULT res        /* Result code to be returned */
+)
+{
+    if (res != FR_NOT_ENABLED &&
+        res != FR_INVALID_DRIVE &&
+        res != FR_INVALID_OBJECT &&
+        res != FR_TIMEOUT) {
+        ff_rel_grant(fs->sobj);
+    }
+}
+#endif
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* File shareing control functions                                       */
+/*-----------------------------------------------------------------------*/
+#if _FS_SHARE
+\r
+static
+FRESULT chk_lock (    /* Check if the file can be accessed */
+    DIR* dj,        /* Directory object pointing the file to be checked */
+    int acc            /* Desired access (0:Read, 1:Write, 2:Delete/Rename) */
+)
+{
+    UINT i, be;
+\r
+    /* Search file semaphore table */
+    for (i = be = 0; i < _FS_SHARE; i++) {
+        if (Files[i].fs) {    /* Existing entry */
+            if (Files[i].fs == dj->fs &&         /* Check if the file matched with an open file */
+                Files[i].clu == dj->sclust &&
+                Files[i].idx == dj->index) break;
+        } else {            /* Blank entry */
+            be++;
+        }
+    }
+    if (i == _FS_SHARE)    /* The file is not opened */
+        return (be || acc == 2) ? FR_OK : FR_TOO_MANY_OPEN_FILES;    /* Is there a blank entry for new file? */
+\r
+    /* The file has been opened. Reject any open against writing file and all write mode open */
+    return (acc || Files[i].ctr == 0x100) ? FR_LOCKED : FR_OK;
+}
+\r
+\r
+static
+int enq_lock (    /* Check if an entry is available for a new file */
+    FATFS* fs    /* File system object */
+)
+{
+    UINT i;
+\r
+    for (i = 0; i < _FS_SHARE && Files[i].fs; i++) ;
+    return (i == _FS_SHARE) ? 0 : 1;
+}
+\r
+\r
+static
+UINT inc_lock (    /* Increment file open counter and returns its index (0:int error) */
+    DIR* dj,    /* Directory object pointing the file to register or increment */
+    int acc        /* Desired access mode (0:Read, !0:Write) */
+)
+{
+    UINT i;
+\r
+\r
+    for (i = 0; i < _FS_SHARE; i++) {    /* Find the file */
+        if (Files[i].fs == dj->fs &&
+            Files[i].clu == dj->sclust &&
+            Files[i].idx == dj->index) break;
+    }
+\r
+    if (i == _FS_SHARE) {                /* Not opened. Register it as new. */
+        for (i = 0; i < _FS_SHARE && Files[i].fs; i++) ;
+        if (i == _FS_SHARE) return 0;    /* No space to register (int err) */
+        Files[i].fs = dj->fs;
+        Files[i].clu = dj->sclust;
+        Files[i].idx = dj->index;
+        Files[i].ctr = 0;
+    }
+\r
+    if (acc && Files[i].ctr) return 0;    /* Access violation (int err) */
+\r
+    Files[i].ctr = acc ? 0x100 : Files[i].ctr + 1;    /* Set semaphore value */
+\r
+    return i + 1;
+}
+\r
+\r
+static
+FRESULT dec_lock (    /* Decrement file open counter */
+    UINT i            /* Semaphore index */
+)
+{
+    WORD n;
+    FRESULT res;
+\r
+\r
+    if (--i < _FS_SHARE) {
+        n = Files[i].ctr;
+        if (n == 0x100) n = 0;
+        if (n) n--;
+        Files[i].ctr = n;
+        if (!n) Files[i].fs = 0;
+        res = FR_OK;
+    } else {
+        res = FR_INT_ERR;
+    }
+    return res;
+}
+\r
+\r
+static
+void clear_lock (    /* Clear lock entries of the volume */
+    FATFS *fs
+)
+{
+    UINT i;
+\r
+    for (i = 0; i < _FS_SHARE; i++) {
+        if (Files[i].fs == fs) Files[i].fs = 0;
+    }
+}
+#endif
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Change window offset                                                  */
+/*-----------------------------------------------------------------------*/
+\r
+static
+FRESULT move_window (
+    FATFS *fs,        /* File system object */
+    DWORD sector    /* Sector number to make appearance in the fs->win[] */
+)                    /* Move to zero only writes back dirty window */
+{
+    DWORD wsect;
+\r
+\r
+    wsect = fs->winsect;
+    if (wsect != sector) {    /* Changed current window */
+#if !_FS_READONLY
+        if (fs->wflag) {    /* Write back dirty window if needed */
+            if (disk_write(fs->drv, fs->win, wsect, 1) != RES_OK)
+                return FR_DISK_ERR;
+            fs->wflag = 0;
+            if (wsect < (fs->fatbase + fs->fsize)) {    /* In FAT area */
+                BYTE nf;
+                for (nf = fs->n_fats; nf > 1; nf--) {    /* Reflect the change to all FAT copies */
+                    wsect += fs->fsize;
+                    disk_write(fs->drv, fs->win, wsect, 1);
+                }
+            }
+        }
+#endif
+        if (sector) {
+            if (disk_read(fs->drv, fs->win, sector, 1) != RES_OK)
+                return FR_DISK_ERR;
+            fs->winsect = sector;
+        }
+    }
+\r
+    return FR_OK;
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Clean-up cached data                                                  */
+/*-----------------------------------------------------------------------*/
+#if !_FS_READONLY
+static
+FRESULT sync (    /* FR_OK: successful, FR_DISK_ERR: failed */
+    FATFS *fs    /* File system object */
+)
+{
+    FRESULT res;
+\r
+\r
+    res = move_window(fs, 0);
+    if (res == FR_OK) {
+    /* Update FSInfo sector if needed */
+    if (fs->fs_type == FS_FAT32 && fs->fsi_flag) {
+        fs->winsect = 0;
+            /* Create FSInfo structure */
+            mem_set(fs->win, 0, 512);
+            ST_WORD(fs->win+BS_55AA, 0xAA55);
+            ST_DWORD(fs->win+FSI_LeadSig, 0x41615252);
+            ST_DWORD(fs->win+FSI_StrucSig, 0x61417272);
+            ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust);
+            ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust);
+            /* Write it into the FSInfo sector */
+            disk_write(fs->drv, fs->win, fs->fsi_sector, 1);
+        fs->fsi_flag = 0;
+    }
+    /* Make sure that no pending write process in the physical drive */
+        if (disk_ioctl(fs->drv, CTRL_SYNC, (void*)0) != RES_OK)
+            res = FR_DISK_ERR;
+    }
+\r
+    return res;
+}
+#endif
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Get sector# from cluster#                                             */
+/*-----------------------------------------------------------------------*/
+\r
+\r
+DWORD clust2sect (    /* !=0: Sector number, 0: Failed - invalid cluster# */
+    FATFS *fs,        /* File system object */
+    DWORD clst        /* Cluster# to be converted */
+)
+{
+    clst -= 2;
+    if (clst >= (fs->n_fatent - 2)) return 0;        /* Invalid cluster# */
+    return clst * fs->csize + fs->database;
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* FAT access - Read value of a FAT entry                                */
+/*-----------------------------------------------------------------------*/
+\r
+\r
+DWORD get_fat (    /* 0xFFFFFFFF:Disk error, 1:Internal error, Else:Cluster status */
+    FATFS *fs,        /* File system object */
+    DWORD clst    /* Cluster# to get the link information */
+)
+{
+    UINT wc, bc;
+    BYTE *p;
+\r
+\r
+    if (clst < 2 || clst >= fs->n_fatent)    /* Chack range */
+        return 1;
+\r
+        switch (fs->fs_type) {
+        case FS_FAT12 :
+        bc = (UINT)clst; bc += bc / 2;
+        if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;
+        wc = fs->win[bc % SS(fs)]; bc++;
+        if (move_window(fs, fs->fatbase + (bc / SS(fs)))) break;
+        wc |= fs->win[bc % SS(fs)] << 8;
+        return (clst & 1) ? (wc >> 4) : (wc & 0xFFF);
+\r
+        case FS_FAT16 :
+        if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)))) break;
+        p = &fs->win[clst * 2 % SS(fs)];
+        return LD_WORD(p);
+\r
+        case FS_FAT32 :
+        if (move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)))) break;
+        p = &fs->win[clst * 4 % SS(fs)];
+        return LD_DWORD(p) & 0x0FFFFFFF;
+    }
+\r
+    return 0xFFFFFFFF;    /* An error occurred at the disk I/O layer */
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* FAT access - Change value of a FAT entry                              */
+/*-----------------------------------------------------------------------*/
+#if !_FS_READONLY
+\r
+FRESULT put_fat (
+    FATFS *fs,        /* File system object */
+    DWORD clst,    /* Cluster# to be changed in range of 2 to fs->n_fatent - 1 */
+    DWORD val        /* New value to mark the cluster */
+)
+{
+    UINT bc;
+    BYTE *p;
+    FRESULT res;
+\r
+\r
+    if (clst < 2 || clst >= fs->n_fatent) {    /* Check range */
+        res = FR_INT_ERR;
+\r
+    } else {
+    switch (fs->fs_type) {
+    case FS_FAT12 :
+            bc = clst; bc += bc / 2;
+            res = move_window(fs, fs->fatbase + (bc / SS(fs)));
+            if (res != FR_OK) break;
+            p = &fs->win[bc % SS(fs)];
+            *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val;
+        bc++;
+            fs->wflag = 1;
+            res = move_window(fs, fs->fatbase + (bc / SS(fs)));
+            if (res != FR_OK) break;
+            p = &fs->win[bc % SS(fs)];
+            *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F));
+        break;
+\r
+    case FS_FAT16 :
+            res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 2)));
+            if (res != FR_OK) break;
+            p = &fs->win[clst * 2 % SS(fs)];
+            ST_WORD(p, (WORD)val);
+        break;
+\r
+    case FS_FAT32 :
+            res = move_window(fs, fs->fatbase + (clst / (SS(fs) / 4)));
+            if (res != FR_OK) break;
+            p = &fs->win[clst * 4 % SS(fs)];
+            val |= LD_DWORD(p) & 0xF0000000;
+            ST_DWORD(p, val);
+        break;
+\r
+    default :
+            res = FR_INT_ERR;
+    }
+        fs->wflag = 1;
+    }
+\r
+    return res;
+}
+#endif /* !_FS_READONLY */
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* FAT handling - Remove a cluster chain                                 */
+/*-----------------------------------------------------------------------*/
+#if !_FS_READONLY
+static
+FRESULT remove_chain (
+    FATFS *fs,        /* File system object */
+    DWORD clst            /* Cluster# to remove a chain from */
+)
+{
+    FRESULT res;
+    DWORD nxt;
+#if _USE_ERASE
+    DWORD scl = clst, ecl = clst, resion[2];
+#endif
+\r
+    if (clst < 2 || clst >= fs->n_fatent) {    /* Check range */
+        res = FR_INT_ERR;
+\r
+    } else {
+        res = FR_OK;
+        while (clst < fs->n_fatent) {            /* Not a last link? */
+            nxt = get_fat(fs, clst);            /* Get cluster status */
+            if (nxt == 0) break;                /* Empty cluster? */
+            if (nxt == 1) { res = FR_INT_ERR; break; }    /* Internal error? */
+            if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }    /* Disk error? */
+            res = put_fat(fs, clst, 0);            /* Mark the cluster "empty" */
+            if (res != FR_OK) break;
+            if (fs->free_clust != 0xFFFFFFFF) {    /* Update FSInfo */
+            fs->free_clust++;
+            fs->fsi_flag = 1;
+            }
+#if _USE_ERASE
+            if (ecl + 1 == nxt) {    /* Next cluster is contiguous */
+                ecl = nxt;
+            } else {                /* End of contiguous clusters */
+                resion[0] = clust2sect(fs, scl);                    /* Start sector */
+                resion[1] = clust2sect(fs, ecl) + fs->csize - 1;    /* End sector */
+                disk_ioctl(fs->drv, CTRL_ERASE_SECTOR, resion);        /* Erase the block */
+                scl = ecl = nxt;
+            }
+#endif
+            clst = nxt;    /* Next cluster */
+        }
+    }
+\r
+    return res;
+}
+#endif
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* FAT handling - Stretch or Create a cluster chain                      */
+/*-----------------------------------------------------------------------*/
+#if !_FS_READONLY
+static
+DWORD create_chain (    /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */
+    FATFS *fs,            /* File system object */
+    DWORD clst            /* Cluster# to stretch. 0 means create a new chain. */
+)
+{
+    DWORD cs, ncl, scl;
+    FRESULT res;
+\r
+\r
+    if (clst == 0) {        /* Create a new chain */
+        scl = fs->last_clust;            /* Get suggested start point */
+        if (!scl || scl >= fs->n_fatent) scl = 1;
+    }
+    else {                    /* Stretch the current chain */
+        cs = get_fat(fs, clst);            /* Check the cluster status */
+        if (cs < 2) return 1;            /* It is an invalid cluster */
+        if (cs < fs->n_fatent) return cs;    /* It is already followed by next cluster */
+        scl = clst;
+    }
+\r
+    ncl = scl;                /* Start cluster */
+    for (;;) {
+        ncl++;                            /* Next cluster */
+        if (ncl >= fs->n_fatent) {        /* Wrap around */
+            ncl = 2;
+            if (ncl > scl) return 0;    /* No free cluster */
+        }
+        cs = get_fat(fs, ncl);            /* Get the cluster status */
+        if (cs == 0) break;                /* Found a free cluster */
+        if (cs == 0xFFFFFFFF || cs == 1)/* An error occurred */
+            return cs;
+        if (ncl == scl) return 0;        /* No free cluster */
+    }
+\r
+    res = put_fat(fs, ncl, 0x0FFFFFFF);    /* Mark the new cluster "last link" */
+    if (res == FR_OK && clst != 0) {
+        res = put_fat(fs, clst, ncl);    /* Link it to the previous one if needed */
+    }
+    if (res == FR_OK) {
+        fs->last_clust = ncl;            /* Update FSINFO */
+    if (fs->free_clust != 0xFFFFFFFF) {
+        fs->free_clust--;
+        fs->fsi_flag = 1;
+        }
+    } else {
+        ncl = (res == FR_DISK_ERR) ? 0xFFFFFFFF : 1;
+    }
+\r
+    return ncl;        /* Return new cluster number or error code */
+}
+#endif /* !_FS_READONLY */
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* FAT handling - Convert offset into cluster with link map table        */
+/*-----------------------------------------------------------------------*/
+\r
+#if _USE_FASTSEEK
+static
+DWORD clmt_clust (    /* <2:Error, >=2:Cluster number */
+    FIL* fp,        /* Pointer to the file object */
+    DWORD ofs        /* File offset to be converted to cluster# */
+)
+{
+    DWORD cl, ncl, *tbl;
+\r
+\r
+    tbl = fp->cltbl + 1;    /* Top of CLMT */
+    cl = ofs / SS(fp->fs) / fp->fs->csize;    /* Cluster order from top of the file */
+    for (;;) {
+        ncl = *tbl++;            /* Number of cluters in the fragment */
+        if (!ncl) return 0;        /* End of table? (error) */
+        if (cl < ncl) break;    /* In this fragment? */
+        cl -= ncl; tbl++;        /* Next fragment */
+    }
+    return cl + *tbl;    /* Return the cluster number */
+}
+#endif    /* _USE_FASTSEEK */
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Directory handling - Set directory index                              */
+/*-----------------------------------------------------------------------*/
+\r
+static
+FRESULT dir_sdi (
+    DIR_t *dj,        /* Pointer to directory object */
+    WORD idx        /* Directory index number */
+)
+{
+    DWORD clst;
+    WORD ic;
+\r
+\r
+    dj->index = idx;
+    clst = dj->sclust;
+    if (clst == 1 || clst >= dj->fs->n_fatent)    /* Check start cluster range */
+        return FR_INT_ERR;
+    if (!clst && dj->fs->fs_type == FS_FAT32)    /* Replace cluster# 0 with root cluster# if in FAT32 */
+        clst = dj->fs->dirbase;
+\r
+    if (clst == 0) {    /* Static table (root-dir in FAT12/16) */
+        dj->clust = clst;
+        if (idx >= dj->fs->n_rootdir)        /* Index is out of range */
+            return FR_INT_ERR;
+        dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / SZ_DIR);    /* Sector# */
+    }
+    else {                /* Dynamic table (sub-dirs or root-dir in FAT32) */
+        ic = SS(dj->fs) / SZ_DIR * dj->fs->csize;    /* Entries per cluster */
+        while (idx >= ic) {    /* Follow cluster chain */
+            clst = get_fat(dj->fs, clst);                /* Get next cluster */
+            if (clst == 0xFFFFFFFF) return FR_DISK_ERR;    /* Disk error */
+            if (clst < 2 || clst >= dj->fs->n_fatent)    /* Reached to end of table or int error */
+                return FR_INT_ERR;
+            idx -= ic;
+        }
+        dj->clust = clst;
+        dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / SZ_DIR);    /* Sector# */
+    }
+\r
+    dj->dir = dj->fs->win + (idx % (SS(dj->fs) / SZ_DIR)) * SZ_DIR;    /* Ptr to the entry in the sector */
+\r
+    return FR_OK;    /* Seek succeeded */
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Directory handling - Move directory index next                        */
+/*-----------------------------------------------------------------------*/
+\r
+static
+FRESULT dir_next (    /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not stretch */
+    DIR_t *dj,        /* Pointer to directory object */
+    int stretch        /* 0: Do not stretch table, 1: Stretch table if needed */
+)
+{
+    DWORD clst;
+    WORD i;
+\r
+\r
+    i = dj->index + 1;
+    if (!i || !dj->sect)    /* Report EOT when index has reached 65535 */
+        return FR_NO_FILE;
+\r
+    if (!(i % (SS(dj->fs) / SZ_DIR))) {    /* Sector changed? */
+        dj->sect++;                /* Next sector */
+\r
+        if (dj->clust == 0) {    /* Static table */
+            if (i >= dj->fs->n_rootdir)    /* Report EOT when end of table */
+                return FR_NO_FILE;
+        }
+        else {                    /* Dynamic table */
+            if (((i / (SS(dj->fs) / SZ_DIR)) & (dj->fs->csize - 1)) == 0) {    /* Cluster changed? */
+                clst = get_fat(dj->fs, dj->clust);                /* Get next cluster */
+                if (clst <= 1) return FR_INT_ERR;
+                if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
+                if (clst >= dj->fs->n_fatent) {                    /* When it reached end of dynamic table */
+#if !_FS_READONLY
+                    BYTE c;
+                    if (!stretch) return FR_NO_FILE;            /* When do not stretch, report EOT */
+                    clst = create_chain(dj->fs, dj->clust);        /* Stretch cluster chain */
+                    if (clst == 0) return FR_DENIED;            /* No free cluster */
+                    if (clst == 1) return FR_INT_ERR;
+                    if (clst == 0xFFFFFFFF) return FR_DISK_ERR;
+                    /* Clean-up stretched table */
+                    if (move_window(dj->fs, 0)) return FR_DISK_ERR;    /* Flush active window */
+                    mem_set(dj->fs->win, 0, SS(dj->fs));            /* Clear window buffer */
+                    dj->fs->winsect = clust2sect(dj->fs, clst);    /* Cluster start sector */
+                    for (c = 0; c < dj->fs->csize; c++) {        /* Fill the new cluster with 0 */
+                        dj->fs->wflag = 1;
+                        if (move_window(dj->fs, 0)) return FR_DISK_ERR;
+                        dj->fs->winsect++;
+                    }
+                    dj->fs->winsect -= c;                        /* Rewind window address */
+#else
+                    return FR_NO_FILE;            /* Report EOT */
+#endif
+            }
+                dj->clust = clst;                /* Initialize data for new cluster */
+                dj->sect = clust2sect(dj->fs, clst);
+        }
+    }
+    }
+\r
+    dj->index = i;
+    dj->dir = dj->fs->win + (i % (SS(dj->fs) / SZ_DIR)) * SZ_DIR;
+\r
+    return FR_OK;
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry   */
+/*-----------------------------------------------------------------------*/
+#if _USE_LFN
+static
+const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30};    /* Offset of LFN chars in the directory entry */
+\r
+\r
+static
+int cmp_lfn (            /* 1:Matched, 0:Not matched */
+    WCHAR *lfnbuf,        /* Pointer to the LFN to be compared */
+    BYTE *dir            /* Pointer to the directory entry containing a part of LFN */
+)
+{
+    UINT i, s;
+    WCHAR wc, uc;
+\r
+\r
+    i = ((dir[LDIR_Ord] & ~LLE) - 1) * 13;    /* Get offset in the LFN buffer */
+    s = 0; wc = 1;
+    do {
+        uc = LD_WORD(dir+LfnOfs[s]);    /* Pick an LFN character from the entry */
+        if (wc) {    /* Last char has not been processed */
+            wc = ff_wtoupper(uc);        /* Convert it to upper case */
+            if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++]))    /* Compare it */
+                return 0;                /* Not matched */
+        } else {
+            if (uc != 0xFFFF) return 0;    /* Check filler */
+    }
+    } while (++s < 13);                /* Repeat until all chars in the entry are checked */
+\r
+    if ((dir[LDIR_Ord] & LLE) && wc && lfnbuf[i])    /* Last segment matched but different length */
+        return 0;
+\r
+    return 1;                        /* The part of LFN matched */
+        }
+\r
+\r
+\r
+static
+int pick_lfn (            /* 1:Succeeded, 0:Buffer overflow */
+    WCHAR *lfnbuf,        /* Pointer to the Unicode-LFN buffer */
+    BYTE *dir            /* Pointer to the directory entry */
+)
+{
+    UINT i, s;
+    WCHAR wc, uc;
+\r
+\r
+    i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13;    /* Offset in the LFN buffer */
+\r
+    s = 0; wc = 1;
+    do {
+        uc = LD_WORD(dir+LfnOfs[s]);        /* Pick an LFN character from the entry */
+        if (wc) {    /* Last char has not been processed */
+            if (i >= _MAX_LFN) return 0;    /* Buffer overflow? */
+            lfnbuf[i++] = wc = uc;            /* Store it */
+        } else {
+            if (uc != 0xFFFF) return 0;        /* Check filler */
+    }
+    } while (++s < 13);                        /* Read all character in the entry */
+\r
+    if (dir[LDIR_Ord] & LLE) {                /* Put terminator if it is the last LFN part */
+        if (i >= _MAX_LFN) return 0;        /* Buffer overflow? */
+        lfnbuf[i] = 0;
+}
+\r
+    return 1;
+}
+\r
+\r
+#if !_FS_READONLY
+static
+void fit_lfn (
+    const WCHAR *lfnbuf,    /* Pointer to the LFN buffer */
+    BYTE *dir,                /* Pointer to the directory entry */
+    BYTE ord,                /* LFN order (1-20) */
+    BYTE sum                /* SFN sum */
+)
+{
+    UINT i, s;
+    WCHAR wc;
+\r
+\r
+    dir[LDIR_Chksum] = sum;            /* Set check sum */
+    dir[LDIR_Attr] = AM_LFN;        /* Set attribute. LFN entry */
+    dir[LDIR_Type] = 0;
+    ST_WORD(dir+LDIR_FstClusLO, 0);
+\r
+    i = (ord - 1) * 13;                /* Get offset in the LFN buffer */
+    s = wc = 0;
+    do {
+        if (wc != 0xFFFF) wc = lfnbuf[i++];    /* Get an effective char */
+        ST_WORD(dir+LfnOfs[s], wc);    /* Put it */
+        if (!wc) wc = 0xFFFF;        /* Padding chars following last char */
+    } while (++s < 13);
+    if (wc == 0xFFFF || !lfnbuf[i]) ord |= LLE;    /* Bottom LFN part is the start of LFN sequence */
+    dir[LDIR_Ord] = ord;            /* Set the LFN order */
+}
+\r
+#endif
+#endif
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Create numbered name                                                  */
+/*-----------------------------------------------------------------------*/
+#if _USE_LFN
+void gen_numname (
+    BYTE *dst,            /* Pointer to generated SFN */
+    const BYTE *src,    /* Pointer to source SFN to be modified */
+    const WCHAR *lfn,    /* Pointer to LFN */
+    WORD seq            /* Sequence number */
+)
+{
+    BYTE ns[8], c;
+    UINT i, j;
+\r
+\r
+    mem_cpy(dst, src, 11);
+\r
+    if (seq > 5) {    /* On many collisions, generate a hash number instead of sequential number */
+        do seq = (seq >> 1) + (seq << 15) + (WORD)*lfn++; while (*lfn);
+    }
+\r
+    /* itoa (hexdecimal) */
+    i = 7;
+    do {
+        c = (seq % 16) + '0';
+        if (c > '9') c += 7;
+        ns[i--] = c;
+        seq /= 16;
+    } while (seq);
+    ns[i] = '~';
+\r
+    /* Append the number */
+    for (j = 0; j < i && dst[j] != ' '; j++) {
+        if (IsDBCS1(dst[j])) {
+            if (j == i - 1) break;
+            j++;
+        }
+    }
+    do {
+        dst[j++] = (i < 8) ? ns[i++] : ' ';
+    } while (j < 8);
+}
+#endif
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Calculate sum of an SFN                                               */
+/*-----------------------------------------------------------------------*/
+#if _USE_LFN
+static
+BYTE sum_sfn (
+    const BYTE *dir        /* Ptr to directory entry */
+)
+{
+    BYTE sum = 0;
+    UINT n = 11;
+\r
+    do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n);
+    return sum;
+}
+#endif
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Directory handling - Find an object in the directory                  */
+/*-----------------------------------------------------------------------*/
+\r
+static
+FRESULT dir_find (
+    DIR_t *dj            /* Pointer to the directory object linked to the file name */
+)
+{
+    FRESULT res;
+    BYTE c, *dir;
+#if _USE_LFN
+    BYTE a, ord, sum;
+#endif
+\r
+    res = dir_sdi(dj, 0);            /* Rewind directory object */
+    if (res != FR_OK) return res;
+\r
+#if _USE_LFN
+    ord = sum = 0xFF;
+#endif
+    do {
+        res = move_window(dj->fs, dj->sect);
+        if (res != FR_OK) break;
+        dir = dj->dir;                    /* Ptr to the directory entry of current index */
+        c = dir[DIR_Name];
+        if (c == 0) { res = FR_NO_FILE; break; }    /* Reached to end of table */
+#if _USE_LFN    /* LFN configuration */
+        a = dir[DIR_Attr] & AM_MASK;
+        if (c == DDE || ((a & AM_VOL) && a != AM_LFN)) {    /* An entry without valid data */
+            ord = 0xFF;
+        } else {
+            if (a == AM_LFN) {            /* An LFN entry is found */
+                if (dj->lfn) {
+                    if (c & LLE) {        /* Is it start of LFN sequence? */
+                        sum = dir[LDIR_Chksum];
+                        c &= ~LLE; ord = c;    /* LFN start order */
+                        dj->lfn_idx = dj->index;
+        }
+                    /* Check validity of the LFN entry and compare it with given name */
+                    ord = (c == ord && sum == dir[LDIR_Chksum] && cmp_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
+            }
+            } else {                    /* An SFN entry is found */
+                if (!ord && sum == sum_sfn(dir)) break;    /* LFN matched? */
+                ord = 0xFF; dj->lfn_idx = 0xFFFF;    /* Reset LFN sequence */
+                if (!(dj->fn[NS] & NS_LOSS) && !mem_cmp(dir, dj->fn, 11)) break;    /* SFN matched? */
+            }
+        }
+#else        /* Non LFN configuration */
+        if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */
+            break;
+#endif
+        res = dir_next(dj, 0);        /* Next entry */
+    } while (res == FR_OK);
+\r
+    return res;
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Read an object from the directory                                     */
+/*-----------------------------------------------------------------------*/
+#if _FS_MINIMIZE <= 1
+static
+FRESULT dir_read (
+    DIR_t *dj            /* Pointer to the directory object that pointing the entry to be read */
+)
+{
+    FRESULT res;
+    BYTE c, *dir;
+#if _USE_LFN
+    BYTE a, ord = 0xFF, sum = 0xFF;
+#endif
+\r
+    res = FR_NO_FILE;
+    while (dj->sect) {
+        res = move_window(dj->fs, dj->sect);
+        if (res != FR_OK) break;
+        dir = dj->dir;                    /* Ptr to the directory entry of current index */
+        c = dir[DIR_Name];
+        if (c == 0) { res = FR_NO_FILE; break; }    /* Reached to end of table */
+#if _USE_LFN    /* LFN configuration */
+        a = dir[DIR_Attr] & AM_MASK;
+        if (c == DDE || (!_FS_RPATH && c == '.') || ((a & AM_VOL) && a != AM_LFN)) {    /* An entry without valid data */
+            ord = 0xFF;
+        } else {
+            if (a == AM_LFN) {            /* An LFN entry is found */
+                if (c & LLE) {            /* Is it start of LFN sequence? */
+                    sum = dir[LDIR_Chksum];
+                    c &= ~LLE; ord = c;
+                    dj->lfn_idx = dj->index;
+        }
+                /* Check LFN validity and capture it */
+                ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF;
+            } else {                    /* An SFN entry is found */
+                if (ord || sum != sum_sfn(dir))    /* Is there a valid LFN? */
+                    dj->lfn_idx = 0xFFFF;        /* It has no LFN. */
+                break;
+        }
+            }
+#else        /* Non LFN configuration */
+        if (c != DDE && (_FS_RPATH || c != '.') && !(dir[DIR_Attr] & AM_VOL))    /* Is it a valid entry? */
+            break;
+#endif
+        res = dir_next(dj, 0);                /* Next entry */
+        if (res != FR_OK) break;
+        }
+\r
+    if (res != FR_OK) dj->sect = 0;
+\r
+    return res;
+    }
+#endif
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Register an object to the directory                                   */
+/*-----------------------------------------------------------------------*/
+#if !_FS_READONLY
+static
+FRESULT dir_register (    /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */
+    DIR_t *dj                /* Target directory with object name to be created */
+)
+{
+    FRESULT res;
+    BYTE c, *dir;
+#if _USE_LFN    /* LFN configuration */
+    WORD n, ne, is;
+    BYTE sn[12], *fn, sum;
+    WCHAR *lfn;
+\r
+\r
+    fn = dj->fn; lfn = dj->lfn;
+    mem_cpy(sn, fn, 12);
+\r
+    if (_FS_RPATH && (sn[NS] & NS_DOT))        /* Cannot create dot entry */
+        return FR_INVALID_NAME;
+\r
+    if (sn[NS] & NS_LOSS) {            /* When LFN is out of 8.3 format, generate a numbered name */
+        fn[NS] = 0; dj->lfn = 0;            /* Find only SFN */
+        for (n = 1; n < 100; n++) {
+            gen_numname(fn, sn, lfn, n);    /* Generate a numbered name */
+            res = dir_find(dj);                /* Check if the name collides with existing SFN */
+            if (res != FR_OK) break;
+        }
+        if (n == 100) return FR_DENIED;        /* Abort if too many collisions */
+        if (res != FR_NO_FILE) return res;    /* Abort if the result is other than 'not collided' */
+        fn[NS] = sn[NS]; dj->lfn = lfn;
+}
+\r
+    if (sn[NS] & NS_LFN) {            /* When LFN is to be created, reserve an SFN + LFN entries. */
+        for (ne = 0; lfn[ne]; ne++) ;
+        ne = (ne + 25) / 13;
+    } else {                        /* Otherwise reserve only an SFN entry. */
+        ne = 1;
+    }
+\r
+    /* Reserve contiguous entries */
+    res = dir_sdi(dj, 0);
+    if (res != FR_OK) return res;
+    n = is = 0;
+    do {
+        res = move_window(dj->fs, dj->sect);
+        if (res != FR_OK) break;
+        c = *dj->dir;                /* Check the entry status */
+        if (c == DDE || c == 0) {    /* Is it a blank entry? */
+            if (n == 0) is = dj->index;    /* First index of the contiguous entry */
+            if (++n == ne) break;    /* A contiguous entry that required count is found */
+        } else {
+            n = 0;                    /* Not a blank entry. Restart to search */
+        }
+        res = dir_next(dj, 1);        /* Next entry with table stretch */
+    } while (res == FR_OK);
+\r
+    if (res == FR_OK && ne > 1) {    /* Initialize LFN entry if needed */
+        res = dir_sdi(dj, is);
+        if (res == FR_OK) {
+            sum = sum_sfn(dj->fn);    /* Sum of the SFN tied to the LFN */
+            ne--;
+            do {                    /* Store LFN entries in bottom first */
+                res = move_window(dj->fs, dj->sect);
+                if (res != FR_OK) break;
+                fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum);
+                dj->fs->wflag = 1;
+                res = dir_next(dj, 0);    /* Next entry */
+            } while (res == FR_OK && --ne);
+        }
+    }
+\r
+#else    /* Non LFN configuration */
+    res = dir_sdi(dj, 0);
+    if (res == FR_OK) {
+        do {    /* Find a blank entry for the SFN */
+            res = move_window(dj->fs, dj->sect);
+            if (res != FR_OK) break;
+            c = *dj->dir;
+            if (c == DDE || c == 0) break;    /* Is it a blank entry? */
+            res = dir_next(dj, 1);            /* Next entry with table stretch */
+        } while (res == FR_OK);
+    }
+#endif
+\r
+    if (res == FR_OK) {        /* Initialize the SFN entry */
+        res = move_window(dj->fs, dj->sect);
+        if (res == FR_OK) {
+            dir = dj->dir;
+            mem_set(dir, 0, SZ_DIR);    /* Clean the entry */
+            mem_cpy(dir, dj->fn, 11);    /* Put SFN */
+#if _USE_LFN
+            dir[DIR_NTres] = *(dj->fn+NS) & (NS_BODY | NS_EXT);    /* Put NT flag */
+#endif
+            dj->fs->wflag = 1;
+        }
+    }
+\r
+    return res;
+}
+#endif /* !_FS_READONLY */
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Remove an object from the directory                                   */
+/*-----------------------------------------------------------------------*/
+#if !_FS_READONLY && !_FS_MINIMIZE
+static
+FRESULT dir_remove (    /* FR_OK: Successful, FR_DISK_ERR: A disk error */
+    DIR_t *dj                /* Directory object pointing the entry to be removed */
+)
+{
+    FRESULT res;
+#if _USE_LFN    /* LFN configuration */
+    WORD i;
+\r
+    i = dj->index;    /* SFN index */
+    res = dir_sdi(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx));    /* Goto the SFN or top of the LFN entries */
+    if (res == FR_OK) {
+        do {
+            res = move_window(dj->fs, dj->sect);
+            if (res != FR_OK) break;
+            *dj->dir = DDE;            /* Mark the entry "deleted" */
+            dj->fs->wflag = 1;
+            if (dj->index >= i) break;    /* When reached SFN, all entries of the object has been deleted. */
+            res = dir_next(dj, 0);        /* Next entry */
+        } while (res == FR_OK);
+        if (res == FR_NO_FILE) res = FR_INT_ERR;
+    }
+\r
+#else            /* Non LFN configuration */
+    res = dir_sdi(dj, dj->index);
+    if (res == FR_OK) {
+        res = move_window(dj->fs, dj->sect);
+        if (res == FR_OK) {
+            *dj->dir = DDE;            /* Mark the entry "deleted" */
+            dj->fs->wflag = 1;
+        }
+    }
+#endif
+\r
+    return res;
+}
+#endif /* !_FS_READONLY */
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Pick a segment and create the object name in directory form           */
+/*-----------------------------------------------------------------------*/
+\r
+static
+FRESULT create_name (
+    DIR_t *dj,            /* Pointer to the directory object */
+    const TCHAR **path    /* Pointer to pointer to the segment in the path string */
+)
+{
+#ifdef _EXCVT
+    static const BYTE excvt[] = _EXCVT;    /* Upper conversion table for extended chars */
+#endif
+\r
+#if _USE_LFN    /* LFN configuration */
+    BYTE b, cf;
+    WCHAR w, *lfn;
+    UINT i, ni, si, di;
+    const TCHAR *p;
+\r
+    /* Create LFN in Unicode */
+    for (p = *path; *p == '/' || *p == '\\'; p++) ;    /* Strip duplicated separator */
+    lfn = dj->lfn;
+    si = di = 0;
+    for (;;) {
+        w = p[si++];                    /* Get a character */
+        if (w < ' ' || w == '/' || w == '\\') break;    /* Break on end of segment */
+        if (di >= _MAX_LFN)                /* Reject too long name */
+            return FR_INVALID_NAME;
+#if !_LFN_UNICODE
+        w &= 0xFF;
+        if (IsDBCS1(w)) {                /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
+            b = (BYTE)p[si++];            /* Get 2nd byte */
+            if (!IsDBCS2(b))
+                return FR_INVALID_NAME;    /* Reject invalid sequence */
+            w = (w << 8) + b;            /* Create a DBC */
+        }
+        w = ff_convert(w, 1);            /* Convert ANSI/OEM to Unicode */
+        if (!w) return FR_INVALID_NAME;    /* Reject invalid code */
+#endif
+        if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject illegal chars for LFN */
+            return FR_INVALID_NAME;
+        lfn[di++] = w;                    /* Store the Unicode char */
+    }
+    *path = &p[si];                        /* Return pointer to the next segment */
+    cf = (w < ' ') ? NS_LAST : 0;        /* Set last segment flag if end of path */
+#if _FS_RPATH
+    if ((di == 1 && lfn[di-1] == '.') || /* Is this a dot entry? */
+        (di == 2 && lfn[di-1] == '.' && lfn[di-2] == '.')) {
+        lfn[di] = 0;
+        for (i = 0; i < 11; i++)
+            dj->fn[i] = (i < di) ? '.' : ' ';
+        dj->fn[i] = cf | NS_DOT;        /* This is a dot entry */
+        return FR_OK;
+    }
+#endif
+    while (di) {                        /* Strip trailing spaces and dots */
+        w = lfn[di-1];
+        if (w != ' ' && w != '.') break;
+        di--;
+    }
+    if (!di) return FR_INVALID_NAME;    /* Reject nul string */
+\r
+    lfn[di] = 0;                        /* LFN is created */
+\r
+    /* Create SFN in directory form */
+    mem_set(dj->fn, ' ', 11);
+    for (si = 0; lfn[si] == ' ' || lfn[si] == '.'; si++) ;    /* Strip leading spaces and dots */
+    if (si) cf |= NS_LOSS | NS_LFN;
+    while (di && lfn[di - 1] != '.') di--;    /* Find extension (di<=si: no extension) */
+\r
+    b = i = 0; ni = 8;
+    for (;;) {
+        w = lfn[si++];                    /* Get an LFN char */
+        if (!w) break;                    /* Break on end of the LFN */
+        if (w == ' ' || (w == '.' && si != di)) {    /* Remove spaces and dots */
+            cf |= NS_LOSS | NS_LFN; continue;
+        }
+\r
+        if (i >= ni || si == di) {        /* Extension or end of SFN */
+            if (ni == 11) {                /* Long extension */
+                cf |= NS_LOSS | NS_LFN; break;
+            }
+            if (si != di) cf |= NS_LOSS | NS_LFN;    /* Out of 8.3 format */
+            if (si > di) break;            /* No extension */
+            si = di; i = 8; ni = 11;    /* Enter extension section */
+            b <<= 2; continue;
+        }
+\r
+        if (w >= 0x80) {                /* Non ASCII char */
+#ifdef _EXCVT
+            w = ff_convert(w, 0);        /* Unicode -> OEM code */
+            if (w) w = excvt[w - 0x80];    /* Convert extended char to upper (SBCS) */
+#else
+            w = ff_convert(ff_wtoupper(w), 0);    /* Upper converted Unicode -> OEM code */
+#endif
+            cf |= NS_LFN;                /* Force create LFN entry */
+        }
+\r
+        if (_DF1S && w >= 0x100) {        /* Double byte char (always false on SBCS cfg) */
+            if (i >= ni - 1) {
+                cf |= NS_LOSS | NS_LFN; i = ni; continue;
+            }
+            dj->fn[i++] = (BYTE)(w >> 8);
+        } else {                        /* Single byte char */
+            if (!w || chk_chr("+,;=[]", w)) {    /* Replace illegal chars for SFN */
+                w = '_'; cf |= NS_LOSS | NS_LFN;/* Lossy conversion */
+            } else {
+                if (IsUpper(w)) {        /* ASCII large capital */
+                    b |= 2;
+    } else {
+                    if (IsLower(w)) {    /* ASCII small capital */
+                        b |= 1; w -= 0x20;
+    }
+                }
+            }
+        }
+        dj->fn[i++] = (BYTE)w;
+    }
+\r
+    if (dj->fn[0] == DDE) dj->fn[0] = NDDE;    /* If the first char collides with deleted mark, replace it with 0x05 */
+\r
+    if (ni == 8) b <<= 2;
+    if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03)    /* Create LFN entry when there are composite capitals */
+        cf |= NS_LFN;
+    if (!(cf & NS_LFN)) {                        /* When LFN is in 8.3 format without extended char, NT flags are created */
+        if ((b & 0x03) == 0x01) cf |= NS_EXT;    /* NT flag (Extension has only small capital) */
+        if ((b & 0x0C) == 0x04) cf |= NS_BODY;    /* NT flag (Filename has only small capital) */
+    }
+\r
+    dj->fn[NS] = cf;    /* SFN is created */
+\r
+    return FR_OK;
+\r
+\r
+#else    /* Non-LFN configuration */
+    BYTE b, c, d, *sfn;
+    UINT ni, si, i;
+    const char *p;
+\r
+    /* Create file name in directory form */
+    for (p = *path; *p == '/' || *p == '\\'; p++) ;    /* Strip duplicated separator */
+    sfn = dj->fn;
+    mem_set(sfn, ' ', 11);
+    si = i = b = 0; ni = 8;
+#if _FS_RPATH
+    if (p[si] == '.') { /* Is this a dot entry? */
+    for (;;) {
+            c = (BYTE)p[si++];
+            if (c != '.' || si >= 3) break;
+            sfn[i++] = c;
+        }
+        if (c != '/' && c != '\\' && c > ' ') return FR_INVALID_NAME;
+        *path = &p[si];                                    /* Return pointer to the next segment */
+        sfn[NS] = (c <= ' ') ? NS_LAST | NS_DOT : NS_DOT;    /* Set last segment flag if end of path */
+        return FR_OK;
+    }
+#endif
+        for (;;) {
+        c = (BYTE)p[si++];
+        if (c <= ' ' || c == '/' || c == '\\') break;    /* Break on end of segment */
+        if (c == '.' || i >= ni) {
+            if (ni != 8 || c != '.') return FR_INVALID_NAME;
+            i = 8; ni = 11;
+            b <<= 2; continue;
+        }
+        if (c >= 0x80) {                /* Extended char? */
+            b |= 3;                        /* Eliminate NT flag */
+#ifdef _EXCVT
+            c = excvt[c-0x80];            /* Upper conversion (SBCS) */
+#else
+#if !_DF1S    /* ASCII only cfg */
+            return FR_INVALID_NAME;
+#endif
+#endif
+        }
+        if (IsDBCS1(c)) {                /* Check if it is a DBC 1st byte (always false on SBCS cfg) */
+            d = (BYTE)p[si++];            /* Get 2nd byte */
+            if (!IsDBCS2(d) || i >= ni - 1)    /* Reject invalid DBC */
+                return FR_INVALID_NAME;
+            sfn[i++] = c;
+            sfn[i++] = d;
+        } else {                        /* Single byte code */
+            if (chk_chr("\"*+,:;<=>\?[]|\x7F", c))    /* Reject illegal chrs for SFN */
+                return FR_INVALID_NAME;
+            if (IsUpper(c)) {            /* ASCII large capital? */
+                b |= 2;
+            } else {
+                if (IsLower(c)) {        /* ASCII small capital? */
+                    b |= 1; c -= 0x20;
+                }
+            }
+            sfn[i++] = c;
+        }
+    }
+    *path = &p[si];                        /* Return pointer to the next segment */
+    c = (c <= ' ') ? NS_LAST : 0;        /* Set last segment flag if end of path */
+\r
+    if (!i) return FR_INVALID_NAME;        /* Reject nul string */
+    if (sfn[0] == DDE) sfn[0] = NDDE;    /* When first char collides with DDE, replace it with 0x05 */
+\r
+    if (ni == 8) b <<= 2;
+    if ((b & 0x03) == 0x01) c |= NS_EXT;    /* NT flag (Name extension has only small capital) */
+    if ((b & 0x0C) == 0x04) c |= NS_BODY;    /* NT flag (Name body has only small capital) */
+\r
+    sfn[NS] = c;        /* Store NT flag, File name is created */
+\r
+    return FR_OK;
+#endif
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Get file information from directory entry                             */
+/*-----------------------------------------------------------------------*/
+#if _FS_MINIMIZE <= 1
+static
+void get_fileinfo (        /* No return code */
+    DIR_t *dj,            /* Pointer to the directory object */
+    FILINFO *fno         /* Pointer to the file information to be filled */
+)
+{
+    UINT i;
+    BYTE nt, *dir;
+    TCHAR *p, c;
+    p = fno->fname;
     \r
-    if (dj->sect) {\r
-        dir = dj->dir;\r
-        nt = dir[DIR_NTres];        /* NT flag */\r
-        for (i = 0; i < 8; i++) {    /* Copy name body */\r
-            c = dir[i];\r
-            if (c == ' ') break;\r
-            if (c == NDDE) c = (TCHAR)DDE;\r
-            if (_USE_LFN && (nt & NS_BODY) && IsUpper(c)) c += 0x20;\r
-#if _LFN_UNICODE\r
-            if (IsDBCS1(c) && i < 7 && IsDBCS2(dir[i+1]))\r
-                c = (c << 8) | dir[++i];\r
-            c = ff_convert(c, 1);\r
-            if (!c) c = '?';\r
-#endif\r
-            *p++ = c;\r
-        }\r
-        if (dir[8] != ' ') {        /* Copy name extension */\r
-            *p++ = '.';\r
-            for (i = 8; i < 11; i++) {\r
-                c = dir[i];\r
-                if (c == ' ') break;\r
-                if (_USE_LFN && (nt & NS_EXT) && IsUpper(c)) c += 0x20;\r
-#if _LFN_UNICODE\r
-                if (IsDBCS1(c) && i < 10 && IsDBCS2(dir[i+1]))\r
-                    c = (c << 8) | dir[++i];\r
-                c = ff_convert(c, 1);\r
-                if (!c) c = '?';\r
-#endif\r
-                *p++ = c;\r
-            }\r
-    }\r
-        fno->fattrib = dir[DIR_Attr];                /* Attribute */\r
-        fno->fsize = LD_DWORD(dir+DIR_FileSize);    /* Size */\r
-        fno->fdate = LD_WORD(dir+DIR_WrtDate);        /* Date */\r
-        fno->ftime = LD_WORD(dir+DIR_WrtTime);        /* Time */\r
-    }\r
-    *p = 0;        /* Terminate SFN str by a \0 */\r
-\r
-#if _USE_LFN\r
-    if (fno->lfname && fno->lfsize) {\r
-        TCHAR *tp = fno->lfname;\r
-        WCHAR w, *lfn;\r
-\r
-        i = 0;\r
-        if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */\r
-            lfn = dj->lfn;\r
-            while ((w = *lfn++) != 0) {            /* Get an LFN char */\r
-#if !_LFN_UNICODE\r
-                w = ff_convert(w, 0);            /* Unicode -> OEM conversion */\r
-                if (!w) { i = 0; break; }        /* Could not convert, no LFN */\r
-                if (_DF1S && w >= 0x100)        /* Put 1st byte if it is a DBC (always false on SBCS cfg) */\r
-                    tp[i++] = (TCHAR)(w >> 8);\r
-#endif\r
-                if (i >= fno->lfsize - 1) { i = 0; break; }    /* Buffer overflow, no LFN */\r
-                tp[i++] = (TCHAR)w;\r
-            }\r
-\r
-        }\r
-        tp[i] = 0;    /* Terminate the LFN str by a \0 */\r
-    }\r
-#endif\r
-}\r
-#endif /* _FS_MINIMIZE <= 1 */\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Follow a file path                                                    */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-static\r
-FRESULT follow_path (    /* FR_OK(0): successful, !=0: error code */\r
-    DIR_t *dj,            /* Directory object to return last directory and found object */\r
-    const TCHAR *path    /* Full-path string to find a file or directory */\r
-)\r
-{\r
-    FRESULT res;\r
-    BYTE *dir, ns;\r
-\r
-\r
-#if _FS_RPATH\r
-    if (*path == '/' || *path == '\\') { /* There is a heading separator */\r
-        path++;    dj->sclust = 0;        /* Strip it and start from the root dir */\r
-    } else {                            /* No heading separator */\r
-        dj->sclust = dj->fs->cdir;    /* Start from the current dir */\r
-    }\r
-#else\r
-    if (*path == '/' || *path == '\\')    /* Strip heading separator if exist */\r
-        path++;\r
-    dj->sclust = 0;                        /* Start from the root dir */\r
-#endif\r
-\r
-    if ((UINT)*path < ' ') {            /* Nul path means the start directory itself */\r
-        res = dir_sdi(dj, 0);\r
-        dj->dir = 0;\r
-\r
-    } else {                            /* Follow path */\r
-        for (;;) {\r
-            res = create_name(dj, &path);    /* Get a segment */\r
-            if (res != FR_OK) break;\r
-            res = dir_find(dj);                /* Find it */\r
-            ns = *(dj->fn+NS);\r
-            if (res != FR_OK) {                /* Failed to find the object */\r
-                if (res != FR_NO_FILE) break;    /* Abort if any hard error occured */\r
-                /* Object not found */\r
-                if (_FS_RPATH && (ns & NS_DOT)) {    /* If dot entry is not exit */\r
-                    dj->sclust = 0; dj->dir = 0;    /* It is the root dir */\r
-                    res = FR_OK;\r
-                    if (!(ns & NS_LAST)) continue;\r
-                } else {                            /* Could not find the object */\r
-                    if (!(ns & NS_LAST)) res = FR_NO_PATH;\r
-                }\r
-                break;\r
-            }\r
-            if (ns & NS_LAST) break;            /* Last segment match. Function completed. */\r
-            dir = dj->dir;                        /* There is next segment. Follow the sub directory */\r
-            if (!(dir[DIR_Attr] & AM_DIR)) {    /* Cannot follow because it is a file */\r
-                res = FR_NO_PATH; break;\r
-            }\r
-            dj->sclust = LD_CLUST(dir);\r
-        }\r
-    }\r
-\r
-    return res;\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Load boot record and check if it is an FAT boot record                */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-static\r
-BYTE check_fs (    /* 0:The FAT BR, 1:Valid BR but not an FAT, 2:Not a BR, 3:Disk error */\r
-    FATFS *fs,    /* File system object */\r
-    DWORD sect    /* Sector# (lba) to check if it is an FAT boot record or not */\r
-)\r
-{\r
-    if (disk_read(fs->drv, fs->win, sect, 1) != RES_OK)    /* Load boot record */\r
-        return 3;\r
-    if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55)                /* Check record signature (always placed at offset 510 even if the sector size is >512) */\r
-        return 2;\r
-\r
-    if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146)    /* Check "FAT" string */\r
-        return 0;\r
-    if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146)\r
-        return 0;\r
-\r
-    return 1;\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Check if the file system object is valid or not                       */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-static\r
-FRESULT chk_mounted (    /* FR_OK(0): successful, !=0: any error occurred */\r
-    const TCHAR **path,    /* Pointer to pointer to the path name (drive number) */\r
-    FATFS **rfs,        /* Pointer to pointer to the found file system object */\r
-    BYTE chk_wp            /* !=0: Check media write protection for write access */\r
-)\r
-{\r
-    BYTE fmt, b, *tbl;\r
-    UINT vol;\r
-    DSTATUS stat;\r
-    DWORD bsect, fasize, tsect, sysect, nclst, szbfat;\r
-    WORD nrsv;\r
-    const TCHAR *p = *path;\r
-    FATFS *fs;\r
-\r
-    /* Get logical drive number from the path name */\r
-    vol = p[0] - '0';                    /* Is there a drive number? */\r
-    if (vol <= 9 && p[1] == ':') {        /* Found a drive number, get and strip it */\r
-        p += 2; *path = p;                /* Return pointer to the path name */\r
-    } else {                            /* No drive number is given */\r
-#if _FS_RPATH\r
-        vol = CurrVol;                    /* Use current drive */\r
-#else\r
-        vol = 0;                        /* Use drive 0 */\r
-#endif\r
-    }\r
-\r
-    /* Check if the logical drive is valid or not */\r
-    if (vol >= _VOLUMES)                 /* Is the drive number valid? */\r
-        return FR_INVALID_DRIVE;\r
-    *rfs = fs = FatFs[vol];                /* Return pointer to the corresponding file system object */\r
-    if (!fs) return FR_NOT_ENABLED;        /* Is the file system object available? */\r
-\r
-    ENTER_FF(fs);                        /* Lock file system */\r
-\r
-    if (fs->fs_type) {                        /* If the logical drive has been mounted */\r
-        stat = disk_status(fs->drv);\r
-        if (!(stat & STA_NOINIT)) {        /* and the physical drive is kept initialized (has not been changed), */\r
-#if !_FS_READONLY\r
-            if (chk_wp && (stat & STA_PROTECT))    /* Check write protection if needed */\r
-                return FR_WRITE_PROTECTED;\r
-#endif\r
-            return FR_OK;                    /* The file system object is valid */\r
-        }\r
-    }\r
-\r
-    /* The logical drive must be mounted. */\r
-    /* Following code attempts to mount a volume. (analyze BPB and initialize the fs object) */\r
-\r
-    fs->fs_type = 0;                    /* Clear the file system object */\r
-    fs->drv = (BYTE)LD2PD(vol);            /* Bind the logical drive and a physical drive */\r
-    stat = disk_initialize(fs->drv);    /* Initialize low level disk I/O layer */\r
-    if (stat & STA_NOINIT)                /* Check if the initialization succeeded */\r
-        return FR_NOT_READY;            /* Failed to initialize due to no media or hard error */\r
-#if _MAX_SS != 512                        /* Get disk sector size (variable sector size cfg only) */\r
-    if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &fs->ssize) != RES_OK)\r
-        return FR_DISK_ERR;\r
-#endif\r
-#if !_FS_READONLY\r
-    if (chk_wp && (stat & STA_PROTECT))    /* Check disk write protection if needed */\r
-        return FR_WRITE_PROTECTED;\r
-#endif\r
-    /* Search FAT partition on the drive. Supports only generic partitionings, FDISK and SFD. */\r
-    fmt = check_fs(fs, bsect = 0);        /* Check sector 0 if it is a VBR */\r
-    if (fmt == 1) {                        /* Not an FAT-VBR, the disk may be partitioned */\r
-        /* Check the partition listed in top of the partition table */\r
-        tbl = &fs->win[MBR_Table + LD2PT(vol) * SZ_PTE];/* Partition table */\r
-        if (tbl[4]) {                                    /* Is the partition existing? */\r
-            bsect = LD_DWORD(&tbl[8]);                    /* Partition offset in LBA */\r
-            fmt = check_fs(fs, bsect);                    /* Check the partition */\r
-        }\r
-    }\r
-    if (fmt == 3) return FR_DISK_ERR;\r
-    if (fmt) return FR_NO_FILESYSTEM;                    /* No FAT volume is found */\r
-\r
-    /* Following code initializes the file system object */\r
-\r
-    if (LD_WORD(fs->win+BPB_BytsPerSec) != SS(fs))        /* (BPB_BytsPerSec must be equal to the physical sector size) */\r
-        return FR_NO_FILESYSTEM;\r
-\r
-    fasize = LD_WORD(fs->win+BPB_FATSz16);                /* Number of sectors per FAT */\r
-    if (!fasize) fasize = LD_DWORD(fs->win+BPB_FATSz32);\r
-    fs->fsize = fasize;\r
-\r
-    fs->n_fats = b = fs->win[BPB_NumFATs];                /* Number of FAT copies */\r
-    if (b != 1 && b != 2) return FR_NO_FILESYSTEM;        /* (Must be 1 or 2) */\r
-    fasize *= b;                                        /* Number of sectors for FAT area */\r
-\r
-    fs->csize = b = fs->win[BPB_SecPerClus];            /* Number of sectors per cluster */\r
-    if (!b || (b & (b - 1))) return FR_NO_FILESYSTEM;    /* (Must be power of 2) */\r
-\r
-    fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt);    /* Number of root directory entries */\r
-    if (fs->n_rootdir % (SS(fs) / SZ_DIR)) return FR_NO_FILESYSTEM;    /* (BPB_RootEntCnt must be sector aligned) */\r
-\r
-    tsect = LD_WORD(fs->win+BPB_TotSec16);                /* Number of sectors on the volume */\r
-    if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32);\r
-\r
-    nrsv = LD_WORD(fs->win+BPB_RsvdSecCnt);                /* Number of reserved sectors */\r
-    if (!nrsv) return FR_NO_FILESYSTEM;                    /* (BPB_RsvdSecCnt must not be 0) */\r
-\r
-    /* Determine the FAT sub type */\r
-    sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZ_DIR);    /* RSV+FAT+DIR */\r
-    if (tsect < sysect) return FR_NO_FILESYSTEM;        /* (Invalid volume size) */\r
-    nclst = (tsect - sysect) / fs->csize;                /* Number of clusters */\r
-    if (!nclst) return FR_NO_FILESYSTEM;                /* (Invalid volume size) */\r
-    fmt = FS_FAT12;\r
-    if (nclst >= MIN_FAT16) fmt = FS_FAT16;\r
-    if (nclst >= MIN_FAT32) fmt = FS_FAT32;\r
-\r
-    /* Boundaries and Limits */\r
-    fs->n_fatent = nclst + 2;                            /* Number of FAT entries */\r
-    fs->database = bsect + sysect;                        /* Data start sector */\r
-    fs->fatbase = bsect + nrsv;                         /* FAT start sector */\r
-    if (fmt == FS_FAT32) {\r
-        if (fs->n_rootdir) return FR_NO_FILESYSTEM;        /* (BPB_RootEntCnt must be 0) */\r
-        fs->dirbase = LD_DWORD(fs->win+BPB_RootClus);    /* Root directory start cluster */\r
-        szbfat = fs->n_fatent * 4;                        /* (Required FAT size) */\r
-    } else {\r
-        if (!fs->n_rootdir)    return FR_NO_FILESYSTEM;    /* (BPB_RootEntCnt must not be 0) */\r
-        fs->dirbase = fs->fatbase + fasize;                /* Root directory start sector */\r
-        szbfat = (fmt == FS_FAT16) ?                    /* (Required FAT size) */\r
-            fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);\r
-    }\r
-    if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs))    /* (BPB_FATSz must not be less than required) */\r
-        return FR_NO_FILESYSTEM;\r
-\r
-#if !_FS_READONLY\r
-    /* Initialize cluster allocation information */\r
-    fs->free_clust = 0xFFFFFFFF;\r
-    fs->last_clust = 0;\r
-\r
-    /* Get fsinfo if available */\r
-    if (fmt == FS_FAT32) {\r
-         fs->fsi_flag = 0;\r
-        fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo);\r
-        if (disk_read(fs->drv, fs->win, fs->fsi_sector, 1) == RES_OK &&\r
-            LD_WORD(fs->win+BS_55AA) == 0xAA55 &&\r
-            LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 &&\r
-            LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) {\r
-                fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free);\r
-                fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count);\r
-        }\r
-    }\r
-#endif\r
-    fs->fs_type = fmt;        /* FAT sub-type */\r
-    fs->id = ++Fsid;        /* File system mount ID */\r
-    fs->winsect = 0;        /* Invalidate sector cache */\r
-    fs->wflag = 0;\r
-#if _FS_RPATH\r
-    fs->cdir = 0;            /* Current directory (root dir) */\r
-#endif\r
-#if _FS_SHARE                /* Clear file lock semaphores */\r
-    clear_lock(fs);\r
-#endif\r
-\r
-    return FR_OK;\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Check if the file/dir object is valid or not                          */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-static\r
-FRESULT validate (        /* FR_OK(0): The object is valid, !=0: Invalid */\r
-    FATFS *fs,        /* Pointer to the file system object */\r
-    WORD id                /* Member id of the target object to be checked */\r
-)\r
-{\r
-    if (!fs || !fs->fs_type || fs->id != id)\r
-        return FR_INVALID_OBJECT;\r
-\r
-    ENTER_FF(fs);        /* Lock file system */\r
-\r
-    if (disk_status(fs->drv) & STA_NOINIT)\r
-        return FR_NOT_READY;\r
-\r
-    return FR_OK;\r
-}\r
-\r
-\r
-\r
-\r
-/*--------------------------------------------------------------------------\r
-\r
-   Public Functions\r
-\r
---------------------------------------------------------------------------*/\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Mount/Unmount a Logical Drive                                         */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_mount (\r
-    BYTE vol,        /* Logical drive number to be mounted/unmounted */\r
-    FATFS *fs        /* Pointer to new file system object (NULL for unmount)*/\r
-)\r
-{\r
-    FATFS *rfs;\r
-\r
-\r
-    if (vol >= _VOLUMES)            /* Check if the drive number is valid */\r
-        return FR_INVALID_DRIVE;\r
-    rfs = FatFs[vol];                /* Get current fs object */\r
-\r
-    if (rfs) {\r
-#if _FS_SHARE\r
-        clear_lock(rfs);\r
-#endif\r
-#if _FS_REENTRANT                    /* Discard sync object of the current volume */\r
-        if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR;\r
-#endif\r
-        rfs->fs_type = 0;            /* Clear old fs object */\r
-    }\r
-\r
-    if (fs) {\r
-        fs->fs_type = 0;            /* Clear new fs object */\r
-#if _FS_REENTRANT                    /* Create sync object for the new volume */\r
-        if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR;\r
-#endif\r
-    }\r
-    FatFs[vol] = fs;                /* Register new fs object */\r
-\r
-    return FR_OK;\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Open or Create a File                                                 */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_open (\r
-    FIL_t *fp,            /* Pointer to the blank file object */\r
-    const TCHAR *path,    /* Pointer to the file name */\r
-    BYTE mode            /* Access mode and file open mode flags */\r
-)\r
-{\r
-    FRESULT res;\r
-    DIR_t dj;\r
-    BYTE *dir;\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    fp->fs = 0;            /* Clear file object */\r
-\r
-#if !_FS_READONLY\r
-    mode &= FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW;\r
-    res = chk_mounted(&path, &dj.fs, (BYTE)(mode & ~FA_READ));\r
-#else\r
-    mode &= FA_READ;\r
-    res = chk_mounted(&path, &dj.fs, 0);\r
-#endif\r
-    INIT_BUF(dj);\r
-    if (res == FR_OK)\r
-        res = follow_path(&dj, path);    /* Follow the file path */\r
-    dir = dj.dir;\r
-\r
-#if !_FS_READONLY    /* R/W configuration */\r
-    if (res == FR_OK) {\r
-        if (!dir)    /* Current dir itself */\r
-            res = FR_INVALID_NAME;\r
-#if _FS_SHARE\r
-        else\r
-            res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);\r
-#endif\r
-    }\r
-    /* Create or Open a file */\r
-    if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)) {\r
-        DWORD dw, cl;\r
-\r
-        if (res != FR_OK) {        /* No file, create new */\r
-            if (res == FR_NO_FILE)            /* There is no file to open, create a new entry */\r
-#if _FS_SHARE\r
-                res = enq_lock(dj.fs) ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;\r
-#else\r
-                res = dir_register(&dj);\r
-#endif\r
-            mode |= FA_CREATE_ALWAYS;        /* File is created */\r
-            dir = dj.dir;                    /* New entry */\r
-        }\r
-        else {                    /* Any object is already existing */\r
-            if (dir[DIR_Attr] & (AM_RDO | AM_DIR)) {    /* Cannot overwrite it (R/O or DIR) */\r
-                res = FR_DENIED;\r
-            } else {\r
-                if (mode & FA_CREATE_NEW)    /* Cannot create as new file */\r
-                    res = FR_EXIST;\r
-            }\r
-        }\r
-        if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) {    /* Truncate it if overwrite mode */\r
-            dw = get_fattime();                    /* Created time */\r
-            ST_DWORD(dir+DIR_CrtTime, dw);\r
-            dir[DIR_Attr] = 0;                    /* Reset attribute */\r
-            ST_DWORD(dir+DIR_FileSize, 0);        /* size = 0 */\r
-            cl = LD_CLUST(dir);                    /* Get start cluster */\r
-            ST_CLUST(dir, 0);                    /* cluster = 0 */\r
-            dj.fs->wflag = 1;\r
-            if (cl) {                            /* Remove the cluster chain if exist */\r
-                dw = dj.fs->winsect;\r
-                res = remove_chain(dj.fs, cl);\r
-                if (res == FR_OK) {\r
-                    dj.fs->last_clust = cl - 1;    /* Reuse the cluster hole */\r
-                    res = move_window(dj.fs, dw);\r
-        }\r
-    }\r
-        }\r
-    }\r
-    else {    /* Open an existing file */\r
-        if (res == FR_OK) {                        /* Follow succeeded */\r
-            if (dir[DIR_Attr] & AM_DIR) {        /* It is a directory */\r
-                res = FR_NO_FILE;\r
-            } else {\r
-        if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */\r
-                    res = FR_DENIED;\r
-            }\r
-    }\r
-    }\r
-    if (res == FR_OK) {\r
-        if (mode & FA_CREATE_ALWAYS)            /* Set file change flag if created or overwritten */\r
-            mode |= FA__WRITTEN;\r
-    fp->dir_sect = dj.fs->winsect;        /* Pointer to the directory entry */\r
-    fp->dir_ptr = dir;\r
-#if _FS_SHARE\r
-        fp->lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);\r
-        if (!fp->lockid) res = FR_INT_ERR;\r
-#endif\r
-    }\r
-\r
-#else                /* R/O configuration */\r
-    if (res == FR_OK) {                    /* Follow succeeded */\r
-        if (!dir) {                        /* Current dir itself */\r
-            res = FR_INVALID_NAME;\r
-        } else {\r
-            if (dir[DIR_Attr] & AM_DIR)    /* It is a directory */\r
-                res = FR_NO_FILE;\r
-        }\r
-    }\r
-#endif\r
-    FREE_BUF();\r
-\r
-    if (res == FR_OK) {\r
-    fp->flag = mode;                    /* File access mode */\r
-        fp->sclust = LD_CLUST(dir);            /* File start cluster */\r
-        fp->fsize = LD_DWORD(dir+DIR_FileSize);    /* File size */\r
-        fp->fptr = 0;                        /* File pointer */\r
-        fp->dsect = 0;\r
-#if _USE_FASTSEEK\r
-        fp->cltbl = 0;                        /* Normal seek mode */\r
-#endif\r
-        fp->fs = dj.fs; fp->id = dj.fs->id;    /* Validate file object */\r
-    }\r
-\r
-    LEAVE_FF(dj.fs, res);\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Read File                                                             */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_read (\r
-    FIL_t *fp,         /* Pointer to the file object */\r
-    void *buff,        /* Pointer to data buffer */\r
-    UINT btr,        /* Number of bytes to read */\r
-    UINT *br        /* Pointer to number of bytes read */\r
-)\r
-{\r
-    FRESULT res;\r
-    DWORD clst, sect, remain;\r
-    UINT rcnt, cc;\r
-    BYTE csect, *rbuff = (BYTE*)buff;\r
-\r
-\r
-    *br = 0;    /* Initialize byte counter */\r
-\r
-    res = validate(fp->fs, fp->id);                /* Check validity */\r
-    if (res != FR_OK) LEAVE_FF(fp->fs, res);\r
-    if (fp->flag & FA__ERROR)                    /* Aborted file? */\r
-        LEAVE_FF(fp->fs, FR_INT_ERR);\r
-    if (!(fp->flag & FA_READ))                     /* Check access mode */\r
-        LEAVE_FF(fp->fs, FR_DENIED);\r
-    remain = fp->fsize - fp->fptr;\r
-    if (btr > remain) btr = (UINT)remain;            /* Truncate btr by remaining bytes */\r
-\r
-    for ( ;  btr;                                /* Repeat until all data read */\r
-        rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {\r
-        if ((fp->fptr % SS(fp->fs)) == 0) {            /* On the sector boundary? */\r
-            csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1));    /* Sector offset in the cluster */\r
-            if (!csect) {                        /* On the cluster boundary? */\r
-                if (fp->fptr == 0) {            /* On the top of the file? */\r
-                    clst = fp->sclust;            /* Follow from the origin */\r
-                } else {                        /* Middle or end of the file */\r
-#if _USE_FASTSEEK\r
-                    if (fp->cltbl)\r
-                        clst = clmt_clust(fp, fp->fptr);    /* Get cluster# from the CLMT */\r
-                    else\r
-#endif\r
-                        clst = get_fat(fp->fs, fp->clust);    /* Follow cluster chain on the FAT */\r
-                }\r
-                if (clst < 2) ABORT(fp->fs, FR_INT_ERR);\r
-                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
-                fp->clust = clst;                /* Update current cluster */\r
-            }\r
-            sect = clust2sect(fp->fs, fp->clust);    /* Get current sector */\r
-            if (!sect) ABORT(fp->fs, FR_INT_ERR);\r
-            sect += csect;\r
-            cc = btr / SS(fp->fs);                    /* When remaining bytes >= sector size, */\r
-            if (cc) {                                /* Read maximum contiguous sectors directly */\r
-                if (csect + cc > fp->fs->csize)    /* Clip at cluster boundary */\r
-                    cc = fp->fs->csize - csect;\r
-                if (disk_read(fp->fs->drv, rbuff, sect, (BYTE)cc) != RES_OK)\r
-                    ABORT(fp->fs, FR_DISK_ERR);\r
-#if !_FS_READONLY && _FS_MINIMIZE <= 2            /* Replace one of the read sectors with cached data if it contains a dirty sector */\r
-#if _FS_TINY\r
-                if (fp->fs->wflag && fp->fs->winsect - sect < cc)\r
-                    mem_cpy(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs));\r
-#else\r
-                if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc)\r
-                    mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs));\r
-#endif\r
-#endif\r
-                rcnt = SS(fp->fs) * cc;                /* Number of bytes transferred */\r
-                continue;\r
-            }\r
-#if !_FS_TINY\r
-            if (fp->dsect != sect) {            /* Load data sector if not in cache */\r
-#if !_FS_READONLY\r
-                if (fp->flag & FA__DIRTY) {        /* Write-back dirty sector cache */\r
-                    if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)\r
-                        ABORT(fp->fs, FR_DISK_ERR);\r
-                    fp->flag &= ~FA__DIRTY;\r
-                }\r
-#endif\r
-                if (disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK)    /* Fill sector cache */\r
-                    ABORT(fp->fs, FR_DISK_ERR);\r
-            }\r
-#endif\r
-            fp->dsect = sect;\r
-        }\r
-        rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));    /* Get partial sector data from sector buffer */\r
-        if (rcnt > btr) rcnt = btr;\r
-#if _FS_TINY\r
-        if (move_window(fp->fs, fp->dsect))        /* Move sector window */\r
-            ABORT(fp->fs, FR_DISK_ERR);\r
-        mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt);    /* Pick partial sector */\r
-#else\r
-        mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt);    /* Pick partial sector */\r
-#endif\r
-    }\r
-\r
-    LEAVE_FF(fp->fs, FR_OK);\r
-}\r
-\r
-\r
-\r
-\r
-#if !_FS_READONLY\r
-/*-----------------------------------------------------------------------*/\r
-/* Write File                                                            */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_write (\r
-    FIL_t *fp,            /* Pointer to the file object */\r
-    const void *buff,    /* Pointer to the data to be written */\r
-    UINT btw,            /* Number of bytes to write */\r
-    UINT *bw            /* Pointer to number of bytes written */\r
-)\r
-{\r
-    FRESULT res;\r
-    DWORD clst, sect;\r
-    UINT wcnt, cc;\r
-    const BYTE *wbuff = (BYTE*)buff;\r
-    BYTE csect;\r
-\r
-\r
-    *bw = 0;    /* Initialize byte counter */\r
-\r
-    res = validate(fp->fs, fp->id);            /* Check validity */\r
-    if (res != FR_OK) LEAVE_FF(fp->fs, res);\r
-    if (fp->flag & FA__ERROR)                /* Aborted file? */\r
-        LEAVE_FF(fp->fs, FR_INT_ERR);\r
-    if (!(fp->flag & FA_WRITE))                /* Check access mode */\r
-        LEAVE_FF(fp->fs, FR_DENIED);\r
-    if ((DWORD)(fp->fsize + btw) < fp->fsize) btw = 0;    /* File size cannot reach 4GB */\r
-\r
-    for ( ;  btw;                            /* Repeat until all data written */\r
-        wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {\r
-        if ((fp->fptr % SS(fp->fs)) == 0) {            /* On the sector boundary? */\r
-            csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1));    /* Sector offset in the cluster */\r
-            if (!csect) {                    /* On the cluster boundary? */\r
-                if (fp->fptr == 0) {                /* On the top of the file? */\r
-                    clst = fp->sclust;        /* Follow from the origin */\r
-                    if (clst == 0)            /* When no cluster is allocated, */\r
-                        fp->sclust = clst = create_chain(fp->fs, 0);    /* Create a new cluster chain */\r
-                } else {                            /* Middle or end of the file */\r
-#if _USE_FASTSEEK\r
-                    if (fp->cltbl)\r
-                        clst = clmt_clust(fp, fp->fptr);    /* Get cluster# from the CLMT */\r
-                    else\r
-#endif\r
-                        clst = create_chain(fp->fs, fp->clust);    /* Follow or stretch cluster chain on the FAT */\r
-                }\r
-                if (clst == 0) break;        /* Could not allocate a new cluster (disk full) */\r
-                if (clst == 1) ABORT(fp->fs, FR_INT_ERR);\r
-                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
-                fp->clust = clst;            /* Update current cluster */\r
-                }\r
-#if _FS_TINY\r
-            if (fp->fs->winsect == fp->dsect && move_window(fp->fs, 0))    /* Write-back sector cache */\r
-                ABORT(fp->fs, FR_DISK_ERR);\r
-#else\r
-            if (fp->flag & FA__DIRTY) {        /* Write-back sector cache */\r
-                if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)\r
-                    ABORT(fp->fs, FR_DISK_ERR);\r
-                fp->flag &= ~FA__DIRTY;\r
-            }\r
-#endif\r
-            sect = clust2sect(fp->fs, fp->clust);    /* Get current sector */\r
-            if (!sect) ABORT(fp->fs, FR_INT_ERR);\r
-            sect += csect;\r
-            cc = btw / SS(fp->fs);                    /* When remaining bytes >= sector size, */\r
-            if (cc) {                                /* Write maximum contiguous sectors directly */\r
-                if (csect + cc > fp->fs->csize)    /* Clip at cluster boundary */\r
-                    cc = fp->fs->csize - csect;\r
-                if (disk_write(fp->fs->drv, wbuff, sect, (BYTE)cc) != RES_OK)\r
-                    ABORT(fp->fs, FR_DISK_ERR);\r
-#if _FS_TINY\r
-                if (fp->fs->winsect - sect < cc) {    /* Refill sector cache if it gets invalidated by the direct write */\r
-                    mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs));\r
-                    fp->fs->wflag = 0;\r
-                }\r
-#else\r
-                if (fp->dsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */\r
-                    mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs));\r
-                    fp->flag &= ~FA__DIRTY;\r
-                }\r
-#endif\r
-                wcnt = SS(fp->fs) * cc;                /* Number of bytes transferred */\r
-                continue;\r
-            }\r
-#if _FS_TINY\r
-            if (fp->fptr >= fp->fsize) {    /* Avoid silly cache filling at growing edge */\r
-                if (move_window(fp->fs, 0)) ABORT(fp->fs, FR_DISK_ERR);\r
-                fp->fs->winsect = sect;\r
-                }\r
-#else\r
-            if (fp->dsect != sect) {        /* Fill sector cache with file data */\r
-                if (fp->fptr < fp->fsize &&\r
-                    disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK)\r
-                        ABORT(fp->fs, FR_DISK_ERR);\r
-            }\r
-#endif\r
-            fp->dsect = sect;\r
-        }\r
-        wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));    /* Put partial sector into file I/O buffer */\r
-        if (wcnt > btw) wcnt = btw;\r
-#if _FS_TINY\r
-        if (move_window(fp->fs, fp->dsect))    /* Move sector window */\r
-            ABORT(fp->fs, FR_DISK_ERR);\r
-        mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt);    /* Fit partial sector */\r
-        fp->fs->wflag = 1;\r
-#else\r
-        mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt);    /* Fit partial sector */\r
-        fp->flag |= FA__DIRTY;\r
-#endif\r
-    }\r
-\r
-    if (fp->fptr > fp->fsize) fp->fsize = fp->fptr;    /* Update file size if needed */\r
-    fp->flag |= FA__WRITTEN;                        /* Set file change flag */\r
-\r
-    LEAVE_FF(fp->fs, FR_OK);\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Synchronize the File Object                                           */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_sync (\r
-    FIL_t *fp        /* Pointer to the file object */\r
-)\r
-{\r
-    FRESULT res;\r
-    DWORD tim;\r
-    BYTE *dir;\r
-\r
-\r
-    res = validate(fp->fs, fp->id);        /* Check validity of the object */\r
-    if (res == FR_OK) {\r
-        if (fp->flag & FA__WRITTEN) {    /* Has the file been written? */\r
-#if !_FS_TINY    /* Write-back dirty buffer */\r
-            if (fp->flag & FA__DIRTY) {\r
-                if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)\r
-                    LEAVE_FF(fp->fs, FR_DISK_ERR);\r
-                fp->flag &= ~FA__DIRTY;\r
-            }\r
-#endif\r
-            /* Update the directory entry */\r
-            res = move_window(fp->fs, fp->dir_sect);\r
-            if (res == FR_OK) {\r
-            dir = fp->dir_ptr;\r
-            dir[DIR_Attr] |= AM_ARC;                        /* Set archive bit */\r
-                ST_DWORD(dir+DIR_FileSize, fp->fsize);        /* Update file size */\r
-                ST_CLUST(dir, fp->sclust);                    /* Update start cluster */\r
-                tim = get_fattime();                        /* Update updated time */\r
-                ST_DWORD(dir+DIR_WrtTime, tim);\r
-                fp->flag &= ~FA__WRITTEN;\r
-                fp->fs->wflag = 1;\r
-            res = sync(fp->fs);\r
-        }\r
-    }\r
-    }\r
-\r
-    LEAVE_FF(fp->fs, res);\r
-}\r
-\r
-#endif /* !_FS_READONLY */\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Close File                                                            */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_close (\r
-    FIL_t *fp        /* Pointer to the file object to be closed */\r
-)\r
-{\r
-    FRESULT res;\r
-\r
-#if _FS_READONLY\r
-    FATFS *fs = fp->fs;\r
-    res = validate(fs, fp->id);\r
-    if (res == FR_OK) fp->fs = 0;    /* Discard file object */\r
-    LEAVE_FF(fs, res);\r
-\r
-#else\r
-    res = f_sync(fp);        /* Flush cached data */\r
-#if _FS_SHARE\r
-    if (res == FR_OK) {        /* Decrement open counter */\r
-#if _FS_REENTRANT\r
-    res = validate(fp->fs, fp->id);\r
-        if (res == FR_OK) {\r
-            res = dec_lock(fp->lockid);    \r
-            unlock_fs(fp->fs, FR_OK);\r
-        }\r
-#else\r
-        res = dec_lock(fp->lockid);\r
-#endif\r
-    }\r
-#endif\r
-    if (res == FR_OK) fp->fs = 0;    /* Discard file object */\r
-    return res;\r
-#endif\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Current Drive/Directory Handlings                                     */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-#if _FS_RPATH >= 1\r
-\r
-FRESULT f_chdrive (\r
-    BYTE drv        /* Drive number */\r
-)\r
-{\r
-    if (drv >= _VOLUMES) return FR_INVALID_DRIVE;\r
-\r
-    CurrVol = drv;\r
-\r
-    return FR_OK;\r
-}\r
-\r
-\r
-\r
-FRESULT f_chdir (\r
-    const TCHAR *path    /* Pointer to the directory path */\r
-)\r
-{\r
-    FRESULT res;\r
-    DIR_t dj;\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    res = chk_mounted(&path, &dj.fs, 0);\r
-    if (res == FR_OK) {\r
-        INIT_BUF(dj);\r
-        res = follow_path(&dj, path);        /* Follow the path */\r
-        FREE_BUF();\r
-        if (res == FR_OK) {                    /* Follow completed */\r
-            if (!dj.dir) {\r
-                dj.fs->cdir = dj.sclust;    /* Start directory itself */\r
-            } else {\r
-                if (dj.dir[DIR_Attr] & AM_DIR)    /* Reached to the directory */\r
-                    dj.fs->cdir = LD_CLUST(dj.dir);\r
-                else\r
-                    res = FR_NO_PATH;        /* Reached but a file */\r
-            }\r
-        }\r
-        if (res == FR_NO_FILE) res = FR_NO_PATH;\r
-    }\r
-\r
-    LEAVE_FF(dj.fs, res);\r
-}\r
-\r
-\r
-#if _FS_RPATH >= 2\r
-FRESULT f_getcwd (\r
-    TCHAR *path,    /* Pointer to the directory path */\r
-    UINT sz_path    /* Size of path */\r
-)\r
-{\r
-    FRESULT res;\r
-    DIR_t dj;\r
-    UINT i, n;\r
-    DWORD ccl;\r
-    TCHAR *tp;\r
-    FILINFO fno;\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    *path = 0;\r
-    res = chk_mounted((const TCHAR**)&path, &dj.fs, 0);    /* Get current volume */\r
-    if (res == FR_OK) {\r
-        INIT_BUF(dj);\r
-        i = sz_path;        /* Bottom of buffer (dir stack base) */\r
-        dj.sclust = dj.fs->cdir;            /* Start to follow upper dir from current dir */\r
-        while ((ccl = dj.sclust) != 0) {    /* Repeat while current dir is a sub-dir */\r
-            res = dir_sdi(&dj, 1);            /* Get parent dir */\r
-            if (res != FR_OK) break;\r
-            res = dir_read(&dj);\r
-            if (res != FR_OK) break;\r
-            dj.sclust = LD_CLUST(dj.dir);    /* Goto parent dir */\r
-            res = dir_sdi(&dj, 0);\r
-            if (res != FR_OK) break;\r
-            do {                            /* Find the entry links to the child dir */\r
-                res = dir_read(&dj);\r
-                if (res != FR_OK) break;\r
-                if (ccl == LD_CLUST(dj.dir)) break;    /* Found the entry */\r
-                res = dir_next(&dj, 0);    \r
-            } while (res == FR_OK);\r
-            if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */\r
-            if (res != FR_OK) break;\r
-#if _USE_LFN\r
-            fno.lfname = path;\r
-            fno.lfsize = i;\r
-#endif\r
-            get_fileinfo(&dj, &fno);        /* Get the dir name and push it to the buffer */\r
-            tp = fno.fname;\r
-            if (_USE_LFN && *path) tp = path;\r
-            for (n = 0; tp[n]; n++) ;\r
-            if (i < n + 3) {\r
-                res = FR_NOT_ENOUGH_CORE; break;\r
-            }\r
-            while (n) path[--i] = tp[--n];\r
-            path[--i] = '/';\r
-        }\r
-        tp = path;\r
-        if (res == FR_OK) {\r
-            *tp++ = '0' + CurrVol;            /* Put drive number */\r
-            *tp++ = ':';\r
-            if (i == sz_path) {                /* Root-dir */\r
-                *tp++ = '/';\r
-            } else {                        /* Sub-dir */\r
-                do        /* Add stacked path str */\r
-                    *tp++ = path[i++];\r
-                while (i < sz_path);\r
-            }\r
-        }\r
-        *tp = 0;\r
-        FREE_BUF();\r
-    }\r
-\r
-    LEAVE_FF(dj.fs, res);\r
-}\r
-#endif /* _FS_RPATH >= 2 */\r
-#endif /* _FS_RPATH >= 1 */\r
-\r
-\r
-\r
-#if _FS_MINIMIZE <= 2\r
-/*-----------------------------------------------------------------------*/\r
-/* Seek File R/W Pointer                                                 */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_lseek (\r
-    FIL_t *fp,        /* Pointer to the file object */\r
-    DWORD ofs        /* File pointer from top of file */\r
-)\r
-{\r
-    FRESULT res;\r
-\r
-\r
-    res = validate(fp->fs, fp->id);        /* Check validity of the object */\r
-    if (res != FR_OK) LEAVE_FF(fp->fs, res);\r
-    if (fp->flag & FA__ERROR)            /* Check abort flag */\r
-        LEAVE_FF(fp->fs, FR_INT_ERR);\r
-\r
-#if _USE_FASTSEEK\r
-    if (fp->cltbl) {    /* Fast seek */\r
-        DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;\r
-\r
-        if (ofs == CREATE_LINKMAP) {    /* Create CLMT */\r
-            tbl = fp->cltbl;\r
-            tlen = *tbl++; ulen = 2;    /* Given table size and required table size */\r
-            cl = fp->sclust;            /* Top of the chain */\r
-            if (cl) {\r
-                do {\r
-                    /* Get a fragment */\r
-                    tcl = cl; ncl = 0; ulen += 2;    /* Top, length and used items */\r
-                    do {\r
-                        pcl = cl; ncl++;\r
-                        cl = get_fat(fp->fs, cl);\r
-                        if (cl <= 1) ABORT(fp->fs, FR_INT_ERR);\r
-                        if (cl == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
-                    } while (cl == pcl + 1);\r
-                    if (ulen <= tlen) {        /* Store the length and top of the fragment */\r
-                        *tbl++ = ncl; *tbl++ = tcl;\r
-                    }\r
-                } while (cl < fp->fs->n_fatent);    /* Repeat until end of chain */\r
-            }\r
-            *fp->cltbl = ulen;    /* Number of items used */\r
-            if (ulen <= tlen)\r
-                *tbl = 0;        /* Terminate table */\r
-            else\r
-                res = FR_NOT_ENOUGH_CORE;    /* Given table size is smaller than required */\r
-\r
-        } else {                        /* Fast seek */\r
-            if (ofs > fp->fsize)        /* Clip offset at the file size */\r
-                ofs = fp->fsize;\r
-            fp->fptr = ofs;                /* Set file pointer */\r
-            if (ofs) {\r
-                fp->clust = clmt_clust(fp, ofs - 1);\r
-                dsc = clust2sect(fp->fs, fp->clust);\r
-                if (!dsc) ABORT(fp->fs, FR_INT_ERR);\r
-                dsc += (ofs - 1) / SS(fp->fs) & (fp->fs->csize - 1);\r
-                if (fp->fptr % SS(fp->fs) && dsc != fp->dsect) {    /* Refill sector cache if needed */\r
-#if !_FS_TINY\r
-#if !_FS_READONLY\r
-                    if (fp->flag & FA__DIRTY) {        /* Write-back dirty sector cache */\r
-                        if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)\r
-                            ABORT(fp->fs, FR_DISK_ERR);\r
-                        fp->flag &= ~FA__DIRTY;\r
-                    }\r
-#endif\r
-                    if (disk_read(fp->fs->drv, fp->buf, dsc, 1) != RES_OK)    /* Load current sector */\r
-                        ABORT(fp->fs, FR_DISK_ERR);\r
-#endif\r
-                    fp->dsect = dsc;\r
-                }\r
-            }\r
-        }\r
-    } else\r
-#endif\r
-\r
-    /* Normal Seek */\r
-    {\r
-        DWORD clst, bcs, nsect, ifptr;\r
-\r
-    if (ofs > fp->fsize                    /* In read-only mode, clip offset with the file size */\r
-#if !_FS_READONLY\r
-         && !(fp->flag & FA_WRITE)\r
-#endif\r
-        ) ofs = fp->fsize;\r
-\r
-    ifptr = fp->fptr;\r
-        fp->fptr = nsect = 0;\r
-        if (ofs) {\r
-            bcs = (DWORD)fp->fs->csize * SS(fp->fs);    /* Cluster size (byte) */\r
-        if (ifptr > 0 &&\r
-                (ofs - 1) / bcs >= (ifptr - 1) / bcs) {    /* When seek to same or following cluster, */\r
-                fp->fptr = (ifptr - 1) & ~(bcs - 1);    /* start from the current cluster */\r
-            ofs -= fp->fptr;\r
-                clst = fp->clust;\r
-        } else {                                    /* When seek to back cluster, */\r
-                clst = fp->sclust;                        /* start from the first cluster */\r
-#if !_FS_READONLY\r
-                if (clst == 0) {                        /* If no cluster chain, create a new chain */\r
-                    clst = create_chain(fp->fs, 0);\r
-                    if (clst == 1) ABORT(fp->fs, FR_INT_ERR);\r
-                    if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
-                    fp->sclust = clst;\r
-            }\r
-#endif\r
-                fp->clust = clst;\r
-        }\r
-            if (clst != 0) {\r
-                while (ofs > bcs) {                        /* Cluster following loop */\r
-#if !_FS_READONLY\r
-                if (fp->flag & FA_WRITE) {            /* Check if in write mode or not */\r
-                        clst = create_chain(fp->fs, clst);    /* Force stretch if in write mode */\r
-                        if (clst == 0) {                /* When disk gets full, clip file size */\r
-                            ofs = bcs; break;\r
-                    }\r
-                } else\r
-#endif\r
-                        clst = get_fat(fp->fs, clst);    /* Follow cluster chain if not in write mode */\r
-                    if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
-                    if (clst <= 1 || clst >= fp->fs->n_fatent) ABORT(fp->fs, FR_INT_ERR);\r
-                    fp->clust = clst;\r
-                    fp->fptr += bcs;\r
-                    ofs -= bcs;\r
-            }\r
-            fp->fptr += ofs;\r
-                if (ofs % SS(fp->fs)) {\r
-                    nsect = clust2sect(fp->fs, clst);    /* Current sector */\r
-                    if (!nsect) ABORT(fp->fs, FR_INT_ERR);\r
-                    nsect += ofs / SS(fp->fs);\r
-            }\r
-        }\r
-    }\r
-        if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) {    /* Fill sector cache if needed */\r
-#if !_FS_TINY\r
-#if !_FS_READONLY\r
-            if (fp->flag & FA__DIRTY) {            /* Write-back dirty sector cache */\r
-                if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)\r
-                    ABORT(fp->fs, FR_DISK_ERR);\r
-                fp->flag &= ~FA__DIRTY;\r
-        }\r
-#endif\r
-            if (disk_read(fp->fs->drv, fp->buf, nsect, 1) != RES_OK)    /* Fill sector cache */\r
-                ABORT(fp->fs, FR_DISK_ERR);\r
-#endif\r
-            fp->dsect = nsect;\r
-    }\r
-#if !_FS_READONLY\r
-        if (fp->fptr > fp->fsize) {            /* Set file change flag if the file size is extended */\r
-        fp->fsize = fp->fptr;\r
-        fp->flag |= FA__WRITTEN;\r
-    }\r
-#endif\r
-}\r
-\r
-    LEAVE_FF(fp->fs, res);\r
-}\r
-\r
-\r
-\r
-#if _FS_MINIMIZE <= 1\r
-/*-----------------------------------------------------------------------*/\r
-/* Create a Directroy Object                                             */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_opendir (\r
-    DIR_t *dj,            /* Pointer to directory object to create */\r
-    const TCHAR *path    /* Pointer to the directory path */\r
-)\r
-{\r
-    FRESULT res;\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    res = chk_mounted(&path, &dj->fs, 0);\r
-    if (res == FR_OK) {\r
-        INIT_BUF(*dj);\r
-        res = follow_path(dj, path);            /* Follow the path to the directory */\r
-        FREE_BUF();\r
-        if (res == FR_OK) {                        /* Follow completed */\r
-            if (dj->dir) {                        /* It is not the root dir */\r
-                if (dj->dir[DIR_Attr] & AM_DIR) {    /* The object is a directory */\r
-                    dj->sclust = LD_CLUST(dj->dir);\r
-                } else {                        /* The object is not a directory */\r
-                    res = FR_NO_PATH;\r
-                }\r
-            }\r
-            if (res == FR_OK) {\r
-            dj->id = dj->fs->id;\r
-                res = dir_sdi(dj, 0);            /* Rewind dir */\r
-            }\r
-        }\r
-        if (res == FR_NO_FILE) res = FR_NO_PATH;\r
-    }\r
-\r
-    LEAVE_FF(dj->fs, res);\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Read Directory Entry in Sequense                                      */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_readdir (\r
-    DIR_t *dj,            /* Pointer to the open directory object */\r
-    FILINFO *fno        /* Pointer to file information to return */\r
-)\r
-{\r
-    FRESULT res;\r
-    DEF_NAMEBUF;\r
-\r
-    res = validate(dj->fs, dj->id);            /* Check validity of the object */\r
-    if (res == FR_OK) {\r
-        if (!fno) {\r
-            res = dir_sdi(dj, 0);            /* Rewind the directory object */\r
-        } else {\r
-            INIT_BUF(*dj);\r
-            res = dir_read(dj);                /* Read an directory item */\r
-            if (res == FR_NO_FILE) {        /* Reached end of dir */\r
-                dj->sect = 0;\r
-                res = FR_OK;\r
-            }\r
-            if (res == FR_OK) {                /* A valid entry is found */\r
-                get_fileinfo(dj, fno);        /* Get the object information */\r
-                res = dir_next(dj, 0);        /* Increment index for next */\r
-                if (res == FR_NO_FILE) {\r
-                    dj->sect = 0;\r
-                    res = FR_OK;\r
-                }\r
-            }\r
-            FREE_BUF();\r
-        }\r
-    }\r
-\r
-    LEAVE_FF(dj->fs, res);\r
-}\r
-\r
-\r
-\r
-#if _FS_MINIMIZE == 0\r
-/*-----------------------------------------------------------------------*/\r
-/* Get File Status                                                       */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_stat (\r
-    const TCHAR *path,    /* Pointer to the file path */\r
-    FILINFO *fno        /* Pointer to file information to return */\r
-)\r
-{\r
-    FRESULT res;\r
-    DIR_t dj;\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    res = chk_mounted(&path, &dj.fs, 0);\r
-    if (res == FR_OK) {\r
-        INIT_BUF(dj);\r
-        res = follow_path(&dj, path);    /* Follow the file path */\r
-        if (res == FR_OK) {                /* Follow completed */\r
-            if (dj.dir)        /* Found an object */\r
-                get_fileinfo(&dj, fno);\r
-            else        /* It is root dir */\r
-                res = FR_INVALID_NAME;\r
-        }\r
-        FREE_BUF();\r
-    }\r
-\r
-    LEAVE_FF(dj.fs, res);\r
-}\r
-\r
-\r
-\r
-#if !_FS_READONLY\r
-/*-----------------------------------------------------------------------*/\r
-/* Get Number of Free Clusters                                           */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_getfree (\r
-    const TCHAR *path,    /* Pointer to the logical drive number (root dir) */\r
-    DWORD *nclst,        /* Pointer to the variable to return number of free clusters */\r
-    FATFS **fatfs        /* Pointer to pointer to corresponding file system object to return */\r
-)\r
-{\r
-    FRESULT res;\r
-    DWORD n, clst, sect, stat;\r
-    UINT i;\r
-    BYTE fat, *p;\r
-\r
-\r
-    /* Get drive number */\r
-    res = chk_mounted(&path, fatfs, 0);\r
-    if (res == FR_OK) {\r
-        /* If free_clust is valid, return it without full cluster scan */\r
-        if ((*fatfs)->free_clust <= (*fatfs)->n_fatent - 2) {\r
-            *nclst = (*fatfs)->free_clust;\r
-        } else {\r
-    /* Get number of free clusters */\r
-    fat = (*fatfs)->fs_type;\r
-    n = 0;\r
-    if (fat == FS_FAT12) {\r
-                clst = 2;\r
-        do {\r
-                    stat = get_fat(*fatfs, clst);\r
-                    if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }\r
-                    if (stat == 1) { res = FR_INT_ERR; break; }\r
-                    if (stat == 0) n++;\r
-                } while (++clst < (*fatfs)->n_fatent);\r
-    } else {\r
-                clst = (*fatfs)->n_fatent;\r
-        sect = (*fatfs)->fatbase;\r
-                i = 0; p = 0;\r
-        do {\r
-                    if (!i) {\r
-                        res = move_window(*fatfs, sect++);\r
-                        if (res != FR_OK) break;\r
-                p = (*fatfs)->win;\r
-                        i = SS(*fatfs);\r
-            }\r
-            if (fat == FS_FAT16) {\r
-                if (LD_WORD(p) == 0) n++;\r
-                        p += 2; i -= 2;\r
-            } else {\r
-                        if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) n++;\r
-                        p += 4; i -= 4;\r
-            }\r
-                } while (--clst);\r
-    }\r
-    (*fatfs)->free_clust = n;\r
-    if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1;\r
-            *nclst = n;\r
-        }\r
-    }\r
-    LEAVE_FF(*fatfs, res);\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Truncate File                                                         */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_truncate (\r
-    FIL_t *fp        /* Pointer to the file object */\r
-)\r
-{\r
-    FRESULT res;\r
-    DWORD ncl;\r
-\r
-\r
-    res = validate(fp->fs, fp->id);        /* Check validity of the object */\r
-    if (res == FR_OK) {\r
-        if (fp->flag & FA__ERROR) {            /* Check abort flag */\r
-            res = FR_INT_ERR;\r
-        } else {\r
-            if (!(fp->flag & FA_WRITE))        /* Check access mode */\r
-                res = FR_DENIED;\r
-        }\r
-    }\r
-    if (res == FR_OK) {\r
-        if (fp->fsize > fp->fptr) {\r
-            fp->fsize = fp->fptr;    /* Set file size to current R/W point */\r
-            fp->flag |= FA__WRITTEN;\r
-            if (fp->fptr == 0) {    /* When set file size to zero, remove entire cluster chain */\r
-                res = remove_chain(fp->fs, fp->sclust);\r
-                fp->sclust = 0;\r
-            } else {                /* When truncate a part of the file, remove remaining clusters */\r
-                ncl = get_fat(fp->fs, fp->clust);\r
-                res = FR_OK;\r
-                if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;\r
-                if (ncl == 1) res = FR_INT_ERR;\r
-                if (res == FR_OK && ncl < fp->fs->n_fatent) {\r
-                    res = put_fat(fp->fs, fp->clust, 0x0FFFFFFF);\r
-                    if (res == FR_OK) res = remove_chain(fp->fs, ncl);\r
-                }\r
-            }\r
-        }\r
-        if (res != FR_OK) fp->flag |= FA__ERROR;\r
-    }\r
-\r
-    LEAVE_FF(fp->fs, res);\r
-    }\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Delete a File or Directory                                            */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_unlink (\r
-    const TCHAR *path        /* Pointer to the file or directory path */\r
-)\r
-{\r
-    FRESULT res;\r
-    DIR_t dj, sdj;\r
-    BYTE *dir;\r
-    DWORD dclst;\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    res = chk_mounted(&path, &dj.fs, 1);\r
-    if (res == FR_OK) {\r
-        INIT_BUF(dj);\r
-        res = follow_path(&dj, path);        /* Follow the file path */\r
-        if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))\r
-            res = FR_INVALID_NAME;            /* Cannot remove dot entry */\r
-#if _FS_SHARE\r
-        if (res == FR_OK) res = chk_lock(&dj, 2);    /* Cannot remove open file */\r
-#endif\r
-        if (res == FR_OK) {                    /* The object is accessible */\r
-            dir = dj.dir;\r
-            if (!dir) {\r
-                res = FR_INVALID_NAME;        /* Cannot remove the start directory */\r
-            } else {\r
-                if (dir[DIR_Attr] & AM_RDO)\r
-                    res = FR_DENIED;        /* Cannot remove R/O object */\r
-            }\r
-            dclst = LD_CLUST(dir);\r
-            if (res == FR_OK && (dir[DIR_Attr] & AM_DIR)) {    /* Is it a sub-dir? */\r
-                if (dclst < 2) {\r
-                    res = FR_INT_ERR;\r
-                } else {\r
-                    mem_cpy(&sdj, &dj, sizeof(DIR_t));    /* Check if the sub-dir is empty or not */\r
-                    sdj.sclust = dclst;\r
-                    res = dir_sdi(&sdj, 2);        /* Exclude dot entries */\r
-                    if (res == FR_OK) {\r
-                        res = dir_read(&sdj);\r
-                        if (res == FR_OK            /* Not empty dir */\r
-#if _FS_RPATH\r
-                        || dclst == sdj.fs->cdir    /* Current dir */\r
-#endif\r
-                        ) res = FR_DENIED;\r
-                        if (res == FR_NO_FILE) res = FR_OK;    /* Empty */\r
-                    }\r
-                }\r
-            }\r
-            if (res == FR_OK) {\r
-                res = dir_remove(&dj);        /* Remove the directory entry */\r
-                if (res == FR_OK) {\r
-                    if (dclst)                /* Remove the cluster chain if exist */\r
-                        res = remove_chain(dj.fs, dclst);\r
-                    if (res == FR_OK) res = sync(dj.fs);\r
-                }\r
-            }\r
-        }\r
-        FREE_BUF();\r
-    }\r
-    LEAVE_FF(dj.fs, res);\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Create a Directory                                                    */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_mkdir (\r
-    const TCHAR *path        /* Pointer to the directory path */\r
-)\r
-{\r
-    FRESULT res;\r
-    DIR_t dj;\r
-    BYTE *dir, n;\r
-    DWORD dsc, dcl, pcl, tim = get_fattime();\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    res = chk_mounted(&path, &dj.fs, 1);\r
-    if (res == FR_OK) {\r
-        INIT_BUF(dj);\r
-        res = follow_path(&dj, path);            /* Follow the file path */\r
-        if (res == FR_OK) res = FR_EXIST;        /* Any object with same name is already existing */\r
-        if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NS] & NS_DOT))\r
-            res = FR_INVALID_NAME;\r
-        if (res == FR_NO_FILE) {                /* Can create a new directory */\r
-            dcl = create_chain(dj.fs, 0);        /* Allocate a cluster for the new directory table */\r
-            res = FR_OK;\r
-            if (dcl == 0) res = FR_DENIED;        /* No space to allocate a new cluster */\r
-            if (dcl == 1) res = FR_INT_ERR;\r
-            if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;\r
-            if (res == FR_OK)                    /* Flush FAT */\r
-                res = move_window(dj.fs, 0);\r
-            if (res == FR_OK) {                    /* Initialize the new directory table */\r
-                dsc = clust2sect(dj.fs, dcl);\r
-                dir = dj.fs->win;\r
-                mem_set(dir, 0, SS(dj.fs));\r
-                mem_set(dir+DIR_Name, ' ', 8+3);    /* Create "." entry */\r
-                dir[DIR_Name] = '.';\r
-                dir[DIR_Attr] = AM_DIR;\r
-                ST_DWORD(dir+DIR_WrtTime, tim);\r
-                ST_CLUST(dir, dcl);\r
-                mem_cpy(dir+SZ_DIR, dir, SZ_DIR);     /* Create ".." entry */\r
-                dir[33] = '.'; pcl = dj.sclust;\r
-                if (dj.fs->fs_type == FS_FAT32 && pcl == dj.fs->dirbase)\r
-                    pcl = 0;\r
-                ST_CLUST(dir+SZ_DIR, pcl);\r
-                for (n = dj.fs->csize; n; n--) {    /* Write dot entries and clear following sectors */\r
-                    dj.fs->winsect = dsc++;\r
-                    dj.fs->wflag = 1;\r
-                    res = move_window(dj.fs, 0);\r
-                    if (res != FR_OK) break;\r
-                    mem_set(dir, 0, SS(dj.fs));\r
-    }\r
-            }\r
-            if (res == FR_OK) res = dir_register(&dj);    /* Register the object to the directoy */\r
-            if (res != FR_OK) {\r
-                remove_chain(dj.fs, dcl);            /* Could not register, remove cluster chain */\r
-            } else {\r
-                dir = dj.dir;\r
-    dir[DIR_Attr] = AM_DIR;                        /* Attribute */\r
-                ST_DWORD(dir+DIR_WrtTime, tim);        /* Created time */\r
-                ST_CLUST(dir, dcl);                    /* Table start cluster */\r
-                dj.fs->wflag = 1;\r
-                res = sync(dj.fs);\r
-            }\r
-        }\r
-        FREE_BUF();\r
-    }\r
-\r
-    LEAVE_FF(dj.fs, res);\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Change Attribute                                                      */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_chmod (\r
-    const TCHAR *path,    /* Pointer to the file path */\r
-    BYTE value,            /* Attribute bits */\r
-    BYTE mask            /* Attribute mask to change */\r
-)\r
-{\r
-    FRESULT res;\r
-    DIR_t dj;\r
-    BYTE *dir;\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    res = chk_mounted(&path, &dj.fs, 1);\r
-    if (res == FR_OK) {\r
-        INIT_BUF(dj);\r
-        res = follow_path(&dj, path);        /* Follow the file path */\r
-        FREE_BUF();\r
-        if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))\r
-            res = FR_INVALID_NAME;\r
-        if (res == FR_OK) {\r
-            dir = dj.dir;\r
-            if (!dir) {                        /* Is it a root directory? */\r
-                res = FR_INVALID_NAME;\r
-            } else {                        /* File or sub directory */\r
-                mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC;    /* Valid attribute mask */\r
-                dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask);    /* Apply attribute change */\r
-                dj.fs->wflag = 1;\r
-                res = sync(dj.fs);\r
-            }\r
-        }\r
-    }\r
-\r
-    LEAVE_FF(dj.fs, res);\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Change Timestamp                                                      */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_utime (\r
-    const TCHAR *path,    /* Pointer to the file/directory name */\r
-    const FILINFO *fno    /* Pointer to the time stamp to be set */\r
-)\r
-{\r
-    FRESULT res;\r
-    DIR_t dj;\r
-    BYTE *dir;\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    res = chk_mounted(&path, &dj.fs, 1);\r
-    if (res == FR_OK) {\r
-        INIT_BUF(dj);\r
-        res = follow_path(&dj, path);    /* Follow the file path */\r
-        FREE_BUF();\r
-        if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))\r
-            res = FR_INVALID_NAME;\r
-        if (res == FR_OK) {\r
-            dir = dj.dir;\r
-            if (!dir) {                    /* Root directory */\r
-                res = FR_INVALID_NAME;\r
-            } else {                    /* File or sub-directory */\r
-                ST_WORD(dir+DIR_WrtTime, fno->ftime);\r
-                ST_WORD(dir+DIR_WrtDate, fno->fdate);\r
-                dj.fs->wflag = 1;\r
-                res = sync(dj.fs);\r
-            }\r
-        }\r
-    }\r
-\r
-    LEAVE_FF(dj.fs, res);\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Rename File/Directory                                                 */\r
-/*-----------------------------------------------------------------------*/\r
-\r
-FRESULT f_rename (\r
-    const TCHAR *path_old,    /* Pointer to the old name */\r
-    const TCHAR *path_new    /* Pointer to the new name */\r
-)\r
-{\r
-    FRESULT res;\r
-    DIR_t djo, djn;\r
-    BYTE buf[21], *dir;\r
-    DWORD dw;\r
-    DEF_NAMEBUF;\r
-\r
-\r
-    res = chk_mounted(&path_old, &djo.fs, 1);\r
-    if (res == FR_OK) {\r
-        djn.fs = djo.fs;\r
-        INIT_BUF(djo);\r
-        res = follow_path(&djo, path_old);        /* Check old object */\r
-        if (_FS_RPATH && res == FR_OK && (djo.fn[NS] & NS_DOT))\r
-            res = FR_INVALID_NAME;\r
-#if _FS_SHARE\r
-        if (res == FR_OK) res = chk_lock(&djo, 2);\r
-#endif\r
-        if (res == FR_OK) {                        /* Old object is found */\r
-            if (!djo.dir) {                        /* Is root dir? */\r
-                res = FR_NO_FILE;\r
-            } else {\r
-                mem_cpy(buf, djo.dir+DIR_Attr, 21);        /* Save the object information except for name */\r
-                mem_cpy(&djn, &djo, sizeof(DIR_t));        /* Check new object */\r
-                res = follow_path(&djn, path_new);\r
-                if (res == FR_OK) res = FR_EXIST;        /* The new object name is already existing */\r
-                if (res == FR_NO_FILE) {                 /* Is it a valid path and no name collision? */\r
-/* Start critical section that any interruption or error can cause cross-link */\r
-                    res = dir_register(&djn);            /* Register the new entry */\r
-                    if (res == FR_OK) {\r
-                        dir = djn.dir;                    /* Copy object information except for name */\r
-                        mem_cpy(dir+13, buf+2, 19);\r
-                        dir[DIR_Attr] = buf[0] | AM_ARC;\r
-                        djo.fs->wflag = 1;\r
-                        if (djo.sclust != djn.sclust && (dir[DIR_Attr] & AM_DIR)) {        /* Update .. entry in the directory if needed */\r
-                            dw = clust2sect(djn.fs, LD_CLUST(dir));\r
-                            if (!dw) {\r
-                                res = FR_INT_ERR;\r
-                            } else {\r
-                                res = move_window(djn.fs, dw);\r
-                                dir = djn.fs->win+SZ_DIR;    /* .. entry */\r
-                                if (res == FR_OK && dir[1] == '.') {\r
-                                    dw = (djn.fs->fs_type == FS_FAT32 && djn.sclust == djn.fs->dirbase) ? 0 : djn.sclust;\r
-                                    ST_CLUST(dir, dw);\r
-                                    djn.fs->wflag = 1;\r
-                                }\r
-                            }\r
-                        }\r
-                        if (res == FR_OK) {\r
-                            res = dir_remove(&djo);        /* Remove old entry */\r
-                            if (res == FR_OK)\r
-                                res = sync(djo.fs);\r
-                        }\r
-                    }\r
-/* End critical section */\r
-                }\r
-            }\r
-        }\r
-        FREE_BUF();\r
-    }\r
-    LEAVE_FF(djo.fs, res);\r
-}\r
-\r
-#endif /* !_FS_READONLY */\r
-#endif /* _FS_MINIMIZE == 0 */\r
-#endif /* _FS_MINIMIZE <= 1 */\r
-#endif /* _FS_MINIMIZE <= 2 */\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Forward data to the stream directly (available on only tiny cfg)      */\r
-/*-----------------------------------------------------------------------*/\r
-#if _USE_FORWARD && _FS_TINY\r
-\r
-FRESULT f_forward (\r
-    FIL_t *fp,                         /* Pointer to the file object */\r
-    UINT (*func)(const BYTE*,UINT),    /* Pointer to the streaming function */\r
-    UINT btr,                        /* Number of bytes to forward */\r
-    UINT *bf                        /* Pointer to number of bytes forwarded */\r
-)\r
-{\r
-    FRESULT res;\r
-    DWORD remain, clst, sect;\r
-    UINT rcnt;\r
-    BYTE csect;\r
-\r
-\r
-    *bf = 0;    /* Initialize byte counter */\r
-\r
-    res = validate(fp->fs, fp->id);                    /* Check validity of the object */\r
-    if (res != FR_OK) LEAVE_FF(fp->fs, res);\r
-    if (fp->flag & FA__ERROR)                        /* Check error flag */\r
-        LEAVE_FF(fp->fs, FR_INT_ERR);\r
-    if (!(fp->flag & FA_READ))                        /* Check access mode */\r
-        LEAVE_FF(fp->fs, FR_DENIED);\r
-\r
-    remain = fp->fsize - fp->fptr;\r
-    if (btr > remain) btr = (UINT)remain;            /* Truncate btr by remaining bytes */\r
-\r
-    for ( ;  btr && (*func)(0, 0);                    /* Repeat until all data transferred or stream becomes busy */\r
-        fp->fptr += rcnt, *bf += rcnt, btr -= rcnt) {\r
-        csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1));    /* Sector offset in the cluster */\r
-        if ((fp->fptr % SS(fp->fs)) == 0) {            /* On the sector boundary? */\r
-            if (!csect) {                            /* On the cluster boundary? */\r
-                clst = (fp->fptr == 0) ?            /* On the top of the file? */\r
-                    fp->sclust : get_fat(fp->fs, fp->clust);\r
-                if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);\r
-                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);\r
-                fp->clust = clst;                    /* Update current cluster */\r
-            }\r
-        }\r
-        sect = clust2sect(fp->fs, fp->clust);        /* Get current data sector */\r
-        if (!sect) ABORT(fp->fs, FR_INT_ERR);\r
-        sect += csect;\r
-        if (move_window(fp->fs, sect))                /* Move sector window */\r
-            ABORT(fp->fs, FR_DISK_ERR);\r
-        fp->dsect = sect;\r
-        rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs));    /* Forward data from sector window */\r
-        if (rcnt > btr) rcnt = btr;\r
-        rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt);\r
-        if (!rcnt) ABORT(fp->fs, FR_INT_ERR);\r
-}\r
-\r
-    LEAVE_FF(fp->fs, FR_OK);\r
-}\r
-#endif /* _USE_FORWARD */\r
-\r
-\r
-\r
-#if _USE_MKFS && !_FS_READONLY\r
-/*-----------------------------------------------------------------------*/\r
-/* Create File System on the Drive                                       */\r
-/*-----------------------------------------------------------------------*/\r
-#define N_ROOTDIR    512        /* Number of root dir entries for FAT12/16 */\r
-#define N_FATS        1        /* Number of FAT copies (1 or 2) */\r
-\r
-\r
-FRESULT f_mkfs (\r
-    BYTE drv,            /* Logical drive number */\r
-    BYTE sfd,        /* Partitioning rule 0:FDISK, 1:SFD */\r
-    UINT au            /* Allocation unit size [bytes] */\r
-)\r
-{\r
-    static const WORD vst[] = { 1024,   512,  256,  128,   64,    32,   16,    8,    4,    2,   0};\r
-    static const WORD cst[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512};\r
-    BYTE fmt, md, *tbl;\r
-    DWORD n_clst, vs, n, wsect;\r
-    UINT i;\r
-    DWORD b_vol, b_fat, b_dir, b_data;    /* Offset (LBA) */\r
-    DWORD n_vol, n_rsv, n_fat, n_dir;    /* Size */\r
-    FATFS *fs;\r
-    DSTATUS stat;\r
-\r
-\r
-    /* Check mounted drive and clear work area */\r
-    if (drv >= _VOLUMES) return FR_INVALID_DRIVE;\r
-    fs = FatFs[drv];\r
-    if (!fs) return FR_NOT_ENABLED;\r
-    fs->fs_type = 0;\r
-    drv = LD2PD(drv);\r
-\r
-    /* Get disk statics */\r
-    stat = disk_initialize(drv);\r
-    if (stat & STA_NOINIT) return FR_NOT_READY;\r
-    if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;\r
-#if _MAX_SS != 512                    /* Get disk sector size */\r
-    if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK)\r
-        return FR_DISK_ERR;\r
-#endif\r
-    if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_vol) != RES_OK || n_vol < 128)\r
-        return FR_DISK_ERR;\r
-    b_vol = (sfd) ? 0 : 63;    /* Volume start sector */\r
-    n_vol -= b_vol;\r
-    if (au & (au - 1)) au = 0;    /* Check validity of the AU size */\r
-    if (!au) {                    /* AU auto selection */\r
-        vs = n_vol / (2000 / (SS(fs) / 512));\r
-        for (i = 0; vs < vst[i]; i++) ;\r
-        au = cst[i];\r
-    }\r
-    au /= SS(fs);        /* Number of sectors per cluster */\r
-    if (au == 0) au = 1;\r
-    if (au > 128) au = 128;\r
-\r
-    /* Pre-compute number of clusters and FAT syb-type */\r
-    n_clst = n_vol / au;\r
-    fmt = FS_FAT12;\r
-    if (n_clst >= MIN_FAT16) fmt = FS_FAT16;\r
-    if (n_clst >= MIN_FAT32) fmt = FS_FAT32;\r
-\r
-    /* Determine offset and size of FAT structure */\r
-    if (fmt == FS_FAT32) {\r
-        n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs);\r
-        n_rsv = 32;\r
-        n_dir = 0;\r
-    } else {\r
-        n_fat = (fmt == FS_FAT12) ? (n_clst * 3 + 1) / 2 + 3 : (n_clst * 2) + 4;\r
-        n_fat = (n_fat + SS(fs) - 1) / SS(fs);\r
-        n_rsv = 1;\r
-        n_dir = (DWORD)N_ROOTDIR * SZ_DIR / SS(fs);\r
-    }\r
-    b_fat = b_vol + n_rsv;                /* FAT area start sector */\r
-    b_dir = b_fat + n_fat * N_FATS;        /* Directory area start sector */\r
-    b_data = b_dir + n_dir;                /* Data area start sector */\r
-    if (n_vol < b_data + au) return FR_MKFS_ABORTED;    /* Too small volume */\r
-\r
-    /* Align data start sector to erase block boundary (for flash memory media) */\r
-    if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK || !n || n > 32768) n = 1;\r
-    n = (b_data + n - 1) & ~(n - 1);    /* Next nearest erase block from current data start */\r
-    n = (n - b_data) / N_FATS;\r
-    if (fmt == FS_FAT32) {        /* FAT32: Move FAT offset */\r
-        n_rsv += n;\r
-        b_fat += n;\r
-    } else {                    /* FAT12/16: Expand FAT size */\r
-        n_fat += n;\r
-    }\r
-\r
-    /* Determine number of clusters and final check of validity of the FAT sub-type */\r
-    n_clst = (n_vol - n_rsv - n_fat * N_FATS - n_dir) / au;\r
-    if (   (fmt == FS_FAT16 && n_clst < MIN_FAT16)\r
-        || (fmt == FS_FAT32 && n_clst < MIN_FAT32))\r
-        return FR_MKFS_ABORTED;\r
-\r
-    /* Create partition table if required */\r
-    if (sfd) {    /* No patition table (SFD) */\r
-        md = 0xF0;\r
-    } else {    /* With patition table (FDISK) */\r
-        DWORD n_disk = b_vol + n_vol;\r
-\r
-        mem_set(fs->win, 0, SS(fs));\r
-        tbl = fs->win+MBR_Table;\r
-        ST_DWORD(tbl, 0x00010180);            /* Partition start in CHS */\r
-        if (n_disk < 63UL * 255 * 1024) {    /* Partition end in CHS */\r
-            n_disk = n_disk / 63 / 255;\r
-            tbl[7] = (BYTE)n_disk;\r
-            tbl[6] = (BYTE)((n_disk >> 2) | 63);\r
-        } else {\r
-            ST_WORD(&tbl[6], 0xFFFF);    /* CHS saturated */\r
-        }\r
-        tbl[5] = 254;\r
-        if (fmt != FS_FAT32)            /* System ID */\r
-            tbl[4] = (n_vol < 0x10000) ? 0x04 : 0x06;\r
-        else\r
-            tbl[4] = 0x0c;\r
-        ST_DWORD(tbl+8, 63);                /* Partition start in LBA */\r
-        ST_DWORD(tbl+12, n_vol);            /* Partition size in LBA */\r
-        ST_WORD(fs->win+BS_55AA, 0xAA55);    /* MBR signature */\r
-        if (disk_write(drv, fs->win, 0, 1) != RES_OK)    /* Put the MBR into first physical sector */\r
-            return FR_DISK_ERR;\r
-        md = 0xF8;\r
-    }\r
-\r
-    /* Create volume boot record */\r
-    tbl = fs->win;                            /* Clear sector */\r
-    mem_set(tbl, 0, SS(fs));\r
-    mem_cpy(tbl, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code, OEM name */\r
-    i = SS(fs);                                /* Sector size */\r
-    ST_WORD(tbl+BPB_BytsPerSec, i);\r
-    tbl[BPB_SecPerClus] = (BYTE)au;            /* Sectors per cluster */\r
-    ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv);        /* Reserved sectors */\r
-    tbl[BPB_NumFATs] = N_FATS;                    /* Number of FATs */\r
-    i = (fmt == FS_FAT32) ? 0 : N_ROOTDIR;    /* Number of rootdir entries */\r
-    ST_WORD(tbl+BPB_RootEntCnt, i);\r
-    if (n_vol < 0x10000) {                    /* Number of total sectors */\r
-        ST_WORD(tbl+BPB_TotSec16, n_vol);\r
-    } else {\r
-        ST_DWORD(tbl+BPB_TotSec32, n_vol);\r
-    }\r
-    tbl[BPB_Media] = md;                    /* Media descriptor */\r
-    ST_WORD(tbl+BPB_SecPerTrk, 63);            /* Number of sectors per track */\r
-    ST_WORD(tbl+BPB_NumHeads, 255);            /* Number of heads */\r
-    ST_DWORD(tbl+BPB_HiddSec, b_vol);        /* Hidden sectors */\r
-    n = get_fattime();                        /* Use current time as VSN */\r
-    if (fmt == FS_FAT32) {\r
-        ST_DWORD(tbl+BS_VolID32, n);        /* VSN */\r
-        ST_DWORD(tbl+BPB_FATSz32, n_fat);    /* Number of sectors per FAT */\r
-        ST_DWORD(tbl+BPB_RootClus, 2);        /* Root directory start cluster (2) */\r
-        ST_WORD(tbl+BPB_FSInfo, 1);            /* FSInfo record offset (VBR+1) */\r
-        ST_WORD(tbl+BPB_BkBootSec, 6);        /* Backup boot record offset (VBR+6) */\r
-        tbl[BS_DrvNum32] = 0x80;                /* Drive number */\r
-        tbl[BS_BootSig32] = 0x29;                /* Extended boot signature */\r
-        mem_cpy(tbl+BS_VolLab32, "NO NAME    " "FAT32   ", 19);    /* Volume label, FAT signature */\r
-    } else {\r
-        ST_DWORD(tbl+BS_VolID, n);            /* VSN */\r
-        ST_WORD(tbl+BPB_FATSz16, n_fat);    /* Number of sectors per FAT */\r
-        tbl[BS_DrvNum] = 0x80;                /* Drive number */\r
-        tbl[BS_BootSig] = 0x29;                /* Extended boot signature */\r
-        mem_cpy(tbl+BS_VolLab, "NO NAME    " "FAT     ", 19);    /* Volume label, FAT signature */\r
-    }\r
-    ST_WORD(tbl+BS_55AA, 0xAA55);            /* Signature (Offset is fixed here regardless of sector size) */\r
-    if (disk_write(drv, tbl, b_vol, 1) != RES_OK)    /* Write VBR */\r
-        return FR_DISK_ERR;\r
-    if (fmt == FS_FAT32)                            /* Write backup VBR if needed (VBR+6) */\r
-        disk_write(drv, tbl, b_vol + 6, 1);\r
-\r
-    /* Initialize FAT area */\r
-    wsect = b_fat;\r
-    for (i = 0; i < N_FATS; i++) {        /* Initialize each FAT copy */\r
-        mem_set(tbl, 0, SS(fs));            /* 1st sector of the FAT  */\r
-        n = md;                                /* Media descriptor byte */\r
-        if (fmt != FS_FAT32) {\r
-            n |= (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00;\r
-            ST_DWORD(tbl+0, n);                /* Reserve cluster #0-1 (FAT12/16) */\r
-        } else {\r
-            n |= 0xFFFFFF00;\r
-            ST_DWORD(tbl+0, n);                /* Reserve cluster #0-1 (FAT32) */\r
-            ST_DWORD(tbl+4, 0xFFFFFFFF);\r
-            ST_DWORD(tbl+8, 0x0FFFFFFF);    /* Reserve cluster #2 for root dir */\r
-        }\r
-        if (disk_write(drv, tbl, wsect++, 1) != RES_OK)\r
-            return FR_DISK_ERR;\r
-        mem_set(tbl, 0, SS(fs));            /* Fill following FAT entries with zero */\r
-        for (n = 1; n < n_fat; n++) {        /* This loop may take a time on FAT32 volume due to many single sector writes */\r
-            if (disk_write(drv, tbl, wsect++, 1) != RES_OK)\r
-                return FR_DISK_ERR;\r
-        }\r
-    }\r
-\r
-    /* Initialize root directory */\r
-    i = (fmt == FS_FAT32) ? au : n_dir;\r
-    do {\r
-        if (disk_write(drv, tbl, wsect++, 1) != RES_OK)\r
-            return FR_DISK_ERR;\r
-    } while (--i);\r
-\r
-#if _USE_ERASE    /* Erase data area if needed */\r
-    {\r
-        DWORD eb[2];\r
-\r
-        eb[0] = wsect; eb[1] = wsect + (n_clst - ((fmt == FS_FAT32) ? 1 : 0)) * au - 1;\r
-        disk_ioctl(drv, CTRL_ERASE_SECTOR, eb);\r
-    }\r
-#endif\r
-\r
-    /* Create FSInfo if needed */\r
-    if (fmt == FS_FAT32) {\r
-        ST_DWORD(tbl+FSI_LeadSig, 0x41615252);\r
-        ST_DWORD(tbl+FSI_StrucSig, 0x61417272);\r
-        ST_DWORD(tbl+FSI_Free_Count, n_clst - 1);    /* Number of free clusters */\r
-        ST_DWORD(tbl+FSI_Nxt_Free, 2);                /* Last allocated cluster# */\r
-        ST_WORD(tbl+BS_55AA, 0xAA55);\r
-        disk_write(drv, tbl, b_vol + 1, 1);    /* Write original (VBR+1) */\r
-        disk_write(drv, tbl, b_vol + 7, 1);    /* Write backup (VBR+7) */\r
-    }\r
-\r
-    return (disk_ioctl(drv, CTRL_SYNC, (void*)0) == RES_OK) ? FR_OK : FR_DISK_ERR;\r
-}\r
-\r
-#endif /* _USE_MKFS && !_FS_READONLY */\r
-\r
-\r
-\r
-\r
-#if _USE_STRFUNC\r
-/*-----------------------------------------------------------------------*/\r
-/* Get a string from the file                                            */\r
-/*-----------------------------------------------------------------------*/\r
-TCHAR* f_gets (\r
-    TCHAR* buff,    /* Pointer to the string buffer to read */\r
-    int len,        /* Size of string buffer (characters) */\r
-    FIL_t* fil    /* Pointer to the file object */\r
-)\r
-{\r
-    int n = 0;\r
-    TCHAR c, *p = buff;\r
-    BYTE s[2];\r
-    UINT rc;\r
-\r
-\r
-    while (n < len - 1) {            /* Read bytes until buffer gets filled */\r
-        f_read(fil, s, 1, &rc);\r
-        if (rc != 1) break;            /* Break on EOF or error */\r
-        c = s[0];\r
-#if _LFN_UNICODE                    /* Read a character in UTF-8 encoding */\r
-        if (c >= 0x80) {\r
-            if (c < 0xC0) continue;    /* Skip stray trailer */\r
-            if (c < 0xE0) {            /* Two-byte sequense */\r
-                f_read(fil, s, 1, &rc);\r
-                if (rc != 1) break;\r
-                c = ((c & 0x1F) << 6) | (s[0] & 0x3F);\r
-                if (c < 0x80) c = '?';\r
-            } else {\r
-                if (c < 0xF0) {        /* Three-byte sequense */\r
-                    f_read(fil, s, 2, &rc);\r
-                    if (rc != 2) break;\r
-                    c = (c << 12) | ((s[0] & 0x3F) << 6) | (s[1] & 0x3F);\r
-                    if (c < 0x800) c = '?';\r
-                } else {            /* Reject four-byte sequense */\r
-                    c = '?';\r
-                }\r
-            }\r
-        }\r
-#endif\r
-#if _USE_STRFUNC >= 2\r
-        if (c == '\r') continue;    /* Strip '\r' */\r
-#endif\r
-        *p++ = c;\r
-        n++;\r
-        if (c == '\n') break;        /* Break on EOL */\r
-    }\r
-    *p = 0;\r
-    return n ? buff : 0;            /* When no data read (eof or error), return with error. */\r
-}\r
-\r
-\r
-\r
-#if !_FS_READONLY\r
-#include <stdarg.h>\r
-/*-----------------------------------------------------------------------*/\r
-/* Put a character to the file                                           */\r
-/*-----------------------------------------------------------------------*/\r
-int f_putc (\r
-    TCHAR c,    /* A character to be output */\r
-    FIL_t* fil    /* Pointer to the file object */\r
-)\r
-{\r
-    UINT bw, btw;\r
-    BYTE s[3];\r
-\r
-\r
-#if _USE_STRFUNC >= 2\r
-    if (c == '\n') f_putc ('\r', fil);    /* LF -> CRLF conversion */\r
-#endif\r
-\r
-#if _LFN_UNICODE    /* Write the character in UTF-8 encoding */\r
-    if (c < 0x80) {            /* 7-bit */\r
-        s[0] = (BYTE)c;\r
-        btw = 1;\r
-    } else {\r
-        if (c < 0x800) {    /* 11-bit */\r
-            s[0] = (BYTE)(0xC0 | (c >> 6));\r
-            s[1] = (BYTE)(0x80 | (c & 0x3F));\r
-            btw = 2;\r
-        } else {            /* 16-bit */\r
-            s[0] = (BYTE)(0xE0 | (c >> 12));\r
-            s[1] = (BYTE)(0x80 | ((c >> 6) & 0x3F));\r
-            s[2] = (BYTE)(0x80 | (c & 0x3F));\r
-            btw = 3;\r
-    }\r
-    }\r
-#else                /* Write the character without conversion */\r
-    s[0] = (BYTE)c;\r
-    btw = 1;\r
-#endif\r
-    f_write(fil, s, btw, &bw);        /* Write the char to the file */\r
-    return (bw == btw) ? 1 : EOF;    /* Return the result */\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Put a string to the file                                              */\r
-/*-----------------------------------------------------------------------*/\r
-int f_puts (\r
-    const TCHAR* str,    /* Pointer to the string to be output */\r
-    FIL_t* fil            /* Pointer to the file object */\r
-)\r
-{\r
-    int n;\r
-\r
-\r
-    for (n = 0; *str; str++, n++) {\r
-        if (f_putc(*str, fil) == EOF) return EOF;\r
-    }\r
-    return n;\r
-}\r
-\r
-\r
-\r
-\r
-/*-----------------------------------------------------------------------*/\r
-/* Put a formatted string to the file                                    */\r
-/*-----------------------------------------------------------------------*/\r
-int f_printf (\r
-    FIL_t* fil,            /* Pointer to the file object */\r
-    const TCHAR* str,    /* Pointer to the format string */\r
-    ...                    /* Optional arguments... */\r
-)\r
-{\r
-    va_list arp;\r
-    BYTE f, r;\r
-    UINT i, j, w;\r
-    ULONG v;\r
-    TCHAR c, d, s[16], *p;\r
-    int res, cc;\r
-\r
-\r
-    va_start(arp, str);\r
-\r
-    for (cc = res = 0; cc != EOF; res += cc) {\r
-        c = *str++;\r
-        if (c == 0) break;            /* End of string */\r
-        if (c != '%') {                /* Non escape character */\r
-            cc = f_putc(c, fil);\r
-            if (cc != EOF) cc = 1;\r
-            continue;\r
-        }\r
-        w = f = 0;\r
-        c = *str++;\r
-        if (c == '0') {                /* Flag: '0' padding */\r
-            f = 1; c = *str++;\r
-        } else {\r
-            if (c == '-') {            /* Flag: left justified */\r
-                f = 2; c = *str++;\r
-        }\r
-        }\r
-        while (IsDigit(c)) {        /* Precision */\r
-            w = w * 10 + c - '0';\r
-            c = *str++;\r
-        }\r
-        if (c == 'l' || c == 'L') {    /* Prefix: Size is long int */\r
-            f |= 4; c = *str++;\r
-        }\r
-        if (!c) break;\r
-        d = c;\r
-        if (IsLower(d)) d -= 0x20;\r
-        switch (d) {                /* Type is... */\r
-        case 'S' :                    /* String */\r
-            p = va_arg(arp, TCHAR*);\r
-            for (j = 0; p[j]; j++) ;\r
-            res = 0;\r
-            while (!(f & 2) && j++ < w) res += (cc = f_putc(' ', fil));\r
-            res += (cc = f_puts(p, fil));\r
-            while (j++ < w) res += (cc = f_putc(' ', fil));\r
-            if (cc != EOF) cc = res;\r
-            continue;\r
-        case 'C' :                    /* Character */\r
-            cc = f_putc((TCHAR)va_arg(arp, int), fil); continue;\r
-        case 'B' :                    /* Binary */\r
-            r = 2; break;\r
-        case 'O' :                    /* Octal */\r
-            r = 8; break;\r
-        case 'D' :                    /* Signed decimal */\r
-        case 'U' :                    /* Unsigned decimal */\r
-            r = 10; break;\r
-        case 'X' :                    /* Hexdecimal */\r
-            r = 16; break;\r
-        default:                    /* Unknown type (passthrough) */\r
-            cc = f_putc(c, fil); continue;\r
-        }\r
-\r
-        /* Get an argument and put it in numeral */\r
-        v = (f & 4) ? va_arg(arp, long) : ((d == 'D') ? (long)va_arg(arp, int) : va_arg(arp, unsigned int));\r
-        if (d == 'D' && (v & 0x80000000)) {\r
-            v = 0 - v;\r
-            f |= 8;\r
-        }\r
-        i = 0;\r
-        do {\r
-            d = (TCHAR)(v % r); v /= r;\r
-            if (d > 9) d += (c == 'x') ? 0x27 : 0x07;\r
-            s[i++] = d + '0';\r
-        } while (v && i < sizeof(s) / sizeof(s[0]));\r
-        if (f & 8) s[i++] = '-';\r
-        j = i; d = (f & 1) ? '0' : ' ';\r
-        res = 0;\r
-        while (!(f & 2) && j++ < w) res += (cc = f_putc(d, fil));\r
-        do res += (cc = f_putc(s[--i], fil)); while(i);\r
-        while (j++ < w) res += (cc = f_putc(' ', fil));\r
-        if (cc != EOF) cc = res;\r
-    }\r
-\r
-    va_end(arp);\r
-    return (cc == EOF) ? cc : res;\r
-}\r
-\r
-#endif /* !_FS_READONLY */\r
-#endif /* _USE_STRFUNC */\r
+    if (dj->sect) {
+        dir = dj->dir;
+        nt = dir[DIR_NTres];        /* NT flag */
+        for (i = 0; i < 8; i++) {    /* Copy name body */
+            c = dir[i];
+            if (c == ' ') break;
+            if (c == NDDE) c = (TCHAR)DDE;
+            if (_USE_LFN && (nt & NS_BODY) && IsUpper(c)) c += 0x20;
+#if _LFN_UNICODE
+            if (IsDBCS1(c) && i < 7 && IsDBCS2(dir[i+1]))
+                c = (c << 8) | dir[++i];
+            c = ff_convert(c, 1);
+            if (!c) c = '?';
+#endif
+            *p++ = c;
+        }
+        if (dir[8] != ' ') {        /* Copy name extension */
+            *p++ = '.';
+            for (i = 8; i < 11; i++) {
+                c = dir[i];
+                if (c == ' ') break;
+                if (_USE_LFN && (nt & NS_EXT) && IsUpper(c)) c += 0x20;
+#if _LFN_UNICODE
+                if (IsDBCS1(c) && i < 10 && IsDBCS2(dir[i+1]))
+                    c = (c << 8) | dir[++i];
+                c = ff_convert(c, 1);
+                if (!c) c = '?';
+#endif
+                *p++ = c;
+            }
+    }
+        fno->fattrib = dir[DIR_Attr];                /* Attribute */
+        fno->fsize = LD_DWORD(dir+DIR_FileSize);    /* Size */
+        fno->fdate = LD_WORD(dir+DIR_WrtDate);        /* Date */
+        fno->ftime = LD_WORD(dir+DIR_WrtTime);        /* Time */
+    }
+    *p = 0;        /* Terminate SFN str by a \0 */
+\r
+#if _USE_LFN
+    if (fno->lfname && fno->lfsize) {
+        TCHAR *tp = fno->lfname;
+        WCHAR w, *lfn;
+\r
+        i = 0;
+        if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */
+            lfn = dj->lfn;
+            while ((w = *lfn++) != 0) {            /* Get an LFN char */
+#if !_LFN_UNICODE
+                w = ff_convert(w, 0);            /* Unicode -> OEM conversion */
+                if (!w) { i = 0; break; }        /* Could not convert, no LFN */
+                if (_DF1S && w >= 0x100)        /* Put 1st byte if it is a DBC (always false on SBCS cfg) */
+                    tp[i++] = (TCHAR)(w >> 8);
+#endif
+                if (i >= fno->lfsize - 1) { i = 0; break; }    /* Buffer overflow, no LFN */
+                tp[i++] = (TCHAR)w;
+            }
+\r
+        }
+        tp[i] = 0;    /* Terminate the LFN str by a \0 */
+    }
+#endif
+}
+#endif /* _FS_MINIMIZE <= 1 */
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Follow a file path                                                    */
+/*-----------------------------------------------------------------------*/
+\r
+static
+FRESULT follow_path (    /* FR_OK(0): successful, !=0: error code */
+    DIR_t *dj,            /* Directory object to return last directory and found object */
+    const TCHAR *path    /* Full-path string to find a file or directory */
+)
+{
+    FRESULT res;
+    BYTE *dir, ns;
+\r
+\r
+#if _FS_RPATH
+    if (*path == '/' || *path == '\\') { /* There is a heading separator */
+        path++;    dj->sclust = 0;        /* Strip it and start from the root dir */
+    } else {                            /* No heading separator */
+        dj->sclust = dj->fs->cdir;    /* Start from the current dir */
+    }
+#else
+    if (*path == '/' || *path == '\\')    /* Strip heading separator if exist */
+        path++;
+    dj->sclust = 0;                        /* Start from the root dir */
+#endif
+\r
+    if ((UINT)*path < ' ') {            /* Nul path means the start directory itself */
+        res = dir_sdi(dj, 0);
+        dj->dir = 0;
+\r
+    } else {                            /* Follow path */
+        for (;;) {
+            res = create_name(dj, &path);    /* Get a segment */
+            if (res != FR_OK) break;
+            res = dir_find(dj);                /* Find it */
+            ns = *(dj->fn+NS);
+            if (res != FR_OK) {                /* Failed to find the object */
+                if (res != FR_NO_FILE) break;    /* Abort if any hard error occured */
+                /* Object not found */
+                if (_FS_RPATH && (ns & NS_DOT)) {    /* If dot entry is not exit */
+                    dj->sclust = 0; dj->dir = 0;    /* It is the root dir */
+                    res = FR_OK;
+                    if (!(ns & NS_LAST)) continue;
+                } else {                            /* Could not find the object */
+                    if (!(ns & NS_LAST)) res = FR_NO_PATH;
+                }
+                break;
+            }
+            if (ns & NS_LAST) break;            /* Last segment match. Function completed. */
+            dir = dj->dir;                        /* There is next segment. Follow the sub directory */
+            if (!(dir[DIR_Attr] & AM_DIR)) {    /* Cannot follow because it is a file */
+                res = FR_NO_PATH; break;
+            }
+            dj->sclust = LD_CLUST(dir);
+        }
+    }
+\r
+    return res;
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Load boot record and check if it is an FAT boot record                */
+/*-----------------------------------------------------------------------*/
+\r
+static
+BYTE check_fs (    /* 0:The FAT BR, 1:Valid BR but not an FAT, 2:Not a BR, 3:Disk error */
+    FATFS *fs,    /* File system object */
+    DWORD sect    /* Sector# (lba) to check if it is an FAT boot record or not */
+)
+{
+    if (disk_read(fs->drv, fs->win, sect, 1) != RES_OK)    /* Load boot record */
+        return 3;
+    if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55)                /* Check record signature (always placed at offset 510 even if the sector size is >512) */
+        return 2;
+\r
+    if ((LD_DWORD(&fs->win[BS_FilSysType]) & 0xFFFFFF) == 0x544146)    /* Check "FAT" string */
+        return 0;
+    if ((LD_DWORD(&fs->win[BS_FilSysType32]) & 0xFFFFFF) == 0x544146)
+        return 0;
+\r
+    return 1;
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Check if the file system object is valid or not                       */
+/*-----------------------------------------------------------------------*/
+\r
+static
+FRESULT chk_mounted (    /* FR_OK(0): successful, !=0: any error occurred */
+    const TCHAR **path,    /* Pointer to pointer to the path name (drive number) */
+    FATFS **rfs,        /* Pointer to pointer to the found file system object */
+    BYTE chk_wp            /* !=0: Check media write protection for write access */
+)
+{
+    BYTE fmt, b, *tbl;
+    UINT vol;
+    DSTATUS stat;
+    DWORD bsect, fasize, tsect, sysect, nclst, szbfat;
+    WORD nrsv;
+    const TCHAR *p = *path;
+    FATFS *fs;
+\r
+    /* Get logical drive number from the path name */
+    vol = p[0] - '0';                    /* Is there a drive number? */
+    if (vol <= 9 && p[1] == ':') {        /* Found a drive number, get and strip it */
+        p += 2; *path = p;                /* Return pointer to the path name */
+    } else {                            /* No drive number is given */
+#if _FS_RPATH
+        vol = CurrVol;                    /* Use current drive */
+#else
+        vol = 0;                        /* Use drive 0 */
+#endif
+    }
+\r
+    /* Check if the logical drive is valid or not */
+    if (vol >= _VOLUMES)                 /* Is the drive number valid? */
+        return FR_INVALID_DRIVE;
+    *rfs = fs = FatFs[vol];                /* Return pointer to the corresponding file system object */
+    if (!fs) return FR_NOT_ENABLED;        /* Is the file system object available? */
+\r
+    ENTER_FF(fs);                        /* Lock file system */
+\r
+    if (fs->fs_type) {                        /* If the logical drive has been mounted */
+        stat = disk_status(fs->drv);
+        if (!(stat & STA_NOINIT)) {        /* and the physical drive is kept initialized (has not been changed), */
+#if !_FS_READONLY
+            if (chk_wp && (stat & STA_PROTECT))    /* Check write protection if needed */
+                return FR_WRITE_PROTECTED;
+#endif
+            return FR_OK;                    /* The file system object is valid */
+        }
+    }
+\r
+    /* The logical drive must be mounted. */
+    /* Following code attempts to mount a volume. (analyze BPB and initialize the fs object) */
+\r
+    fs->fs_type = 0;                    /* Clear the file system object */
+    fs->drv = (BYTE)LD2PD(vol);            /* Bind the logical drive and a physical drive */
+    stat = disk_initialize(fs->drv);    /* Initialize low level disk I/O layer */
+    if (stat & STA_NOINIT)                /* Check if the initialization succeeded */
+        return FR_NOT_READY;            /* Failed to initialize due to no media or hard error */
+#if _MAX_SS != 512                        /* Get disk sector size (variable sector size cfg only) */
+    if (disk_ioctl(fs->drv, GET_SECTOR_SIZE, &fs->ssize) != RES_OK)
+        return FR_DISK_ERR;
+#endif
+#if !_FS_READONLY
+    if (chk_wp && (stat & STA_PROTECT))    /* Check disk write protection if needed */
+        return FR_WRITE_PROTECTED;
+#endif
+    /* Search FAT partition on the drive. Supports only generic partitionings, FDISK and SFD. */
+    fmt = check_fs(fs, bsect = 0);        /* Check sector 0 if it is a VBR */
+    if (fmt == 1) {                        /* Not an FAT-VBR, the disk may be partitioned */
+        /* Check the partition listed in top of the partition table */
+        tbl = &fs->win[MBR_Table + LD2PT(vol) * SZ_PTE];/* Partition table */
+        if (tbl[4]) {                                    /* Is the partition existing? */
+            bsect = LD_DWORD(&tbl[8]);                    /* Partition offset in LBA */
+            fmt = check_fs(fs, bsect);                    /* Check the partition */
+        }
+    }
+    if (fmt == 3) return FR_DISK_ERR;
+    if (fmt) return FR_NO_FILESYSTEM;                    /* No FAT volume is found */
+\r
+    /* Following code initializes the file system object */
+\r
+    if (LD_WORD(fs->win+BPB_BytsPerSec) != SS(fs))        /* (BPB_BytsPerSec must be equal to the physical sector size) */
+        return FR_NO_FILESYSTEM;
+\r
+    fasize = LD_WORD(fs->win+BPB_FATSz16);                /* Number of sectors per FAT */
+    if (!fasize) fasize = LD_DWORD(fs->win+BPB_FATSz32);
+    fs->fsize = fasize;
+\r
+    fs->n_fats = b = fs->win[BPB_NumFATs];                /* Number of FAT copies */
+    if (b != 1 && b != 2) return FR_NO_FILESYSTEM;        /* (Must be 1 or 2) */
+    fasize *= b;                                        /* Number of sectors for FAT area */
+\r
+    fs->csize = b = fs->win[BPB_SecPerClus];            /* Number of sectors per cluster */
+    if (!b || (b & (b - 1))) return FR_NO_FILESYSTEM;    /* (Must be power of 2) */
+\r
+    fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt);    /* Number of root directory entries */
+    if (fs->n_rootdir % (SS(fs) / SZ_DIR)) return FR_NO_FILESYSTEM;    /* (BPB_RootEntCnt must be sector aligned) */
+\r
+    tsect = LD_WORD(fs->win+BPB_TotSec16);                /* Number of sectors on the volume */
+    if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32);
+\r
+    nrsv = LD_WORD(fs->win+BPB_RsvdSecCnt);                /* Number of reserved sectors */
+    if (!nrsv) return FR_NO_FILESYSTEM;                    /* (BPB_RsvdSecCnt must not be 0) */
+\r
+    /* Determine the FAT sub type */
+    sysect = nrsv + fasize + fs->n_rootdir / (SS(fs) / SZ_DIR);    /* RSV+FAT+DIR */
+    if (tsect < sysect) return FR_NO_FILESYSTEM;        /* (Invalid volume size) */
+    nclst = (tsect - sysect) / fs->csize;                /* Number of clusters */
+    if (!nclst) return FR_NO_FILESYSTEM;                /* (Invalid volume size) */
+    fmt = FS_FAT12;
+    if (nclst >= MIN_FAT16) fmt = FS_FAT16;
+    if (nclst >= MIN_FAT32) fmt = FS_FAT32;
+\r
+    /* Boundaries and Limits */
+    fs->n_fatent = nclst + 2;                            /* Number of FAT entries */
+    fs->database = bsect + sysect;                        /* Data start sector */
+    fs->fatbase = bsect + nrsv;                         /* FAT start sector */
+    if (fmt == FS_FAT32) {
+        if (fs->n_rootdir) return FR_NO_FILESYSTEM;        /* (BPB_RootEntCnt must be 0) */
+        fs->dirbase = LD_DWORD(fs->win+BPB_RootClus);    /* Root directory start cluster */
+        szbfat = fs->n_fatent * 4;                        /* (Required FAT size) */
+    } else {
+        if (!fs->n_rootdir)    return FR_NO_FILESYSTEM;    /* (BPB_RootEntCnt must not be 0) */
+        fs->dirbase = fs->fatbase + fasize;                /* Root directory start sector */
+        szbfat = (fmt == FS_FAT16) ?                    /* (Required FAT size) */
+            fs->n_fatent * 2 : fs->n_fatent * 3 / 2 + (fs->n_fatent & 1);
+    }
+    if (fs->fsize < (szbfat + (SS(fs) - 1)) / SS(fs))    /* (BPB_FATSz must not be less than required) */
+        return FR_NO_FILESYSTEM;
+\r
+#if !_FS_READONLY
+    /* Initialize cluster allocation information */
+    fs->free_clust = 0xFFFFFFFF;
+    fs->last_clust = 0;
+\r
+    /* Get fsinfo if available */
+    if (fmt == FS_FAT32) {
+         fs->fsi_flag = 0;
+        fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo);
+        if (disk_read(fs->drv, fs->win, fs->fsi_sector, 1) == RES_OK &&
+            LD_WORD(fs->win+BS_55AA) == 0xAA55 &&
+            LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 &&
+            LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) {
+                fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free);
+                fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count);
+        }
+    }
+#endif
+    fs->fs_type = fmt;        /* FAT sub-type */
+    fs->id = ++Fsid;        /* File system mount ID */
+    fs->winsect = 0;        /* Invalidate sector cache */
+    fs->wflag = 0;
+#if _FS_RPATH
+    fs->cdir = 0;            /* Current directory (root dir) */
+#endif
+#if _FS_SHARE                /* Clear file lock semaphores */
+    clear_lock(fs);
+#endif
+\r
+    return FR_OK;
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Check if the file/dir object is valid or not                          */
+/*-----------------------------------------------------------------------*/
+\r
+static
+FRESULT validate (        /* FR_OK(0): The object is valid, !=0: Invalid */
+    FATFS *fs,        /* Pointer to the file system object */
+    WORD id                /* Member id of the target object to be checked */
+)
+{
+    if (!fs || !fs->fs_type || fs->id != id)
+        return FR_INVALID_OBJECT;
+\r
+    ENTER_FF(fs);        /* Lock file system */
+\r
+    if (disk_status(fs->drv) & STA_NOINIT)
+        return FR_NOT_READY;
+\r
+    return FR_OK;
+}
+\r
+\r
+\r
+\r
+/*--------------------------------------------------------------------------
+\r
+   Public Functions
+\r
+--------------------------------------------------------------------------*/
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Mount/Unmount a Logical Drive                                         */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_mount (
+    BYTE vol,        /* Logical drive number to be mounted/unmounted */
+    FATFS *fs        /* Pointer to new file system object (NULL for unmount)*/
+)
+{
+    FATFS *rfs;
+\r
+\r
+    if (vol >= _VOLUMES)            /* Check if the drive number is valid */
+        return FR_INVALID_DRIVE;
+    rfs = FatFs[vol];                /* Get current fs object */
+\r
+    if (rfs) {
+#if _FS_SHARE
+        clear_lock(rfs);
+#endif
+#if _FS_REENTRANT                    /* Discard sync object of the current volume */
+        if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR;
+#endif
+        rfs->fs_type = 0;            /* Clear old fs object */
+    }
+\r
+    if (fs) {
+        fs->fs_type = 0;            /* Clear new fs object */
+#if _FS_REENTRANT                    /* Create sync object for the new volume */
+        if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR;
+#endif
+    }
+    FatFs[vol] = fs;                /* Register new fs object */
+\r
+    return FR_OK;
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Open or Create a File                                                 */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_open (
+    FIL_t *fp,            /* Pointer to the blank file object */
+    const TCHAR *path,    /* Pointer to the file name */
+    BYTE mode            /* Access mode and file open mode flags */
+)
+{
+    FRESULT res;
+    DIR_t dj;
+    BYTE *dir;
+    DEF_NAMEBUF;
+\r
+\r
+    fp->fs = 0;            /* Clear file object */
+\r
+#if !_FS_READONLY
+    mode &= FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW;
+    res = chk_mounted(&path, &dj.fs, (BYTE)(mode & ~FA_READ));
+#else
+    mode &= FA_READ;
+    res = chk_mounted(&path, &dj.fs, 0);
+#endif
+    INIT_BUF(dj);
+    if (res == FR_OK)
+        res = follow_path(&dj, path);    /* Follow the file path */
+    dir = dj.dir;
+\r
+#if !_FS_READONLY    /* R/W configuration */
+    if (res == FR_OK) {
+        if (!dir)    /* Current dir itself */
+            res = FR_INVALID_NAME;
+#if _FS_SHARE
+        else
+            res = chk_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
+#endif
+    }
+    /* Create or Open a file */
+    if (mode & (FA_CREATE_ALWAYS|FA_OPEN_ALWAYS|FA_CREATE_NEW)) {
+        DWORD dw, cl;
+\r
+        if (res != FR_OK) {        /* No file, create new */
+            if (res == FR_NO_FILE)            /* There is no file to open, create a new entry */
+#if _FS_SHARE
+                res = enq_lock(dj.fs) ? dir_register(&dj) : FR_TOO_MANY_OPEN_FILES;
+#else
+                res = dir_register(&dj);
+#endif
+            mode |= FA_CREATE_ALWAYS;        /* File is created */
+            dir = dj.dir;                    /* New entry */
+        }
+        else {                    /* Any object is already existing */
+            if (dir[DIR_Attr] & (AM_RDO | AM_DIR)) {    /* Cannot overwrite it (R/O or DIR) */
+                res = FR_DENIED;
+            } else {
+                if (mode & FA_CREATE_NEW)    /* Cannot create as new file */
+                    res = FR_EXIST;
+            }
+        }
+        if (res == FR_OK && (mode & FA_CREATE_ALWAYS)) {    /* Truncate it if overwrite mode */
+            dw = get_fattime();                    /* Created time */
+            ST_DWORD(dir+DIR_CrtTime, dw);
+            dir[DIR_Attr] = 0;                    /* Reset attribute */
+            ST_DWORD(dir+DIR_FileSize, 0);        /* size = 0 */
+            cl = LD_CLUST(dir);                    /* Get start cluster */
+            ST_CLUST(dir, 0);                    /* cluster = 0 */
+            dj.fs->wflag = 1;
+            if (cl) {                            /* Remove the cluster chain if exist */
+                dw = dj.fs->winsect;
+                res = remove_chain(dj.fs, cl);
+                if (res == FR_OK) {
+                    dj.fs->last_clust = cl - 1;    /* Reuse the cluster hole */
+                    res = move_window(dj.fs, dw);
+        }
+    }
+        }
+    }
+    else {    /* Open an existing file */
+        if (res == FR_OK) {                        /* Follow succeeded */
+            if (dir[DIR_Attr] & AM_DIR) {        /* It is a directory */
+                res = FR_NO_FILE;
+            } else {
+        if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */
+                    res = FR_DENIED;
+            }
+    }
+    }
+    if (res == FR_OK) {
+        if (mode & FA_CREATE_ALWAYS)            /* Set file change flag if created or overwritten */
+            mode |= FA__WRITTEN;
+    fp->dir_sect = dj.fs->winsect;        /* Pointer to the directory entry */
+    fp->dir_ptr = dir;
+#if _FS_SHARE
+        fp->lockid = inc_lock(&dj, (mode & ~FA_READ) ? 1 : 0);
+        if (!fp->lockid) res = FR_INT_ERR;
+#endif
+    }
+\r
+#else                /* R/O configuration */
+    if (res == FR_OK) {                    /* Follow succeeded */
+        if (!dir) {                        /* Current dir itself */
+            res = FR_INVALID_NAME;
+        } else {
+            if (dir[DIR_Attr] & AM_DIR)    /* It is a directory */
+                res = FR_NO_FILE;
+        }
+    }
+#endif
+    FREE_BUF();
+\r
+    if (res == FR_OK) {
+    fp->flag = mode;                    /* File access mode */
+        fp->sclust = LD_CLUST(dir);            /* File start cluster */
+        fp->fsize = LD_DWORD(dir+DIR_FileSize);    /* File size */
+        fp->fptr = 0;                        /* File pointer */
+        fp->dsect = 0;
+#if _USE_FASTSEEK
+        fp->cltbl = 0;                        /* Normal seek mode */
+#endif
+        fp->fs = dj.fs; fp->id = dj.fs->id;    /* Validate file object */
+    }
+\r
+    LEAVE_FF(dj.fs, res);
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Read File                                                             */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_read (
+    FIL_t *fp,         /* Pointer to the file object */
+    void *buff,        /* Pointer to data buffer */
+    UINT btr,        /* Number of bytes to read */
+    UINT *br        /* Pointer to number of bytes read */
+)
+{
+    FRESULT res;
+    DWORD clst, sect, remain;
+    UINT rcnt, cc;
+    BYTE csect, *rbuff = (BYTE*)buff;
+\r
+\r
+    *br = 0;    /* Initialize byte counter */
+\r
+    res = validate(fp->fs, fp->id);                /* Check validity */
+    if (res != FR_OK) LEAVE_FF(fp->fs, res);
+    if (fp->flag & FA__ERROR)                    /* Aborted file? */
+        LEAVE_FF(fp->fs, FR_INT_ERR);
+    if (!(fp->flag & FA_READ))                     /* Check access mode */
+        LEAVE_FF(fp->fs, FR_DENIED);
+    remain = fp->fsize - fp->fptr;
+    if (btr > remain) btr = (UINT)remain;            /* Truncate btr by remaining bytes */
+\r
+    for ( ;  btr;                                /* Repeat until all data read */
+        rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) {
+        if ((fp->fptr % SS(fp->fs)) == 0) {            /* On the sector boundary? */
+            csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1));    /* Sector offset in the cluster */
+            if (!csect) {                        /* On the cluster boundary? */
+                if (fp->fptr == 0) {            /* On the top of the file? */
+                    clst = fp->sclust;            /* Follow from the origin */
+                } else {                        /* Middle or end of the file */
+#if _USE_FASTSEEK
+                    if (fp->cltbl)
+                        clst = clmt_clust(fp, fp->fptr);    /* Get cluster# from the CLMT */
+                    else
+#endif
+                        clst = get_fat(fp->fs, fp->clust);    /* Follow cluster chain on the FAT */
+                }
+                if (clst < 2) ABORT(fp->fs, FR_INT_ERR);
+                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
+                fp->clust = clst;                /* Update current cluster */
+            }
+            sect = clust2sect(fp->fs, fp->clust);    /* Get current sector */
+            if (!sect) ABORT(fp->fs, FR_INT_ERR);
+            sect += csect;
+            cc = btr / SS(fp->fs);                    /* When remaining bytes >= sector size, */
+            if (cc) {                                /* Read maximum contiguous sectors directly */
+                if (csect + cc > fp->fs->csize)    /* Clip at cluster boundary */
+                    cc = fp->fs->csize - csect;
+                if (disk_read(fp->fs->drv, rbuff, sect, (BYTE)cc) != RES_OK)
+                    ABORT(fp->fs, FR_DISK_ERR);
+#if !_FS_READONLY && _FS_MINIMIZE <= 2            /* Replace one of the read sectors with cached data if it contains a dirty sector */
+#if _FS_TINY
+                if (fp->fs->wflag && fp->fs->winsect - sect < cc)
+                    mem_cpy(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs));
+#else
+                if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc)
+                    mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs));
+#endif
+#endif
+                rcnt = SS(fp->fs) * cc;                /* Number of bytes transferred */
+                continue;
+            }
+#if !_FS_TINY
+            if (fp->dsect != sect) {            /* Load data sector if not in cache */
+#if !_FS_READONLY
+                if (fp->flag & FA__DIRTY) {        /* Write-back dirty sector cache */
+                    if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
+                        ABORT(fp->fs, FR_DISK_ERR);
+                    fp->flag &= ~FA__DIRTY;
+                }
+#endif
+                if (disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK)    /* Fill sector cache */
+                    ABORT(fp->fs, FR_DISK_ERR);
+            }
+#endif
+            fp->dsect = sect;
+        }
+        rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));    /* Get partial sector data from sector buffer */
+        if (rcnt > btr) rcnt = btr;
+#if _FS_TINY
+        if (move_window(fp->fs, fp->dsect))        /* Move sector window */
+            ABORT(fp->fs, FR_DISK_ERR);
+        mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt);    /* Pick partial sector */
+#else
+        mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt);    /* Pick partial sector */
+#endif
+    }
+\r
+    LEAVE_FF(fp->fs, FR_OK);
+}
+\r
+\r
+\r
+\r
+#if !_FS_READONLY
+/*-----------------------------------------------------------------------*/
+/* Write File                                                            */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_write (
+    FIL_t *fp,            /* Pointer to the file object */
+    const void *buff,    /* Pointer to the data to be written */
+    UINT btw,            /* Number of bytes to write */
+    UINT *bw            /* Pointer to number of bytes written */
+)
+{
+    FRESULT res;
+    DWORD clst, sect;
+    UINT wcnt, cc;
+    const BYTE *wbuff = (BYTE*)buff;
+    BYTE csect;
+\r
+\r
+    *bw = 0;    /* Initialize byte counter */
+\r
+    res = validate(fp->fs, fp->id);            /* Check validity */
+    if (res != FR_OK) LEAVE_FF(fp->fs, res);
+    if (fp->flag & FA__ERROR)                /* Aborted file? */
+        LEAVE_FF(fp->fs, FR_INT_ERR);
+    if (!(fp->flag & FA_WRITE))                /* Check access mode */
+        LEAVE_FF(fp->fs, FR_DENIED);
+    if ((DWORD)(fp->fsize + btw) < fp->fsize) btw = 0;    /* File size cannot reach 4GB */
+\r
+    for ( ;  btw;                            /* Repeat until all data written */
+        wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) {
+        if ((fp->fptr % SS(fp->fs)) == 0) {            /* On the sector boundary? */
+            csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1));    /* Sector offset in the cluster */
+            if (!csect) {                    /* On the cluster boundary? */
+                if (fp->fptr == 0) {                /* On the top of the file? */
+                    clst = fp->sclust;        /* Follow from the origin */
+                    if (clst == 0)            /* When no cluster is allocated, */
+                        fp->sclust = clst = create_chain(fp->fs, 0);    /* Create a new cluster chain */
+                } else {                            /* Middle or end of the file */
+#if _USE_FASTSEEK
+                    if (fp->cltbl)
+                        clst = clmt_clust(fp, fp->fptr);    /* Get cluster# from the CLMT */
+                    else
+#endif
+                        clst = create_chain(fp->fs, fp->clust);    /* Follow or stretch cluster chain on the FAT */
+                }
+                if (clst == 0) break;        /* Could not allocate a new cluster (disk full) */
+                if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
+                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
+                fp->clust = clst;            /* Update current cluster */
+                }
+#if _FS_TINY
+            if (fp->fs->winsect == fp->dsect && move_window(fp->fs, 0))    /* Write-back sector cache */
+                ABORT(fp->fs, FR_DISK_ERR);
+#else
+            if (fp->flag & FA__DIRTY) {        /* Write-back sector cache */
+                if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
+                    ABORT(fp->fs, FR_DISK_ERR);
+                fp->flag &= ~FA__DIRTY;
+            }
+#endif
+            sect = clust2sect(fp->fs, fp->clust);    /* Get current sector */
+            if (!sect) ABORT(fp->fs, FR_INT_ERR);
+            sect += csect;
+            cc = btw / SS(fp->fs);                    /* When remaining bytes >= sector size, */
+            if (cc) {                                /* Write maximum contiguous sectors directly */
+                if (csect + cc > fp->fs->csize)    /* Clip at cluster boundary */
+                    cc = fp->fs->csize - csect;
+                if (disk_write(fp->fs->drv, wbuff, sect, (BYTE)cc) != RES_OK)
+                    ABORT(fp->fs, FR_DISK_ERR);
+#if _FS_TINY
+                if (fp->fs->winsect - sect < cc) {    /* Refill sector cache if it gets invalidated by the direct write */
+                    mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs));
+                    fp->fs->wflag = 0;
+                }
+#else
+                if (fp->dsect - sect < cc) { /* Refill sector cache if it gets invalidated by the direct write */
+                    mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs));
+                    fp->flag &= ~FA__DIRTY;
+                }
+#endif
+                wcnt = SS(fp->fs) * cc;                /* Number of bytes transferred */
+                continue;
+            }
+#if _FS_TINY
+            if (fp->fptr >= fp->fsize) {    /* Avoid silly cache filling at growing edge */
+                if (move_window(fp->fs, 0)) ABORT(fp->fs, FR_DISK_ERR);
+                fp->fs->winsect = sect;
+                }
+#else
+            if (fp->dsect != sect) {        /* Fill sector cache with file data */
+                if (fp->fptr < fp->fsize &&
+                    disk_read(fp->fs->drv, fp->buf, sect, 1) != RES_OK)
+                        ABORT(fp->fs, FR_DISK_ERR);
+            }
+#endif
+            fp->dsect = sect;
+        }
+        wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs));    /* Put partial sector into file I/O buffer */
+        if (wcnt > btw) wcnt = btw;
+#if _FS_TINY
+        if (move_window(fp->fs, fp->dsect))    /* Move sector window */
+            ABORT(fp->fs, FR_DISK_ERR);
+        mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt);    /* Fit partial sector */
+        fp->fs->wflag = 1;
+#else
+        mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt);    /* Fit partial sector */
+        fp->flag |= FA__DIRTY;
+#endif
+    }
+\r
+    if (fp->fptr > fp->fsize) fp->fsize = fp->fptr;    /* Update file size if needed */
+    fp->flag |= FA__WRITTEN;                        /* Set file change flag */
+\r
+    LEAVE_FF(fp->fs, FR_OK);
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Synchronize the File Object                                           */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_sync (
+    FIL_t *fp        /* Pointer to the file object */
+)
+{
+    FRESULT res;
+    DWORD tim;
+    BYTE *dir;
+\r
+\r
+    res = validate(fp->fs, fp->id);        /* Check validity of the object */
+    if (res == FR_OK) {
+        if (fp->flag & FA__WRITTEN) {    /* Has the file been written? */
+#if !_FS_TINY    /* Write-back dirty buffer */
+            if (fp->flag & FA__DIRTY) {
+                if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
+                    LEAVE_FF(fp->fs, FR_DISK_ERR);
+                fp->flag &= ~FA__DIRTY;
+            }
+#endif
+            /* Update the directory entry */
+            res = move_window(fp->fs, fp->dir_sect);
+            if (res == FR_OK) {
+            dir = fp->dir_ptr;
+            dir[DIR_Attr] |= AM_ARC;                        /* Set archive bit */
+                ST_DWORD(dir+DIR_FileSize, fp->fsize);        /* Update file size */
+                ST_CLUST(dir, fp->sclust);                    /* Update start cluster */
+                tim = get_fattime();                        /* Update updated time */
+                ST_DWORD(dir+DIR_WrtTime, tim);
+                fp->flag &= ~FA__WRITTEN;
+                fp->fs->wflag = 1;
+            res = sync(fp->fs);
+        }
+    }
+    }
+\r
+    LEAVE_FF(fp->fs, res);
+}
+\r
+#endif /* !_FS_READONLY */
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Close File                                                            */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_close (
+    FIL_t *fp        /* Pointer to the file object to be closed */
+)
+{
+    FRESULT res;
+\r
+#if _FS_READONLY
+    FATFS *fs = fp->fs;
+    res = validate(fs, fp->id);
+    if (res == FR_OK) fp->fs = 0;    /* Discard file object */
+    LEAVE_FF(fs, res);
+\r
+#else
+    res = f_sync(fp);        /* Flush cached data */
+#if _FS_SHARE
+    if (res == FR_OK) {        /* Decrement open counter */
+#if _FS_REENTRANT
+    res = validate(fp->fs, fp->id);
+        if (res == FR_OK) {
+            res = dec_lock(fp->lockid);
+            unlock_fs(fp->fs, FR_OK);
+        }
+#else
+        res = dec_lock(fp->lockid);
+#endif
+    }
+#endif
+    if (res == FR_OK) fp->fs = 0;    /* Discard file object */
+    return res;
+#endif
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Current Drive/Directory Handlings                                     */
+/*-----------------------------------------------------------------------*/
+\r
+#if _FS_RPATH >= 1
+\r
+FRESULT f_chdrive (
+    BYTE drv        /* Drive number */
+)
+{
+    if (drv >= _VOLUMES) return FR_INVALID_DRIVE;
+\r
+    CurrVol = drv;
+\r
+    return FR_OK;
+}
+\r
+\r
+\r
+FRESULT f_chdir (
+    const TCHAR *path    /* Pointer to the directory path */
+)
+{
+    FRESULT res;
+    DIR_t dj;
+    DEF_NAMEBUF;
+\r
+\r
+    res = chk_mounted(&path, &dj.fs, 0);
+    if (res == FR_OK) {
+        INIT_BUF(dj);
+        res = follow_path(&dj, path);        /* Follow the path */
+        FREE_BUF();
+        if (res == FR_OK) {                    /* Follow completed */
+            if (!dj.dir) {
+                dj.fs->cdir = dj.sclust;    /* Start directory itself */
+            } else {
+                if (dj.dir[DIR_Attr] & AM_DIR)    /* Reached to the directory */
+                    dj.fs->cdir = LD_CLUST(dj.dir);
+                else
+                    res = FR_NO_PATH;        /* Reached but a file */
+            }
+        }
+        if (res == FR_NO_FILE) res = FR_NO_PATH;
+    }
+\r
+    LEAVE_FF(dj.fs, res);
+}
+\r
+\r
+#if _FS_RPATH >= 2
+FRESULT f_getcwd (
+    TCHAR *path,    /* Pointer to the directory path */
+    UINT sz_path    /* Size of path */
+)
+{
+    FRESULT res;
+    DIR_t dj;
+    UINT i, n;
+    DWORD ccl;
+    TCHAR *tp;
+    FILINFO fno;
+    DEF_NAMEBUF;
+\r
+\r
+    *path = 0;
+    res = chk_mounted((const TCHAR**)&path, &dj.fs, 0);    /* Get current volume */
+    if (res == FR_OK) {
+        INIT_BUF(dj);
+        i = sz_path;        /* Bottom of buffer (dir stack base) */
+        dj.sclust = dj.fs->cdir;            /* Start to follow upper dir from current dir */
+        while ((ccl = dj.sclust) != 0) {    /* Repeat while current dir is a sub-dir */
+            res = dir_sdi(&dj, 1);            /* Get parent dir */
+            if (res != FR_OK) break;
+            res = dir_read(&dj);
+            if (res != FR_OK) break;
+            dj.sclust = LD_CLUST(dj.dir);    /* Goto parent dir */
+            res = dir_sdi(&dj, 0);
+            if (res != FR_OK) break;
+            do {                            /* Find the entry links to the child dir */
+                res = dir_read(&dj);
+                if (res != FR_OK) break;
+                if (ccl == LD_CLUST(dj.dir)) break;    /* Found the entry */
+                res = dir_next(&dj, 0);
+            } while (res == FR_OK);
+            if (res == FR_NO_FILE) res = FR_INT_ERR;/* It cannot be 'not found'. */
+            if (res != FR_OK) break;
+#if _USE_LFN
+            fno.lfname = path;
+            fno.lfsize = i;
+#endif
+            get_fileinfo(&dj, &fno);        /* Get the dir name and push it to the buffer */
+            tp = fno.fname;
+            if (_USE_LFN && *path) tp = path;
+            for (n = 0; tp[n]; n++) ;
+            if (i < n + 3) {
+                res = FR_NOT_ENOUGH_CORE; break;
+            }
+            while (n) path[--i] = tp[--n];
+            path[--i] = '/';
+        }
+        tp = path;
+        if (res == FR_OK) {
+            *tp++ = '0' + CurrVol;            /* Put drive number */
+            *tp++ = ':';
+            if (i == sz_path) {                /* Root-dir */
+                *tp++ = '/';
+            } else {                        /* Sub-dir */
+                do        /* Add stacked path str */
+                    *tp++ = path[i++];
+                while (i < sz_path);
+            }
+        }
+        *tp = 0;
+        FREE_BUF();
+    }
+\r
+    LEAVE_FF(dj.fs, res);
+}
+#endif /* _FS_RPATH >= 2 */
+#endif /* _FS_RPATH >= 1 */
+\r
+\r
+\r
+#if _FS_MINIMIZE <= 2
+/*-----------------------------------------------------------------------*/
+/* Seek File R/W Pointer                                                 */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_lseek (
+    FIL_t *fp,        /* Pointer to the file object */
+    DWORD ofs        /* File pointer from top of file */
+)
+{
+    FRESULT res;
+\r
+\r
+    res = validate(fp->fs, fp->id);        /* Check validity of the object */
+    if (res != FR_OK) LEAVE_FF(fp->fs, res);
+    if (fp->flag & FA__ERROR)            /* Check abort flag */
+        LEAVE_FF(fp->fs, FR_INT_ERR);
+\r
+#if _USE_FASTSEEK
+    if (fp->cltbl) {    /* Fast seek */
+        DWORD cl, pcl, ncl, tcl, dsc, tlen, ulen, *tbl;
+\r
+        if (ofs == CREATE_LINKMAP) {    /* Create CLMT */
+            tbl = fp->cltbl;
+            tlen = *tbl++; ulen = 2;    /* Given table size and required table size */
+            cl = fp->sclust;            /* Top of the chain */
+            if (cl) {
+                do {
+                    /* Get a fragment */
+                    tcl = cl; ncl = 0; ulen += 2;    /* Top, length and used items */
+                    do {
+                        pcl = cl; ncl++;
+                        cl = get_fat(fp->fs, cl);
+                        if (cl <= 1) ABORT(fp->fs, FR_INT_ERR);
+                        if (cl == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
+                    } while (cl == pcl + 1);
+                    if (ulen <= tlen) {        /* Store the length and top of the fragment */
+                        *tbl++ = ncl; *tbl++ = tcl;
+                    }
+                } while (cl < fp->fs->n_fatent);    /* Repeat until end of chain */
+            }
+            *fp->cltbl = ulen;    /* Number of items used */
+            if (ulen <= tlen)
+                *tbl = 0;        /* Terminate table */
+            else
+                res = FR_NOT_ENOUGH_CORE;    /* Given table size is smaller than required */
+\r
+        } else {                        /* Fast seek */
+            if (ofs > fp->fsize)        /* Clip offset at the file size */
+                ofs = fp->fsize;
+            fp->fptr = ofs;                /* Set file pointer */
+            if (ofs) {
+                fp->clust = clmt_clust(fp, ofs - 1);
+                dsc = clust2sect(fp->fs, fp->clust);
+                if (!dsc) ABORT(fp->fs, FR_INT_ERR);
+                dsc += (ofs - 1) / SS(fp->fs) & (fp->fs->csize - 1);
+                if (fp->fptr % SS(fp->fs) && dsc != fp->dsect) {    /* Refill sector cache if needed */
+#if !_FS_TINY
+#if !_FS_READONLY
+                    if (fp->flag & FA__DIRTY) {        /* Write-back dirty sector cache */
+                        if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
+                            ABORT(fp->fs, FR_DISK_ERR);
+                        fp->flag &= ~FA__DIRTY;
+                    }
+#endif
+                    if (disk_read(fp->fs->drv, fp->buf, dsc, 1) != RES_OK)    /* Load current sector */
+                        ABORT(fp->fs, FR_DISK_ERR);
+#endif
+                    fp->dsect = dsc;
+                }
+            }
+        }
+    } else
+#endif
+\r
+    /* Normal Seek */
+    {
+        DWORD clst, bcs, nsect, ifptr;
+\r
+    if (ofs > fp->fsize                    /* In read-only mode, clip offset with the file size */
+#if !_FS_READONLY
+         && !(fp->flag & FA_WRITE)
+#endif
+        ) ofs = fp->fsize;
+\r
+    ifptr = fp->fptr;
+        fp->fptr = nsect = 0;
+        if (ofs) {
+            bcs = (DWORD)fp->fs->csize * SS(fp->fs);    /* Cluster size (byte) */
+        if (ifptr > 0 &&
+                (ofs - 1) / bcs >= (ifptr - 1) / bcs) {    /* When seek to same or following cluster, */
+                fp->fptr = (ifptr - 1) & ~(bcs - 1);    /* start from the current cluster */
+            ofs -= fp->fptr;
+                clst = fp->clust;
+        } else {                                    /* When seek to back cluster, */
+                clst = fp->sclust;                        /* start from the first cluster */
+#if !_FS_READONLY
+                if (clst == 0) {                        /* If no cluster chain, create a new chain */
+                    clst = create_chain(fp->fs, 0);
+                    if (clst == 1) ABORT(fp->fs, FR_INT_ERR);
+                    if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
+                    fp->sclust = clst;
+            }
+#endif
+                fp->clust = clst;
+        }
+            if (clst != 0) {
+                while (ofs > bcs) {                        /* Cluster following loop */
+#if !_FS_READONLY
+                if (fp->flag & FA_WRITE) {            /* Check if in write mode or not */
+                        clst = create_chain(fp->fs, clst);    /* Force stretch if in write mode */
+                        if (clst == 0) {                /* When disk gets full, clip file size */
+                            ofs = bcs; break;
+                    }
+                } else
+#endif
+                        clst = get_fat(fp->fs, clst);    /* Follow cluster chain if not in write mode */
+                    if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
+                    if (clst <= 1 || clst >= fp->fs->n_fatent) ABORT(fp->fs, FR_INT_ERR);
+                    fp->clust = clst;
+                    fp->fptr += bcs;
+                    ofs -= bcs;
+            }
+            fp->fptr += ofs;
+                if (ofs % SS(fp->fs)) {
+                    nsect = clust2sect(fp->fs, clst);    /* Current sector */
+                    if (!nsect) ABORT(fp->fs, FR_INT_ERR);
+                    nsect += ofs / SS(fp->fs);
+            }
+        }
+    }
+        if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) {    /* Fill sector cache if needed */
+#if !_FS_TINY
+#if !_FS_READONLY
+            if (fp->flag & FA__DIRTY) {            /* Write-back dirty sector cache */
+                if (disk_write(fp->fs->drv, fp->buf, fp->dsect, 1) != RES_OK)
+                    ABORT(fp->fs, FR_DISK_ERR);
+                fp->flag &= ~FA__DIRTY;
+        }
+#endif
+            if (disk_read(fp->fs->drv, fp->buf, nsect, 1) != RES_OK)    /* Fill sector cache */
+                ABORT(fp->fs, FR_DISK_ERR);
+#endif
+            fp->dsect = nsect;
+    }
+#if !_FS_READONLY
+        if (fp->fptr > fp->fsize) {            /* Set file change flag if the file size is extended */
+        fp->fsize = fp->fptr;
+        fp->flag |= FA__WRITTEN;
+    }
+#endif
+}
+\r
+    LEAVE_FF(fp->fs, res);
+}
+\r
+\r
+\r
+#if _FS_MINIMIZE <= 1
+/*-----------------------------------------------------------------------*/
+/* Create a Directroy Object                                             */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_opendir (
+    DIR_t *dj,            /* Pointer to directory object to create */
+    const TCHAR *path    /* Pointer to the directory path */
+)
+{
+    FRESULT res;
+    DEF_NAMEBUF;
+\r
+\r
+    res = chk_mounted(&path, &dj->fs, 0);
+    if (res == FR_OK) {
+        INIT_BUF(*dj);
+        res = follow_path(dj, path);            /* Follow the path to the directory */
+        FREE_BUF();
+        if (res == FR_OK) {                        /* Follow completed */
+            if (dj->dir) {                        /* It is not the root dir */
+                if (dj->dir[DIR_Attr] & AM_DIR) {    /* The object is a directory */
+                    dj->sclust = LD_CLUST(dj->dir);
+                } else {                        /* The object is not a directory */
+                    res = FR_NO_PATH;
+                }
+            }
+            if (res == FR_OK) {
+            dj->id = dj->fs->id;
+                res = dir_sdi(dj, 0);            /* Rewind dir */
+            }
+        }
+        if (res == FR_NO_FILE) res = FR_NO_PATH;
+    }
+\r
+    LEAVE_FF(dj->fs, res);
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Read Directory Entry in Sequense                                      */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_readdir (
+    DIR_t *dj,            /* Pointer to the open directory object */
+    FILINFO *fno        /* Pointer to file information to return */
+)
+{
+    FRESULT res;
+    DEF_NAMEBUF;
+\r
+    res = validate(dj->fs, dj->id);            /* Check validity of the object */
+    if (res == FR_OK) {
+        if (!fno) {
+            res = dir_sdi(dj, 0);            /* Rewind the directory object */
+        } else {
+            INIT_BUF(*dj);
+            res = dir_read(dj);                /* Read an directory item */
+            if (res == FR_NO_FILE) {        /* Reached end of dir */
+                dj->sect = 0;
+                res = FR_OK;
+            }
+            if (res == FR_OK) {                /* A valid entry is found */
+                get_fileinfo(dj, fno);        /* Get the object information */
+                res = dir_next(dj, 0);        /* Increment index for next */
+                if (res == FR_NO_FILE) {
+                    dj->sect = 0;
+                    res = FR_OK;
+                }
+            }
+            FREE_BUF();
+        }
+    }
+\r
+    LEAVE_FF(dj->fs, res);
+}
+\r
+\r
+\r
+#if _FS_MINIMIZE == 0
+/*-----------------------------------------------------------------------*/
+/* Get File Status                                                       */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_stat (
+    const TCHAR *path,    /* Pointer to the file path */
+    FILINFO *fno        /* Pointer to file information to return */
+)
+{
+    FRESULT res;
+    DIR_t dj;
+    DEF_NAMEBUF;
+\r
+\r
+    res = chk_mounted(&path, &dj.fs, 0);
+    if (res == FR_OK) {
+        INIT_BUF(dj);
+        res = follow_path(&dj, path);    /* Follow the file path */
+        if (res == FR_OK) {                /* Follow completed */
+            if (dj.dir)        /* Found an object */
+                get_fileinfo(&dj, fno);
+            else        /* It is root dir */
+                res = FR_INVALID_NAME;
+        }
+        FREE_BUF();
+    }
+\r
+    LEAVE_FF(dj.fs, res);
+}
+\r
+\r
+\r
+#if !_FS_READONLY
+/*-----------------------------------------------------------------------*/
+/* Get Number of Free Clusters                                           */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_getfree (
+    const TCHAR *path,    /* Pointer to the logical drive number (root dir) */
+    DWORD *nclst,        /* Pointer to the variable to return number of free clusters */
+    FATFS **fatfs        /* Pointer to pointer to corresponding file system object to return */
+)
+{
+    FRESULT res;
+    DWORD n, clst, sect, stat;
+    UINT i;
+    BYTE fat, *p;
+\r
+\r
+    /* Get drive number */
+    res = chk_mounted(&path, fatfs, 0);
+    if (res == FR_OK) {
+        /* If free_clust is valid, return it without full cluster scan */
+        if ((*fatfs)->free_clust <= (*fatfs)->n_fatent - 2) {
+            *nclst = (*fatfs)->free_clust;
+        } else {
+    /* Get number of free clusters */
+    fat = (*fatfs)->fs_type;
+    n = 0;
+    if (fat == FS_FAT12) {
+                clst = 2;
+        do {
+                    stat = get_fat(*fatfs, clst);
+                    if (stat == 0xFFFFFFFF) { res = FR_DISK_ERR; break; }
+                    if (stat == 1) { res = FR_INT_ERR; break; }
+                    if (stat == 0) n++;
+                } while (++clst < (*fatfs)->n_fatent);
+    } else {
+                clst = (*fatfs)->n_fatent;
+        sect = (*fatfs)->fatbase;
+                i = 0; p = 0;
+        do {
+                    if (!i) {
+                        res = move_window(*fatfs, sect++);
+                        if (res != FR_OK) break;
+                p = (*fatfs)->win;
+                        i = SS(*fatfs);
+            }
+            if (fat == FS_FAT16) {
+                if (LD_WORD(p) == 0) n++;
+                        p += 2; i -= 2;
+            } else {
+                        if ((LD_DWORD(p) & 0x0FFFFFFF) == 0) n++;
+                        p += 4; i -= 4;
+            }
+                } while (--clst);
+    }
+    (*fatfs)->free_clust = n;
+    if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1;
+            *nclst = n;
+        }
+    }
+    LEAVE_FF(*fatfs, res);
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Truncate File                                                         */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_truncate (
+    FIL_t *fp        /* Pointer to the file object */
+)
+{
+    FRESULT res;
+    DWORD ncl;
+\r
+\r
+    res = validate(fp->fs, fp->id);        /* Check validity of the object */
+    if (res == FR_OK) {
+        if (fp->flag & FA__ERROR) {            /* Check abort flag */
+            res = FR_INT_ERR;
+        } else {
+            if (!(fp->flag & FA_WRITE))        /* Check access mode */
+                res = FR_DENIED;
+        }
+    }
+    if (res == FR_OK) {
+        if (fp->fsize > fp->fptr) {
+            fp->fsize = fp->fptr;    /* Set file size to current R/W point */
+            fp->flag |= FA__WRITTEN;
+            if (fp->fptr == 0) {    /* When set file size to zero, remove entire cluster chain */
+                res = remove_chain(fp->fs, fp->sclust);
+                fp->sclust = 0;
+            } else {                /* When truncate a part of the file, remove remaining clusters */
+                ncl = get_fat(fp->fs, fp->clust);
+                res = FR_OK;
+                if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR;
+                if (ncl == 1) res = FR_INT_ERR;
+                if (res == FR_OK && ncl < fp->fs->n_fatent) {
+                    res = put_fat(fp->fs, fp->clust, 0x0FFFFFFF);
+                    if (res == FR_OK) res = remove_chain(fp->fs, ncl);
+                }
+            }
+        }
+        if (res != FR_OK) fp->flag |= FA__ERROR;
+    }
+\r
+    LEAVE_FF(fp->fs, res);
+    }
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Delete a File or Directory                                            */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_unlink (
+    const TCHAR *path        /* Pointer to the file or directory path */
+)
+{
+    FRESULT res;
+    DIR_t dj, sdj;
+    BYTE *dir;
+    DWORD dclst;
+    DEF_NAMEBUF;
+\r
+\r
+    res = chk_mounted(&path, &dj.fs, 1);
+    if (res == FR_OK) {
+        INIT_BUF(dj);
+        res = follow_path(&dj, path);        /* Follow the file path */
+        if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
+            res = FR_INVALID_NAME;            /* Cannot remove dot entry */
+#if _FS_SHARE
+        if (res == FR_OK) res = chk_lock(&dj, 2);    /* Cannot remove open file */
+#endif
+        if (res == FR_OK) {                    /* The object is accessible */
+            dir = dj.dir;
+            if (!dir) {
+                res = FR_INVALID_NAME;        /* Cannot remove the start directory */
+            } else {
+                if (dir[DIR_Attr] & AM_RDO)
+                    res = FR_DENIED;        /* Cannot remove R/O object */
+            }
+            dclst = LD_CLUST(dir);
+            if (res == FR_OK && (dir[DIR_Attr] & AM_DIR)) {    /* Is it a sub-dir? */
+                if (dclst < 2) {
+                    res = FR_INT_ERR;
+                } else {
+                    mem_cpy(&sdj, &dj, sizeof(DIR_t));    /* Check if the sub-dir is empty or not */
+                    sdj.sclust = dclst;
+                    res = dir_sdi(&sdj, 2);        /* Exclude dot entries */
+                    if (res == FR_OK) {
+                        res = dir_read(&sdj);
+                        if (res == FR_OK            /* Not empty dir */
+#if _FS_RPATH
+                        || dclst == sdj.fs->cdir    /* Current dir */
+#endif
+                        ) res = FR_DENIED;
+                        if (res == FR_NO_FILE) res = FR_OK;    /* Empty */
+                    }
+                }
+            }
+            if (res == FR_OK) {
+                res = dir_remove(&dj);        /* Remove the directory entry */
+                if (res == FR_OK) {
+                    if (dclst)                /* Remove the cluster chain if exist */
+                        res = remove_chain(dj.fs, dclst);
+                    if (res == FR_OK) res = sync(dj.fs);
+                }
+            }
+        }
+        FREE_BUF();
+    }
+    LEAVE_FF(dj.fs, res);
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Create a Directory                                                    */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_mkdir (
+    const TCHAR *path        /* Pointer to the directory path */
+)
+{
+    FRESULT res;
+    DIR_t dj;
+    BYTE *dir, n;
+    DWORD dsc, dcl, pcl, tim = get_fattime();
+    DEF_NAMEBUF;
+\r
+\r
+    res = chk_mounted(&path, &dj.fs, 1);
+    if (res == FR_OK) {
+        INIT_BUF(dj);
+        res = follow_path(&dj, path);            /* Follow the file path */
+        if (res == FR_OK) res = FR_EXIST;        /* Any object with same name is already existing */
+        if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[NS] & NS_DOT))
+            res = FR_INVALID_NAME;
+        if (res == FR_NO_FILE) {                /* Can create a new directory */
+            dcl = create_chain(dj.fs, 0);        /* Allocate a cluster for the new directory table */
+            res = FR_OK;
+            if (dcl == 0) res = FR_DENIED;        /* No space to allocate a new cluster */
+            if (dcl == 1) res = FR_INT_ERR;
+            if (dcl == 0xFFFFFFFF) res = FR_DISK_ERR;
+            if (res == FR_OK)                    /* Flush FAT */
+                res = move_window(dj.fs, 0);
+            if (res == FR_OK) {                    /* Initialize the new directory table */
+                dsc = clust2sect(dj.fs, dcl);
+                dir = dj.fs->win;
+                mem_set(dir, 0, SS(dj.fs));
+                mem_set(dir+DIR_Name, ' ', 8+3);    /* Create "." entry */
+                dir[DIR_Name] = '.';
+                dir[DIR_Attr] = AM_DIR;
+                ST_DWORD(dir+DIR_WrtTime, tim);
+                ST_CLUST(dir, dcl);
+                mem_cpy(dir+SZ_DIR, dir, SZ_DIR);     /* Create ".." entry */
+                dir[33] = '.'; pcl = dj.sclust;
+                if (dj.fs->fs_type == FS_FAT32 && pcl == dj.fs->dirbase)
+                    pcl = 0;
+                ST_CLUST(dir+SZ_DIR, pcl);
+                for (n = dj.fs->csize; n; n--) {    /* Write dot entries and clear following sectors */
+                    dj.fs->winsect = dsc++;
+                    dj.fs->wflag = 1;
+                    res = move_window(dj.fs, 0);
+                    if (res != FR_OK) break;
+                    mem_set(dir, 0, SS(dj.fs));
+    }
+            }
+            if (res == FR_OK) res = dir_register(&dj);    /* Register the object to the directoy */
+            if (res != FR_OK) {
+                remove_chain(dj.fs, dcl);            /* Could not register, remove cluster chain */
+            } else {
+                dir = dj.dir;
+    dir[DIR_Attr] = AM_DIR;                        /* Attribute */
+                ST_DWORD(dir+DIR_WrtTime, tim);        /* Created time */
+                ST_CLUST(dir, dcl);                    /* Table start cluster */
+                dj.fs->wflag = 1;
+                res = sync(dj.fs);
+            }
+        }
+        FREE_BUF();
+    }
+\r
+    LEAVE_FF(dj.fs, res);
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Change Attribute                                                      */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_chmod (
+    const TCHAR *path,    /* Pointer to the file path */
+    BYTE value,            /* Attribute bits */
+    BYTE mask            /* Attribute mask to change */
+)
+{
+    FRESULT res;
+    DIR_t dj;
+    BYTE *dir;
+    DEF_NAMEBUF;
+\r
+\r
+    res = chk_mounted(&path, &dj.fs, 1);
+    if (res == FR_OK) {
+        INIT_BUF(dj);
+        res = follow_path(&dj, path);        /* Follow the file path */
+        FREE_BUF();
+        if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
+            res = FR_INVALID_NAME;
+        if (res == FR_OK) {
+            dir = dj.dir;
+            if (!dir) {                        /* Is it a root directory? */
+                res = FR_INVALID_NAME;
+            } else {                        /* File or sub directory */
+                mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC;    /* Valid attribute mask */
+                dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask);    /* Apply attribute change */
+                dj.fs->wflag = 1;
+                res = sync(dj.fs);
+            }
+        }
+    }
+\r
+    LEAVE_FF(dj.fs, res);
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Change Timestamp                                                      */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_utime (
+    const TCHAR *path,    /* Pointer to the file/directory name */
+    const FILINFO *fno    /* Pointer to the time stamp to be set */
+)
+{
+    FRESULT res;
+    DIR_t dj;
+    BYTE *dir;
+    DEF_NAMEBUF;
+\r
+\r
+    res = chk_mounted(&path, &dj.fs, 1);
+    if (res == FR_OK) {
+        INIT_BUF(dj);
+        res = follow_path(&dj, path);    /* Follow the file path */
+        FREE_BUF();
+        if (_FS_RPATH && res == FR_OK && (dj.fn[NS] & NS_DOT))
+            res = FR_INVALID_NAME;
+        if (res == FR_OK) {
+            dir = dj.dir;
+            if (!dir) {                    /* Root directory */
+                res = FR_INVALID_NAME;
+            } else {                    /* File or sub-directory */
+                ST_WORD(dir+DIR_WrtTime, fno->ftime);
+                ST_WORD(dir+DIR_WrtDate, fno->fdate);
+                dj.fs->wflag = 1;
+                res = sync(dj.fs);
+            }
+        }
+    }
+\r
+    LEAVE_FF(dj.fs, res);
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Rename File/Directory                                                 */
+/*-----------------------------------------------------------------------*/
+\r
+FRESULT f_rename (
+    const TCHAR *path_old,    /* Pointer to the old name */
+    const TCHAR *path_new    /* Pointer to the new name */
+)
+{
+    FRESULT res;
+    DIR_t djo, djn;
+    BYTE buf[21], *dir;
+    DWORD dw;
+    DEF_NAMEBUF;
+\r
+\r
+    res = chk_mounted(&path_old, &djo.fs, 1);
+    if (res == FR_OK) {
+        djn.fs = djo.fs;
+        INIT_BUF(djo);
+        res = follow_path(&djo, path_old);        /* Check old object */
+        if (_FS_RPATH && res == FR_OK && (djo.fn[NS] & NS_DOT))
+            res = FR_INVALID_NAME;
+#if _FS_SHARE
+        if (res == FR_OK) res = chk_lock(&djo, 2);
+#endif
+        if (res == FR_OK) {                        /* Old object is found */
+            if (!djo.dir) {                        /* Is root dir? */
+                res = FR_NO_FILE;
+            } else {
+                mem_cpy(buf, djo.dir+DIR_Attr, 21);        /* Save the object information except for name */
+                mem_cpy(&djn, &djo, sizeof(DIR_t));        /* Check new object */
+                res = follow_path(&djn, path_new);
+                if (res == FR_OK) res = FR_EXIST;        /* The new object name is already existing */
+                if (res == FR_NO_FILE) {                 /* Is it a valid path and no name collision? */
+/* Start critical section that any interruption or error can cause cross-link */
+                    res = dir_register(&djn);            /* Register the new entry */
+                    if (res == FR_OK) {
+                        dir = djn.dir;                    /* Copy object information except for name */
+                        mem_cpy(dir+13, buf+2, 19);
+                        dir[DIR_Attr] = buf[0] | AM_ARC;
+                        djo.fs->wflag = 1;
+                        if (djo.sclust != djn.sclust && (dir[DIR_Attr] & AM_DIR)) {        /* Update .. entry in the directory if needed */
+                            dw = clust2sect(djn.fs, LD_CLUST(dir));
+                            if (!dw) {
+                                res = FR_INT_ERR;
+                            } else {
+                                res = move_window(djn.fs, dw);
+                                dir = djn.fs->win+SZ_DIR;    /* .. entry */
+                                if (res == FR_OK && dir[1] == '.') {
+                                    dw = (djn.fs->fs_type == FS_FAT32 && djn.sclust == djn.fs->dirbase) ? 0 : djn.sclust;
+                                    ST_CLUST(dir, dw);
+                                    djn.fs->wflag = 1;
+                                }
+                            }
+                        }
+                        if (res == FR_OK) {
+                            res = dir_remove(&djo);        /* Remove old entry */
+                            if (res == FR_OK)
+                                res = sync(djo.fs);
+                        }
+                    }
+/* End critical section */
+                }
+            }
+        }
+        FREE_BUF();
+    }
+    LEAVE_FF(djo.fs, res);
+}
+\r
+#endif /* !_FS_READONLY */
+#endif /* _FS_MINIMIZE == 0 */
+#endif /* _FS_MINIMIZE <= 1 */
+#endif /* _FS_MINIMIZE <= 2 */
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Forward data to the stream directly (available on only tiny cfg)      */
+/*-----------------------------------------------------------------------*/
+#if _USE_FORWARD && _FS_TINY
+\r
+FRESULT f_forward (
+    FIL_t *fp,                         /* Pointer to the file object */
+    UINT (*func)(const BYTE*,UINT),    /* Pointer to the streaming function */
+    UINT btr,                        /* Number of bytes to forward */
+    UINT *bf                        /* Pointer to number of bytes forwarded */
+)
+{
+    FRESULT res;
+    DWORD remain, clst, sect;
+    UINT rcnt;
+    BYTE csect;
+\r
+\r
+    *bf = 0;    /* Initialize byte counter */
+\r
+    res = validate(fp->fs, fp->id);                    /* Check validity of the object */
+    if (res != FR_OK) LEAVE_FF(fp->fs, res);
+    if (fp->flag & FA__ERROR)                        /* Check error flag */
+        LEAVE_FF(fp->fs, FR_INT_ERR);
+    if (!(fp->flag & FA_READ))                        /* Check access mode */
+        LEAVE_FF(fp->fs, FR_DENIED);
+\r
+    remain = fp->fsize - fp->fptr;
+    if (btr > remain) btr = (UINT)remain;            /* Truncate btr by remaining bytes */
+\r
+    for ( ;  btr && (*func)(0, 0);                    /* Repeat until all data transferred or stream becomes busy */
+        fp->fptr += rcnt, *bf += rcnt, btr -= rcnt) {
+        csect = (BYTE)(fp->fptr / SS(fp->fs) & (fp->fs->csize - 1));    /* Sector offset in the cluster */
+        if ((fp->fptr % SS(fp->fs)) == 0) {            /* On the sector boundary? */
+            if (!csect) {                            /* On the cluster boundary? */
+                clst = (fp->fptr == 0) ?            /* On the top of the file? */
+                    fp->sclust : get_fat(fp->fs, fp->clust);
+                if (clst <= 1) ABORT(fp->fs, FR_INT_ERR);
+                if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR);
+                fp->clust = clst;                    /* Update current cluster */
+            }
+        }
+        sect = clust2sect(fp->fs, fp->clust);        /* Get current data sector */
+        if (!sect) ABORT(fp->fs, FR_INT_ERR);
+        sect += csect;
+        if (move_window(fp->fs, sect))                /* Move sector window */
+            ABORT(fp->fs, FR_DISK_ERR);
+        fp->dsect = sect;
+        rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs));    /* Forward data from sector window */
+        if (rcnt > btr) rcnt = btr;
+        rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt);
+        if (!rcnt) ABORT(fp->fs, FR_INT_ERR);
+}
+\r
+    LEAVE_FF(fp->fs, FR_OK);
+}
+#endif /* _USE_FORWARD */
+\r
+\r
+\r
+#if _USE_MKFS && !_FS_READONLY
+/*-----------------------------------------------------------------------*/
+/* Create File System on the Drive                                       */
+/*-----------------------------------------------------------------------*/
+#define N_ROOTDIR    512        /* Number of root dir entries for FAT12/16 */
+#define N_FATS        1        /* Number of FAT copies (1 or 2) */
+\r
+\r
+FRESULT f_mkfs (
+    BYTE drv,            /* Logical drive number */
+    BYTE sfd,        /* Partitioning rule 0:FDISK, 1:SFD */
+    UINT au            /* Allocation unit size [bytes] */
+)
+{
+    static const WORD vst[] = { 1024,   512,  256,  128,   64,    32,   16,    8,    4,    2,   0};
+    static const WORD cst[] = {32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512};
+    BYTE fmt, md, *tbl;
+    DWORD n_clst, vs, n, wsect;
+    UINT i;
+    DWORD b_vol, b_fat, b_dir, b_data;    /* Offset (LBA) */
+    DWORD n_vol, n_rsv, n_fat, n_dir;    /* Size */
+    FATFS *fs;
+    DSTATUS stat;
+\r
+\r
+    /* Check mounted drive and clear work area */
+    if (drv >= _VOLUMES) return FR_INVALID_DRIVE;
+    fs = FatFs[drv];
+    if (!fs) return FR_NOT_ENABLED;
+    fs->fs_type = 0;
+    drv = LD2PD(drv);
+\r
+    /* Get disk statics */
+    stat = disk_initialize(drv);
+    if (stat & STA_NOINIT) return FR_NOT_READY;
+    if (stat & STA_PROTECT) return FR_WRITE_PROTECTED;
+#if _MAX_SS != 512                    /* Get disk sector size */
+    if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK)
+        return FR_DISK_ERR;
+#endif
+    if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_vol) != RES_OK || n_vol < 128)
+        return FR_DISK_ERR;
+    b_vol = (sfd) ? 0 : 63;    /* Volume start sector */
+    n_vol -= b_vol;
+    if (au & (au - 1)) au = 0;    /* Check validity of the AU size */
+    if (!au) {                    /* AU auto selection */
+        vs = n_vol / (2000 / (SS(fs) / 512));
+        for (i = 0; vs < vst[i]; i++) ;
+        au = cst[i];
+    }
+    au /= SS(fs);        /* Number of sectors per cluster */
+    if (au == 0) au = 1;
+    if (au > 128) au = 128;
+\r
+    /* Pre-compute number of clusters and FAT syb-type */
+    n_clst = n_vol / au;
+    fmt = FS_FAT12;
+    if (n_clst >= MIN_FAT16) fmt = FS_FAT16;
+    if (n_clst >= MIN_FAT32) fmt = FS_FAT32;
+\r
+    /* Determine offset and size of FAT structure */
+    if (fmt == FS_FAT32) {
+        n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs);
+        n_rsv = 32;
+        n_dir = 0;
+    } else {
+        n_fat = (fmt == FS_FAT12) ? (n_clst * 3 + 1) / 2 + 3 : (n_clst * 2) + 4;
+        n_fat = (n_fat + SS(fs) - 1) / SS(fs);
+        n_rsv = 1;
+        n_dir = (DWORD)N_ROOTDIR * SZ_DIR / SS(fs);
+    }
+    b_fat = b_vol + n_rsv;                /* FAT area start sector */
+    b_dir = b_fat + n_fat * N_FATS;        /* Directory area start sector */
+    b_data = b_dir + n_dir;                /* Data area start sector */
+    if (n_vol < b_data + au) return FR_MKFS_ABORTED;    /* Too small volume */
+\r
+    /* Align data start sector to erase block boundary (for flash memory media) */
+    if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK || !n || n > 32768) n = 1;
+    n = (b_data + n - 1) & ~(n - 1);    /* Next nearest erase block from current data start */
+    n = (n - b_data) / N_FATS;
+    if (fmt == FS_FAT32) {        /* FAT32: Move FAT offset */
+        n_rsv += n;
+        b_fat += n;
+    } else {                    /* FAT12/16: Expand FAT size */
+        n_fat += n;
+    }
+\r
+    /* Determine number of clusters and final check of validity of the FAT sub-type */
+    n_clst = (n_vol - n_rsv - n_fat * N_FATS - n_dir) / au;
+    if (   (fmt == FS_FAT16 && n_clst < MIN_FAT16)
+        || (fmt == FS_FAT32 && n_clst < MIN_FAT32))
+        return FR_MKFS_ABORTED;
+\r
+    /* Create partition table if required */
+    if (sfd) {    /* No patition table (SFD) */
+        md = 0xF0;
+    } else {    /* With patition table (FDISK) */
+        DWORD n_disk = b_vol + n_vol;
+\r
+        mem_set(fs->win, 0, SS(fs));
+        tbl = fs->win+MBR_Table;
+        ST_DWORD(tbl, 0x00010180);            /* Partition start in CHS */
+        if (n_disk < 63UL * 255 * 1024) {    /* Partition end in CHS */
+            n_disk = n_disk / 63 / 255;
+            tbl[7] = (BYTE)n_disk;
+            tbl[6] = (BYTE)((n_disk >> 2) | 63);
+        } else {
+            ST_WORD(&tbl[6], 0xFFFF);    /* CHS saturated */
+        }
+        tbl[5] = 254;
+        if (fmt != FS_FAT32)            /* System ID */
+            tbl[4] = (n_vol < 0x10000) ? 0x04 : 0x06;
+        else
+            tbl[4] = 0x0c;
+        ST_DWORD(tbl+8, 63);                /* Partition start in LBA */
+        ST_DWORD(tbl+12, n_vol);            /* Partition size in LBA */
+        ST_WORD(fs->win+BS_55AA, 0xAA55);    /* MBR signature */
+        if (disk_write(drv, fs->win, 0, 1) != RES_OK)    /* Put the MBR into first physical sector */
+            return FR_DISK_ERR;
+        md = 0xF8;
+    }
+\r
+    /* Create volume boot record */
+    tbl = fs->win;                            /* Clear sector */
+    mem_set(tbl, 0, SS(fs));
+    mem_cpy(tbl, "\xEB\xFE\x90" "MSDOS5.0", 11);/* Boot jump code, OEM name */
+    i = SS(fs);                                /* Sector size */
+    ST_WORD(tbl+BPB_BytsPerSec, i);
+    tbl[BPB_SecPerClus] = (BYTE)au;            /* Sectors per cluster */
+    ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv);        /* Reserved sectors */
+    tbl[BPB_NumFATs] = N_FATS;                    /* Number of FATs */
+    i = (fmt == FS_FAT32) ? 0 : N_ROOTDIR;    /* Number of rootdir entries */
+    ST_WORD(tbl+BPB_RootEntCnt, i);
+    if (n_vol < 0x10000) {                    /* Number of total sectors */
+        ST_WORD(tbl+BPB_TotSec16, n_vol);
+    } else {
+        ST_DWORD(tbl+BPB_TotSec32, n_vol);
+    }
+    tbl[BPB_Media] = md;                    /* Media descriptor */
+    ST_WORD(tbl+BPB_SecPerTrk, 63);            /* Number of sectors per track */
+    ST_WORD(tbl+BPB_NumHeads, 255);            /* Number of heads */
+    ST_DWORD(tbl+BPB_HiddSec, b_vol);        /* Hidden sectors */
+    n = get_fattime();                        /* Use current time as VSN */
+    if (fmt == FS_FAT32) {
+        ST_DWORD(tbl+BS_VolID32, n);        /* VSN */
+        ST_DWORD(tbl+BPB_FATSz32, n_fat);    /* Number of sectors per FAT */
+        ST_DWORD(tbl+BPB_RootClus, 2);        /* Root directory start cluster (2) */
+        ST_WORD(tbl+BPB_FSInfo, 1);            /* FSInfo record offset (VBR+1) */
+        ST_WORD(tbl+BPB_BkBootSec, 6);        /* Backup boot record offset (VBR+6) */
+        tbl[BS_DrvNum32] = 0x80;                /* Drive number */
+        tbl[BS_BootSig32] = 0x29;                /* Extended boot signature */
+        mem_cpy(tbl+BS_VolLab32, "NO NAME    " "FAT32   ", 19);    /* Volume label, FAT signature */
+    } else {
+        ST_DWORD(tbl+BS_VolID, n);            /* VSN */
+        ST_WORD(tbl+BPB_FATSz16, n_fat);    /* Number of sectors per FAT */
+        tbl[BS_DrvNum] = 0x80;                /* Drive number */
+        tbl[BS_BootSig] = 0x29;                /* Extended boot signature */
+        mem_cpy(tbl+BS_VolLab, "NO NAME    " "FAT     ", 19);    /* Volume label, FAT signature */
+    }
+    ST_WORD(tbl+BS_55AA, 0xAA55);            /* Signature (Offset is fixed here regardless of sector size) */
+    if (disk_write(drv, tbl, b_vol, 1) != RES_OK)    /* Write VBR */
+        return FR_DISK_ERR;
+    if (fmt == FS_FAT32)                            /* Write backup VBR if needed (VBR+6) */
+        disk_write(drv, tbl, b_vol + 6, 1);
+\r
+    /* Initialize FAT area */
+    wsect = b_fat;
+    for (i = 0; i < N_FATS; i++) {        /* Initialize each FAT copy */
+        mem_set(tbl, 0, SS(fs));            /* 1st sector of the FAT  */
+        n = md;                                /* Media descriptor byte */
+        if (fmt != FS_FAT32) {
+            n |= (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00;
+            ST_DWORD(tbl+0, n);                /* Reserve cluster #0-1 (FAT12/16) */
+        } else {
+            n |= 0xFFFFFF00;
+            ST_DWORD(tbl+0, n);                /* Reserve cluster #0-1 (FAT32) */
+            ST_DWORD(tbl+4, 0xFFFFFFFF);
+            ST_DWORD(tbl+8, 0x0FFFFFFF);    /* Reserve cluster #2 for root dir */
+        }
+        if (disk_write(drv, tbl, wsect++, 1) != RES_OK)
+            return FR_DISK_ERR;
+        mem_set(tbl, 0, SS(fs));            /* Fill following FAT entries with zero */
+        for (n = 1; n < n_fat; n++) {        /* This loop may take a time on FAT32 volume due to many single sector writes */
+            if (disk_write(drv, tbl, wsect++, 1) != RES_OK)
+                return FR_DISK_ERR;
+        }
+    }
+\r
+    /* Initialize root directory */
+    i = (fmt == FS_FAT32) ? au : n_dir;
+    do {
+        if (disk_write(drv, tbl, wsect++, 1) != RES_OK)
+            return FR_DISK_ERR;
+    } while (--i);
+\r
+#if _USE_ERASE    /* Erase data area if needed */
+    {
+        DWORD eb[2];
+\r
+        eb[0] = wsect; eb[1] = wsect + (n_clst - ((fmt == FS_FAT32) ? 1 : 0)) * au - 1;
+        disk_ioctl(drv, CTRL_ERASE_SECTOR, eb);
+    }
+#endif
+\r
+    /* Create FSInfo if needed */
+    if (fmt == FS_FAT32) {
+        ST_DWORD(tbl+FSI_LeadSig, 0x41615252);
+        ST_DWORD(tbl+FSI_StrucSig, 0x61417272);
+        ST_DWORD(tbl+FSI_Free_Count, n_clst - 1);    /* Number of free clusters */
+        ST_DWORD(tbl+FSI_Nxt_Free, 2);                /* Last allocated cluster# */
+        ST_WORD(tbl+BS_55AA, 0xAA55);
+        disk_write(drv, tbl, b_vol + 1, 1);    /* Write original (VBR+1) */
+        disk_write(drv, tbl, b_vol + 7, 1);    /* Write backup (VBR+7) */
+    }
+\r
+    return (disk_ioctl(drv, CTRL_SYNC, (void*)0) == RES_OK) ? FR_OK : FR_DISK_ERR;
+}
+\r
+#endif /* _USE_MKFS && !_FS_READONLY */
+\r
+\r
+\r
+\r
+#if _USE_STRFUNC
+/*-----------------------------------------------------------------------*/
+/* Get a string from the file                                            */
+/*-----------------------------------------------------------------------*/
+TCHAR* f_gets (
+    TCHAR* buff,    /* Pointer to the string buffer to read */
+    int len,        /* Size of string buffer (characters) */
+    FIL_t* fil    /* Pointer to the file object */
+)
+{
+    int n = 0;
+    TCHAR c, *p = buff;
+    BYTE s[2];
+    UINT rc;
+\r
+\r
+    while (n < len - 1) {            /* Read bytes until buffer gets filled */
+        f_read(fil, s, 1, &rc);
+        if (rc != 1) break;            /* Break on EOF or error */
+        c = s[0];
+#if _LFN_UNICODE                    /* Read a character in UTF-8 encoding */
+        if (c >= 0x80) {
+            if (c < 0xC0) continue;    /* Skip stray trailer */
+            if (c < 0xE0) {            /* Two-byte sequense */
+                f_read(fil, s, 1, &rc);
+                if (rc != 1) break;
+                c = ((c & 0x1F) << 6) | (s[0] & 0x3F);
+                if (c < 0x80) c = '?';
+            } else {
+                if (c < 0xF0) {        /* Three-byte sequense */
+                    f_read(fil, s, 2, &rc);
+                    if (rc != 2) break;
+                    c = (c << 12) | ((s[0] & 0x3F) << 6) | (s[1] & 0x3F);
+                    if (c < 0x800) c = '?';
+                } else {            /* Reject four-byte sequense */
+                    c = '?';
+                }
+            }
+        }
+#endif
+#if _USE_STRFUNC >= 2
+        if (c == '\r') continue;    /* Strip '\r' */
+#endif
+        *p++ = c;
+        n++;
+        if (c == '\n') break;        /* Break on EOL */
+    }
+    *p = 0;
+    return n ? buff : 0;            /* When no data read (eof or error), return with error. */
+}
+\r
+\r
+\r
+#if !_FS_READONLY
+#include <stdarg.h>
+/*-----------------------------------------------------------------------*/
+/* Put a character to the file                                           */
+/*-----------------------------------------------------------------------*/
+int f_putc (
+    TCHAR c,    /* A character to be output */
+    FIL_t* fil    /* Pointer to the file object */
+)
+{
+    UINT bw, btw;
+    BYTE s[3];
+\r
+\r
+#if _USE_STRFUNC >= 2
+    if (c == '\n') f_putc ('\r', fil);    /* LF -> CRLF conversion */
+#endif
+\r
+#if _LFN_UNICODE    /* Write the character in UTF-8 encoding */
+    if (c < 0x80) {            /* 7-bit */
+        s[0] = (BYTE)c;
+        btw = 1;
+    } else {
+        if (c < 0x800) {    /* 11-bit */
+            s[0] = (BYTE)(0xC0 | (c >> 6));
+            s[1] = (BYTE)(0x80 | (c & 0x3F));
+            btw = 2;
+        } else {            /* 16-bit */
+            s[0] = (BYTE)(0xE0 | (c >> 12));
+            s[1] = (BYTE)(0x80 | ((c >> 6) & 0x3F));
+            s[2] = (BYTE)(0x80 | (c & 0x3F));
+            btw = 3;
+    }
+    }
+#else                /* Write the character without conversion */
+    s[0] = (BYTE)c;
+    btw = 1;
+#endif
+    f_write(fil, s, btw, &bw);        /* Write the char to the file */
+    return (bw == btw) ? 1 : EOF;    /* Return the result */
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Put a string to the file                                              */
+/*-----------------------------------------------------------------------*/
+int f_puts (
+    const TCHAR* str,    /* Pointer to the string to be output */
+    FIL_t* fil            /* Pointer to the file object */
+)
+{
+    int n;
+\r
+\r
+    for (n = 0; *str; str++, n++) {
+        if (f_putc(*str, fil) == EOF) return EOF;
+    }
+    return n;
+}
+\r
+\r
+\r
+\r
+/*-----------------------------------------------------------------------*/
+/* Put a formatted string to the file                                    */
+/*-----------------------------------------------------------------------*/
+int f_printf (
+    FIL_t* fil,            /* Pointer to the file object */
+    const TCHAR* str,    /* Pointer to the format string */
+    ...                    /* Optional arguments... */
+)
+{
+    va_list arp;
+    BYTE f, r;
+    UINT i, j, w;
+    ULONG v;
+    TCHAR c, d, s[16], *p;
+    int res, cc;
+\r
+\r
+    va_start(arp, str);
+\r
+    for (cc = res = 0; cc != EOF; res += cc) {
+        c = *str++;
+        if (c == 0) break;            /* End of string */
+        if (c != '%') {                /* Non escape character */
+            cc = f_putc(c, fil);
+            if (cc != EOF) cc = 1;
+            continue;
+        }
+        w = f = 0;
+        c = *str++;
+        if (c == '0') {                /* Flag: '0' padding */
+            f = 1; c = *str++;
+        } else {
+            if (c == '-') {            /* Flag: left justified */
+                f = 2; c = *str++;
+        }
+        }
+        while (IsDigit(c)) {        /* Precision */
+            w = w * 10 + c - '0';
+            c = *str++;
+        }
+        if (c == 'l' || c == 'L') {    /* Prefix: Size is long int */
+            f |= 4; c = *str++;
+        }
+        if (!c) break;
+        d = c;
+        if (IsLower(d)) d -= 0x20;
+        switch (d) {                /* Type is... */
+        case 'S' :                    /* String */
+            p = va_arg(arp, TCHAR*);
+            for (j = 0; p[j]; j++) ;
+            res = 0;
+            while (!(f & 2) && j++ < w) res += (cc = f_putc(' ', fil));
+            res += (cc = f_puts(p, fil));
+            while (j++ < w) res += (cc = f_putc(' ', fil));
+            if (cc != EOF) cc = res;
+            continue;
+        case 'C' :                    /* Character */
+            cc = f_putc((TCHAR)va_arg(arp, int), fil); continue;
+        case 'B' :                    /* Binary */
+            r = 2; break;
+        case 'O' :                    /* Octal */
+            r = 8; break;
+        case 'D' :                    /* Signed decimal */
+        case 'U' :                    /* Unsigned decimal */
+            r = 10; break;
+        case 'X' :                    /* Hexdecimal */
+            r = 16; break;
+        default:                    /* Unknown type (passthrough) */
+            cc = f_putc(c, fil); continue;
+        }
+\r
+        /* Get an argument and put it in numeral */
+        v = (f & 4) ? va_arg(arp, long) : ((d == 'D') ? (long)va_arg(arp, int) : va_arg(arp, unsigned int));
+        if (d == 'D' && (v & 0x80000000)) {
+            v = 0 - v;
+            f |= 8;
+        }
+        i = 0;
+        do {
+            d = (TCHAR)(v % r); v /= r;
+            if (d > 9) d += (c == 'x') ? 0x27 : 0x07;
+            s[i++] = d + '0';
+        } while (v && i < sizeof(s) / sizeof(s[0]));
+        if (f & 8) s[i++] = '-';
+        j = i; d = (f & 1) ? '0' : ' ';
+        res = 0;
+        while (!(f & 2) && j++ < w) res += (cc = f_putc(d, fil));
+        do res += (cc = f_putc(s[--i], fil)); while(i);
+        while (j++ < w) res += (cc = f_putc(' ', fil));
+        if (cc != EOF) cc = res;
+    }
+\r
+    va_end(arp);
+    return (cc == EOF) ? cc : res;
+}
+\r
+#endif /* !_FS_READONLY */
+#endif /* _USE_STRFUNC */
index 8a94eb9..4919939 100644 (file)
-/*---------------------------------------------------------------------------/\r
-/  FatFs - FAT file system module include file  R0.08b    (C)ChaN, 2011\r
-/----------------------------------------------------------------------------/\r
-/ FatFs module is a generic FAT file system module for small embedded systems.\r
-/ This is a free software that opened for education, research and commercial\r
-/ developments under license policy of following trems.\r
-/\r
-/  Copyright (C) 2011, ChaN, all right reserved.\r
-/\r
-/ * The FatFs module is a free software and there is NO WARRANTY.\r
-/ * No restriction on use. You can use, modify and redistribute it for\r
-/   personal, non-profit or commercial product UNDER YOUR RESPONSIBILITY.\r
-/ * Redistributions of source code must retain the above copyright notice.\r
-/\r
-/----------------------------------------------------------------------------*/\r
-\r
-#ifndef _FATFS\r
-#define _FATFS    8237    /* Revision ID */\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-#include "integer.h"    /* Basic integer types */\r
-#include "ffconf.h"        /* FatFs configuration options */\r
-\r
-#if _FATFS != _FFCONF\r
-#error Wrong configuration file (ffconf.h).\r
-#endif\r
-\r
-\r
-\r
-#define _DRIVES        4\r
-/* Number of logical drives to be used. This affects the size of internal table. */\r
-/* Definitions of volume management */\r
-\r
-#if _MULTI_PARTITION        /* Multiple partition configuration */\r
-#define LD2PD(vol) (VolToPart[vol].pd)    /* Get physical drive# */\r
-#define LD2PT(vol) (VolToPart[vol].pt)    /* Get partition# */\r
-typedef struct {\r
-    BYTE pd;    /* Physical drive# */\r
-    BYTE pt;    /* Partition # (0-3) */\r
-} PARTITION;\r
-extern const PARTITION VolToPart[];    /* Volume - Physical location resolution table */\r
-\r
-#else                        /* Single partition configuration */\r
-#define LD2PD(vol) (vol)    /* Logical drive# is bound to the same physical drive# */\r
-#define LD2PT(vol) 0        /* Always mounts the 1st partition */\r
-\r
-#endif\r
-\r
-\r
-\r
-/* Type of path name strings on FatFs API */\r
-\r
-#if _LFN_UNICODE            /* Unicode string */\r
-#if !_USE_LFN\r
-#error _LFN_UNICODE must be 0 in non-LFN cfg.\r
-#endif\r
-#ifndef _INC_TCHAR\r
-typedef WCHAR TCHAR;\r
-#define _T(x) L ## x\r
-#define _TEXT(x) L ## x\r
-#endif\r
-\r
-#else                        /* ANSI/OEM string */\r
-#ifndef _INC_TCHAR\r
-typedef char TCHAR;\r
-#define _T(x) x\r
-#define _TEXT(x) x\r
-#endif\r
-\r
-#endif\r
-\r
-\r
-\r
-/* File system object structure (FATFS) */\r
-\r
-typedef struct {\r
-    BYTE    fs_type;        /* FAT sub-type (0:Not mounted) */\r
-    BYTE    drv;            /* Physical drive number */\r
-    BYTE    csize;            /* Sectors per cluster (1,2,4...128) */\r
-    BYTE    n_fats;            /* Number of FAT copies (1,2) */\r
-    BYTE    wflag;            /* win[] dirty flag (1:must be written back) */\r
-    BYTE    fsi_flag;        /* fsinfo dirty flag (1:must be written back) */\r
-    WORD    id;                /* File system mount ID */\r
-    WORD    n_rootdir;        /* Number of root directory entries (FAT12/16) */\r
-#if _MAX_SS != 512\r
-    WORD    ssize;            /* Bytes per sector (512,1024,2048,4096) */\r
-#endif\r
-#if _FS_REENTRANT\r
-    _SYNC_t    sobj;            /* Identifier of sync object */\r
-#endif\r
-#if !_FS_READONLY\r
-    DWORD    last_clust;        /* Last allocated cluster */\r
-    DWORD    free_clust;        /* Number of free clusters */\r
-    DWORD    fsi_sector;        /* fsinfo sector (FAT32) */\r
-#endif\r
-#if _FS_RPATH\r
-    DWORD    cdir;            /* Current directory start cluster (0:root) */\r
-#endif\r
-    DWORD    n_fatent;        /* Number of FAT entries (= number of clusters + 2) */\r
-    DWORD    fsize;            /* Sectors per FAT */\r
-    DWORD    fatbase;        /* FAT start sector */\r
-    DWORD    dirbase;        /* Root directory start sector (FAT32:Cluster#) */\r
-    DWORD    database;        /* Data start sector */\r
-    DWORD    winsect;        /* Current sector appearing in the win[] */\r
-    BYTE    win[_MAX_SS];    /* Disk access window for Directory, FAT (and Data on tiny cfg) */\r
-} FATFS;\r
-\r
-\r
-\r
-/* File object structure (FIL) */\r
-\r
-typedef struct {\r
-    FATFS*    fs;                /* Pointer to the owner file system object */\r
-    WORD    id;                /* Owner file system mount ID */\r
-    BYTE    flag;            /* File status flags */\r
-    BYTE    pad1;\r
-    DWORD    fptr;            /* File read/write pointer (0 on file open) */\r
-    DWORD    fsize;            /* File size */\r
-    DWORD    sclust;            /* File start cluster (0 when fsize==0) */\r
-    DWORD    clust;            /* Current cluster */\r
-    DWORD    dsect;            /* Current data sector */\r
-#if !_FS_READONLY\r
-    DWORD    dir_sect;        /* Sector containing the directory entry */\r
-    BYTE*    dir_ptr;        /* Ponter to the directory entry in the window */\r
-#endif\r
-#if _USE_FASTSEEK\r
-    DWORD*    cltbl;            /* Pointer to the cluster link map table (null on file open) */\r
-#endif\r
-#if _FS_SHARE\r
-    UINT    lockid;            /* File lock ID (index of file semaphore table) */\r
-#endif\r
-#if !_FS_TINY\r
-    BYTE    buf[_MAX_SS];    /* File data read/write buffer */\r
-#endif\r
-} FIL_t;\r
-\r
-\r
-\r
-/* Directory object structure (DIR) */\r
-\r
-typedef struct {\r
-    FATFS*    fs;                /* Pointer to the owner file system object */\r
-    WORD    id;                /* Owner file system mount ID */\r
-    WORD    index;            /* Current read/write index number */\r
-    DWORD    sclust;            /* Table start cluster (0:Root dir) */\r
-    DWORD    clust;            /* Current cluster */\r
-    DWORD    sect;            /* Current sector */\r
-    BYTE*    dir;            /* Pointer to the current SFN entry in the win[] */\r
-    BYTE*    fn;                /* Pointer to the SFN (in/out) {file[8],ext[3],status[1]} */\r
-#if _USE_LFN\r
-    WCHAR*    lfn;            /* Pointer to the LFN working buffer */\r
-    WORD    lfn_idx;        /* Last matched LFN index number (0xFFFF:No LFN) */\r
-#endif\r
-} DIR_t;\r
-\r
-\r
-\r
-/* File status structure (FILINFO) */\r
-\r
-typedef struct {\r
-    DWORD    fsize;            /* File size */\r
-    WORD    fdate;            /* Last modified date */\r
-    WORD    ftime;            /* Last modified time */\r
-    BYTE    fattrib;        /* Attribute */\r
-    TCHAR    fname[13];        /* Short file name (8.3 format) */\r
-#if _USE_LFN\r
-    TCHAR*    lfname;            /* Pointer to the LFN buffer */\r
-    UINT     lfsize;            /* Size of LFN buffer in TCHAR */\r
-#endif\r
-} FILINFO;\r
-\r
-\r
-\r
-/* File function return code (FRESULT) */\r
-\r
-typedef enum {\r
-    FR_OK = 0,                /* (0) Succeeded */\r
-    FR_DISK_ERR,            /* (1) A hard error occured in the low level disk I/O layer */\r
-    FR_INT_ERR,                /* (2) Assertion failed */\r
-    FR_NOT_READY,            /* (3) The physical drive cannot work */\r
-    FR_NO_FILE,                /* (4) Could not find the file */\r
-    FR_NO_PATH,                /* (5) Could not find the path */\r
-    FR_INVALID_NAME,        /* (6) The path name format is invalid */\r
-    FR_DENIED,                /* (7) Acces denied due to prohibited access or directory full */\r
-    FR_EXIST,                /* (8) Acces denied due to prohibited access */\r
-    FR_INVALID_OBJECT,        /* (9) The file/directory object is invalid */\r
-    FR_WRITE_PROTECTED,        /* (10) The physical drive is write protected */\r
-    FR_INVALID_DRIVE,        /* (11) The logical drive number is invalid */\r
-    FR_NOT_ENABLED,            /* (12) The volume has no work area */\r
-    FR_NO_FILESYSTEM,        /* (13) There is no valid FAT volume on the physical drive */\r
-    FR_MKFS_ABORTED,        /* (14) The f_mkfs() aborted due to any parameter error */\r
-    FR_TIMEOUT,                /* (15) Could not get a grant to access the volume within defined period */\r
-    FR_LOCKED,                /* (16) The operation is rejected according to the file shareing policy */\r
-    FR_NOT_ENOUGH_CORE,        /* (17) LFN working buffer could not be allocated */\r
-    FR_TOO_MANY_OPEN_FILES    /* (18) Number of open files > _FS_SHARE */\r
-} FRESULT;\r
-\r
-\r
-\r
-/*--------------------------------------------------------------*/\r
-/* FatFs module application interface                  */\r
-\r
-FRESULT f_mount (BYTE, FATFS*);                        /* Mount/Unmount a logical drive */\r
-FRESULT f_open (FIL_t*, const TCHAR*, BYTE);            /* Open or create a file */\r
-FRESULT f_read (FIL_t*, void*, UINT, UINT*);            /* Read data from a file */\r
-FRESULT f_lseek (FIL_t*, DWORD);                        /* Move file pointer of a file object */\r
-FRESULT f_close (FIL_t*);                                /* Close an open file object */\r
-FRESULT f_opendir (DIR_t*, const TCHAR*);                /* Open an existing directory */\r
-FRESULT f_readdir (DIR_t*, FILINFO*);                    /* Read a directory item */\r
-FRESULT f_stat (const TCHAR*, FILINFO*);            /* Get file status */\r
-FRESULT f_write (FIL_t*, const void*, UINT, UINT*);    /* Write data to a file */\r
-FRESULT f_getfree (const TCHAR*, DWORD*, FATFS**);    /* Get number of free clusters on the drive */\r
-FRESULT f_truncate (FIL_t*);                            /* Truncate file */\r
-FRESULT f_sync (FIL_t*);                                /* Flush cached data of a writing file */\r
-FRESULT f_unlink (const TCHAR*);                    /* Delete an existing file or directory */\r
-FRESULT f_mkdir (const TCHAR*);                        /* Create a new directory */\r
-FRESULT f_chmod (const TCHAR*, BYTE, BYTE);            /* Change attriburte of the file/dir */\r
-FRESULT f_utime (const TCHAR*, const FILINFO*);        /* Change timestamp of the file/dir */\r
-FRESULT f_rename (const TCHAR*, const TCHAR*);        /* Rename/Move a file or directory */\r
-FRESULT f_forward (FIL_t*, UINT(*)(const BYTE*,UINT), UINT, UINT*);    /* Forward data to the stream */\r
-FRESULT f_mkfs (BYTE, BYTE, UINT);                    /* Create a file system on the drive */\r
-FRESULT f_chdrive (BYTE);                            /* Change current drive */\r
-FRESULT f_chdir (const TCHAR*);                        /* Change current directory */\r
-FRESULT f_getcwd (TCHAR*, UINT);                    /* Get current directory */\r
-int f_putc (TCHAR, FIL_t*);                            /* Put a character to the file */\r
-int f_puts (const TCHAR*, FIL_t*);                    /* Put a string to the file */\r
-int f_printf (FIL_t*, const TCHAR*, ...);                /* Put a formatted string to the file */\r
-TCHAR* f_gets (TCHAR*, int, FIL_t*);                    /* Get a string from the file */\r
-\r
-#ifndef EOF\r
-#define EOF (-1)\r
-#endif\r
-\r
-#define f_eof(fp) (((fp)->fptr == (fp)->fsize) ? 1 : 0)\r
-#define f_error(fp) (((fp)->flag & FA__ERROR) ? 1 : 0)\r
-#define f_tell(fp) ((fp)->fptr)\r
-#define f_size(fp) ((fp)->fsize)\r
-\r
-\r
-\r
-\r
-/*--------------------------------------------------------------*/\r
-/* Additional user defined functions                            */\r
-\r
-/* RTC function */\r
-#if !_FS_READONLY\r
-DWORD get_fattime (void);\r
-#endif\r
-\r
-/* Unicode support functions */\r
-#if _USE_LFN                        /* Unicode - OEM code conversion */\r
-WCHAR ff_convert (WCHAR, UINT);        /* OEM-Unicode bidirectional conversion */\r
-WCHAR ff_wtoupper (WCHAR);            /* Unicode upper-case conversion */\r
-#if _USE_LFN == 3                    /* Memory functions */\r
-void* ff_memalloc (UINT);            /* Allocate memory block */\r
-void ff_memfree (void*);            /* Free memory block */\r
-#endif\r
-#endif\r
-\r
-/* Sync functions */\r
-#if _FS_REENTRANT\r
-int ff_cre_syncobj (BYTE, _SYNC_t*);/* Create a sync object */\r
-int ff_req_grant (_SYNC_t);            /* Lock sync object */\r
-void ff_rel_grant (_SYNC_t);        /* Unlock sync object */\r
-int ff_del_syncobj (_SYNC_t);        /* Delete a sync object */\r
-#endif\r
-\r
-\r
-\r
-\r
-/*--------------------------------------------------------------*/\r
-/* Flags and offset address                                     */\r
-\r
-\r
-/* File access control and file status flags (FIL.flag) */\r
-\r
-#define    FA_READ                0x01\r
-#define    FA_OPEN_EXISTING    0x00\r
-#define FA__ERROR            0x80\r
-\r
-#if !_FS_READONLY\r
-#define    FA_WRITE            0x02\r
-#define    FA_CREATE_NEW        0x04\r
-#define    FA_CREATE_ALWAYS    0x08\r
-#define    FA_OPEN_ALWAYS        0x10\r
-#define FA__WRITTEN            0x20\r
-#define FA__DIRTY            0x40\r
-#endif\r
-\r
-\r
-/* FAT sub type (FATFS.fs_type) */\r
+/*---------------------------------------------------------------------------/
+/  FatFs - FAT file system module include file  R0.08b    (C)ChaN, 2011
+/----------------------------------------------------------------------------/
+/ FatFs module is a generic FAT file system module for small embedded systems.
+/ This is a free software that opened for education, research and commercial
+/ developments under license policy of following trems.
+/
+/  Copyright (C) 2011, ChaN, all right reserved.
+/
+/ * The FatFs module is a free software and there is NO WARRANTY.
+/ * No restriction on use. You can use, modify and redistribute it for
+/   personal, non-profit or commercial product UNDER YOUR RESPONSIBILITY.
+/ * Redistributions of source code must retain the above copyright notice.
+/
+/----------------------------------------------------------------------------*/
+\r
+#ifndef _FATFS
+#define _FATFS    8237    /* Revision ID */
+\r
+#ifdef __cplusplus
+extern "C" {
+#endif
+\r
+#include "integer.h"    /* Basic integer types */
+#include "ffconf.h"        /* FatFs configuration options */
+\r
+#if _FATFS != _FFCONF
+#error Wrong configuration file (ffconf.h).
+#endif
+\r
+\r
+\r
+#define _DRIVES        4
+/* Number of logical drives to be used. This affects the size of internal table. */
+/* Definitions of volume management */
+\r
+#if _MULTI_PARTITION        /* Multiple partition configuration */
+#define LD2PD(vol) (VolToPart[vol].pd)    /* Get physical drive# */
+#define LD2PT(vol) (VolToPart[vol].pt)    /* Get partition# */
+typedef struct {
+    BYTE pd;    /* Physical drive# */
+    BYTE pt;    /* Partition # (0-3) */
+} PARTITION;
+extern const PARTITION VolToPart[];    /* Volume - Physical location resolution table */
+\r
+#else                        /* Single partition configuration */
+#define LD2PD(vol) (vol)    /* Logical drive# is bound to the same physical drive# */
+#define LD2PT(vol) 0        /* Always mounts the 1st partition */
+\r
+#endif
+\r
+\r
+\r
+/* Type of path name strings on FatFs API */
+\r
+#if _LFN_UNICODE            /* Unicode string */
+#if !_USE_LFN
+#error _LFN_UNICODE must be 0 in non-LFN cfg.
+#endif
+#ifndef _INC_TCHAR
+typedef WCHAR TCHAR;
+#define _T(x) L ## x
+#define _TEXT(x) L ## x
+#endif
+\r
+#else                        /* ANSI/OEM string */
+#ifndef _INC_TCHAR
+typedef char TCHAR;
+#define _T(x) x
+#define _TEXT(x) x
+#endif
+\r
+#endif
+\r
+\r
+\r
+/* File system object structure (FATFS) */
+\r
+typedef struct {
+    BYTE    fs_type;        /* FAT sub-type (0:Not mounted) */
+    BYTE    drv;            /* Physical drive number */
+    BYTE    csize;            /* Sectors per cluster (1,2,4...128) */
+    BYTE    n_fats;            /* Number of FAT copies (1,2) */
+    BYTE    wflag;            /* win[] dirty flag (1:must be written back) */
+    BYTE    fsi_flag;        /* fsinfo dirty flag (1:must be written back) */
+    WORD    id;                /* File system mount ID */
+    WORD    n_rootdir;        /* Number of root directory entries (FAT12/16) */
+#if _MAX_SS != 512
+    WORD    ssize;            /* Bytes per sector (512,1024,2048,4096) */
+#endif
+#if _FS_REENTRANT
+    _SYNC_t    sobj;            /* Identifier of sync object */
+#endif
+#if !_FS_READONLY
+    DWORD    last_clust;        /* Last allocated cluster */
+    DWORD    free_clust;        /* Number of free clusters */
+    DWORD    fsi_sector;        /* fsinfo sector (FAT32) */
+#endif
+#if _FS_RPATH
+    DWORD    cdir;            /* Current directory start cluster (0:root) */
+#endif
+    DWORD    n_fatent;        /* Number of FAT entries (= number of clusters + 2) */
+    DWORD    fsize;            /* Sectors per FAT */
+    DWORD    fatbase;        /* FAT start sector */
+    DWORD    dirbase;        /* Root directory start sector (FAT32:Cluster#) */
+    DWORD    database;        /* Data start sector */
+    DWORD    winsect;        /* Current sector appearing in the win[] */
+    BYTE    win[_MAX_SS];    /* Disk access window for Directory, FAT (and Data on tiny cfg) */
+} FATFS;
+\r
+\r
+\r
+/* File object structure (FIL) */
+\r
+typedef struct {
+    FATFS*    fs;                /* Pointer to the owner file system object */
+    WORD    id;                /* Owner file system mount ID */
+    BYTE    flag;            /* File status flags */
+    BYTE    pad1;
+    DWORD    fptr;            /* File read/write pointer (0 on file open) */
+    DWORD    fsize;            /* File size */
+    DWORD    sclust;            /* File start cluster (0 when fsize==0) */
+    DWORD    clust;            /* Current cluster */
+    DWORD    dsect;            /* Current data sector */
+#if !_FS_READONLY
+    DWORD    dir_sect;        /* Sector containing the directory entry */
+    BYTE*    dir_ptr;        /* Ponter to the directory entry in the window */
+#endif
+#if _USE_FASTSEEK
+    DWORD*    cltbl;            /* Pointer to the cluster link map table (null on file open) */
+#endif
+#if _FS_SHARE
+    UINT    lockid;            /* File lock ID (index of file semaphore table) */
+#endif
+#if !_FS_TINY
+    BYTE    buf[_MAX_SS];    /* File data read/write buffer */
+#endif
+} FIL_t;
+\r
+\r
+\r
+/* Directory object structure (DIR) */
+\r
+typedef struct {
+    FATFS*    fs;                /* Pointer to the owner file system object */
+    WORD    id;                /* Owner file system mount ID */
+    WORD    index;            /* Current read/write index number */
+    DWORD    sclust;            /* Table start cluster (0:Root dir) */
+    DWORD    clust;            /* Current cluster */
+    DWORD    sect;            /* Current sector */
+    BYTE*    dir;            /* Pointer to the current SFN entry in the win[] */
+    BYTE*    fn;                /* Pointer to the SFN (in/out) {file[8],ext[3],status[1]} */
+#if _USE_LFN
+    WCHAR*    lfn;            /* Pointer to the LFN working buffer */
+    WORD    lfn_idx;        /* Last matched LFN index number (0xFFFF:No LFN) */
+#endif
+} DIR_t;
+\r
+\r
+\r
+/* File status structure (FILINFO) */
+\r
+typedef struct {
+    DWORD    fsize;            /* File size */
+    WORD    fdate;            /* Last modified date */
+    WORD    ftime;            /* Last modified time */
+    BYTE    fattrib;        /* Attribute */
+    TCHAR    fname[13];        /* Short file name (8.3 format) */
+#if _USE_LFN
+    TCHAR*    lfname;            /* Pointer to the LFN buffer */
+    UINT     lfsize;            /* Size of LFN buffer in TCHAR */
+#endif
+} FILINFO;
+\r
+\r
+\r
+/* File function return code (FRESULT) */
+\r
+typedef enum {
+    FR_OK = 0,                /* (0) Succeeded */
+    FR_DISK_ERR,            /* (1) A hard error occured in the low level disk I/O layer */
+    FR_INT_ERR,                /* (2) Assertion failed */
+    FR_NOT_READY,            /* (3) The physical drive cannot work */
+    FR_NO_FILE,                /* (4) Could not find the file */
+    FR_NO_PATH,                /* (5) Could not find the path */
+    FR_INVALID_NAME,        /* (6) The path name format is invalid */
+    FR_DENIED,                /* (7) Acces denied due to prohibited access or directory full */
+    FR_EXIST,                /* (8) Acces denied due to prohibited access */
+    FR_INVALID_OBJECT,        /* (9) The file/directory object is invalid */
+    FR_WRITE_PROTECTED,        /* (10) The physical drive is write protected */
+    FR_INVALID_DRIVE,        /* (11) The logical drive number is invalid */
+    FR_NOT_ENABLED,            /* (12) The volume has no work area */
+    FR_NO_FILESYSTEM,        /* (13) There is no valid FAT volume on the physical drive */
+    FR_MKFS_ABORTED,        /* (14) The f_mkfs() aborted due to any parameter error */
+    FR_TIMEOUT,                /* (15) Could not get a grant to access the volume within defined period */
+    FR_LOCKED,                /* (16) The operation is rejected according to the file shareing policy */
+    FR_NOT_ENOUGH_CORE,        /* (17) LFN working buffer could not be allocated */
+    FR_TOO_MANY_OPEN_FILES    /* (18) Number of open files > _FS_SHARE */
+} FRESULT;
+\r
+\r
+\r
+/*--------------------------------------------------------------*/
+/* FatFs module application interface                  */
+\r
+FRESULT f_mount (BYTE, FATFS*);                        /* Mount/Unmount a logical drive */
+FRESULT f_open (FIL_t*, const TCHAR*, BYTE);            /* Open or create a file */
+FRESULT f_read (FIL_t*, void*, UINT, UINT*);            /* Read data from a file */
+FRESULT f_lseek (FIL_t*, DWORD);                        /* Move file pointer of a file object */
+FRESULT f_close (FIL_t*);                                /* Close an open file object */
+FRESULT f_opendir (DIR_t*, const TCHAR*);                /* Open an existing directory */
+FRESULT f_readdir (DIR_t*, FILINFO*);                    /* Read a directory item */
+FRESULT f_stat (const TCHAR*, FILINFO*);            /* Get file status */
+FRESULT f_write (FIL_t*, const void*, UINT, UINT*);    /* Write data to a file */
+FRESULT f_getfree (const TCHAR*, DWORD*, FATFS**);    /* Get number of free clusters on the drive */
+FRESULT f_truncate (FIL_t*);                            /* Truncate file */
+FRESULT f_sync (FIL_t*);                                /* Flush cached data of a writing file */
+FRESULT f_unlink (const TCHAR*);                    /* Delete an existing file or directory */
+FRESULT f_mkdir (const TCHAR*);                        /* Create a new directory */
+FRESULT f_chmod (const TCHAR*, BYTE, BYTE);            /* Change attriburte of the file/dir */
+FRESULT f_utime (const TCHAR*, const FILINFO*);        /* Change timestamp of the file/dir */
+FRESULT f_rename (const TCHAR*, const TCHAR*);        /* Rename/Move a file or directory */
+FRESULT f_forward (FIL_t*, UINT(*)(const BYTE*,UINT), UINT, UINT*);    /* Forward data to the stream */
+FRESULT f_mkfs (BYTE, BYTE, UINT);                    /* Create a file system on the drive */
+FRESULT f_chdrive (BYTE);                            /* Change current drive */
+FRESULT f_chdir (const TCHAR*);                        /* Change current directory */
+FRESULT f_getcwd (TCHAR*, UINT);                    /* Get current directory */
+int f_putc (TCHAR, FIL_t*);                            /* Put a character to the file */
+int f_puts (const TCHAR*, FIL_t*);                    /* Put a string to the file */
+int f_printf (FIL_t*, const TCHAR*, ...);                /* Put a formatted string to the file */
+TCHAR* f_gets (TCHAR*, int, FIL_t*);                    /* Get a string from the file */
+\r
+#ifndef EOF
+#define EOF (-1)
+#endif
+\r
+#define f_eof(fp) (((fp)->fptr == (fp)->fsize) ? 1 : 0)
+#define f_error(fp) (((fp)->flag & FA__ERROR) ? 1 : 0)
+#define f_tell(fp) ((fp)->fptr)
+#define f_size(fp) ((fp)->fsize)
+\r
+\r
+\r
+\r
+/*--------------------------------------------------------------*/
+/* Additional user defined functions                            */
+\r
+/* RTC function */
+#if !_FS_READONLY
+DWORD get_fattime (void);
+#endif
+\r
+/* Unicode support functions */
+#if _USE_LFN                        /* Unicode - OEM code conversion */
+WCHAR ff_convert (WCHAR, UINT);        /* OEM-Unicode bidirectional conversion */
+WCHAR ff_wtoupper (WCHAR);            /* Unicode upper-case conversion */
+#if _USE_LFN == 3                    /* Memory functions */
+void* ff_memalloc (UINT);            /* Allocate memory block */
+void ff_memfree (void*);            /* Free memory block */
+#endif
+#endif
+\r
+/* Sync functions */
+#if _FS_REENTRANT
+int ff_cre_syncobj (BYTE, _SYNC_t*);/* Create a sync object */
+int ff_req_grant (_SYNC_t);            /* Lock sync object */
+void ff_rel_grant (_SYNC_t);        /* Unlock sync object */
+int ff_del_syncobj (_SYNC_t);        /* Delete a sync object */
+#endif
+\r
+\r
+\r
+\r
+/*--------------------------------------------------------------*/
+/* Flags and offset address                                     */
+\r
+\r
+/* File access control and file status flags (FIL.flag) */
+\r
+#define    FA_READ                0x01
+#define    FA_OPEN_EXISTING    0x00
+#define FA__ERROR            0x80
+\r
+#if !_FS_READONLY
+#define    FA_WRITE            0x02
+#define    FA_CREATE_NEW        0x04
+#define    FA_CREATE_ALWAYS    0x08
+#define    FA_OPEN_ALWAYS        0x10
+#define FA__WRITTEN            0x20
+#define FA__DIRTY            0x40
+#endif
+\r
+\r
+/* FAT sub type (FATFS.fs_type) */
 \r
-#define FS_FAT12    1\r
-#define FS_FAT16    2\r
-#define FS_FAT32    3\r
+#define FS_FAT12    1
+#define FS_FAT16    2
+#define FS_FAT32    3
 \r
 \r
-/* File attribute bits for directory entry */\r
-\r
-#define    AM_RDO    0x01    /* Read only */\r
-#define    AM_HID    0x02    /* Hidden */\r
-#define    AM_SYS    0x04    /* System */\r
-#define    AM_VOL    0x08    /* Volume label */\r
-#define AM_LFN    0x0F    /* LFN entry */\r
-#define AM_DIR    0x10    /* Directory */\r
-#define AM_ARC    0x20    /* Archive */\r
-#define AM_MASK    0x3F    /* Mask of defined bits */\r
+/* File attribute bits for directory entry */
+\r
+#define    AM_RDO    0x01    /* Read only */
+#define    AM_HID    0x02    /* Hidden */
+#define    AM_SYS    0x04    /* System */
+#define    AM_VOL    0x08    /* Volume label */
+#define AM_LFN    0x0F    /* LFN entry */
+#define AM_DIR    0x10    /* Directory */
+#define AM_ARC    0x20    /* Archive */
+#define AM_MASK    0x3F    /* Mask of defined bits */
 \r
 \r
-/* Fast seek function */\r
-#define CREATE_LINKMAP    0xFFFFFFFF\r
+/* Fast seek function */
+#define CREATE_LINKMAP    0xFFFFFFFF
 \r
 \r
 \r
-/*--------------------------------*/\r
-/* Multi-byte word access macros  */\r
+/*--------------------------------*/
+/* Multi-byte word access macros  */
 \r
-#if _WORD_ACCESS == 1    /* Enable word access to the FAT structure */\r
-#define    LD_WORD(ptr)        (WORD)(*(WORD*)(BYTE*)(ptr))\r
-#define    LD_DWORD(ptr)        (DWORD)(*(DWORD*)(BYTE*)(ptr))\r
-#define    ST_WORD(ptr,val)    *(WORD*)(BYTE*)(ptr)=(WORD)(val)\r
-#define    ST_DWORD(ptr,val)    *(DWORD*)(BYTE*)(ptr)=(DWORD)(val)\r
-#else                    /* Use byte-by-byte access to the FAT structure */\r
-#define    LD_WORD(ptr)        (WORD)(((WORD)*((BYTE*)(ptr)+1)<<8)|(WORD)*(BYTE*)(ptr))\r
-#define    LD_DWORD(ptr)        (DWORD)(((DWORD)*((BYTE*)(ptr)+3)<<24)|((DWORD)*((BYTE*)(ptr)+2)<<16)|((WORD)*((BYTE*)(ptr)+1)<<8)|*(BYTE*)(ptr))\r
-#define    ST_WORD(ptr,val)    *(BYTE*)(ptr)=(BYTE)(val); *((BYTE*)(ptr)+1)=(BYTE)((WORD)(val)>>8)\r
-#define    ST_DWORD(ptr,val)    *(BYTE*)(ptr)=(BYTE)(val); *((BYTE*)(ptr)+1)=(BYTE)((WORD)(val)>>8); *((BYTE*)(ptr)+2)=(BYTE)((DWORD)(val)>>16); *((BYTE*)(ptr)+3)=(BYTE)((DWORD)(val)>>24)\r
-#endif\r
+#if _WORD_ACCESS == 1    /* Enable word access to the FAT structure */
+#define    LD_WORD(ptr)        (WORD)(*(WORD*)(BYTE*)(ptr))
+#define    LD_DWORD(ptr)        (DWORD)(*(DWORD*)(BYTE*)(ptr))
+#define    ST_WORD(ptr,val)    *(WORD*)(BYTE*)(ptr)=(WORD)(val)
+#define    ST_DWORD(ptr,val)    *(DWORD*)(BYTE*)(ptr)=(DWORD)(val)
+#else                    /* Use byte-by-byte access to the FAT structure */
+#define    LD_WORD(ptr)        (WORD)(((WORD)*((BYTE*)(ptr)+1)<<8)|(WORD)*(BYTE*)(ptr))
+#define    LD_DWORD(ptr)        (DWORD)(((DWORD)*((BYTE*)(ptr)+3)<<24)|((DWORD)*((BYTE*)(ptr)+2)<<16)|((WORD)*((BYTE*)(ptr)+1)<<8)|*(BYTE*)(ptr))
+#define    ST_WORD(ptr,val)    *(BYTE*)(ptr)=(BYTE)(val); *((BYTE*)(ptr)+1)=(BYTE)((WORD)(val)>>8)
+#define    ST_DWORD(ptr,val)    *(BYTE*)(ptr)=(BYTE)(val); *((BYTE*)(ptr)+1)=(BYTE)((WORD)(val)>>8); *((BYTE*)(ptr)+2)=(BYTE)((DWORD)(val)>>16); *((BYTE*)(ptr)+3)=(BYTE)((DWORD)(val)>>24)
+#endif
 \r
-#ifdef __cplusplus\r
-}\r
-#endif\r
+#ifdef __cplusplus
+}
+#endif
 \r
-#endif /* _FATFS */\r
+#endif /* _FATFS */
index 4042bd4..4daa303 100644 (file)
-/*---------------------------------------------------------------------------/\r
-/  FatFs - FAT file system module configuration file  R0.08b (C)ChaN, 2011\r
-/----------------------------------------------------------------------------/\r
-/\r
-/ CAUTION! Do not forget to make clean the project after any changes to\r
-/ the configuration options.\r
-/\r
-/----------------------------------------------------------------------------*/\r
-#ifndef _FFCONF\r
-#define _FFCONF 8237    /* Revision ID */\r
-\r
-\r
-/*---------------------------------------------------------------------------/\r
-/ Function and Buffer Configurations\r
-/----------------------------------------------------------------------------*/\r
-\r
-#define    _FS_TINY        0    /* 0:Normal or 1:Tiny */\r
-/* When _FS_TINY is set to 1, FatFs uses the sector buffer in the file system\r
-/  object instead of the sector buffer in the individual file object for file\r
-/  data transfer. This reduces memory consumption 512 bytes each file object. */\r
-\r
-\r
-#define _FS_READONLY    0    /* 0:Read/Write or 1:Read only */\r
-/* Setting _FS_READONLY to 1 defines read only configuration. This removes\r
-/  writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename,\r
-/  f_truncate and useless f_getfree. */\r
-\r
-\r
-#define _FS_MINIMIZE    0    /* 0 to 3 */\r
-/* The _FS_MINIMIZE option defines minimization level to remove some functions.\r
-/\r
-/   0: Full function.\r
-/   1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and f_rename\r
-/      are removed.\r
-/   2: f_opendir and f_readdir are removed in addition to 1.\r
-/   3: f_lseek is removed in addition to 2. */\r
-\r
-\r
-#define    _USE_STRFUNC    1    /* 0:Disable or 1/2:Enable */\r
-/* To enable string functions, set _USE_STRFUNC to 1 or 2. */\r
-\r
-\r
-#define    _USE_MKFS        1    /* 0:Disable or 1:Enable */\r
-/* To enable f_mkfs function, set _USE_MKFS to 1 and set _FS_READONLY to 0 */\r
-\r
-\r
-#define    _USE_FORWARD    0    /* 0:Disable or 1:Enable */\r
-/* To enable f_forward function, set _USE_FORWARD to 1 and set _FS_TINY to 1. */\r
-\r
+/*---------------------------------------------------------------------------/
+/  FatFs - FAT file system module configuration file  R0.08b (C)ChaN, 2011
+/----------------------------------------------------------------------------/
+/
+/ CAUTION! Do not forget to make clean the project after any changes to
+/ the configuration options.
+/
+/----------------------------------------------------------------------------*/
+#ifndef _FFCONF
+#define _FFCONF 8237    /* Revision ID */
+\r
+\r
+/*---------------------------------------------------------------------------/
+/ Function and Buffer Configurations
+/----------------------------------------------------------------------------*/
+\r
+#define    _FS_TINY        0    /* 0:Normal or 1:Tiny */
+/* When _FS_TINY is set to 1, FatFs uses the sector buffer in the file system
+/  object instead of the sector buffer in the individual file object for file
+/  data transfer. This reduces memory consumption 512 bytes each file object. */
+\r
+\r
+#define _FS_READONLY    0    /* 0:Read/Write or 1:Read only */
+/* Setting _FS_READONLY to 1 defines read only configuration. This removes
+/  writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename,
+/  f_truncate and useless f_getfree. */
+\r
+\r
+#define _FS_MINIMIZE    0    /* 0 to 3 */
+/* The _FS_MINIMIZE option defines minimization level to remove some functions.
+/
+/   0: Full function.
+/   1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and f_rename
+/      are removed.
+/   2: f_opendir and f_readdir are removed in addition to 1.
+/   3: f_lseek is removed in addition to 2. */
+\r
+\r
+#define    _USE_STRFUNC    1    /* 0:Disable or 1/2:Enable */
+/* To enable string functions, set _USE_STRFUNC to 1 or 2. */
+\r
+\r
+#define    _USE_MKFS        1    /* 0:Disable or 1:Enable */
+/* To enable f_mkfs function, set _USE_MKFS to 1 and set _FS_READONLY to 0 */
+\r
+\r
+#define    _USE_FORWARD    0    /* 0:Disable or 1:Enable */
+/* To enable f_forward function, set _USE_FORWARD to 1 and set _FS_TINY to 1. */
+\r
 \r
-#define    _USE_FASTSEEK    0    /* 0:Disable or 1:Enable */\r
-/* To enable fast seek feature, set _USE_FASTSEEK to 1. */\r
+#define    _USE_FASTSEEK    0    /* 0:Disable or 1:Enable */
+/* To enable fast seek feature, set _USE_FASTSEEK to 1. */
 \r
 \r
 \r
-/*---------------------------------------------------------------------------/\r
-/ Locale and Namespace Configurations\r
-/----------------------------------------------------------------------------*/\r
+/*---------------------------------------------------------------------------/
+/ Locale and Namespace Configurations
+/----------------------------------------------------------------------------*/
 \r
-#define _CODE_PAGE    1252\r
-/* The _CODE_PAGE specifies the OEM code page to be used on the target system.\r
-/  Incorrect setting of the code page can cause a file open failure.\r
-/\r
-/   932  - Japanese Shift-JIS (DBCS, OEM, Windows)\r
-/   936  - Simplified Chinese GBK (DBCS, OEM, Windows)\r
-/   949  - Korean (DBCS, OEM, Windows)\r
-/   950  - Traditional Chinese Big5 (DBCS, OEM, Windows)\r
-/   1250 - Central Europe (Windows)\r
-/   1251 - Cyrillic (Windows)\r
-/   1252 - Latin 1 (Windows)\r
-/   1253 - Greek (Windows)\r
-/   1254 - Turkish (Windows)\r
-/   1255 - Hebrew (Windows)\r
-/   1256 - Arabic (Windows)\r
-/   1257 - Baltic (Windows)\r
-/   1258 - Vietnam (OEM, Windows)\r
-/   437  - U.S. (OEM)\r
-/   720  - Arabic (OEM)\r
-/   737  - Greek (OEM)\r
-/   775  - Baltic (OEM)\r
-/   850  - Multilingual Latin 1 (OEM)\r
-/   858  - Multilingual Latin 1 + Euro (OEM)\r
-/   852  - Latin 2 (OEM)\r
-/   855  - Cyrillic (OEM)\r
-/   866  - Russian (OEM)\r
-/   857  - Turkish (OEM)\r
-/   862  - Hebrew (OEM)\r
-/   874  - Thai (OEM, Windows)\r
-/    1    - ASCII only (Valid for non LFN cfg.)\r
-*/\r
+#define _CODE_PAGE    1252
+/* The _CODE_PAGE specifies the OEM code page to be used on the target system.
+/  Incorrect setting of the code page can cause a file open failure.
+/
+/   932  - Japanese Shift-JIS (DBCS, OEM, Windows)
+/   936  - Simplified Chinese GBK (DBCS, OEM, Windows)
+/   949  - Korean (DBCS, OEM, Windows)
+/   950  - Traditional Chinese Big5 (DBCS, OEM, Windows)
+/   1250 - Central Europe (Windows)
+/   1251 - Cyrillic (Windows)
+/   1252 - Latin 1 (Windows)
+/   1253 - Greek (Windows)
+/   1254 - Turkish (Windows)
+/   1255 - Hebrew (Windows)
+/   1256 - Arabic (Windows)
+/   1257 - Baltic (Windows)
+/   1258 - Vietnam (OEM, Windows)
+/   437  - U.S. (OEM)
+/   720  - Arabic (OEM)
+/   737  - Greek (OEM)
+/   775  - Baltic (OEM)
+/   850  - Multilingual Latin 1 (OEM)
+/   858  - Multilingual Latin 1 + Euro (OEM)
+/   852  - Latin 2 (OEM)
+/   855  - Cyrillic (OEM)
+/   866  - Russian (OEM)
+/   857  - Turkish (OEM)
+/   862  - Hebrew (OEM)
+/   874  - Thai (OEM, Windows)
+/    1    - ASCII only (Valid for non LFN cfg.)
+*/
 \r
 \r
-#define    _USE_LFN    1        /* 0 to 3 */\r
-#define    _MAX_LFN    255        /* Maximum LFN length to handle (12 to 255) */\r
-/* The _USE_LFN option switches the LFN support.\r
-/\r
-/   0: Disable LFN feature. _MAX_LFN and _LFN_UNICODE have no effect.\r
-/   1: Enable LFN with static working buffer on the BSS. Always NOT reentrant.\r
-/   2: Enable LFN with dynamic working buffer on the STACK.\r
-/   3: Enable LFN with dynamic working buffer on the HEAP.\r
-/\r
-/  The LFN working buffer occupies (_MAX_LFN + 1) * 2 bytes. To enable LFN,\r
-/  Unicode handling functions ff_convert() and ff_wtoupper() must be added\r
-/  to the project. When enable to use heap, memory control functions\r
-/  ff_memalloc() and ff_memfree() must be added to the project. */\r
+#define    _USE_LFN    1        /* 0 to 3 */
+#define    _MAX_LFN    255        /* Maximum LFN length to handle (12 to 255) */
+/* The _USE_LFN option switches the LFN support.
+/
+/   0: Disable LFN feature. _MAX_LFN and _LFN_UNICODE have no effect.
+/   1: Enable LFN with static working buffer on the BSS. Always NOT reentrant.
+/   2: Enable LFN with dynamic working buffer on the STACK.
+/   3: Enable LFN with dynamic working buffer on the HEAP.
+/
+/  The LFN working buffer occupies (_MAX_LFN + 1) * 2 bytes. To enable LFN,
+/  Unicode handling functions ff_convert() and ff_wtoupper() must be added
+/  to the project. When enable to use heap, memory control functions
+/  ff_memalloc() and ff_memfree() must be added to the project. */
 \r
 \r
-#define    _LFN_UNICODE    0    /* 0:ANSI/OEM or 1:Unicode */\r
-/* To switch the character code set on FatFs API to Unicode,\r
-/  enable LFN feature and set _LFN_UNICODE to 1. */\r
+#define    _LFN_UNICODE    0    /* 0:ANSI/OEM or 1:Unicode */
+/* To switch the character code set on FatFs API to Unicode,
+/  enable LFN feature and set _LFN_UNICODE to 1. */
 \r
 \r
-#define _FS_RPATH        0    /* 0 to 2 */\r
-/* The _FS_RPATH option configures relative path feature.\r
-/\r
-/   0: Disable relative path feature and remove related functions.\r
-/   1: Enable relative path. f_chdrive() and f_chdir() are available.\r
-/   2: f_getcwd() is available in addition to 1.\r
-/\r
-/  Note that output of the f_readdir fnction is affected by this option. */\r
+#define _FS_RPATH        0    /* 0 to 2 */
+/* The _FS_RPATH option configures relative path feature.
+/
+/   0: Disable relative path feature and remove related functions.
+/   1: Enable relative path. f_chdrive() and f_chdir() are available.
+/   2: f_getcwd() is available in addition to 1.
+/
+/  Note that output of the f_readdir fnction is affected by this option. */
 \r
 \r
 \r
-/*---------------------------------------------------------------------------/\r
-/ Physical Drive Configurations\r
-/----------------------------------------------------------------------------*/\r
+/*---------------------------------------------------------------------------/
+/ Physical Drive Configurations
+/----------------------------------------------------------------------------*/
 \r
-#define _VOLUMES    1\r
-/* Number of volumes (logical drives) to be used. */\r
+#define _VOLUMES    1
+/* Number of volumes (logical drives) to be used. */
 \r
 \r
-#define    _MAX_SS        512        /* 512, 1024, 2048 or 4096 */\r
-/* Maximum sector size to be handled.\r
-/  Always set 512 for memory card and hard disk but a larger value may be\r
-/  required for on-board flash memory, floppy disk and optical disk.\r
-/  When _MAX_SS is larger than 512, it configures FatFs to variable sector size\r
-/  and GET_SECTOR_SIZE command must be implememted to the disk_ioctl function. */\r
+#define    _MAX_SS        512        /* 512, 1024, 2048 or 4096 */
+/* Maximum sector size to be handled.
+/  Always set 512 for memory card and hard disk but a larger value may be
+/  required for on-board flash memory, floppy disk and optical disk.
+/  When _MAX_SS is larger than 512, it configures FatFs to variable sector size
+/  and GET_SECTOR_SIZE command must be implememted to the disk_ioctl function. */
 \r
 \r
-#define    _MULTI_PARTITION    0    /* 0:Single partition or 1:Multiple partition */\r
-/* When set to 0, each volume is bound to the same physical drive number and\r
-/ it can mount only first primaly partition. When it is set to 1, each volume\r
-/ is tied to the partitions listed in VolToPart[]. */\r
+#define    _MULTI_PARTITION    0    /* 0:Single partition or 1:Multiple partition */
+/* When set to 0, each volume is bound to the same physical drive number and
+/ it can mount only first primaly partition. When it is set to 1, each volume
+/ is tied to the partitions listed in VolToPart[]. */
 \r
 \r
-#define    _USE_ERASE    0    /* 0:Disable or 1:Enable */\r
-/* To enable sector erase feature, set _USE_ERASE to 1. CTRL_ERASE_SECTOR command\r
-/  should be added to the disk_ioctl functio. */\r
-\r
-\r
-\r
-/*---------------------------------------------------------------------------/\r
-/ System Configurations\r
-/----------------------------------------------------------------------------*/\r
-\r
-#define _WORD_ACCESS    0    /* 0 or 1 */\r
-/* Set 0 first and it is always compatible with all platforms. The _WORD_ACCESS\r
-/  option defines which access method is used to the word data on the FAT volume.\r
-/\r
-/   0: Byte-by-byte access.\r
-/   1: Word access. Do not choose this unless following condition is met.\r
-/\r
-/  When the byte order on the memory is big-endian or address miss-aligned word\r
-/  access results incorrect behavior, the _WORD_ACCESS must be set to 0.\r
-/  If it is not the case, the value can also be set to 1 to improve the\r
-/  performance and code size. */\r
-\r
-\r
-/* A header file that defines sync object types on the O/S, such as\r
-/  windows.h, ucos_ii.h and semphr.h, must be included prior to ff.h. */\r
-\r
-#define _FS_REENTRANT    0        /* 0:Disable or 1:Enable */\r
-#define _FS_TIMEOUT        1000    /* Timeout period in unit of time ticks */\r
-#define    _SYNC_t            HANDLE    /* O/S dependent type of sync object. e.g. HANDLE, OS_EVENT*, ID and etc.. */\r
+#define    _USE_ERASE    0    /* 0:Disable or 1:Enable */
+/* To enable sector erase feature, set _USE_ERASE to 1. CTRL_ERASE_SECTOR command
+/  should be added to the disk_ioctl functio. */
+\r
+\r
+\r
+/*---------------------------------------------------------------------------/
+/ System Configurations
+/----------------------------------------------------------------------------*/
+\r
+#define _WORD_ACCESS    0    /* 0 or 1 */
+/* Set 0 first and it is always compatible with all platforms. The _WORD_ACCESS
+/  option defines which access method is used to the word data on the FAT volume.
+/
+/   0: Byte-by-byte access.
+/   1: Word access. Do not choose this unless following condition is met.
+/
+/  When the byte order on the memory is big-endian or address miss-aligned word
+/  access results incorrect behavior, the _WORD_ACCESS must be set to 0.
+/  If it is not the case, the value can also be set to 1 to improve the
+/  performance and code size. */
+\r
+\r
+/* A header file that defines sync object types on the O/S, such as
+/  windows.h, ucos_ii.h and semphr.h, must be included prior to ff.h. */
+\r
+#define _FS_REENTRANT    0        /* 0:Disable or 1:Enable */
+#define _FS_TIMEOUT        1000    /* Timeout period in unit of time ticks */
+#define    _SYNC_t            HANDLE    /* O/S dependent type of sync object. e.g. HANDLE, OS_EVENT*, ID and etc.. */
 \r
-/* The _FS_REENTRANT option switches the reentrancy (thread safe) of the FatFs module.\r
-/\r
-/   0: Disable reentrancy. _SYNC_t and _FS_TIMEOUT have no effect.\r
-/   1: Enable reentrancy. Also user provided synchronization handlers,\r
-/      ff_req_grant, ff_rel_grant, ff_del_syncobj and ff_cre_syncobj\r
-/      function must be added to the project. */\r
+/* The _FS_REENTRANT option switches the reentrancy (thread safe) of the FatFs module.
+/
+/   0: Disable reentrancy. _SYNC_t and _FS_TIMEOUT have no effect.
+/   1: Enable reentrancy. Also user provided synchronization handlers,
+/      ff_req_grant, ff_rel_grant, ff_del_syncobj and ff_cre_syncobj
+/      function must be added to the project. */
 \r
 \r
-#define    _FS_SHARE    0    /* 0:Disable or >=1:Enable */\r
-/* To enable file shareing feature, set _FS_SHARE to 1 or greater. The value\r
-   defines how many files can be opened simultaneously. */\r
+#define    _FS_SHARE    0    /* 0:Disable or >=1:Enable */
+/* To enable file shareing feature, set _FS_SHARE to 1 or greater. The value
+   defines how many files can be opened simultaneously. */
 \r
 \r
-#endif /* _FFCONFIG */\r
+#endif /* _FFCONFIG */
index 137b988..2c288f6 100644 (file)
@@ -1,37 +1,37 @@
-/*-------------------------------------------*/\r
-/* Integer type definitions for FatFs module */\r
-/*-------------------------------------------*/\r
+/*-------------------------------------------*/
+/* Integer type definitions for FatFs module */
+/*-------------------------------------------*/
 \r
-#ifndef _INTEGER\r
-#define _INTEGER\r
+#ifndef _INTEGER
+#define _INTEGER
 \r
-#ifdef _WIN32  /* FatFs development platform */\r
+#ifdef _WIN32  /* FatFs development platform */
 \r
-#include <windows.h>\r
-#include <tchar.h>\r
+#include <windows.h>
+#include <tchar.h>
 \r
-#else                  /* Embedded platform */\r
+#else                  /* Embedded platform */
 \r
-/* These types must be 16-bit, 32-bit or larger integer */\r
-typedef int                            INT;\r
-typedef unsigned int   UINT;\r
+/* These types must be 16-bit, 32-bit or larger integer */
+typedef int                            INT;
+typedef unsigned int   UINT;
 \r
-/* These types must be 8-bit integer */\r
-typedef char                   CHAR;\r
-typedef unsigned char  UCHAR;\r
-typedef unsigned char  BYTE;\r
+/* These types must be 8-bit integer */
+typedef char                   CHAR;
+typedef unsigned char  UCHAR;
+typedef unsigned char  BYTE;
 \r
-/* These types must be 16-bit integer */\r
-typedef short                  SHORT;\r
-typedef unsigned short USHORT;\r
-typedef unsigned short WORD;\r
-typedef unsigned short WCHAR;\r
+/* These types must be 16-bit integer */
+typedef short                  SHORT;
+typedef unsigned short USHORT;
+typedef unsigned short WORD;
+typedef unsigned short WCHAR;
 \r
-/* These types must be 32-bit integer */\r
-typedef long                   LONG;\r
-typedef unsigned long  ULONG;\r
-typedef unsigned long  DWORD;\r
+/* These types must be 32-bit integer */
+typedef long                   LONG;
+typedef unsigned long  ULONG;
+typedef unsigned long  DWORD;
 \r
-#endif\r
+#endif
 \r
-#endif\r
+#endif
index eb0ab4e..c1eefe0 100644 (file)
-/*------------------------------------------------------------------------*/\r
-/* Unicode - Local code bidirectional converter  (C)ChaN, 2009            */\r
-/* (SBCS code pages)                                                      */\r
-/*------------------------------------------------------------------------*/\r
-/*  437   U.S. (OEM)\r
-/   720   Arabic (OEM)\r
-/   1256  Arabic (Windows)\r
-/   737   Greek (OEM)\r
-/   1253  Greek (Windows)\r
-/   1250  Central Europe (Windows)\r
-/   775   Baltic (OEM)\r
-/   1257  Baltic (Windows)\r
-/   850   Multilingual Latin 1 (OEM)\r
-/   852   Latin 2 (OEM)\r
-/   1252  Latin 1 (Windows)\r
-/   855   Cyrillic (OEM)\r
-/   1251  Cyrillic (Windows)\r
-/   866   Russian (OEM)\r
-/   857   Turkish (OEM)\r
-/   1254  Turkish (Windows)\r
-/   858   Multilingual Latin 1 + Euro (OEM)\r
-/   862   Hebrew (OEM)\r
-/   1255  Hebrew (Windows)\r
-/   874   Thai (OEM, Windows)\r
-/   1258  Vietnam (OEM, Windows)\r
-*/\r
-\r
-#include "../ff.h"\r
-\r
-\r
-#if _CODE_PAGE == 437\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP437(0x80-0xFF) to Unicode conversion table */\r
-       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,\r
-       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5,\r
-       0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,\r
-       0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192,\r
-       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,\r
-       0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,\r
-       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,\r
-       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,\r
-       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,\r
-       0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4,\r
-       0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229,\r
-       0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248,\r
-       0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 720\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP720(0x80-0xFF) to Unicode conversion table */\r
-       0x0000, 0x0000, 0x00E9, 0x00E2, 0x0000, 0x00E0, 0x0000, 0x00E7,\r
-       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0000, 0x0000, 0x0000,\r
-       0x0000, 0x0651, 0x0652, 0x00F4, 0x00A4, 0x0640, 0x00FB, 0x00F9,\r
-       0x0621, 0x0622, 0x0623, 0x0624, 0x00A3, 0x0625, 0x0626, 0x0627,\r
-       0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F,\r
-       0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x00AB, 0x00BB,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,\r
-       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,\r
-       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,\r
-       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,\r
-       0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x0641, 0x00B5, 0x0642,\r
-       0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A,\r
-       0x2261, 0x064B, 0x064C, 0x064D, 0x064E, 0x064F, 0xO650, 0x2248,\r
-       0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 737\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP737(0x80-0xFF) to Unicode conversion table */\r
-       0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398,\r
-       0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0,\r
-       0x03A1, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9,\r
-       0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8,\r
-       0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0,\r
-       0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,\r
-       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,\r
-       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,\r
-       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,\r
-       0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD,\r
-       0x03CB, 0x03CE, 0x0386, 0x0388, 0x0389, 0x038A, 0x038C, 0x038E,\r
-       0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248,\r
-       0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 775\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP775(0x80-0xFF) to Unicode conversion table */\r
-       0x0106, 0x00FC, 0x00E9, 0x0101, 0x00E4, 0x0123, 0x00E5, 0x0107,\r
-       0x0142, 0x0113, 0x0156, 0x0157, 0x012B, 0x0179, 0x00C4, 0x00C5,\r
-       0x00C9, 0x00E6, 0x00C6, 0x014D, 0x00F6, 0x0122, 0x00A2, 0x015A,\r
-       0x015B, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x00A4,\r
-       0x0100, 0x012A, 0x00F3, 0x017B, 0x017C, 0x017A, 0x201D, 0x00A6,\r
-       0x00A9, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x0141, 0x00AB, 0x00BB,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x0104, 0x010C, 0x0118,\r
-       0x0116, 0x2563, 0x2551, 0x2557, 0x255D, 0x012E, 0x0160, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0172, 0x016A,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x017D,\r
-       0x0105, 0x010D, 0x0119, 0x0117, 0x012F, 0x0161, 0x0173, 0x016B,\r
-       0x017E, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,\r
-       0x00D3, 0x00DF, 0x014C, 0x0143, 0x00F5, 0x00D5, 0x00B5, 0x0144,\r
-       0x0136, 0x0137, 0x013B, 0x013C, 0x0146, 0x0112, 0x0145, 0x2019,\r
-       0x00AD, 0x00B1, 0x201C, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x201E,\r
-       0x00B0, 0x2219, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 850\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP850(0x80-0xFF) to Unicode conversion table */\r
-       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,\r
-       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5,\r
-       0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,\r
-       0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192,\r
-       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,\r
-       0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x00C0,\r
-       0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,\r
-       0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE,\r
-       0x00CF, 0x2518, 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580,\r
-       0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE,\r
-       0x00DE, 0x00DA, 0x00DB, 0x00D9, 0x00FD, 0x00DD, 0x00AF, 0x00B4,\r
-       0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8,\r
-       0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 852\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP852(0x80-0xFF) to Unicode conversion table */\r
-       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7,\r
-       0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106,\r
-       0x00C9, 0x0139, 0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A,\r
-       0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D,\r
-       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x0104, 0x0105, 0x017D, 0x017E,\r
-       0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x011A,\r
-       0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,\r
-       0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE,\r
-       0x011B, 0x2518, 0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580,\r
-       0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161,\r
-       0x0154, 0x00DA, 0x0155, 0x0170, 0x00FD, 0x00DD, 0x0163, 0x00B4,\r
-       0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8,\r
-       0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 855\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP855(0x80-0xFF) to Unicode conversion table */\r
-       0x0452, 0x0402, 0x0453, 0x0403, 0x0451, 0x0401, 0x0454, 0x0404,\r
-       0x0455, 0x0405, 0x0456, 0x0406, 0x0457, 0x0407, 0x0458, 0x0408,\r
-       0x0459, 0x0409, 0x045A, 0x040A, 0x045B, 0x040B, 0x045C, 0x040C,\r
-       0x045E, 0x040E, 0x045F, 0x040F, 0x044E, 0x042E, 0x044A, 0x042A,\r
-       0x0430, 0x0410, 0x0431, 0x0411, 0x0446, 0x0426, 0x0434, 0x0414,\r
-       0x0435, 0x0415, 0x0444, 0x0424, 0x0433, 0x0413, 0x00AB, 0x00BB,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x0445, 0x0425, 0x0438,\r
-       0x0418, 0x2563, 0x2551, 0x2557, 0x255D, 0x0439, 0x0419, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x043A, 0x041A,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,\r
-       0x043B, 0x041B, 0x043C, 0x041C, 0x043D, 0x041D, 0x043E, 0x041E,\r
-       0x043F, 0x2518, 0x250C, 0x2588, 0x2584, 0x041F, 0x044F, 0x2580,\r
-       0x042F, 0x0440, 0x0420, 0x0441, 0x0421, 0x0442, 0x0422, 0x0443,\r
-       0x0423, 0x0436, 0x0416, 0x0432, 0x0412, 0x044C, 0x042C, 0x2116,\r
-       0x00AD, 0x044B, 0x042B, 0x0437, 0x0417, 0x0448, 0x0428, 0x044D,\r
-       0x042D, 0x0449, 0x0429, 0x0447, 0x0427, 0x00A7, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 857\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP857(0x80-0xFF) to Unicode conversion table */\r
-       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,\r
-       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5,\r
-       0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,\r
-       0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F,\r
-       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x011E, 0x011F,\r
-       0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x00C0,\r
-       0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,\r
-       0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0x0000, 0x00CD, 0x00CE,\r
-       0x00CF, 0x2518, 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580,\r
-       0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x0000,\r
-       0x00D7, 0x00DA, 0x00DB, 0x00D9, 0x00EC, 0x00FF, 0x00AF, 0x00B4,\r
-       0x00AD, 0x00B1, 0x0000, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8,\r
-       0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 858\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP858(0x80-0xFF) to Unicode conversion table */\r
-       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,\r
-       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5,\r
-       0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,\r
-       0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192,\r
-       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,\r
-       0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x00C0,\r
-       0x00A9, 0x2563, 0x2551, 0x2557, 0x2550, 0x00A2, 0x00A5, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,\r
-       0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x20AC, 0x00CD, 0x00CE,\r
-       0x00CF, 0x2518, 0x250C, 0x2588, 0x2584, 0x00C6, 0x00CC, 0x2580,\r
-       0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE,\r
-       0x00DE, 0x00DA, 0x00DB, 0x00D9, 0x00FD, 0x00DD, 0x00AF, 0x00B4,\r
-       0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8,\r
-       0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 862\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP862(0x80-0xFF) to Unicode conversion table */\r
-       0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7,\r
-       0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF,\r
-       0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7,\r
-       0x05E8, 0x05E9, 0x05EA, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192,\r
-       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,\r
-       0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,\r
-       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,\r
-       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,\r
-       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,\r
-       0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4,\r
-       0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229,\r
-       0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248,\r
-       0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 866\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP866(0x80-0xFF) to Unicode conversion table */\r
-       0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,\r
-       0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F,\r
-       0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,\r
-       0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F,\r
-       0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,\r
-       0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F,\r
-       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,\r
-       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,\r
-       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,\r
-       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,\r
-       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,\r
-       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,\r
-       0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,\r
-       0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F,\r
-       0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E,\r
-       0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4, 0x25A0, 0x00A0\r
-};\r
-\r
-#elif _CODE_PAGE == 874\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP874(0x80-0xFF) to Unicode conversion table */\r
-       0x20AC, 0x0000, 0x0000, 0x0000, 0x0000, 0x2026, 0x0000, 0x0000,\r
-       0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,\r
-       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,\r
-       0x00A0, 0x0E01, 0x0E02, 0x0E03, 0x0E04, 0x0E05, 0x0E06, 0x0E07,\r
-       0x0E08, 0x0E09, 0x0E0A, 0x0E0B, 0x0E0C, 0x0E0D, 0x0E0E, 0x0E0F,\r
-       0x0E10, 0x0E11, 0x0E12, 0x0E13, 0x0E14, 0x0E15, 0x0E16, 0x0E17,\r
-       0x0E18, 0x0E19, 0x0E1A, 0x0E1B, 0x0E1C, 0x0E1D, 0x0E1E, 0x0E1F,\r
-       0x0E20, 0x0E21, 0x0E22, 0x0E23, 0x0E24, 0x0E25, 0x0E26, 0x0E27,\r
-       0x0E28, 0x0E29, 0x0E2A, 0x0E2B, 0x0E2C, 0x0E2D, 0x0E2E, 0x0E2F,\r
-       0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37,\r
-       0x0E38, 0x0E39, 0x0E3A, 0x0000, 0x0000, 0x0000, 0x0000, 0x0E3F,\r
-       0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45, 0x0E46, 0x0E47,\r
-       0x0E48, 0x0E49, 0x0E4A, 0x0E4B, 0x0E4C, 0x0E4D, 0x0E4E, 0x0E4F,\r
-       0x0E50, 0x0E51, 0x0E52, 0x0E53, 0x0E54, 0x0E55, 0x0E56, 0x0E57,\r
-       0x0E58, 0x0E59, 0x0E5A, 0x0E5B, 0x0000, 0x0000, 0x0000, 0x0000\r
-};\r
-\r
-#elif _CODE_PAGE == 1250\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP1250(0x80-0xFF) to Unicode conversion table */\r
-       0x20AC, 0x0000, 0x201A, 0x0000, 0x201E, 0x2026, 0x2020, 0x2021,\r
-       0x0000, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179,\r
-       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x0000, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A,\r
-       0x00A0, 0x02C7, 0x02D8, 0x0141, 0x00A4, 0x0104, 0x00A6, 0x00A7,\r
-       0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B,\r
-       0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, 0x00B6, 0x00B7,\r
-       0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C,\r
-       0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7,\r
-       0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E,\r
-       0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7,\r
-       0x0158, 0x016E, 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF,\r
-       0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7,\r
-       0x010D, 0x00E9, 0x0119, 0x00EB, 0x011B, 0x00ED, 0x00EE, 0x010F,\r
-       0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7,\r
-       0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, 0x0163, 0x02D9\r
-};\r
-\r
-#elif _CODE_PAGE == 1251\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP1251(0x80-0xFF) to Unicode conversion table */\r
-       0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021,\r
-       0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F,\r
-       0x0452, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x0000, 0x2111, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F,\r
-       0x00A0, 0x040E, 0x045E, 0x0408, 0x00A4, 0x0490, 0x00A6, 0x00A7,\r
-       0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407,\r
-       0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, 0x00B6, 0x00B7,\r
-       0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457,\r
-       0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,\r
-       0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F,\r
-       0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,\r
-       0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F,\r
-       0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,\r
-       0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F,\r
-       0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,\r
-       0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F\r
-};\r
-\r
-#elif _CODE_PAGE == 1252\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP1252(0x80-0xFF) to Unicode conversion table */\r
-       0x20AC, 0x0000, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,\r
-       0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x0000, 0x017D, 0x0000,\r
-       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x0000, 0x017E, 0x0178,\r
-       0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,\r
-       0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,\r
-       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,\r
-       0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF,\r
-       0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7,\r
-       0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF,\r
-       0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7,\r
-       0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF,\r
-       0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7,\r
-       0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF,\r
-       0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7,\r
-       0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF\r
-};\r
-\r
-#elif _CODE_PAGE == 1253\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP1253(0x80-0xFF) to Unicode conversion table */\r
-       0x20AC, 0x0000, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,\r
-       0x0000, 0x2030, 0x0000, 0x2039, 0x000C, 0x0000, 0x0000, 0x0000,\r
-       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x0000, 0x2122, 0x0000, 0x203A, 0x0000, 0x0000, 0x0000, 0x0000,\r
-       0x00A0, 0x0385, 0x0386, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,\r
-       0x00A8, 0x00A9, 0x0000, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x2015,\r
-       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x00B5, 0x00B6, 0x00B7,\r
-       0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F,\r
-       0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,\r
-       0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F,\r
-       0x03A0, 0x03A1, 0x0000, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7,\r
-       0x03A8, 0x03A9, 0x03AA, 0x03AD, 0x03AC, 0x03AD, 0x03AE, 0x03AF,\r
-       0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7,\r
-       0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF,\r
-       0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7,\r
-       0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD, 0x03CE, 0x0000\r
-};\r
-\r
-#elif _CODE_PAGE == 1254\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP1254(0x80-0xFF) to Unicode conversion table */\r
-       0x20AC, 0x0000, 0x210A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,\r
-       0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x0000, 0x0000, 0x0000,\r
-       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x0000, 0x0000, 0x0178,\r
-       0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,\r
-       0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,\r
-       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,\r
-       0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF,\r
-       0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7,\r
-       0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF,\r
-       0x011E, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7,\r
-       0x00D8, 0x00D9, 0x00DA, 0x00BD, 0x00DC, 0x0130, 0x015E, 0x00DF,\r
-       0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7,\r
-       0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF,\r
-       0x011F, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7,\r
-       0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0131, 0x015F, 0x00FF\r
-};\r
-\r
-#elif _CODE_PAGE == 1255\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP1255(0x80-0xFF) to Unicode conversion table */\r
-       0x20AC, 0x0000, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,\r
-       0x02C6, 0x2030, 0x0000, 0x2039, 0x0000, 0x0000, 0x0000, 0x0000,\r
-       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x02DC, 0x2122, 0x0000, 0x203A, 0x0000, 0x0000, 0x0000, 0x0000,\r
-       0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,\r
-       0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,\r
-       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,\r
-       0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF,\r
-       0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7,\r
-       0x05B8, 0x05B9, 0x0000, 0x05BB, 0x05BC, 0x05BD, 0x05BE, 0x05BF,\r
-       0x05C0, 0x05C1, 0x05C2, 0x05C3, 0x05F0, 0x05F1, 0x05F2, 0x05F3,\r
-       0x05F4, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,\r
-       0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7,\r
-       0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF,\r
-       0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7,\r
-       0x05E8, 0x05E9, 0x05EA, 0x0000, 0x0000, 0x200E, 0x200F, 0x0000\r
-};\r
-\r
-#elif _CODE_PAGE == 1256\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP1256(0x80-0xFF) to Unicode conversion table */\r
-       0x20AC, 0x067E, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,\r
-       0x02C6, 0x2030, 0x0679, 0x2039, 0x0152, 0x0686, 0x0698, 0x0688,\r
-       0x06AF, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x06A9, 0x2122, 0x0691, 0x203A, 0x0153, 0x200C, 0x200D, 0x06BA,\r
-       0x00A0, 0x060C, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,\r
-       0x00A8, 0x00A9, 0x06BE, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,\r
-       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,\r
-       0x00B8, 0x00B9, 0x061B, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x061F,\r
-       0x06C1, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627,\r
-       0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F,\r
-       0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x00D7,\r
-       0x0637, 0x0638, 0x0639, 0x063A, 0x0640, 0x0640, 0x0642, 0x0643,\r
-       0x00E0, 0x0644, 0x00E2, 0x0645, 0x0646, 0x0647, 0x0648, 0x00E7,\r
-       0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x0649, 0x064A, 0x00EE, 0x00EF,\r
-       0x064B, 0x064C, 0x064D, 0x064E, 0x00F4, 0x064F, 0x0650, 0x00F7,\r
-       0x0651, 0x00F9, 0x0652, 0x00FB, 0x00FC, 0x200E, 0x200F, 0x06D2\r
-}\r
-\r
-#elif _CODE_PAGE == 1257\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP1257(0x80-0xFF) to Unicode conversion table */\r
-       0x20AC, 0x0000, 0x201A, 0x0000, 0x201E, 0x2026, 0x2020, 0x2021,\r
-       0x0000, 0x2030, 0x0000, 0x2039, 0x0000, 0x00A8, 0x02C7, 0x00B8,\r
-       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x0000, 0x2122, 0x0000, 0x203A, 0x0000, 0x00AF, 0x02DB, 0x0000,\r
-       0x00A0, 0x0000, 0x00A2, 0x00A3, 0x00A4, 0x0000, 0x00A6, 0x00A7,\r
-       0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,\r
-       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,\r
-       0x00B8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6,\r
-       0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112,\r
-       0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B,\r
-       0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7,\r
-       0x0172, 0x0141, 0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF,\r
-       0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113,\r
-       0x010D, 0x00E9, 0x017A, 0x0117, 0x0123, 0x0137, 0x012B, 0x013C,\r
-       0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7,\r
-       0x0173, 0x014E, 0x015B, 0x016B, 0x00FC, 0x017C, 0x017E, 0x02D9\r
-};\r
-\r
-#elif _CODE_PAGE == 1258\r
-#define _TBLDEF 1\r
-static\r
-const WCHAR Tbl[] = {  /*  CP1258(0x80-0xFF) to Unicode conversion table */\r
-       0x20AC, 0x0000, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,\r
-       0x02C6, 0x2030, 0x0000, 0x2039, 0x0152, 0x0000, 0x0000, 0x0000,\r
-       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,\r
-       0x02DC, 0x2122, 0x0000, 0x203A, 0x0153, 0x0000, 0x0000, 0x0178,\r
-       0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,\r
-       0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,\r
-       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,\r
-       0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF,\r
-       0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x00C5, 0x00C6, 0x00C7,\r
-       0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0300, 0x00CD, 0x00CE, 0x00CF,\r
-       0x0110, 0x00D1, 0x0309, 0x00D3, 0x00D4, 0x01A0, 0x00D6, 0x00D7,\r
-       0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x01AF, 0x0303, 0x00DF,\r
-       0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x00E5, 0x00E6, 0x00E7,\r
-       0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x0301, 0x00ED, 0x00EE, 0x00EF,\r
-       0x0111, 0x00F1, 0x0323, 0x00F3, 0x00F4, 0x01A1, 0x00F6, 0x00F7,\r
-       0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x01B0, 0x20AB, 0x00FF\r
-};\r
-\r
-#endif\r
-\r
-\r
-#if !_TBLDEF || !_USE_LFN\r
-#error This file is not needed in current configuration. Remove from the project.\r
-#endif\r
-\r
-\r
-WCHAR ff_convert (     /* Converted character, Returns zero on error */\r
-       WCHAR   src,    /* Character code to be converted */\r
-       UINT    dir             /* 0: Unicode to OEMCP, 1: OEMCP to Unicode */\r
-)\r
-{\r
-       WCHAR c;\r
-\r
-\r
-       if (src < 0x80) {       /* ASCII */\r
-               c = src;\r
-\r
-       } else {\r
-               if (dir) {              /* OEMCP to Unicode */\r
-                       c = (src >= 0x100) ? 0 : Tbl[src - 0x80];\r
-\r
-               } else {                /* Unicode to OEMCP */\r
-                       for (c = 0; c < 0x80; c++) {\r
-                               if (src == Tbl[c]) break;\r
-                       }\r
-                       c = (c + 0x80) & 0xFF;\r
-               }\r
-       }\r
-\r
-       return c;\r
-}\r
-\r
-\r
-WCHAR ff_wtoupper (    /* Upper converted character */\r
-       WCHAR chr               /* Input character */\r
-)\r
-{\r
-       static const WCHAR tbl_lower[] = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0xA1, 0x00A2, 0x00A3, 0x00A5, 0x00AC, 0x00AF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0x0FF, 0x101, 0x103, 0x105, 0x107, 0x109, 0x10B, 0x10D, 0x10F, 0x111, 0x113, 0x115, 0x117, 0x119, 0x11B, 0x11D, 0x11F, 0x121, 0x123, 0x125, 0x127, 0x129, 0x12B, 0x12D, 0x12F, 0x131, 0x133, 0x135, 0x137, 0x13A, 0x13C, 0x13E, 0x140, 0x142, 0x144, 0x146, 0x148, 0x14B, 0x14D, 0x14F, 0x151, 0x153, 0x155, 0x157, 0x159, 0x15B, 0x15D, 0x15F, 0x161, 0x163, 0x165, 0x167, 0x169, 0x16B, 0x16D, 0x16F, 0x171, 0x173, 0x175, 0x177, 0x17A, 0x17C, 0x17E, 0x192, 0x3B1, 0x3B2, 0x3B3, 0x3B4, 0x3B5, 0x3B6, 0x3B7, 0x3B8, 0x3B9, 0x3BA, 0x3BB, 0x3BC, 0x3BD, 0x3BE, 0x3BF, 0x3C0, 0x3C1, 0x3C3, 0x3C4, 0x3C5, 0x3C6, 0x3C7, 0x3C8, 0x3C9, 0x3CA, 0x430, 0x431, 0x432, 0x433, 0x434, 0x435, 0x436, 0x437, 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43E, 0x43F, 0x440, 0x441, 0x442, 0x443, 0x444, 0x445, 0x446, 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F, 0x451, 0x452, 0x453, 0x454, 0x455, 0x456, 0x457, 0x458, 0x459, 0x45A, 0x45B, 0x45C, 0x45E, 0x45F, 0x2170, 0x2171, 0x2172, 0x2173, 0x2174, 0x2175, 0x2176, 0x2177, 0x2178, 0x2179, 0x217A, 0x217B, 0x217C, 0x217D, 0x217E, 0x217F, 0xFF41, 0xFF42, 0xFF43, 0xFF44, 0xFF45, 0xFF46, 0xFF47, 0xFF48, 0xFF49, 0xFF4A, 0xFF4B, 0xFF4C, 0xFF4D, 0xFF4E, 0xFF4F, 0xFF50, 0xFF51, 0xFF52, 0xFF53, 0xFF54, 0xFF55, 0xFF56, 0xFF57, 0xFF58, 0xFF59, 0xFF5A, 0 };\r
-       static const WCHAR tbl_upper[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x21, 0xFFE0, 0xFFE1, 0xFFE5, 0xFFE2, 0xFFE3, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0x178, 0x100, 0x102, 0x104, 0x106, 0x108, 0x10A, 0x10C, 0x10E, 0x110, 0x112, 0x114, 0x116, 0x118, 0x11A, 0x11C, 0x11E, 0x120, 0x122, 0x124, 0x126, 0x128, 0x12A, 0x12C, 0x12E, 0x130, 0x132, 0x134, 0x136, 0x139, 0x13B, 0x13D, 0x13F, 0x141, 0x143, 0x145, 0x147, 0x14A, 0x14C, 0x14E, 0x150, 0x152, 0x154, 0x156, 0x158, 0x15A, 0x15C, 0x15E, 0x160, 0x162, 0x164, 0x166, 0x168, 0x16A, 0x16C, 0x16E, 0x170, 0x172, 0x174, 0x176, 0x179, 0x17B, 0x17D, 0x191, 0x391, 0x392, 0x393, 0x394, 0x395, 0x396, 0x397, 0x398, 0x399, 0x39A, 0x39B, 0x39C, 0x39D, 0x39E, 0x39F, 0x3A0, 0x3A1, 0x3A3, 0x3A4, 0x3A5, 0x3A6, 0x3A7, 0x3A8, 0x3A9, 0x3AA, 0x410, 0x411, 0x412, 0x413, 0x414, 0x415, 0x416, 0x417, 0x418, 0x419, 0x41A, 0x41B, 0x41C, 0x41D, 0x41E, 0x41F, 0x420, 0x421, 0x422, 0x423, 0x424, 0x425, 0x426, 0x427, 0x428, 0x429, 0x42A, 0x42B, 0x42C, 0x42D, 0x42E, 0x42F, 0x401, 0x402, 0x403, 0x404, 0x405, 0x406, 0x407, 0x408, 0x409, 0x40A, 0x40B, 0x40C, 0x40E, 0x40F, 0x2160, 0x2161, 0x2162, 0x2163, 0x2164, 0x2165, 0x2166, 0x2167, 0x2168, 0x2169, 0x216A, 0x216B, 0x216C, 0x216D, 0x216E, 0x216F, 0xFF21, 0xFF22, 0xFF23, 0xFF24, 0xFF25, 0xFF26, 0xFF27, 0xFF28, 0xFF29, 0xFF2A, 0xFF2B, 0xFF2C, 0xFF2D, 0xFF2E, 0xFF2F, 0xFF30, 0xFF31, 0xFF32, 0xFF33, 0xFF34, 0xFF35, 0xFF36, 0xFF37, 0xFF38, 0xFF39, 0xFF3A, 0 };\r
-       int i;\r
-\r
-\r
-       for (i = 0; tbl_lower[i] && chr != tbl_lower[i]; i++) ;\r
-\r
-       return tbl_lower[i] ? tbl_upper[i] : chr;\r
-}\r
+/*------------------------------------------------------------------------*/
+/* Unicode - Local code bidirectional converter  (C)ChaN, 2009            */
+/* (SBCS code pages)                                                      */
+/*------------------------------------------------------------------------*/
+/*  437   U.S. (OEM)
+/   720   Arabic (OEM)
+/   1256  Arabic (Windows)
+/   737   Greek (OEM)
+/   1253  Greek (Windows)
+/   1250  Central Europe (Windows)
+/   775   Baltic (OEM)
+/   1257  Baltic (Windows)
+/   850   Multilingual Latin 1 (OEM)
+/   852   Latin 2 (OEM)
+/   1252  Latin 1 (Windows)
+/   855   Cyrillic (OEM)
+/   1251  Cyrillic (Windows)
+/   866   Russian (OEM)
+/   857   Turkish (OEM)
+/   1254  Turkish (Windows)
+/   858   Multilingual Latin 1 + Euro (OEM)
+/   862   Hebrew (OEM)
+/   1255  Hebrew (Windows)
+/   874   Thai (OEM, Windows)
+/   1258  Vietnam (OEM, Windows)
+*/
+\r
+#include "../ff.h"
+\r
+\r
+#if _CODE_PAGE == 437
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP437(0x80-0xFF) to Unicode conversion table */
+       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,
+       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5,
+       0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,
+       0x00FF, 0x00D6, 0x00DC, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192,
+       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,
+       0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,
+       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,
+       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,
+       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,
+       0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4,
+       0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229,
+       0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248,
+       0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 720
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP720(0x80-0xFF) to Unicode conversion table */
+       0x0000, 0x0000, 0x00E9, 0x00E2, 0x0000, 0x00E0, 0x0000, 0x00E7,
+       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0000, 0x0000, 0x0000,
+       0x0000, 0x0651, 0x0652, 0x00F4, 0x00A4, 0x0640, 0x00FB, 0x00F9,
+       0x0621, 0x0622, 0x0623, 0x0624, 0x00A3, 0x0625, 0x0626, 0x0627,
+       0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F,
+       0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x00AB, 0x00BB,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,
+       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,
+       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,
+       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,
+       0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x0641, 0x00B5, 0x0642,
+       0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A,
+       0x2261, 0x064B, 0x064C, 0x064D, 0x064E, 0x064F, 0xO650, 0x2248,
+       0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 737
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP737(0x80-0xFF) to Unicode conversion table */
+       0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397, 0x0398,
+       0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F, 0x03A0,
+       0x03A1, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7, 0x03A8, 0x03A9,
+       0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8,
+       0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF, 0x03C0,
+       0x03C1, 0x03C3, 0x03C2, 0x03C4, 0x03C5, 0x03C6, 0x03C7, 0x03C8,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,
+       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,
+       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,
+       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,
+       0x03C9, 0x03AC, 0x03AD, 0x03AE, 0x03CA, 0x03AF, 0x03CC, 0x03CD,
+       0x03CB, 0x03CE, 0x0386, 0x0388, 0x0389, 0x038A, 0x038C, 0x038E,
+       0x038F, 0x00B1, 0x2265, 0x2264, 0x03AA, 0x03AB, 0x00F7, 0x2248,
+       0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 775
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP775(0x80-0xFF) to Unicode conversion table */
+       0x0106, 0x00FC, 0x00E9, 0x0101, 0x00E4, 0x0123, 0x00E5, 0x0107,
+       0x0142, 0x0113, 0x0156, 0x0157, 0x012B, 0x0179, 0x00C4, 0x00C5,
+       0x00C9, 0x00E6, 0x00C6, 0x014D, 0x00F6, 0x0122, 0x00A2, 0x015A,
+       0x015B, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x00A4,
+       0x0100, 0x012A, 0x00F3, 0x017B, 0x017C, 0x017A, 0x201D, 0x00A6,
+       0x00A9, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x0141, 0x00AB, 0x00BB,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x0104, 0x010C, 0x0118,
+       0x0116, 0x2563, 0x2551, 0x2557, 0x255D, 0x012E, 0x0160, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0172, 0x016A,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x017D,
+       0x0105, 0x010D, 0x0119, 0x0117, 0x012F, 0x0161, 0x0173, 0x016B,
+       0x017E, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,
+       0x00D3, 0x00DF, 0x014C, 0x0143, 0x00F5, 0x00D5, 0x00B5, 0x0144,
+       0x0136, 0x0137, 0x013B, 0x013C, 0x0146, 0x0112, 0x0145, 0x2019,
+       0x00AD, 0x00B1, 0x201C, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x201E,
+       0x00B0, 0x2219, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 850
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP850(0x80-0xFF) to Unicode conversion table */
+       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,
+       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5,
+       0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,
+       0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192,
+       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,
+       0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x00C0,
+       0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,
+       0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x0131, 0x00CD, 0x00CE,
+       0x00CF, 0x2518, 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580,
+       0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE,
+       0x00DE, 0x00DA, 0x00DB, 0x00D9, 0x00FD, 0x00DD, 0x00AF, 0x00B4,
+       0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8,
+       0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 852
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP852(0x80-0xFF) to Unicode conversion table */
+       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x016F, 0x0107, 0x00E7,
+       0x0142, 0x00EB, 0x0150, 0x0151, 0x00EE, 0x0179, 0x00C4, 0x0106,
+       0x00C9, 0x0139, 0x013A, 0x00F4, 0x00F6, 0x013D, 0x013E, 0x015A,
+       0x015B, 0x00D6, 0x00DC, 0x0164, 0x0165, 0x0141, 0x00D7, 0x010D,
+       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x0104, 0x0105, 0x017D, 0x017E,
+       0x0118, 0x0119, 0x00AC, 0x017A, 0x010C, 0x015F, 0x00AB, 0x00BB,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x011A,
+       0x015E, 0x2563, 0x2551, 0x2557, 0x255D, 0x017B, 0x017C, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x0102, 0x0103,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,
+       0x0111, 0x0110, 0x010E, 0x00CB, 0x010F, 0x0147, 0x00CD, 0x00CE,
+       0x011B, 0x2518, 0x250C, 0x2588, 0x2584, 0x0162, 0x016E, 0x2580,
+       0x00D3, 0x00DF, 0x00D4, 0x0143, 0x0144, 0x0148, 0x0160, 0x0161,
+       0x0154, 0x00DA, 0x0155, 0x0170, 0x00FD, 0x00DD, 0x0163, 0x00B4,
+       0x00AD, 0x02DD, 0x02DB, 0x02C7, 0x02D8, 0x00A7, 0x00F7, 0x00B8,
+       0x00B0, 0x00A8, 0x02D9, 0x0171, 0x0158, 0x0159, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 855
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP855(0x80-0xFF) to Unicode conversion table */
+       0x0452, 0x0402, 0x0453, 0x0403, 0x0451, 0x0401, 0x0454, 0x0404,
+       0x0455, 0x0405, 0x0456, 0x0406, 0x0457, 0x0407, 0x0458, 0x0408,
+       0x0459, 0x0409, 0x045A, 0x040A, 0x045B, 0x040B, 0x045C, 0x040C,
+       0x045E, 0x040E, 0x045F, 0x040F, 0x044E, 0x042E, 0x044A, 0x042A,
+       0x0430, 0x0410, 0x0431, 0x0411, 0x0446, 0x0426, 0x0434, 0x0414,
+       0x0435, 0x0415, 0x0444, 0x0424, 0x0433, 0x0413, 0x00AB, 0x00BB,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x0445, 0x0425, 0x0438,
+       0x0418, 0x2563, 0x2551, 0x2557, 0x255D, 0x0439, 0x0419, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x043A, 0x041A,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,
+       0x043B, 0x041B, 0x043C, 0x041C, 0x043D, 0x041D, 0x043E, 0x041E,
+       0x043F, 0x2518, 0x250C, 0x2588, 0x2584, 0x041F, 0x044F, 0x2580,
+       0x042F, 0x0440, 0x0420, 0x0441, 0x0421, 0x0442, 0x0422, 0x0443,
+       0x0423, 0x0436, 0x0416, 0x0432, 0x0412, 0x044C, 0x042C, 0x2116,
+       0x00AD, 0x044B, 0x042B, 0x0437, 0x0417, 0x0448, 0x0428, 0x044D,
+       0x042D, 0x0449, 0x0429, 0x0447, 0x0427, 0x00A7, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 857
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP857(0x80-0xFF) to Unicode conversion table */
+       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,
+       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x0131, 0x00C4, 0x00C5,
+       0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,
+       0x0130, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x015E, 0x015F,
+       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x011E, 0x011F,
+       0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x00C0,
+       0x00A9, 0x2563, 0x2551, 0x2557, 0x255D, 0x00A2, 0x00A5, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,
+       0x00BA, 0x00AA, 0x00CA, 0x00CB, 0x00C8, 0x0000, 0x00CD, 0x00CE,
+       0x00CF, 0x2518, 0x250C, 0x2588, 0x2584, 0x00A6, 0x00CC, 0x2580,
+       0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x0000,
+       0x00D7, 0x00DA, 0x00DB, 0x00D9, 0x00EC, 0x00FF, 0x00AF, 0x00B4,
+       0x00AD, 0x00B1, 0x0000, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8,
+       0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 858
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP858(0x80-0xFF) to Unicode conversion table */
+       0x00C7, 0x00FC, 0x00E9, 0x00E2, 0x00E4, 0x00E0, 0x00E5, 0x00E7,
+       0x00EA, 0x00EB, 0x00E8, 0x00EF, 0x00EE, 0x00EC, 0x00C4, 0x00C5,
+       0x00C9, 0x00E6, 0x00C6, 0x00F4, 0x00F6, 0x00F2, 0x00FB, 0x00F9,
+       0x00FF, 0x00D6, 0x00DC, 0x00F8, 0x00A3, 0x00D8, 0x00D7, 0x0192,
+       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,
+       0x00BF, 0x00AE, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x00C1, 0x00C2, 0x00C0,
+       0x00A9, 0x2563, 0x2551, 0x2557, 0x2550, 0x00A2, 0x00A5, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x00E3, 0x00C3,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x00A4,
+       0x00F0, 0x00D0, 0x00CA, 0x00CB, 0x00C8, 0x20AC, 0x00CD, 0x00CE,
+       0x00CF, 0x2518, 0x250C, 0x2588, 0x2584, 0x00C6, 0x00CC, 0x2580,
+       0x00D3, 0x00DF, 0x00D4, 0x00D2, 0x00F5, 0x00D5, 0x00B5, 0x00FE,
+       0x00DE, 0x00DA, 0x00DB, 0x00D9, 0x00FD, 0x00DD, 0x00AF, 0x00B4,
+       0x00AD, 0x00B1, 0x2017, 0x00BE, 0x00B6, 0x00A7, 0x00F7, 0x00B8,
+       0x00B0, 0x00A8, 0x00B7, 0x00B9, 0x00B3, 0x00B2, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 862
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP862(0x80-0xFF) to Unicode conversion table */
+       0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7,
+       0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF,
+       0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7,
+       0x05E8, 0x05E9, 0x05EA, 0x00A2, 0x00A3, 0x00A5, 0x20A7, 0x0192,
+       0x00E1, 0x00ED, 0x00F3, 0x00FA, 0x00F1, 0x00D1, 0x00AA, 0x00BA,
+       0x00BF, 0x2310, 0x00AC, 0x00BD, 0x00BC, 0x00A1, 0x00AB, 0x00BB,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,
+       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,
+       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,
+       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,
+       0x03B1, 0x00DF, 0x0393, 0x03C0, 0x03A3, 0x03C3, 0x00B5, 0x03C4,
+       0x03A6, 0x0398, 0x03A9, 0x03B4, 0x221E, 0x03C6, 0x03B5, 0x2229,
+       0x2261, 0x00B1, 0x2265, 0x2264, 0x2320, 0x2321, 0x00F7, 0x2248,
+       0x00B0, 0x2219, 0x00B7, 0x221A, 0x207F, 0x00B2, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 866
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP866(0x80-0xFF) to Unicode conversion table */
+       0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
+       0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F,
+       0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,
+       0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F,
+       0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,
+       0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F,
+       0x2591, 0x2592, 0x2593, 0x2502, 0x2524, 0x2561, 0x2562, 0x2556,
+       0x2555, 0x2563, 0x2551, 0x2557, 0x255D, 0x255C, 0x255B, 0x2510,
+       0x2514, 0x2534, 0x252C, 0x251C, 0x2500, 0x253C, 0x255E, 0x255F,
+       0x255A, 0x2554, 0x2569, 0x2566, 0x2560, 0x2550, 0x256C, 0x2567,
+       0x2568, 0x2564, 0x2565, 0x2559, 0x2558, 0x2552, 0x2553, 0x256B,
+       0x256A, 0x2518, 0x250C, 0x2588, 0x2584, 0x258C, 0x2590, 0x2580,
+       0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,
+       0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F,
+       0x0401, 0x0451, 0x0404, 0x0454, 0x0407, 0x0457, 0x040E, 0x045E,
+       0x00B0, 0x2219, 0x00B7, 0x221A, 0x2116, 0x00A4, 0x25A0, 0x00A0
+};
+\r
+#elif _CODE_PAGE == 874
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP874(0x80-0xFF) to Unicode conversion table */
+       0x20AC, 0x0000, 0x0000, 0x0000, 0x0000, 0x2026, 0x0000, 0x0000,
+       0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+       0x00A0, 0x0E01, 0x0E02, 0x0E03, 0x0E04, 0x0E05, 0x0E06, 0x0E07,
+       0x0E08, 0x0E09, 0x0E0A, 0x0E0B, 0x0E0C, 0x0E0D, 0x0E0E, 0x0E0F,
+       0x0E10, 0x0E11, 0x0E12, 0x0E13, 0x0E14, 0x0E15, 0x0E16, 0x0E17,
+       0x0E18, 0x0E19, 0x0E1A, 0x0E1B, 0x0E1C, 0x0E1D, 0x0E1E, 0x0E1F,
+       0x0E20, 0x0E21, 0x0E22, 0x0E23, 0x0E24, 0x0E25, 0x0E26, 0x0E27,
+       0x0E28, 0x0E29, 0x0E2A, 0x0E2B, 0x0E2C, 0x0E2D, 0x0E2E, 0x0E2F,
+       0x0E30, 0x0E31, 0x0E32, 0x0E33, 0x0E34, 0x0E35, 0x0E36, 0x0E37,
+       0x0E38, 0x0E39, 0x0E3A, 0x0000, 0x0000, 0x0000, 0x0000, 0x0E3F,
+       0x0E40, 0x0E41, 0x0E42, 0x0E43, 0x0E44, 0x0E45, 0x0E46, 0x0E47,
+       0x0E48, 0x0E49, 0x0E4A, 0x0E4B, 0x0E4C, 0x0E4D, 0x0E4E, 0x0E4F,
+       0x0E50, 0x0E51, 0x0E52, 0x0E53, 0x0E54, 0x0E55, 0x0E56, 0x0E57,
+       0x0E58, 0x0E59, 0x0E5A, 0x0E5B, 0x0000, 0x0000, 0x0000, 0x0000
+};
+\r
+#elif _CODE_PAGE == 1250
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP1250(0x80-0xFF) to Unicode conversion table */
+       0x20AC, 0x0000, 0x201A, 0x0000, 0x201E, 0x2026, 0x2020, 0x2021,
+       0x0000, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179,
+       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x0000, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A,
+       0x00A0, 0x02C7, 0x02D8, 0x0141, 0x00A4, 0x0104, 0x00A6, 0x00A7,
+       0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B,
+       0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, 0x00B6, 0x00B7,
+       0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C,
+       0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7,
+       0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E,
+       0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7,
+       0x0158, 0x016E, 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF,
+       0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7,
+       0x010D, 0x00E9, 0x0119, 0x00EB, 0x011B, 0x00ED, 0x00EE, 0x010F,
+       0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7,
+       0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, 0x0163, 0x02D9
+};
+\r
+#elif _CODE_PAGE == 1251
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP1251(0x80-0xFF) to Unicode conversion table */
+       0x0402, 0x0403, 0x201A, 0x0453, 0x201E, 0x2026, 0x2020, 0x2021,
+       0x20AC, 0x2030, 0x0409, 0x2039, 0x040A, 0x040C, 0x040B, 0x040F,
+       0x0452, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x0000, 0x2111, 0x0459, 0x203A, 0x045A, 0x045C, 0x045B, 0x045F,
+       0x00A0, 0x040E, 0x045E, 0x0408, 0x00A4, 0x0490, 0x00A6, 0x00A7,
+       0x0401, 0x00A9, 0x0404, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x0407,
+       0x00B0, 0x00B1, 0x0406, 0x0456, 0x0491, 0x00B5, 0x00B6, 0x00B7,
+       0x0451, 0x2116, 0x0454, 0x00BB, 0x0458, 0x0405, 0x0455, 0x0457,
+       0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417,
+       0x0418, 0x0419, 0x041A, 0x041B, 0x041C, 0x041D, 0x041E, 0x041F,
+       0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427,
+       0x0428, 0x0429, 0x042A, 0x042B, 0x042C, 0x042D, 0x042E, 0x042F,
+       0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437,
+       0x0438, 0x0439, 0x043A, 0x043B, 0x043C, 0x043D, 0x043E, 0x043F,
+       0x0440, 0x0441, 0x0442, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447,
+       0x0448, 0x0449, 0x044A, 0x044B, 0x044C, 0x044D, 0x044E, 0x044F
+};
+\r
+#elif _CODE_PAGE == 1252
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP1252(0x80-0xFF) to Unicode conversion table */
+       0x20AC, 0x0000, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
+       0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x0000, 0x017D, 0x0000,
+       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x0000, 0x017E, 0x0178,
+       0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
+       0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
+       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,
+       0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF,
+       0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7,
+       0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF,
+       0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7,
+       0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF,
+       0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7,
+       0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF,
+       0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7,
+       0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF
+};
+\r
+#elif _CODE_PAGE == 1253
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP1253(0x80-0xFF) to Unicode conversion table */
+       0x20AC, 0x0000, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
+       0x0000, 0x2030, 0x0000, 0x2039, 0x000C, 0x0000, 0x0000, 0x0000,
+       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x0000, 0x2122, 0x0000, 0x203A, 0x0000, 0x0000, 0x0000, 0x0000,
+       0x00A0, 0x0385, 0x0386, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
+       0x00A8, 0x00A9, 0x0000, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x2015,
+       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x0384, 0x00B5, 0x00B6, 0x00B7,
+       0x0388, 0x0389, 0x038A, 0x00BB, 0x038C, 0x00BD, 0x038E, 0x038F,
+       0x0390, 0x0391, 0x0392, 0x0393, 0x0394, 0x0395, 0x0396, 0x0397,
+       0x0398, 0x0399, 0x039A, 0x039B, 0x039C, 0x039D, 0x039E, 0x039F,
+       0x03A0, 0x03A1, 0x0000, 0x03A3, 0x03A4, 0x03A5, 0x03A6, 0x03A7,
+       0x03A8, 0x03A9, 0x03AA, 0x03AD, 0x03AC, 0x03AD, 0x03AE, 0x03AF,
+       0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7,
+       0x03B8, 0x03B9, 0x03BA, 0x03BB, 0x03BC, 0x03BD, 0x03BE, 0x03BF,
+       0x03C0, 0x03C1, 0x03C2, 0x03C3, 0x03C4, 0x03C5, 0x03C6, 0x03C7,
+       0x03C8, 0x03C9, 0x03CA, 0x03CB, 0x03CC, 0x03CD, 0x03CE, 0x0000
+};
+\r
+#elif _CODE_PAGE == 1254
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP1254(0x80-0xFF) to Unicode conversion table */
+       0x20AC, 0x0000, 0x210A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
+       0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x0000, 0x0000, 0x0000,
+       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x0000, 0x0000, 0x0178,
+       0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
+       0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
+       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,
+       0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF,
+       0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7,
+       0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF,
+       0x011E, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7,
+       0x00D8, 0x00D9, 0x00DA, 0x00BD, 0x00DC, 0x0130, 0x015E, 0x00DF,
+       0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7,
+       0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF,
+       0x011F, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7,
+       0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x0131, 0x015F, 0x00FF
+};
+\r
+#elif _CODE_PAGE == 1255
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP1255(0x80-0xFF) to Unicode conversion table */
+       0x20AC, 0x0000, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
+       0x02C6, 0x2030, 0x0000, 0x2039, 0x0000, 0x0000, 0x0000, 0x0000,
+       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x02DC, 0x2122, 0x0000, 0x203A, 0x0000, 0x0000, 0x0000, 0x0000,
+       0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
+       0x00A8, 0x00A9, 0x00D7, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
+       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,
+       0x00B8, 0x00B9, 0x00F7, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF,
+       0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7,
+       0x05B8, 0x05B9, 0x0000, 0x05BB, 0x05BC, 0x05BD, 0x05BE, 0x05BF,
+       0x05C0, 0x05C1, 0x05C2, 0x05C3, 0x05F0, 0x05F1, 0x05F2, 0x05F3,
+       0x05F4, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+       0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7,
+       0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF,
+       0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7,
+       0x05E8, 0x05E9, 0x05EA, 0x0000, 0x0000, 0x200E, 0x200F, 0x0000
+};
+\r
+#elif _CODE_PAGE == 1256
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP1256(0x80-0xFF) to Unicode conversion table */
+       0x20AC, 0x067E, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
+       0x02C6, 0x2030, 0x0679, 0x2039, 0x0152, 0x0686, 0x0698, 0x0688,
+       0x06AF, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x06A9, 0x2122, 0x0691, 0x203A, 0x0153, 0x200C, 0x200D, 0x06BA,
+       0x00A0, 0x060C, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
+       0x00A8, 0x00A9, 0x06BE, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
+       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,
+       0x00B8, 0x00B9, 0x061B, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x061F,
+       0x06C1, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627,
+       0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F,
+       0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x00D7,
+       0x0637, 0x0638, 0x0639, 0x063A, 0x0640, 0x0640, 0x0642, 0x0643,
+       0x00E0, 0x0644, 0x00E2, 0x0645, 0x0646, 0x0647, 0x0648, 0x00E7,
+       0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x0649, 0x064A, 0x00EE, 0x00EF,
+       0x064B, 0x064C, 0x064D, 0x064E, 0x00F4, 0x064F, 0x0650, 0x00F7,
+       0x0651, 0x00F9, 0x0652, 0x00FB, 0x00FC, 0x200E, 0x200F, 0x06D2
+}
+\r
+#elif _CODE_PAGE == 1257
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP1257(0x80-0xFF) to Unicode conversion table */
+       0x20AC, 0x0000, 0x201A, 0x0000, 0x201E, 0x2026, 0x2020, 0x2021,
+       0x0000, 0x2030, 0x0000, 0x2039, 0x0000, 0x00A8, 0x02C7, 0x00B8,
+       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x0000, 0x2122, 0x0000, 0x203A, 0x0000, 0x00AF, 0x02DB, 0x0000,
+       0x00A0, 0x0000, 0x00A2, 0x00A3, 0x00A4, 0x0000, 0x00A6, 0x00A7,
+       0x00D8, 0x00A9, 0x0156, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
+       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,
+       0x00B8, 0x00B9, 0x0157, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00E6,
+       0x0104, 0x012E, 0x0100, 0x0106, 0x00C4, 0x00C5, 0x0118, 0x0112,
+       0x010C, 0x00C9, 0x0179, 0x0116, 0x0122, 0x0136, 0x012A, 0x013B,
+       0x0160, 0x0143, 0x0145, 0x00D3, 0x014C, 0x00D5, 0x00D6, 0x00D7,
+       0x0172, 0x0141, 0x015A, 0x016A, 0x00DC, 0x017B, 0x017D, 0x00DF,
+       0x0105, 0x012F, 0x0101, 0x0107, 0x00E4, 0x00E5, 0x0119, 0x0113,
+       0x010D, 0x00E9, 0x017A, 0x0117, 0x0123, 0x0137, 0x012B, 0x013C,
+       0x0161, 0x0144, 0x0146, 0x00F3, 0x014D, 0x00F5, 0x00F6, 0x00F7,
+       0x0173, 0x014E, 0x015B, 0x016B, 0x00FC, 0x017C, 0x017E, 0x02D9
+};
+\r
+#elif _CODE_PAGE == 1258
+#define _TBLDEF 1
+static
+const WCHAR Tbl[] = {  /*  CP1258(0x80-0xFF) to Unicode conversion table */
+       0x20AC, 0x0000, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
+       0x02C6, 0x2030, 0x0000, 0x2039, 0x0152, 0x0000, 0x0000, 0x0000,
+       0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
+       0x02DC, 0x2122, 0x0000, 0x203A, 0x0153, 0x0000, 0x0000, 0x0178,
+       0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7,
+       0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF,
+       0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7,
+       0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF,
+       0x00C0, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x00C5, 0x00C6, 0x00C7,
+       0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x0300, 0x00CD, 0x00CE, 0x00CF,
+       0x0110, 0x00D1, 0x0309, 0x00D3, 0x00D4, 0x01A0, 0x00D6, 0x00D7,
+       0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x01AF, 0x0303, 0x00DF,
+       0x00E0, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x00E5, 0x00E6, 0x00E7,
+       0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x0301, 0x00ED, 0x00EE, 0x00EF,
+       0x0111, 0x00F1, 0x0323, 0x00F3, 0x00F4, 0x01A1, 0x00F6, 0x00F7,
+       0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x01B0, 0x20AB, 0x00FF
+};
+\r
+#endif
+\r
+\r
+#if !_TBLDEF || !_USE_LFN
+#error This file is not needed in current configuration. Remove from the project.
+#endif
+\r
+\r
+WCHAR ff_convert (     /* Converted character, Returns zero on error */
+       WCHAR   src,    /* Character code to be converted */
+       UINT    dir             /* 0: Unicode to OEMCP, 1: OEMCP to Unicode */
+)
+{
+       WCHAR c;
+\r
+\r
+       if (src < 0x80) {       /* ASCII */
+               c = src;
+\r
+       } else {
+               if (dir) {              /* OEMCP to Unicode */
+                       c = (src >= 0x100) ? 0 : Tbl[src - 0x80];
+\r
+               } else {                /* Unicode to OEMCP */
+                       for (c = 0; c < 0x80; c++) {
+                               if (src == Tbl[c]) break;
+                       }
+                       c = (c + 0x80) & 0xFF;
+               }
+       }
+\r
+       return c;
+}
+\r
+\r
+WCHAR ff_wtoupper (    /* Upper converted character */
+       WCHAR chr               /* Input character */
+)
+{
+       static const WCHAR tbl_lower[] = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0xA1, 0x00A2, 0x00A3, 0x00A5, 0x00AC, 0x00AF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0x0FF, 0x101, 0x103, 0x105, 0x107, 0x109, 0x10B, 0x10D, 0x10F, 0x111, 0x113, 0x115, 0x117, 0x119, 0x11B, 0x11D, 0x11F, 0x121, 0x123, 0x125, 0x127, 0x129, 0x12B, 0x12D, 0x12F, 0x131, 0x133, 0x135, 0x137, 0x13A, 0x13C, 0x13E, 0x140, 0x142, 0x144, 0x146, 0x148, 0x14B, 0x14D, 0x14F, 0x151, 0x153, 0x155, 0x157, 0x159, 0x15B, 0x15D, 0x15F, 0x161, 0x163, 0x165, 0x167, 0x169, 0x16B, 0x16D, 0x16F, 0x171, 0x173, 0x175, 0x177, 0x17A, 0x17C, 0x17E, 0x192, 0x3B1, 0x3B2, 0x3B3, 0x3B4, 0x3B5, 0x3B6, 0x3B7, 0x3B8, 0x3B9, 0x3BA, 0x3BB, 0x3BC, 0x3BD, 0x3BE, 0x3BF, 0x3C0, 0x3C1, 0x3C3, 0x3C4, 0x3C5, 0x3C6, 0x3C7, 0x3C8, 0x3C9, 0x3CA, 0x430, 0x431, 0x432, 0x433, 0x434, 0x435, 0x436, 0x437, 0x438, 0x439, 0x43A, 0x43B, 0x43C, 0x43D, 0x43E, 0x43F, 0x440, 0x441, 0x442, 0x443, 0x444, 0x445, 0x446, 0x447, 0x448, 0x449, 0x44A, 0x44B, 0x44C, 0x44D, 0x44E, 0x44F, 0x451, 0x452, 0x453, 0x454, 0x455, 0x456, 0x457, 0x458, 0x459, 0x45A, 0x45B, 0x45C, 0x45E, 0x45F, 0x2170, 0x2171, 0x2172, 0x2173, 0x2174, 0x2175, 0x2176, 0x2177, 0x2178, 0x2179, 0x217A, 0x217B, 0x217C, 0x217D, 0x217E, 0x217F, 0xFF41, 0xFF42, 0xFF43, 0xFF44, 0xFF45, 0xFF46, 0xFF47, 0xFF48, 0xFF49, 0xFF4A, 0xFF4B, 0xFF4C, 0xFF4D, 0xFF4E, 0xFF4F, 0xFF50, 0xFF51, 0xFF52, 0xFF53, 0xFF54, 0xFF55, 0xFF56, 0xFF57, 0xFF58, 0xFF59, 0xFF5A, 0 };
+       static const WCHAR tbl_upper[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x21, 0xFFE0, 0xFFE1, 0xFFE5, 0xFFE2, 0xFFE3, 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0x178, 0x100, 0x102, 0x104, 0x106, 0x108, 0x10A, 0x10C, 0x10E, 0x110, 0x112, 0x114, 0x116, 0x118, 0x11A, 0x11C, 0x11E, 0x120, 0x122, 0x124, 0x126, 0x128, 0x12A, 0x12C, 0x12E, 0x130, 0x132, 0x134, 0x136, 0x139, 0x13B, 0x13D, 0x13F, 0x141, 0x143, 0x145, 0x147, 0x14A, 0x14C, 0x14E, 0x150, 0x152, 0x154, 0x156, 0x158, 0x15A, 0x15C, 0x15E, 0x160, 0x162, 0x164, 0x166, 0x168, 0x16A, 0x16C, 0x16E, 0x170, 0x172, 0x174, 0x176, 0x179, 0x17B, 0x17D, 0x191, 0x391, 0x392, 0x393, 0x394, 0x395, 0x396, 0x397, 0x398, 0x399, 0x39A, 0x39B, 0x39C, 0x39D, 0x39E, 0x39F, 0x3A0, 0x3A1, 0x3A3, 0x3A4, 0x3A5, 0x3A6, 0x3A7, 0x3A8, 0x3A9, 0x3AA, 0x410, 0x411, 0x412, 0x413, 0x414, 0x415, 0x416, 0x417, 0x418, 0x419, 0x41A, 0x41B, 0x41C, 0x41D, 0x41E, 0x41F, 0x420, 0x421, 0x422, 0x423, 0x424, 0x425, 0x426, 0x427, 0x428, 0x429, 0x42A, 0x42B, 0x42C, 0x42D, 0x42E, 0x42F, 0x401, 0x402, 0x403, 0x404, 0x405, 0x406, 0x407, 0x408, 0x409, 0x40A, 0x40B, 0x40C, 0x40E, 0x40F, 0x2160, 0x2161, 0x2162, 0x2163, 0x2164, 0x2165, 0x2166, 0x2167, 0x2168, 0x2169, 0x216A, 0x216B, 0x216C, 0x216D, 0x216E, 0x216F, 0xFF21, 0xFF22, 0xFF23, 0xFF24, 0xFF25, 0xFF26, 0xFF27, 0xFF28, 0xFF29, 0xFF2A, 0xFF2B, 0xFF2C, 0xFF2D, 0xFF2E, 0xFF2F, 0xFF30, 0xFF31, 0xFF32, 0xFF33, 0xFF34, 0xFF35, 0xFF36, 0xFF37, 0xFF38, 0xFF39, 0xFF3A, 0 };
+       int i;
+\r
+\r
+       for (i = 0; tbl_lower[i] && chr != tbl_lower[i]; i++) ;
+\r
+       return tbl_lower[i] ? tbl_upper[i] : chr;
+}
index 0b1e763..bfb38fe 100644 (file)
@@ -1,31 +1,31 @@
-/* mbed Microcontroller Library - FATDirHandle\r
- * Copyright (c) 2008, sford\r
- */\r
+/* mbed Microcontroller Library - FATDirHandle
+ * Copyright (c) 2008, sford
+ */
 \r
-#ifndef MBED_FATDIRHANDLE_H\r
-#define MBED_FATDIRHANDLE_H\r
+#ifndef MBED_FATDIRHANDLE_H
+#define MBED_FATDIRHANDLE_H
 \r
-#include "DirHandle.h"\r
-#include "ff.h"\r
+#include "DirHandle.h"
+#include "ff.h"
 \r
-namespace mbed {\r
+namespace mbed {
 \r
-class FATDirHandle : public DirHandle {\r
+class FATDirHandle : public DirHandle {
 \r
- public:\r
-    FATDirHandle(const DIR_t &the_dir);\r
-    virtual int closedir();\r
-    virtual struct dirent *readdir();\r
-    virtual void rewinddir();\r
-    virtual off_t telldir();\r
-    virtual void seekdir(off_t location);\r
+ public:
+    FATDirHandle(const DIR_t &the_dir);
+    virtual int closedir();
+    virtual struct dirent *readdir();
+    virtual void rewinddir();
+    virtual off_t telldir();
+    virtual void seekdir(off_t location);
 \r
- private:\r
-    DIR_t dir;\r
-    struct dirent cur_entry;\r
+ private:
+    DIR_t dir;
+    struct dirent cur_entry;
 \r
-};\r
+};
 \r
-}\r
+}
 \r
-#endif\r
+#endif
index 9e9f9fd..e18488c 100644 (file)
@@ -13,24 +13,24 @@ namespace mbed {
 
 #if FFSDEBUG_ENABLED
 static const char *FR_ERRORS[] = {
-    "FR_OK = 0", 
-    "FR_NOT_READY",          
-    "FR_NO_FILE",              
-    "FR_NO_PATH",             
-    "FR_INVALID_NAME",     
-    "FR_INVALID_DRIVE",      
-    "FR_DENIED",              
-    "FR_EXIST",              
-    "FR_RW_ERROR",          
-    "FR_WRITE_PROTECTED", 
-    "FR_NOT_ENABLED",    
-    "FR_NO_FILESYSTEM",    
-    "FR_INVALID_OBJECT",    
-    "FR_MKFS_ABORTED"    
+    "FR_OK = 0",
+    "FR_NOT_READY",
+    "FR_NO_FILE",
+    "FR_NO_PATH",
+    "FR_INVALID_NAME",
+    "FR_INVALID_DRIVE",
+    "FR_DENIED",
+    "FR_EXIST",
+    "FR_RW_ERROR",
+    "FR_WRITE_PROTECTED",
+    "FR_NOT_ENABLED",
+    "FR_NO_FILESYSTEM",
+    "FR_INVALID_OBJECT",
+    "FR_MKFS_ABORTED"
 };
 #endif
 
-FATFileHandle::FATFileHandle(FIL_t fh) { 
+FATFileHandle::FATFileHandle(FIL_t fh) {
     _fh = fh;
 }
     
@@ -45,7 +45,7 @@ ssize_t FATFileHandle::write(const void* buffer, size_t length) {
     FFSDEBUG("write(%d)\n", length);
     UINT n;
     FRESULT res = f_write(&_fh, buffer, length, &n);
-    if(res) { 
+    if(res) {
         FFSDEBUG("f_write() failed (%d, %s)", res, FR_ERRORS[res]);
         return -1;
     }
index 4e698c4..4c2d545 100644 (file)
@@ -1,33 +1,33 @@
-/* mbed Microcontroller Library - FATFileHandle\r
- * Copyright (c) 2008, sford\r
- */\r
+/* mbed Microcontroller Library - FATFileHandle
+ * Copyright (c) 2008, sford
+ */
 \r
-#ifndef MBED_FATFILEHANDLE_H\r
-#define MBED_FATFILEHANDLE_H\r
+#ifndef MBED_FATFILEHANDLE_H
+#define MBED_FATFILEHANDLE_H
 \r
-#include "FileHandle.h"\r
-#include "ff.h"\r
+#include "FileHandle.h"
+#include "ff.h"
 \r
-namespace mbed {\r
+namespace mbed {
 \r
-class FATFileHandle : public FileHandle {\r
-public:\r
+class FATFileHandle : public FileHandle {
+public:
 \r
-    FATFileHandle(FIL_t fh);\r
-    virtual int close();\r
-    virtual ssize_t write(const void* buffer, size_t length);\r
-    virtual ssize_t read(void* buffer, size_t length);\r
-    virtual int isatty();\r
-    virtual off_t lseek(off_t position, int whence);\r
-    virtual int fsync();\r
-    virtual off_t flen();\r
+    FATFileHandle(FIL_t fh);
+    virtual int close();
+    virtual ssize_t write(const void* buffer, size_t length);
+    virtual ssize_t read(void* buffer, size_t length);
+    virtual int isatty();
+    virtual off_t lseek(off_t position, int whence);
+    virtual int fsync();
+    virtual off_t flen();
 \r
-protected:\r
+protected:
 \r
-    FIL_t _fh;\r
+    FIL_t _fh;
 \r
-};\r
+};
 \r
-}\r
+}
 \r
-#endif\r
+#endif
index a756c07..8f06397 100644 (file)
@@ -22,20 +22,20 @@ namespace mbed {
 
 #if FFSDEBUG_ENABLED
 static const char *FR_ERRORS[] = {
-    "FR_OK = 0", 
-    "FR_NOT_READY",          
-    "FR_NO_FILE",              
-    "FR_NO_PATH",             
-    "FR_INVALID_NAME",     
-    "FR_INVALID_DRIVE",      
-    "FR_DENIED",              
-    "FR_EXIST",              
-    "FR_RW_ERROR",          
-    "FR_WRITE_PROTECTED", 
-    "FR_NOT_ENABLED",    
-    "FR_NO_FILESYSTEM",    
-    "FR_INVALID_OBJECT",    
-    "FR_MKFS_ABORTED"    
+    "FR_OK = 0",
+    "FR_NOT_READY",
+    "FR_NO_FILE",
+    "FR_NO_PATH",
+    "FR_INVALID_NAME",
+    "FR_INVALID_DRIVE",
+    "FR_DENIED",
+    "FR_EXIST",
+    "FR_RW_ERROR",
+    "FR_WRITE_PROTECTED",
+    "FR_NOT_ENABLED",
+    "FR_NO_FILESYSTEM",
+    "FR_INVALID_OBJECT",
+    "FR_MKFS_ABORTED"
 };
 #endif
 
@@ -88,7 +88,7 @@ FileHandle *FATFileSystem::open(const char* name, int flags) {
 
     FIL_t fh;
     FRESULT res = f_open(&fh, n, openmode);
-    if(res) { 
+    if(res) {
         FFSDEBUG("f_open('w') failed (%d, %s)\n", res, FR_ERRORS[res]);
         return NULL;
     }
@@ -100,7 +100,7 @@ FileHandle *FATFileSystem::open(const char* name, int flags) {
     
 int FATFileSystem::remove(const char *filename) {
     FRESULT res = f_unlink(filename);
-    if(res) { 
+    if(res) {
         FFSDEBUG("f_unlink() failed (%d, %s)\n", res, FR_ERRORS[res]);
         return -1;
     }
index 75d5808..06756a2 100644 (file)
@@ -1,61 +1,61 @@
-/* mbed Microcontroller Library - FATFileSystem\r
- * Copyright (c) 2008, sford\r
- */\r
-\r
-/* Library: FATFileSystem.h\r
- * A library of stuff to make a fat filesystem on top of a block device\r
- */\r
-\r
-#ifndef MBED_FATFILESYSTEM_H\r
-#define MBED_FATFILESYSTEM_H\r
-\r
-#ifndef FFSDEBUG_ENABLED\r
-#define FFSDEBUG_ENABLED 0\r
-#endif\r
-\r
-#if FFSDEBUG_ENABLED\r
-#define FFSDEBUG(FMT, ...) printf(FMT, ##__VA_ARGS__)\r
-#else\r
-#define FFSDEBUG(FMT, ...)\r
-#endif\r
-\r
-#include "FileSystemLike.h"\r
-#include "FileHandle.h"\r
-#include "ff.h"\r
-#include "diskio.h"\r
-\r
-namespace mbed {\r
-/* Class: FATFileSystem\r
- * The class itself\r
- */\r
-class FATFileSystem : public FileSystemLike {\r
-public:\r
-\r
-    FATFileSystem(const char* n);\r
-    virtual ~FATFileSystem();\r
+/* mbed Microcontroller Library - FATFileSystem
+ * Copyright (c) 2008, sford
+ */
+\r
+/* Library: FATFileSystem.h
+ * A library of stuff to make a fat filesystem on top of a block device
+ */
+\r
+#ifndef MBED_FATFILESYSTEM_H
+#define MBED_FATFILESYSTEM_H
+\r
+#ifndef FFSDEBUG_ENABLED
+#define FFSDEBUG_ENABLED 0
+#endif
+\r
+#if FFSDEBUG_ENABLED
+#define FFSDEBUG(FMT, ...) printf(FMT, ##__VA_ARGS__)
+#else
+#define FFSDEBUG(FMT, ...)
+#endif
+\r
+#include "FileSystemLike.h"
+#include "FileHandle.h"
+#include "ff.h"
+#include "diskio.h"
+\r
+namespace mbed {
+/* Class: FATFileSystem
+ * The class itself
+ */
+class FATFileSystem : public FileSystemLike {
+public:
+\r
+    FATFileSystem(const char* n);
+    virtual ~FATFileSystem();
     \r
-    /* Function: open\r
-       * open a file on the filesystem. never called directly\r
-       */\r
-    virtual FileHandle *open(const char* name, int flags);\r
-    virtual int remove(const char *filename);\r
-    virtual int format();\r
-        virtual DirHandle *opendir(const char *name);\r
-        virtual int mkdir(const char *name, mode_t mode);\r
+    /* Function: open
+       * open a file on the filesystem. never called directly
+       */
+    virtual FileHandle *open(const char* name, int flags);
+    virtual int remove(const char *filename);
+    virtual int format();
+        virtual DirHandle *opendir(const char *name);
+        virtual int mkdir(const char *name, mode_t mode);
     \r
-    FATFS _fs;                                // Work area (file system object) for logical drive    \r
-    static FATFileSystem *_ffs[_DRIVES];    // FATFileSystem objects, as parallel to FatFs drives array\r
-    int _fsid;\r
+    FATFS _fs;                                // Work area (file system object) for logical drive
+    static FATFileSystem *_ffs[_DRIVES];    // FATFileSystem objects, as parallel to FatFs drives array
+    int _fsid;
     \r
-    virtual int disk_initialize() { return 0; }\r
-    virtual int disk_status() { return 0; }\r
-    virtual int disk_read(char *buffer, int sector) = 0;\r
-    virtual int disk_write(const char *buffer, int sector) = 0;\r
-    virtual int disk_sync() { return 0; }\r
-    virtual int disk_sectors() = 0;\r
+    virtual int disk_initialize() { return 0; }
+    virtual int disk_status() { return 0; }
+    virtual int disk_read(char *buffer, int sector) = 0;
+    virtual int disk_write(const char *buffer, int sector) = 0;
+    virtual int disk_sync() { return 0; }
+    virtual int disk_sectors() = 0;
      \r
-};\r
+};
     \r
-}\r
+}
 \r
-#endif\r
+#endif
index 6eea590..46a815a 100644 (file)
-/* mbed SDFileSystem Library, for providing file access to SD cards\r
- * Copyright (c) 2008-2010, sford\r
- *\r
- * Permission is hereby granted, free of charge, to any person obtaining a copy\r
- * of this software and associated documentation files (the "Software"), to deal\r
- * in the Software without restriction, including without limitation the rights\r
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
- * copies of the Software, and to permit persons to whom the Software is\r
- * furnished to do so, subject to the following conditions:\r
- *\r
- * The above copyright notice and this permission notice shall be included in\r
- * all copies or substantial portions of the Software.\r
- *\r
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
- * THE SOFTWARE.\r
- */\r
-\r
-/* Introduction\r
- * ------------\r
- * SD and MMC cards support a number of interfaces, but common to them all\r
- * is one based on SPI. This is the one I'm implmenting because it means\r
- * it is much more portable even though not so performant, and we already \r
- * have the mbed SPI Interface!\r
- *\r
- * The main reference I'm using is Chapter 7, "SPI Mode" of: \r
- *  http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf\r
- *\r
- * SPI Startup\r
- * -----------\r
- * The SD card powers up in SD mode. The SPI interface mode is selected by\r
- * asserting CS low and sending the reset command (CMD0). The card will \r
- * respond with a (R1) response.\r
- *\r
- * CMD8 is optionally sent to determine the voltage range supported, and \r
- * indirectly determine whether it is a version 1.x SD/non-SD card or \r
- * version 2.x. I'll just ignore this for now.\r
- *\r
- * ACMD41 is repeatedly issued to initialise the card, until "in idle"\r
- * (bit 0) of the R1 response goes to '0', indicating it is initialised.\r
- *\r
- * You should also indicate whether the host supports High Capicity cards,\r
- * and check whether the card is high capacity - i'll also ignore this\r
- *\r
- * SPI Protocol\r
- * ------------\r
- * The SD SPI protocol is based on transactions made up of 8-bit words, with\r
- * the host starting every bus transaction by asserting the CS signal low. The\r
- * card always responds to commands, data blocks and errors.\r
- * \r
- * The protocol supports a CRC, but by default it is off (except for the \r
- * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)\r
- * I'll leave the CRC off I think! \r
- * \r
- * Standard capacity cards have variable data block sizes, whereas High \r
- * Capacity cards fix the size of data block to 512 bytes. I'll therefore\r
- * just always use the Standard Capacity cards with a block size of 512 bytes.\r
- * This is set with CMD16.\r
- *\r
- * You can read and write single blocks (CMD17, CMD25) or multiple blocks \r
- * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When\r
- * the card gets a read command, it responds with a response token, and then \r
- * a data token or an error.\r
- * \r
- * SPI Command Format\r
- * ------------------\r
- * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.\r
- *\r
- * +---------------+------------+------------+-----------+----------+--------------+\r
- * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |\r
- * +---------------+------------+------------+-----------+----------+--------------+\r
- *\r
- * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)\r
- *\r
- * All Application Specific commands shall be preceded with APP_CMD (CMD55).\r
- *\r
- * SPI Response Format\r
- * -------------------\r
- * The main response format (R1) is a status byte (normally zero). Key flags:\r
- *  idle - 1 if the card is in an idle state/initialising \r
- *  cmd  - 1 if an illegal command code was detected\r
- *\r
- *    +-------------------------------------------------+\r
- * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |\r
- *    +-------------------------------------------------+\r
- *\r
- * R1b is the same, except it is followed by a busy signal (zeros) until\r
- * the first non-zero byte when it is ready again.\r
- *\r
- * Data Response Token\r
- * -------------------\r
- * Every data block written to the card is acknowledged by a byte \r
- * response token\r
- *\r
- * +----------------------+\r
- * | xxx | 0 | status | 1 |\r
- * +----------------------+\r
- *              010 - OK!\r
- *              101 - CRC Error\r
- *              110 - Write Error\r
- *\r
- * Single Block Read and Write\r
- * ---------------------------\r
- *\r
- * Block transfers have a byte header, followed by the data, followed\r
- * by a 16-bit CRC. In our case, the data will always be 512 bytes.\r
- *  \r
- * +------+---------+---------+- -  - -+---------+-----------+----------+\r
- * | 0xFE | data[0] | data[1] |        | data[n] | crc[15:8] | crc[7:0] | \r
- * +------+---------+---------+- -  - -+---------+-----------+----------+\r
- */\r
+/* mbed SDFileSystem Library, for providing file access to SD cards
+ * Copyright (c) 2008-2010, sford
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+\r
+/* Introduction
+ * ------------
+ * SD and MMC cards support a number of interfaces, but common to them all
+ * is one based on SPI. This is the one I'm implmenting because it means
+ * it is much more portable even though not so performant, and we already
+ * have the mbed SPI Interface!
+ *
+ * The main reference I'm using is Chapter 7, "SPI Mode" of:
+ *  http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Spec.pdf
+ *
+ * SPI Startup
+ * -----------
+ * The SD card powers up in SD mode. The SPI interface mode is selected by
+ * asserting CS low and sending the reset command (CMD0). The card will
+ * respond with a (R1) response.
+ *
+ * CMD8 is optionally sent to determine the voltage range supported, and
+ * indirectly determine whether it is a version 1.x SD/non-SD card or
+ * version 2.x. I'll just ignore this for now.
+ *
+ * ACMD41 is repeatedly issued to initialise the card, until "in idle"
+ * (bit 0) of the R1 response goes to '0', indicating it is initialised.
+ *
+ * You should also indicate whether the host supports High Capicity cards,
+ * and check whether the card is high capacity - i'll also ignore this
+ *
+ * SPI Protocol
+ * ------------
+ * The SD SPI protocol is based on transactions made up of 8-bit words, with
+ * the host starting every bus transaction by asserting the CS signal low. The
+ * card always responds to commands, data blocks and errors.
+ *
+ * The protocol supports a CRC, but by default it is off (except for the
+ * first reset CMD0, where the CRC can just be pre-calculated, and CMD8)
+ * I'll leave the CRC off I think!
+ *
+ * Standard capacity cards have variable data block sizes, whereas High
+ * Capacity cards fix the size of data block to 512 bytes. I'll therefore
+ * just always use the Standard Capacity cards with a block size of 512 bytes.
+ * This is set with CMD16.
+ *
+ * You can read and write single blocks (CMD17, CMD25) or multiple blocks
+ * (CMD18, CMD25). For simplicity, I'll just use single block accesses. When
+ * the card gets a read command, it responds with a response token, and then
+ * a data token or an error.
+ *
+ * SPI Command Format
+ * ------------------
+ * Commands are 6-bytes long, containing the command, 32-bit argument, and CRC.
+ *
+ * +---------------+------------+------------+-----------+----------+--------------+
+ * | 01 | cmd[5:0] | arg[31:24] | arg[23:16] | arg[15:8] | arg[7:0] | crc[6:0] | 1 |
+ * +---------------+------------+------------+-----------+----------+--------------+
+ *
+ * As I'm not using CRC, I can fix that byte to what is needed for CMD0 (0x95)
+ *
+ * All Application Specific commands shall be preceded with APP_CMD (CMD55).
+ *
+ * SPI Response Format
+ * -------------------
+ * The main response format (R1) is a status byte (normally zero). Key flags:
+ *  idle - 1 if the card is in an idle state/initialising
+ *  cmd  - 1 if an illegal command code was detected
+ *
+ *    +-------------------------------------------------+
+ * R1 | 0 | arg | addr | seq | crc | cmd | erase | idle |
+ *    +-------------------------------------------------+
+ *
+ * R1b is the same, except it is followed by a busy signal (zeros) until
+ * the first non-zero byte when it is ready again.
+ *
+ * Data Response Token
+ * -------------------
+ * Every data block written to the card is acknowledged by a byte
+ * response token
+ *
+ * +----------------------+
+ * | xxx | 0 | status | 1 |
+ * +----------------------+
+ *              010 - OK!
+ *              101 - CRC Error
+ *              110 - Write Error
+ *
+ * Single Block Read and Write
+ * ---------------------------
+ *
+ * Block transfers have a byte header, followed by the data, followed
+ * by a 16-bit CRC. In our case, the data will always be 512 bytes.
+ *
+ * +------+---------+---------+- -  - -+---------+-----------+----------+
+ * | 0xFE | data[0] | data[1] |        | data[n] | crc[15:8] | crc[7:0] |
+ * +------+---------+---------+- -  - -+---------+-----------+----------+
+ */
  \r
-#include "SDFileSystem.h"\r
-\r
-#define SD_COMMAND_TIMEOUT 5000\r
-\r
-SDFileSystem::SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name) :\r
-  FATFileSystem(name), _spi(mosi, miso, sclk), _cs(cs) {\r
-      _cs = 1; \r
-}\r
-\r
-#define R1_IDLE_STATE           (1 << 0)\r
-#define R1_ERASE_RESET          (1 << 1)\r
-#define R1_ILLEGAL_COMMAND      (1 << 2)\r
-#define R1_COM_CRC_ERROR        (1 << 3)\r
-#define R1_ERASE_SEQUENCE_ERROR (1 << 4)\r
-#define R1_ADDRESS_ERROR        (1 << 5)\r
-#define R1_PARAMETER_ERROR      (1 << 6)\r
-\r
-// Types\r
-//  - v1.x Standard Capacity\r
-//  - v2.x Standard Capacity\r
-//  - v2.x High Capacity\r
-//  - Not recognised as an SD Card\r
-\r
-#define SDCARD_FAIL 0\r
-#define SDCARD_V1   1\r
-#define SDCARD_V2   2\r
-#define SDCARD_V2HC 3\r
-\r
-int SDFileSystem::initialise_card() {\r
-    // Set to 100kHz for initialisation, and clock card with cs = 1\r
-    _spi.frequency(100000); \r
-    _cs = 1;\r
-    for(int i=0; i<16; i++) {   \r
-        _spi.write(0xFF);\r
-    }\r
-\r
-    // send CMD0, should return with all zeros except IDLE STATE set (bit 0)\r
-    if(_cmd(0, 0) != R1_IDLE_STATE) { \r
-        fprintf(stderr, "No disk, or could not put SD card in to SPI idle state\n");\r
-        return SDCARD_FAIL;\r
-    }\r
-\r
-    // send CMD8 to determine whther it is ver 2.x\r
-    int r = _cmd8();\r
-    if(r == R1_IDLE_STATE) {\r
-        return initialise_card_v2();\r
-    } else if(r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {\r
-        return initialise_card_v1();\r
-    } else {\r
-        fprintf(stderr, "Not in idle state after sending CMD8 (not an SD card?)\n");\r
-        return SDCARD_FAIL;\r
-    }\r
-}\r
-\r
-int SDFileSystem::initialise_card_v1() {\r
-    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {\r
-        _cmd(55, 0); \r
-        if(_cmd(41, 0) == 0) { \r
-            return SDCARD_V1;\r
-        }\r
-    }\r
-\r
-    fprintf(stderr, "Timeout waiting for v1.x card\n");\r
-    return SDCARD_FAIL;\r
-}\r
-\r
-int SDFileSystem::initialise_card_v2() {\r
-    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {\r
-        _cmd(55, 0); \r
-        if(_cmd(41, 0) == 0) { \r
-            _cmd58();\r
-            return SDCARD_V2;\r
-        }\r
-    }\r
-\r
-    fprintf(stderr, "Timeout waiting for v2.x card\n");\r
-    return SDCARD_FAIL;\r
-}\r
-\r
-int SDFileSystem::disk_initialize() {\r
-    initialise_card();\r
-    _sectors = _sd_sectors();\r
-\r
-    // Set block length to 512 (CMD16)\r
-    if(_cmd(16, 512) != 0) {\r
-        fprintf(stderr, "Set 512-byte block timed out\n");\r
-        return 1;\r
-    }\r
+#include "SDFileSystem.h"
+\r
+#define SD_COMMAND_TIMEOUT 5000
+\r
+SDFileSystem::SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name) :
+  FATFileSystem(name), _spi(mosi, miso, sclk), _cs(cs) {
+      _cs = 1;
+}
+\r
+#define R1_IDLE_STATE           (1 << 0)
+#define R1_ERASE_RESET          (1 << 1)
+#define R1_ILLEGAL_COMMAND      (1 << 2)
+#define R1_COM_CRC_ERROR        (1 << 3)
+#define R1_ERASE_SEQUENCE_ERROR (1 << 4)
+#define R1_ADDRESS_ERROR        (1 << 5)
+#define R1_PARAMETER_ERROR      (1 << 6)
+\r
+// Types
+//  - v1.x Standard Capacity
+//  - v2.x Standard Capacity
+//  - v2.x High Capacity
+//  - Not recognised as an SD Card
+\r
+#define SDCARD_FAIL 0
+#define SDCARD_V1   1
+#define SDCARD_V2   2
+#define SDCARD_V2HC 3
+\r
+int SDFileSystem::initialise_card() {
+    // Set to 100kHz for initialisation, and clock card with cs = 1
+    _spi.frequency(100000);
+    _cs = 1;
+    for(int i=0; i<16; i++) {
+        _spi.write(0xFF);
+    }
+\r
+    // send CMD0, should return with all zeros except IDLE STATE set (bit 0)
+    if(_cmd(0, 0) != R1_IDLE_STATE) {
+        fprintf(stderr, "No disk, or could not put SD card in to SPI idle state\n");
+        return SDCARD_FAIL;
+    }
+\r
+    // send CMD8 to determine whther it is ver 2.x
+    int r = _cmd8();
+    if(r == R1_IDLE_STATE) {
+        return initialise_card_v2();
+    } else if(r == (R1_IDLE_STATE | R1_ILLEGAL_COMMAND)) {
+        return initialise_card_v1();
+    } else {
+        fprintf(stderr, "Not in idle state after sending CMD8 (not an SD card?)\n");
+        return SDCARD_FAIL;
+    }
+}
+\r
+int SDFileSystem::initialise_card_v1() {
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        _cmd(55, 0);
+        if(_cmd(41, 0) == 0) {
+            return SDCARD_V1;
+        }
+    }
+\r
+    fprintf(stderr, "Timeout waiting for v1.x card\n");
+    return SDCARD_FAIL;
+}
+\r
+int SDFileSystem::initialise_card_v2() {
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        _cmd(55, 0);
+        if(_cmd(41, 0) == 0) {
+            _cmd58();
+            return SDCARD_V2;
+        }
+    }
+\r
+    fprintf(stderr, "Timeout waiting for v2.x card\n");
+    return SDCARD_FAIL;
+}
+\r
+int SDFileSystem::disk_initialize() {
+    initialise_card();
+    _sectors = _sd_sectors();
+\r
+    // Set block length to 512 (CMD16)
+    if(_cmd(16, 512) != 0) {
+        fprintf(stderr, "Set 512-byte block timed out\n");
+        return 1;
+    }
         \r
-    _spi.frequency(1000000); // Set to 1MHz for data transfer\r
-    return 0;\r
-}\r
-\r
-int SDFileSystem::disk_write(const char *buffer, int block_number) {\r
-    // set write address for single block (CMD24)\r
-    if(_cmd(24, block_number * 512) != 0) {\r
-        return 1;\r
-    }\r
-\r
-    // send the data block\r
-    _write(buffer, 512);    \r
-    return 0;    \r
-}\r
-\r
-int SDFileSystem::disk_read(char *buffer, int block_number) {        \r
-    // set read address for single block (CMD17)\r
-    if(_cmd(17, block_number * 512) != 0) {\r
-        return 1;\r
-    }\r
+    _spi.frequency(1000000); // Set to 1MHz for data transfer
+    return 0;
+}
+\r
+int SDFileSystem::disk_write(const char *buffer, int block_number) {
+    // set write address for single block (CMD24)
+    if(_cmd(24, block_number * 512) != 0) {
+        return 1;
+    }
+\r
+    // send the data block
+    _write(buffer, 512);
+    return 0;
+}
+\r
+int SDFileSystem::disk_read(char *buffer, int block_number) {
+    // set read address for single block (CMD17)
+    if(_cmd(17, block_number * 512) != 0) {
+        return 1;
+    }
     \r
-    // receive the data\r
-    _read(buffer, 512);\r
-    return 0;\r
-}\r
-\r
-int SDFileSystem::disk_status() { return 0; }\r
-int SDFileSystem::disk_sync() { return 0; }\r
-int SDFileSystem::disk_sectors() { return _sectors; }\r
-\r
-// PRIVATE FUNCTIONS\r
-\r
-int SDFileSystem::_cmd(int cmd, int arg) {\r
-    _cs = 0; \r
-\r
-    // send a command\r
-    _spi.write(0x40 | cmd);\r
-    _spi.write(arg >> 24);\r
-    _spi.write(arg >> 16);\r
-    _spi.write(arg >> 8);\r
-    _spi.write(arg >> 0);\r
-    _spi.write(0x95);\r
-\r
-    // wait for the repsonse (response[7] == 0)\r
-    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {\r
-        int response = _spi.write(0xFF);\r
-        if(!(response & 0x80)) {\r
-            _cs = 1;\r
-            _spi.write(0xFF);\r
-            return response;\r
-        }\r
-    }\r
-    _cs = 1;\r
-    _spi.write(0xFF);\r
-    return -1; // timeout\r
-}\r
-int SDFileSystem::_cmdx(int cmd, int arg) {\r
-    _cs = 0; \r
-\r
-    // send a command\r
-    _spi.write(0x40 | cmd);\r
-    _spi.write(arg >> 24);\r
-    _spi.write(arg >> 16);\r
-    _spi.write(arg >> 8);\r
-    _spi.write(arg >> 0);\r
-    _spi.write(0x95);\r
-\r
-    // wait for the repsonse (response[7] == 0)\r
-    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {\r
-        int response = _spi.write(0xFF);\r
-        if(!(response & 0x80)) {\r
-            return response;\r
-        }\r
-    }\r
-    _cs = 1;\r
-    _spi.write(0xFF);\r
-    return -1; // timeout\r
-}\r
-\r
-\r
-int SDFileSystem::_cmd58() {\r
-    _cs = 0; \r
-    int arg = 0;\r
+    // receive the data
+    _read(buffer, 512);
+    return 0;
+}
+\r
+int SDFileSystem::disk_status() { return 0; }
+int SDFileSystem::disk_sync() { return 0; }
+int SDFileSystem::disk_sectors() { return _sectors; }
+\r
+// PRIVATE FUNCTIONS
+\r
+int SDFileSystem::_cmd(int cmd, int arg) {
+    _cs = 0;
+\r
+    // send a command
+    _spi.write(0x40 | cmd);
+    _spi.write(arg >> 24);
+    _spi.write(arg >> 16);
+    _spi.write(arg >> 8);
+    _spi.write(arg >> 0);
+    _spi.write(0x95);
+\r
+    // wait for the repsonse (response[7] == 0)
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        int response = _spi.write(0xFF);
+        if(!(response & 0x80)) {
+            _cs = 1;
+            _spi.write(0xFF);
+            return response;
+        }
+    }
+    _cs = 1;
+    _spi.write(0xFF);
+    return -1; // timeout
+}
+int SDFileSystem::_cmdx(int cmd, int arg) {
+    _cs = 0;
+\r
+    // send a command
+    _spi.write(0x40 | cmd);
+    _spi.write(arg >> 24);
+    _spi.write(arg >> 16);
+    _spi.write(arg >> 8);
+    _spi.write(arg >> 0);
+    _spi.write(0x95);
+\r
+    // wait for the repsonse (response[7] == 0)
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        int response = _spi.write(0xFF);
+        if(!(response & 0x80)) {
+            return response;
+        }
+    }
+    _cs = 1;
+    _spi.write(0xFF);
+    return -1; // timeout
+}
+\r
+\r
+int SDFileSystem::_cmd58() {
+    _cs = 0;
+    int arg = 0;
     \r
-    // send a command\r
-    _spi.write(0x40 | 58);\r
-    _spi.write(arg >> 24);\r
-    _spi.write(arg >> 16);\r
-    _spi.write(arg >> 8);\r
-    _spi.write(arg >> 0);\r
-    _spi.write(0x95);\r
-\r
-    // wait for the repsonse (response[7] == 0)\r
-    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {\r
-        int response = _spi.write(0xFF);\r
-        if(!(response & 0x80)) {\r
-            int ocr = _spi.write(0xFF) << 24;\r
-            ocr |= _spi.write(0xFF) << 16;\r
-            ocr |= _spi.write(0xFF) << 8;\r
-            ocr |= _spi.write(0xFF) << 0;\r
-//            printf("OCR = 0x%08X\n", ocr);\r
-            _cs = 1;\r
-            _spi.write(0xFF);\r
-            return response;\r
-        }\r
-    }\r
-    _cs = 1;\r
-    _spi.write(0xFF);\r
-    return -1; // timeout\r
-}\r
-\r
-int SDFileSystem::_cmd8() {\r
-    _cs = 0; \r
+    // send a command
+    _spi.write(0x40 | 58);
+    _spi.write(arg >> 24);
+    _spi.write(arg >> 16);
+    _spi.write(arg >> 8);
+    _spi.write(arg >> 0);
+    _spi.write(0x95);
+\r
+    // wait for the repsonse (response[7] == 0)
+    for(int i=0; i<SD_COMMAND_TIMEOUT; i++) {
+        int response = _spi.write(0xFF);
+        if(!(response & 0x80)) {
+            int ocr = _spi.write(0xFF) << 24;
+            ocr |= _spi.write(0xFF) << 16;
+            ocr |= _spi.write(0xFF) << 8;
+            ocr |= _spi.write(0xFF) << 0;
+//            printf("OCR = 0x%08X\n", ocr);
+            _cs = 1;
+            _spi.write(0xFF);
+            return response;
+        }
+    }
+    _cs = 1;
+    _spi.write(0xFF);
+    return -1; // timeout
+}
+\r
+int SDFileSystem::_cmd8() {
+    _cs = 0;
     \r
-    // send a command\r
-    _spi.write(0x40 | 8); // CMD8\r
-    _spi.write(0x00);     // reserved\r
-    _spi.write(0x00);     // reserved\r
-    _spi.write(0x01);     // 3.3v\r
-    _spi.write(0xAA);     // check pattern\r
-    _spi.write(0x87);     // crc\r
-\r
-    // wait for the repsonse (response[7] == 0)\r
-    for(int i=0; i<SD_COMMAND_TIMEOUT * 1000; i++) {\r
-        char response[5];\r
-        response[0] = _spi.write(0xFF);\r
-        if(!(response[0] & 0x80)) {\r
-                for(int j=1; j<5; j++) {\r
-                    response[i] = _spi.write(0xFF);\r
-                }\r
-                _cs = 1;\r
-                _spi.write(0xFF);\r
-                return response[0];\r
-        }\r
-    }\r
-    _cs = 1;\r
-    _spi.write(0xFF);\r
-    return -1; // timeout\r
-}\r
-\r
-int SDFileSystem::_read(char *buffer, int length) {\r
-    _cs = 0;\r
-\r
-    // read until start byte (0xFF)\r
-    while(_spi.write(0xFF) != 0xFE);\r
-\r
-    // read data\r
-    for(int i=0; i<length; i++) {\r
-        buffer[i] = _spi.write(0xFF);\r
-    }\r
-    _spi.write(0xFF); // checksum\r
-    _spi.write(0xFF);\r
-\r
-    _cs = 1;    \r
-    _spi.write(0xFF);\r
-    return 0;\r
-}\r
-\r
-int SDFileSystem::_write(const char *buffer, int length) {\r
-    _cs = 0;\r
+    // send a command
+    _spi.write(0x40 | 8); // CMD8
+    _spi.write(0x00);     // reserved
+    _spi.write(0x00);     // reserved
+    _spi.write(0x01);     // 3.3v
+    _spi.write(0xAA);     // check pattern
+    _spi.write(0x87);     // crc
+\r
+    // wait for the repsonse (response[7] == 0)
+    for(int i=0; i<SD_COMMAND_TIMEOUT * 1000; i++) {
+        char response[5];
+        response[0] = _spi.write(0xFF);
+        if(!(response[0] & 0x80)) {
+                for(int j=1; j<5; j++) {
+                    response[i] = _spi.write(0xFF);
+                }
+                _cs = 1;
+                _spi.write(0xFF);
+                return response[0];
+        }
+    }
+    _cs = 1;
+    _spi.write(0xFF);
+    return -1; // timeout
+}
+\r
+int SDFileSystem::_read(char *buffer, int length) {
+    _cs = 0;
+\r
+    // read until start byte (0xFF)
+    while(_spi.write(0xFF) != 0xFE);
+\r
+    // read data
+    for(int i=0; i<length; i++) {
+        buffer[i] = _spi.write(0xFF);
+    }
+    _spi.write(0xFF); // checksum
+    _spi.write(0xFF);
+\r
+    _cs = 1;
+    _spi.write(0xFF);
+    return 0;
+}
+\r
+int SDFileSystem::_write(const char *buffer, int length) {
+    _cs = 0;
     \r
-    // indicate start of block\r
-    _spi.write(0xFE);\r
+    // indicate start of block
+    _spi.write(0xFE);
     \r
-    // write the data\r
-    for(int i=0; i<length; i++) {\r
-        _spi.write(buffer[i]);\r
-    }\r
+    // write the data
+    for(int i=0; i<length; i++) {
+        _spi.write(buffer[i]);
+    }
     \r
-    // write the checksum\r
-    _spi.write(0xFF); \r
-    _spi.write(0xFF);\r
-\r
-    // check the repsonse token\r
-    if((_spi.write(0xFF) & 0x1F) != 0x05) {\r
-        _cs = 1;\r
-        _spi.write(0xFF);        \r
-        return 1;\r
-    }\r
-\r
-    // wait for write to finish\r
-    while(_spi.write(0xFF) == 0);\r
-\r
-    _cs = 1; \r
-    _spi.write(0xFF);\r
-    return 0;\r
-}\r
-\r
-static int ext_bits(char *data, int msb, int lsb) {\r
-    int bits = 0;\r
-    int size = 1 + msb - lsb; \r
-    for(int i=0; i<size; i++) {\r
-        int position = lsb + i;\r
-        int byte = 15 - (position >> 3);\r
-        int bit = position & 0x7;\r
-        int value = (data[byte] >> bit) & 1;\r
-        bits |= value << i;\r
-    }\r
-    return bits;\r
-}\r
-\r
-int SDFileSystem::_sd_sectors() {\r
-\r
-    // CMD9, Response R2 (R1 byte + 16-byte block read)\r
-    if(_cmdx(9, 0) != 0) {\r
-        fprintf(stderr, "Didn't get a response from the disk\n");\r
-        return 0;\r
-    }\r
+    // write the checksum
+    _spi.write(0xFF);
+    _spi.write(0xFF);
+\r
+    // check the repsonse token
+    if((_spi.write(0xFF) & 0x1F) != 0x05) {
+        _cs = 1;
+        _spi.write(0xFF);
+        return 1;
+    }
+\r
+    // wait for write to finish
+    while(_spi.write(0xFF) == 0);
+\r
+    _cs = 1;
+    _spi.write(0xFF);
+    return 0;
+}
+\r
+static int ext_bits(char *data, int msb, int lsb) {
+    int bits = 0;
+    int size = 1 + msb - lsb;
+    for(int i=0; i<size; i++) {
+        int position = lsb + i;
+        int byte = 15 - (position >> 3);
+        int bit = position & 0x7;
+        int value = (data[byte] >> bit) & 1;
+        bits |= value << i;
+    }
+    return bits;
+}
+\r
+int SDFileSystem::_sd_sectors() {
+\r
+    // CMD9, Response R2 (R1 byte + 16-byte block read)
+    if(_cmdx(9, 0) != 0) {
+        fprintf(stderr, "Didn't get a response from the disk\n");
+        return 0;
+    }
     \r
-    char csd[16];    \r
-    if(_read(csd, 16) != 0) {\r
-        fprintf(stderr, "Couldn't read csd response from disk\n");\r
-        return 0;\r
-    }\r
-\r
-    // csd_structure : csd[127:126]\r
-    // c_size        : csd[73:62]\r
-    // c_size_mult   : csd[49:47]\r
-    // read_bl_len   : csd[83:80] - the *maximum* read block length\r
-\r
-    int csd_structure = ext_bits(csd, 127, 126);\r
-    int c_size = ext_bits(csd, 73, 62);\r
-    int c_size_mult = ext_bits(csd, 49, 47);\r
-    int read_bl_len = ext_bits(csd, 83, 80);\r
-\r
-//    printf("CSD_STRUCT = %d\n", csd_structure);\r
+    char csd[16];
+    if(_read(csd, 16) != 0) {
+        fprintf(stderr, "Couldn't read csd response from disk\n");
+        return 0;
+    }
+\r
+    // csd_structure : csd[127:126]
+    // c_size        : csd[73:62]
+    // c_size_mult   : csd[49:47]
+    // read_bl_len   : csd[83:80] - the *maximum* read block length
+\r
+    int csd_structure = ext_bits(csd, 127, 126);
+    int c_size = ext_bits(csd, 73, 62);
+    int c_size_mult = ext_bits(csd, 49, 47);
+    int read_bl_len = ext_bits(csd, 83, 80);
+\r
+//    printf("CSD_STRUCT = %d\n", csd_structure);
     \r
-    if(csd_structure != 0) {\r
-        fprintf(stderr, "This disk tastes funny! I only know about type 0 CSD structures\n");\r
-        return 0;\r
-    }\r
+    if(csd_structure != 0) {
+        fprintf(stderr, "This disk tastes funny! I only know about type 0 CSD structures\n");
+        return 0;
+    }
              \r
-    // memory capacity = BLOCKNR * BLOCK_LEN\r
-    // where\r
-    //  BLOCKNR = (C_SIZE+1) * MULT\r
-    //  MULT = 2^(C_SIZE_MULT+2) (C_SIZE_MULT < 8)\r
-    //  BLOCK_LEN = 2^READ_BL_LEN, (READ_BL_LEN < 12)         \r
+    // memory capacity = BLOCKNR * BLOCK_LEN
+    // where
+    //  BLOCKNR = (C_SIZE+1) * MULT
+    //  MULT = 2^(C_SIZE_MULT+2) (C_SIZE_MULT < 8)
+    //  BLOCK_LEN = 2^READ_BL_LEN, (READ_BL_LEN < 12)
                             \r
-    int block_len = 1 << read_bl_len;\r
-    int mult = 1 << (c_size_mult + 2);\r
-    int blocknr = (c_size + 1) * mult;\r
-    int capacity = blocknr * block_len;\r
+    int block_len = 1 << read_bl_len;
+    int mult = 1 << (c_size_mult + 2);
+    int blocknr = (c_size + 1) * mult;
+    int capacity = blocknr * block_len;
         \r
-    int blocks = capacity / 512;\r
+    int blocks = capacity / 512;
         \r
-    return blocks;\r
-}\r
+    return blocks;
+}
index 3617ffc..f58ed83 100644 (file)
@@ -1,81 +1,81 @@
-/* mbed SDFileSystem Library, for providing file access to SD cards\r
- * Copyright (c) 2008-2010, sford\r
- *\r
- * Permission is hereby granted, free of charge, to any person obtaining a copy\r
- * of this software and associated documentation files (the "Software"), to deal\r
- * in the Software without restriction, including without limitation the rights\r
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
- * copies of the Software, and to permit persons to whom the Software is\r
- * furnished to do so, subject to the following conditions:\r
- *\r
- * The above copyright notice and this permission notice shall be included in\r
- * all copies or substantial portions of the Software.\r
- *\r
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r
- * THE SOFTWARE.\r
- */\r
+/* mbed SDFileSystem Library, for providing file access to SD cards
+ * Copyright (c) 2008-2010, sford
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
 \r
-#ifndef MBED_SDFILESYSTEM_H\r
-#define MBED_SDFILESYSTEM_H\r
+#ifndef MBED_SDFILESYSTEM_H
+#define MBED_SDFILESYSTEM_H
 \r
-#include "mbed.h"\r
-#include "FATFileSystem.h"\r
+#include "mbed.h"
+#include "FATFileSystem.h"
 \r
-/** Access the filesystem on an SD Card using SPI\r
- *\r
- * @code\r
- * #include "mbed.h"\r
- * #include "SDFileSystem.h"\r
- *\r
- * SDFileSystem sd(p5, p6, p7, p12, "sd"); // mosi, miso, sclk, cs\r
- *  \r
- * int main() {\r
- *     FILE *fp = fopen("/sd/myfile.txt", "w");\r
- *     fprintf(fp, "Hello World!\n");\r
- *     fclose(fp);\r
- * }\r
- */\r
-class SDFileSystem : public FATFileSystem {\r
-public:\r
+/** Access the filesystem on an SD Card using SPI
+ *
+ * @code
+ * #include "mbed.h"
+ * #include "SDFileSystem.h"
+ *
+ * SDFileSystem sd(p5, p6, p7, p12, "sd"); // mosi, miso, sclk, cs
+ *
+ * int main() {
+ *     FILE *fp = fopen("/sd/myfile.txt", "w");
+ *     fprintf(fp, "Hello World!\n");
+ *     fclose(fp);
+ * }
+ */
+class SDFileSystem : public FATFileSystem {
+public:
 \r
-    /** Create the File System for accessing an SD Card using SPI\r
-     *\r
-     * @param mosi SPI mosi pin connected to SD Card\r
-     * @param miso SPI miso pin conencted to SD Card\r
-     * @param sclk SPI sclk pin connected to SD Card\r
-     * @param cs   DigitalOut pin used as SD Card chip select\r
-     * @param name The name used to access the virtual filesystem\r
-     */\r
-    SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name);\r
-    virtual int disk_initialize();\r
-    virtual int disk_write(const char *buffer, int block_number);\r
-    virtual int disk_read(char *buffer, int block_number);    \r
-    virtual int disk_status();\r
-    virtual int disk_sync();\r
-    virtual int disk_sectors();\r
+    /** Create the File System for accessing an SD Card using SPI
+     *
+     * @param mosi SPI mosi pin connected to SD Card
+     * @param miso SPI miso pin conencted to SD Card
+     * @param sclk SPI sclk pin connected to SD Card
+     * @param cs   DigitalOut pin used as SD Card chip select
+     * @param name The name used to access the virtual filesystem
+     */
+    SDFileSystem(PinName mosi, PinName miso, PinName sclk, PinName cs, const char* name);
+    virtual int disk_initialize();
+    virtual int disk_write(const char *buffer, int block_number);
+    virtual int disk_read(char *buffer, int block_number);
+    virtual int disk_status();
+    virtual int disk_sync();
+    virtual int disk_sectors();
 \r
-protected:\r
+protected:
 \r
-    int _cmd(int cmd, int arg);\r
-    int _cmdx(int cmd, int arg);\r
-    int _cmd8();\r
-    int _cmd58();\r
-    int initialise_card();\r
-    int initialise_card_v1();\r
-    int initialise_card_v2();\r
+    int _cmd(int cmd, int arg);
+    int _cmdx(int cmd, int arg);
+    int _cmd8();
+    int _cmd58();
+    int initialise_card();
+    int initialise_card_v1();
+    int initialise_card_v2();
     \r
-    int _read(char *buffer, int length);\r
-    int _write(const char *buffer, int length);\r
-    int _sd_sectors();\r
-    int _sectors;\r
+    int _read(char *buffer, int length);
+    int _write(const char *buffer, int length);
+    int _sd_sectors();
+    int _sectors;
     \r
-    SPI _spi;\r
-    DigitalOut _cs;     \r
-};\r
+    SPI _spi;
+    DigitalOut _cs;
+};
 \r
-#endif\r
+#endif
index 058d9ce..3d85848 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 
@@ -47,14 +47,14 @@ void Config::set_string( string setting, string value ){
     this->kernel->call_event(ON_CONFIG_RELOAD);
 }
 
-void Config::get_module_list(vector<uint16_t>* list, uint16_t family){ 
+void Config::get_module_list(vector<uint16_t>* list, uint16_t family){
     for( unsigned int i=1; i<this->config_cache.size(); i++){
-        ConfigValue* value = this->config_cache.at(i); 
+        ConfigValue* value = this->config_cache.at(i);
         //if( value->check_sums.size() == 3 && value->check_sums.at(2) == 29545 && value->check_sums.at(0) == family ){
         if( value->check_sums[2] == 29545 && value->check_sums[0] == family ){
-            // We found a module enable for this family, add it's number 
+            // We found a module enable for this family, add it's number
             list->push_back(value->check_sums[1]);
-        } 
+        }
     }
 }
 
@@ -88,28 +88,28 @@ void Config::config_cache_clear(){
 
 
 ConfigValue* Config::value(uint16_t check_sum_a, uint16_t check_sum_b, uint16_t check_sum_c ){
-    uint16_t check_sums[3]; 
-    check_sums[0] = check_sum_a; 
+    uint16_t check_sums[3];
+    check_sums[0] = check_sum_a;
     check_sums[1] = check_sum_b;
     check_sums[2] = check_sum_c;
     return this->value(check_sums);
-}    
+}
 
 ConfigValue* Config::value(uint16_t check_sum_a, uint16_t check_sum_b){
-    uint16_t check_sums[3]; 
-    check_sums[0] = check_sum_a; 
+    uint16_t check_sums[3];
+    check_sums[0] = check_sum_a;
     check_sums[1] = check_sum_b;
     check_sums[2] = 0x0000;
     return this->value(check_sums);
-}    
+}
 
 ConfigValue* Config::value(uint16_t check_sum){
-    uint16_t check_sums[3]; 
-    check_sums[0] = check_sum; 
+    uint16_t check_sums[3];
+    check_sums[0] = check_sum;
     check_sums[1] = 0x0000;
     check_sums[2] = 0x0000;
     return this->value(check_sums);
-}    
+}
     
 // Get a value from the configuration as a string
 // Because we don't like to waste space in Flash with lengthy config parameter names, we take a checksum instead so that the name does not have to be stored
@@ -120,18 +120,18 @@ ConfigValue* Config::value(uint16_t check_sums[]){
     if( !cache_preloaded ){ this->config_cache_load(); }
      
     for( unsigned int i=1; i<this->config_cache.size(); i++){
-        // If this line matches the checksum 
+        // If this line matches the checksum
         bool match = true;
         unsigned int counter = 0;
         while(check_sums[counter] != 0x0000 && counter <= 2 ){
              if(this->config_cache[i]->check_sums[counter] != check_sums[counter] ){
                 match = false;
-                break; 
+                break;
             }
             counter++;
-        } 
-        if( match == false ){ 
-            continue; 
+        }
+        if( match == false ){
+            continue;
         }
         result = this->config_cache[i];
         break;
index 282bad2..05c9b3a 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef CONFIG_H
index 9b1bd84..5b55a0d 100644 (file)
@@ -2,7 +2,7 @@
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef CONFIGCACHE_H
@@ -17,33 +17,33 @@ class ConfigCache : public std::vector<ConfigValue*> {
     public:
         ConfigCache(){}
         
-        // If we find an existing value, replace it, otherwise, push it at the back of the list 
+        // If we find an existing value, replace it, otherwise, push it at the back of the list
         void replace_or_push_back(ConfigValue* new_value){
        
-           bool value_exists = false; 
-            // For each already existing element 
+           bool value_exists = false;
+            // For each already existing element
             for( unsigned int i=1; i<this->size(); i++){
-                // If this configvalue matches the checksum 
+                // If this configvalue matches the checksum
                 bool match = true;
                 unsigned int counter = 0;
                 while( counter < 3 && new_value->check_sums[counter] != 0x0000 ){
                     if(this->at(i)->check_sums[counter] != new_value->check_sums[counter]  ){
                         match = false;
-                        break; 
+                        break;
                     }
                     counter++;
                 }
                 if( match == false ){ continue; }
                 value_exists = true;
                 
-                // Replace with the provided value 
+                // Replace with the provided value
                 delete this->at(i);
                 this->at(i) = new_value;
                 break;
             }
 
             // Value does not already exists, add to the list
-            if( value_exists == false ){ 
+            if( value_exists == false ){
                 this->push_back(new_value);
             }
 
index 1d4cbe5..0e2e017 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef CONFIGSOURCE_H
index 7e77f17..3c67ebb 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef FILECONFIGSOURCE_H
index 35a521a..cbfca21 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef CONFIGVALUE_H
@@ -26,9 +26,9 @@ class ConfigValue{
         ConfigValue(){
             this->found = false;
             this->default_set = false;
-            this->check_sums[0] = 0x0000; 
-            this->check_sums[1] = 0x0000; 
-            this->check_sums[2] = 0x0000; 
+            this->check_sums[0] = 0x0000;
+            this->check_sums[1] = 0x0000;
+            this->check_sums[2] = 0x0000;
         };
 
         ConfigValue* required(){
@@ -47,7 +47,7 @@ class ConfigValue{
                 if( result == 0.0 && this->value.find_first_not_of("0.") != string::npos ){
                     error("config setting with value '%s' and checksums[%u,%u,%u] is not a valid number, please see http://smoothieware.org/configuring-smoothie\r\n", this->value.c_str(), this->check_sums[0], this->check_sums[1], this->check_sums[2] );
                 }
-                return result; 
+                return result;
             }
            
         }
@@ -56,7 +56,7 @@ class ConfigValue{
             //if( this->found == false && this->default_set == true ){
             //    return this->default_string;
             //}else{
-                return this->value; 
+                return this->value;
             //}
         }
 
@@ -68,7 +68,7 @@ class ConfigValue{
                     return true;
                 }else{
                     return false;
-                } 
+                }
             }
         }
 
@@ -81,7 +81,7 @@ class ConfigValue{
         ConfigValue* by_default(double val){
             this->default_set = true;
             this->default_double = val;
-            return this; 
+            return this;
         }
 
         ConfigValue* by_default(std::string val){
@@ -92,15 +92,15 @@ class ConfigValue{
         }
 
         bool has_characters( string mask ){
-            if( this->value.find_first_of(mask) != string::npos ){ return true; }else{ return false; } 
+            if( this->value.find_first_of(mask) != string::npos ){ return true; }else{ return false; }
         }
 
         bool is_inverted(){
             return this->has_characters(string("!"));
         }
 
-        double default_double; 
-        uint16_t check_sums[3]; 
+        double default_double;
+        uint16_t check_sums[3];
         string value;
         bool found;
         bool default_set;
index 1ffb5f4..a70763e 100644 (file)
@@ -12,7 +12,7 @@ class Digipot{
         Digipot(){ }
       
         char current_to_wiper( double current ){
-            return char(ceil(double((113.33*current)))); 
+            return char(ceil(double((113.33*current))));
         }
 
         void i2c_send( char first, char second, char third ){
@@ -20,25 +20,25 @@ class Digipot{
             this->i2c->write(first);
             this->i2c->write(second);
             this->i2c->write(third);
-            this->i2c->stop(); 
+            this->i2c->stop();
         }
 
-        void set_current( int channel, double current ){ 
+        void set_current( int channel, double current ){
 
             current = min( max( current, 0.0L ), 2.0L );
 
-            // I2C com 
-            this->i2c = new mbed::I2C(p9, p10); 
+            // I2C com
+            this->i2c = new mbed::I2C(p9, p10);
            
-            // Initial setup 
-            this->i2c_send( 0x58, 0x40, 0xff );   
-            this->i2c_send( 0x58, 0xA0, 0xff );   
+            // Initial setup
+            this->i2c_send( 0x58, 0x40, 0xff );
+            this->i2c_send( 0x58, 0xA0, 0xff );
 
             // Set actual wiper value
-            char adresses[4] = { 0x00, 0x10, 0x60, 0x70 };  
-            this->i2c_send( 0x58, adresses[channel], this->current_to_wiper(current) );   
+            char adresses[4] = { 0x00, 0x10, 0x60, 0x70 };
+            this->i2c_send( 0x58, adresses[channel], this->current_to_wiper(current) );
 
-        } 
+        }
 
         mbed::I2C* i2c;
 };
index 33de796..238a21c 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "libs/Kernel.h"
 
 
 // List of callback functions, ordered as their corresponding events
-const ModuleCallback kernel_callback_functions[NUMBER_OF_DEFINED_EVENTS] = { 
-        &Module::on_main_loop, 
+const ModuleCallback kernel_callback_functions[NUMBER_OF_DEFINED_EVENTS] = {
+        &Module::on_main_loop,
         &Module::on_console_line_received,
-        &Module::on_gcode_received, 
+        &Module::on_gcode_received,
         &Module::on_stepper_wake_up,
         &Module::on_gcode_execute,
         &Module::on_speed_change,
@@ -49,13 +49,13 @@ const ModuleCallback kernel_callback_functions[NUMBER_OF_DEFINED_EVENTS] = {
 Kernel::Kernel(){
 
     // Value init for the arrays
-    for( uint8_t i=0; i<NUMBER_OF_DEFINED_EVENTS; i++ ){ 
+    for( uint8_t i=0; i<NUMBER_OF_DEFINED_EVENTS; i++ ){
         for( uint8_t index=0; index<32; index++ ){
-            this->hooks[i][index] = NULL; 
-        } 
+            this->hooks[i][index] = NULL;
+        }
     }
 
-    // Config first, because we need the baud_rate setting before we start serial 
+    // Config first, because we need the baud_rate setting before we start serial
     this->config         = new Config();
 
     // Serial second, because the other modules might want to say something
@@ -84,33 +84,33 @@ Kernel::Kernel(){
     this->add_module( this->config );
     this->add_module( this->serial );
 
-    // HAL stuff 
+    // HAL stuff
     this->slow_ticker          = new SlowTicker();
     this->step_ticker          = new StepTicker();
     this->adc                  = new Adc();
     this->digipot              = new Digipot();
 
-    // LPC17xx-specific 
+    // LPC17xx-specific
     NVIC_SetPriorityGrouping(0);
-    NVIC_SetPriority(TIMER0_IRQn, 2); 
-    NVIC_SetPriority(TIMER1_IRQn, 1); 
-    NVIC_SetPriority(TIMER2_IRQn, 3); 
+    NVIC_SetPriority(TIMER0_IRQn, 2);
+    NVIC_SetPriority(TIMER1_IRQn, 1);
+    NVIC_SetPriority(TIMER2_IRQn, 3);
 
     // Set other priorities lower than the timers
-    NVIC_SetPriority(ADC_IRQn, 4); 
-    NVIC_SetPriority(USB_IRQn, 4); 
+    NVIC_SetPriority(ADC_IRQn, 4);
+    NVIC_SetPriority(USB_IRQn, 4);
  
-    // If MRI is enabled 
+    // If MRI is enabled
     if( MRI_ENABLE ){
-        if( NVIC_GetPriority(UART0_IRQn) > 0 ){ NVIC_SetPriority(UART0_IRQn, 4); } 
-        if( NVIC_GetPriority(UART1_IRQn) > 0 ){ NVIC_SetPriority(UART1_IRQn, 4); } 
-        if( NVIC_GetPriority(UART2_IRQn) > 0 ){ NVIC_SetPriority(UART2_IRQn, 4); } 
-        if( NVIC_GetPriority(UART3_IRQn) > 0 ){ NVIC_SetPriority(UART3_IRQn, 4); } 
+        if( NVIC_GetPriority(UART0_IRQn) > 0 ){ NVIC_SetPriority(UART0_IRQn, 4); }
+        if( NVIC_GetPriority(UART1_IRQn) > 0 ){ NVIC_SetPriority(UART1_IRQn, 4); }
+        if( NVIC_GetPriority(UART2_IRQn) > 0 ){ NVIC_SetPriority(UART2_IRQn, 4); }
+        if( NVIC_GetPriority(UART3_IRQn) > 0 ){ NVIC_SetPriority(UART3_IRQn, 4); }
     }else{
-        NVIC_SetPriority(UART0_IRQn, 4); 
-        NVIC_SetPriority(UART1_IRQn, 4); 
-        NVIC_SetPriority(UART2_IRQn, 4); 
-        NVIC_SetPriority(UART3_IRQn, 4); 
+        NVIC_SetPriority(UART0_IRQn, 4);
+        NVIC_SetPriority(UART1_IRQn, 4);
+        NVIC_SetPriority(UART2_IRQn, 4);
+        NVIC_SetPriority(UART3_IRQn, 4);
     }
 
     // Configure the step ticker
@@ -119,7 +119,7 @@ Kernel::Kernel(){
     this->step_ticker->set_reset_delay( microseconds_per_step_pulse / 1000000L );
     this->step_ticker->set_frequency(   base_stepping_frequency );
 
-    // Core modules 
+    // Core modules
     this->add_module( this->gcode_dispatch = new GcodeDispatch() );
     this->add_module( this->robot          = new Robot()         );
     this->add_module( this->stepper        = new Stepper()       );
@@ -137,7 +137,7 @@ void Kernel::add_module(Module* module){
 }
 
 void Kernel::register_for_event(unsigned int id_event, Module* module){
-    uint8_t current_id = 0; 
+    uint8_t current_id = 0;
     Module* current = this->hooks[id_event][0];
     while(current != NULL ){
         if( current == module ){ return; }
index 1fffc7c..6497f9c 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef KERNEL_H
@@ -53,7 +53,7 @@ class Kernel {
 
         // These modules are aviable to all other modules
         SerialConsole*    serial;
-        StreamOutputPool* streams; 
+        StreamOutputPool* streams;
 
         GcodeDispatch*    gcode_dispatch;
         Robot*            robot;
index 85b174c..0c26f9c 100644 (file)
-/******************************************************************************\r
- * @file:    LPC17xx.h\r
- * @purpose: CMSIS Cortex-M3 Core Peripheral Access Layer Header File for \r
- *           NXP LPC17xx Device Series \r
- * @version: V1.04\r
- * @date:    2. July 2009\r
- *----------------------------------------------------------------------------\r
- *\r
- * Copyright (C) 2008 ARM Limited. All rights reserved.\r
- *\r
- * ARM Limited (ARM) is supplying this software for use with Cortex-M3 \r
- * processor based microcontrollers.  This file can be freely distributed \r
- * within development tools that are supporting such ARM based processors. \r
- *\r
- * THIS SOFTWARE IS PROVIDED "AS IS".  NO WARRANTIES, WHETHER EXPRESS, IMPLIED\r
- * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF\r
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.\r
- * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR\r
- * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.\r
- *\r
- ******************************************************************************/\r
-\r
-\r
-#ifndef __LPC17xx_H__\r
-#define __LPC17xx_H__\r
-\r
-/*\r
- * ==========================================================================\r
- * ---------- Interrupt Number Definition -----------------------------------\r
- * ==========================================================================\r
- */\r
-\r
-typedef enum IRQn\r
-{\r
-/******  Cortex-M3 Processor Exceptions Numbers ***************************************************/\r
-  NonMaskableInt_IRQn           = -14,      /*!< 2 Non Maskable Interrupt                         */\r
-  MemoryManagement_IRQn         = -12,      /*!< 4 Cortex-M3 Memory Management Interrupt          */\r
-  BusFault_IRQn                 = -11,      /*!< 5 Cortex-M3 Bus Fault Interrupt                  */\r
-  UsageFault_IRQn               = -10,      /*!< 6 Cortex-M3 Usage Fault Interrupt                */\r
-  SVCall_IRQn                   = -5,       /*!< 11 Cortex-M3 SV Call Interrupt                   */\r
-  DebugMonitor_IRQn             = -4,       /*!< 12 Cortex-M3 Debug Monitor Interrupt             */\r
-  PendSV_IRQn                   = -2,       /*!< 14 Cortex-M3 Pend SV Interrupt                   */\r
-  SysTick_IRQn                  = -1,       /*!< 15 Cortex-M3 System Tick Interrupt               */\r
-\r
-/******  LPC17xx Specific Interrupt Numbers *******************************************************/\r
-  WDT_IRQn                      = 0,        /*!< Watchdog Timer Interrupt                         */\r
-  TIMER0_IRQn                   = 1,        /*!< Timer0 Interrupt                                 */\r
-  TIMER1_IRQn                   = 2,        /*!< Timer1 Interrupt                                 */\r
-  TIMER2_IRQn                   = 3,        /*!< Timer2 Interrupt                                 */\r
-  TIMER3_IRQn                   = 4,        /*!< Timer3 Interrupt                                 */\r
-  UART0_IRQn                    = 5,        /*!< UART0 Interrupt                                  */\r
-  UART1_IRQn                    = 6,        /*!< UART1 Interrupt                                  */\r
-  UART2_IRQn                    = 7,        /*!< UART2 Interrupt                                  */\r
-  UART3_IRQn                    = 8,        /*!< UART3 Interrupt                                  */\r
-  PWM1_IRQn                     = 9,        /*!< PWM1 Interrupt                                   */\r
-  I2C0_IRQn                     = 10,       /*!< I2C0 Interrupt                                   */\r
-  I2C1_IRQn                     = 11,       /*!< I2C1 Interrupt                                   */\r
-  I2C2_IRQn                     = 12,       /*!< I2C2 Interrupt                                   */\r
-  SPI_IRQn                      = 13,       /*!< SPI Interrupt                                    */\r
-  SSP0_IRQn                     = 14,       /*!< SSP0 Interrupt                                   */\r
-  SSP1_IRQn                     = 15,       /*!< SSP1 Interrupt                                   */\r
-  PLL0_IRQn                     = 16,       /*!< PLL0 Lock (Main PLL) Interrupt                   */\r
-  RTC_IRQn                      = 17,       /*!< Real Time Clock Interrupt                        */\r
-  EINT0_IRQn                    = 18,       /*!< External Interrupt 0 Interrupt                   */\r
-  EINT1_IRQn                    = 19,       /*!< External Interrupt 1 Interrupt                   */\r
-  EINT2_IRQn                    = 20,       /*!< External Interrupt 2 Interrupt                   */\r
-  EINT3_IRQn                    = 21,       /*!< External Interrupt 3 Interrupt                   */\r
-  ADC_IRQn                      = 22,       /*!< A/D Converter Interrupt                          */\r
-  BOD_IRQn                      = 23,       /*!< Brown-Out Detect Interrupt                       */\r
-  USB_IRQn                      = 24,       /*!< USB Interrupt                                    */\r
-  CAN_IRQn                      = 25,       /*!< CAN Interrupt                                    */\r
-  DMA_IRQn                      = 26,       /*!< General Purpose DMA Interrupt                    */\r
-  I2S_IRQn                      = 27,       /*!< I2S Interrupt                                    */\r
-  ENET_IRQn                     = 28,       /*!< Ethernet Interrupt                               */\r
-  RIT_IRQn                      = 29,       /*!< Repetitive Interrupt Timer Interrupt             */\r
-  MCPWM_IRQn                    = 30,       /*!< Motor Control PWM Interrupt                      */\r
-  QEI_IRQn                      = 31,       /*!< Quadrature Encoder Interface Interrupt           */\r
-  PLL1_IRQn                     = 32,       /*!< PLL1 Lock (USB PLL) Interrupt                    */\r
-} IRQn_Type;\r
-\r
-\r
-/*\r
- * ==========================================================================\r
- * ----------- Processor and Core Peripheral Section ------------------------\r
- * ==========================================================================\r
- */\r
-\r
-/* Configuration of the Cortex-M3 Processor and Core Peripherals */\r
-#define __MPU_PRESENT             1         /*!< MPU present or not                               */\r
-#define __NVIC_PRIO_BITS          5         /*!< Number of Bits used for Priority Levels          */\r
-#define __Vendor_SysTickConfig    0         /*!< Set to 1 if different SysTick Config is used     */\r
-\r
-\r
-#include "score_cm3.h"                       /* Cortex-M3 processor and core peripherals           */\r
-//#include "system_LPC17xx.h"                 /* System Header                                      */\r
-\r
-\r
-/******************************************************************************/\r
-/*                Device Specific Peripheral registers structures             */\r
-/******************************************************************************/\r
-\r
-#if defined ( __CC_ARM   )\r
-#pragma anon_unions\r
-#endif\r
-\r
-/*------------- System Control (SC) ------------------------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t FLASHCFG;               /* Flash Accelerator Module           */\r
-       uint32_t RESERVED0[31];\r
-  __IO uint32_t PLL0CON;                /* Clocking and Power Control         */\r
-  __IO uint32_t PLL0CFG;\r
-  __I  uint32_t PLL0STAT;\r
-  __O  uint32_t PLL0FEED;\r
-       uint32_t RESERVED1[4];\r
-  __IO uint32_t PLL1CON;\r
-  __IO uint32_t PLL1CFG;\r
-  __I  uint32_t PLL1STAT;\r
-  __O  uint32_t PLL1FEED;\r
-       uint32_t RESERVED2[4];\r
-  __IO uint32_t PCON;\r
-  __IO uint32_t PCONP;\r
-       uint32_t RESERVED3[15];\r
-  __IO uint32_t CCLKCFG;\r
-  __IO uint32_t USBCLKCFG;\r
-  __IO uint32_t CLKSRCSEL;\r
-       uint32_t RESERVED4[12];\r
-  __IO uint32_t EXTINT;                 /* External Interrupts                */\r
-       uint32_t RESERVED5;\r
-  __IO uint32_t EXTMODE;\r
-  __IO uint32_t EXTPOLAR;\r
-       uint32_t RESERVED6[12];\r
-  __IO uint32_t RSID;                   /* Reset                              */\r
-       uint32_t RESERVED7[7];\r
-  __IO uint32_t SCS;                    /* Syscon Miscellaneous Registers     */\r
-  __IO uint32_t IRCTRIM;                /* Clock Dividers                     */\r
-  __IO uint32_t PCLKSEL0;\r
-  __IO uint32_t PCLKSEL1;\r
-       uint32_t RESERVED8[4];\r
-  __IO uint32_t USBIntSt;               /* USB Device/OTG Interrupt Register  */\r
-       uint32_t RESERVED9;\r
-  __IO uint32_t CLKOUTCFG;              /* Clock Output Configuration         */\r
- } LPC_SC_TypeDef;\r
-\r
-/*------------- Pin Connect Block (PINCON) -----------------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t PINSEL0;\r
-  __IO uint32_t PINSEL1;\r
-  __IO uint32_t PINSEL2;\r
-  __IO uint32_t PINSEL3;\r
-  __IO uint32_t PINSEL4;\r
-  __IO uint32_t PINSEL5;\r
-  __IO uint32_t PINSEL6;\r
-  __IO uint32_t PINSEL7;\r
-  __IO uint32_t PINSEL8;\r
-  __IO uint32_t PINSEL9;\r
-  __IO uint32_t PINSEL10;\r
-       uint32_t RESERVED0[5];\r
-  __IO uint32_t PINMODE0;\r
-  __IO uint32_t PINMODE1;\r
-  __IO uint32_t PINMODE2;\r
-  __IO uint32_t PINMODE3;\r
-  __IO uint32_t PINMODE4;\r
-  __IO uint32_t PINMODE5;\r
-  __IO uint32_t PINMODE6;\r
-  __IO uint32_t PINMODE7;\r
-  __IO uint32_t PINMODE8;\r
-  __IO uint32_t PINMODE9;\r
-  __IO uint32_t PINMODE_OD0;\r
-  __IO uint32_t PINMODE_OD1;\r
-  __IO uint32_t PINMODE_OD2;\r
-  __IO uint32_t PINMODE_OD3;\r
-  __IO uint32_t PINMODE_OD4;\r
-  __IO uint32_t I2CPADCFG;\r
-} LPC_PINCON_TypeDef;\r
-\r
-/*------------- General Purpose Input/Output (GPIO) --------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t FIODIR;\r
-       uint32_t RESERVED0[3];\r
-  __IO uint32_t FIOMASK;\r
-  __IO uint32_t FIOPIN;\r
-  __IO uint32_t FIOSET;\r
-  __O  uint32_t FIOCLR;\r
-} LPC_GPIO_TypeDef;\r
-\r
-typedef struct\r
-{\r
-  __I  uint32_t IntStatus;\r
-  __I  uint32_t IO0IntStatR;\r
-  __I  uint32_t IO0IntStatF;\r
-  __O  uint32_t IO0IntClr;\r
-  __IO uint32_t IO0IntEnR;\r
-  __IO uint32_t IO0IntEnF;\r
-       uint32_t RESERVED0[3];\r
-  __I  uint32_t IO2IntStatR;\r
-  __I  uint32_t IO2IntStatF;\r
-  __O  uint32_t IO2IntClr;\r
-  __IO uint32_t IO2IntEnR;\r
-  __IO uint32_t IO2IntEnF;\r
-} LPC_GPIOINT_TypeDef;\r
-\r
-/*------------- Timer (TIM) --------------------------------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t IR;\r
-  __IO uint32_t TCR;\r
-  __IO uint32_t TC;\r
-  __IO uint32_t PR;\r
-  __IO uint32_t PC;\r
-  __IO uint32_t MCR;\r
-  __IO uint32_t MR0;\r
-  __IO uint32_t MR1;\r
-  __IO uint32_t MR2;\r
-  __IO uint32_t MR3;\r
-  __IO uint32_t CCR;\r
-  __I  uint32_t CR0;\r
-  __I  uint32_t CR1;\r
-       uint32_t RESERVED0[2];\r
-  __IO uint32_t EMR;\r
-       uint32_t RESERVED1[12];\r
-  __IO uint32_t CTCR;\r
-} LPC_TIM_TypeDef;\r
-\r
-/*------------- Pulse-Width Modulation (PWM) ---------------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t IR;\r
-  __IO uint32_t TCR;\r
-  __IO uint32_t TC;\r
-  __IO uint32_t PR;\r
-  __IO uint32_t PC;\r
-  __IO uint32_t MCR;\r
-  __IO uint32_t MR0;\r
-  __IO uint32_t MR1;\r
-  __IO uint32_t MR2;\r
-  __IO uint32_t MR3;\r
-  __IO uint32_t CCR;\r
-  __I  uint32_t CR0;\r
-  __I  uint32_t CR1;\r
-  __I  uint32_t CR2;\r
-  __I  uint32_t CR3;\r
-       uint32_t RESERVED0;\r
-  __IO uint32_t MR4;\r
-  __IO uint32_t MR5;\r
-  __IO uint32_t MR6;\r
-  __IO uint32_t PCR;\r
-  __IO uint32_t LER;\r
-       uint32_t RESERVED1[7];\r
-  __IO uint32_t CTCR;\r
-} LPC_PWM_TypeDef;\r
-\r
-/*------------- Universal Asynchronous Receiver Transmitter (UART) -----------*/\r
-typedef struct\r
-{\r
-  union {\r
-  __I  uint8_t  RBR;\r
-  __O  uint8_t  THR;\r
-  __IO uint8_t  DLL;\r
-       uint32_t RESERVED0;\r
-  };\r
-  union {\r
-  __IO uint8_t  DLM;\r
-  __IO uint32_t IER;\r
-  };\r
-  union {\r
-  __I  uint32_t IIR;\r
-  __O  uint8_t  FCR;\r
-  };\r
-  __IO uint8_t  LCR;\r
-       uint8_t  RESERVED1[7];\r
-  __I  uint8_t  LSR;\r
-       uint8_t  RESERVED2[7];\r
-  __IO uint8_t  SCR;\r
-       uint8_t  RESERVED3[3];\r
-  __IO uint32_t ACR;\r
-  __IO uint8_t  ICR;\r
-       uint8_t  RESERVED4[3];\r
-  __IO uint8_t  FDR;\r
-       uint8_t  RESERVED5[7];\r
-  __IO uint8_t  TER;\r
-       uint8_t  RESERVED6[39];\r
-  __I  uint8_t  FIFOLVL;\r
-} LPC_UART_TypeDef;\r
-\r
-typedef struct\r
-{\r
-  union {\r
-  __I  uint8_t  RBR;\r
-  __O  uint8_t  THR;\r
-  __IO uint8_t  DLL;\r
-       uint32_t RESERVED0;\r
-  };\r
-  union {\r
-  __IO uint8_t  DLM;\r
-  __IO uint32_t IER;\r
-  };\r
-  union {\r
-  __I  uint32_t IIR;\r
-  __O  uint8_t  FCR;\r
-  };\r
-  __IO uint8_t  LCR;\r
-       uint8_t  RESERVED1[7];\r
-  __I  uint8_t  LSR;\r
-       uint8_t  RESERVED2[7];\r
-  __IO uint8_t  SCR;\r
-       uint8_t  RESERVED3[3];\r
-  __IO uint32_t ACR;\r
-  __IO uint8_t  ICR;\r
-       uint8_t  RESERVED4[3];\r
-  __IO uint8_t  FDR;\r
-       uint8_t  RESERVED5[7];\r
-  __IO uint8_t  TER;\r
-       uint8_t  RESERVED6[39];\r
-  __I  uint8_t  FIFOLVL;\r
-       uint8_t  RESERVED7[363];\r
-  __IO uint32_t DMAREQSEL;\r
-} LPC_UART0_TypeDef;\r
-\r
-typedef struct\r
-{\r
-  union {\r
-  __I  uint8_t  RBR;\r
-  __O  uint8_t  THR;\r
-  __IO uint8_t  DLL;\r
-       uint32_t RESERVED0;\r
-  };\r
-  union {\r
-  __IO uint8_t  DLM;\r
-  __IO uint32_t IER;\r
-  };\r
-  union {\r
-  __I  uint32_t IIR;\r
-  __O  uint8_t  FCR;\r
-  };\r
-  __IO uint8_t  LCR;\r
-       uint8_t  RESERVED1[3];\r
-  __IO uint8_t  MCR;\r
-       uint8_t  RESERVED2[3];\r
-  __I  uint8_t  LSR;\r
-       uint8_t  RESERVED3[3];\r
-  __I  uint8_t  MSR;\r
-       uint8_t  RESERVED4[3];\r
-  __IO uint8_t  SCR;\r
-       uint8_t  RESERVED5[3];\r
-  __IO uint32_t ACR;\r
-       uint32_t RESERVED6;\r
-  __IO uint32_t FDR;\r
-       uint32_t RESERVED7;\r
-  __IO uint8_t  TER;\r
-       uint8_t  RESERVED8[27];\r
-  __IO uint8_t  RS485CTRL;\r
-       uint8_t  RESERVED9[3];\r
-  __IO uint8_t  ADRMATCH;\r
-       uint8_t  RESERVED10[3];\r
-  __IO uint8_t  RS485DLY;\r
-       uint8_t  RESERVED11[3];\r
-  __I  uint8_t  FIFOLVL;\r
-} LPC_UART1_TypeDef;\r
-\r
-/*------------- Serial Peripheral Interface (SPI) ----------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t SPCR;\r
-  __I  uint32_t SPSR;\r
-  __IO uint32_t SPDR;\r
-  __IO uint32_t SPCCR;\r
-       uint32_t RESERVED0[3];\r
-  __IO uint32_t SPINT;\r
-} LPC_SPI_TypeDef;\r
-\r
-/*------------- Synchronous Serial Communication (SSP) -----------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t CR0;\r
-  __IO uint32_t CR1;\r
-  __IO uint32_t DR;\r
-  __I  uint32_t SR;\r
-  __IO uint32_t CPSR;\r
-  __IO uint32_t IMSC;\r
-  __IO uint32_t RIS;\r
-  __IO uint32_t MIS;\r
-  __IO uint32_t ICR;\r
-  __IO uint32_t DMACR;\r
-} LPC_SSP_TypeDef;\r
-\r
-/*------------- Inter-Integrated Circuit (I2C) -------------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t I2CONSET;\r
-  __I  uint32_t I2STAT;\r
-  __IO uint32_t I2DAT;\r
-  __IO uint32_t I2ADR0;\r
-  __IO uint32_t I2SCLH;\r
-  __IO uint32_t I2SCLL;\r
-  __O  uint32_t I2CONCLR;\r
-  __IO uint32_t MMCTRL;\r
-  __IO uint32_t I2ADR1;\r
-  __IO uint32_t I2ADR2;\r
-  __IO uint32_t I2ADR3;\r
-  __I  uint32_t I2DATA_BUFFER;\r
-  __IO uint32_t I2MASK0;\r
-  __IO uint32_t I2MASK1;\r
-  __IO uint32_t I2MASK2;\r
-  __IO uint32_t I2MASK3;\r
-} LPC_I2C_TypeDef;\r
-\r
-/*------------- Inter IC Sound (I2S) -----------------------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t I2SDAO;\r
-  __IO uint32_t I2SDAI;\r
-  __O  uint32_t I2STXFIFO;\r
-  __I  uint32_t I2SRXFIFO;\r
-  __I  uint32_t I2SSTATE;\r
-  __IO uint32_t I2SDMA1;\r
-  __IO uint32_t I2SDMA2;\r
-  __IO uint32_t I2SIRQ;\r
-  __IO uint32_t I2STXRATE;\r
-  __IO uint32_t I2SRXRATE;\r
-  __IO uint32_t I2STXBITRATE;\r
-  __IO uint32_t I2SRXBITRATE;\r
-  __IO uint32_t I2STXMODE;\r
-  __IO uint32_t I2SRXMODE;\r
-} LPC_I2S_TypeDef;\r
-\r
-/*------------- Repetitive Interrupt Timer (RIT) -----------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t RICOMPVAL;\r
-  __IO uint32_t RIMASK;\r
-  __IO uint8_t  RICTRL;\r
-       uint8_t  RESERVED0[3];\r
-  __IO uint32_t RICOUNTER;\r
-} LPC_RIT_TypeDef;\r
-\r
-/*------------- Real-Time Clock (RTC) ----------------------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint8_t  ILR;\r
-       uint8_t  RESERVED0[7];\r
-  __IO uint8_t  CCR;\r
-       uint8_t  RESERVED1[3];\r
-  __IO uint8_t  CIIR;\r
-       uint8_t  RESERVED2[3];\r
-  __IO uint8_t  AMR;\r
-       uint8_t  RESERVED3[3];\r
-  __I  uint32_t CTIME0;\r
-  __I  uint32_t CTIME1;\r
-  __I  uint32_t CTIME2;\r
-  __IO uint8_t  SEC;\r
-       uint8_t  RESERVED4[3];\r
-  __IO uint8_t  MIN;\r
-       uint8_t  RESERVED5[3];\r
-  __IO uint8_t  HOUR;\r
-       uint8_t  RESERVED6[3];\r
-  __IO uint8_t  DOM;\r
-       uint8_t  RESERVED7[3];\r
-  __IO uint8_t  DOW;\r
-       uint8_t  RESERVED8[3];\r
-  __IO uint16_t DOY;\r
-       uint16_t RESERVED9;\r
-  __IO uint8_t  MONTH;\r
-       uint8_t  RESERVED10[3];\r
-  __IO uint16_t YEAR;\r
-       uint16_t RESERVED11;\r
-  __IO uint32_t CALIBRATION;\r
-  __IO uint32_t GPREG0;\r
-  __IO uint32_t GPREG1;\r
-  __IO uint32_t GPREG2;\r
-  __IO uint32_t GPREG3;\r
-  __IO uint32_t GPREG4;\r
-  __IO uint8_t  RTC_AUXEN;\r
-       uint8_t  RESERVED12[3];\r
-  __IO uint8_t  RTC_AUX;\r
-       uint8_t  RESERVED13[3];\r
-  __IO uint8_t  ALSEC;\r
-       uint8_t  RESERVED14[3];\r
-  __IO uint8_t  ALMIN;\r
-       uint8_t  RESERVED15[3];\r
-  __IO uint8_t  ALHOUR;\r
-       uint8_t  RESERVED16[3];\r
-  __IO uint8_t  ALDOM;\r
-       uint8_t  RESERVED17[3];\r
-  __IO uint8_t  ALDOW;\r
-       uint8_t  RESERVED18[3];\r
-  __IO uint16_t ALDOY;\r
-       uint16_t RESERVED19;\r
-  __IO uint8_t  ALMON;\r
-       uint8_t  RESERVED20[3];\r
-  __IO uint16_t ALYEAR;\r
-       uint16_t RESERVED21;\r
-} LPC_RTC_TypeDef;\r
-\r
-/*------------- Watchdog Timer (WDT) -----------------------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint8_t  WDMOD;\r
-       uint8_t  RESERVED0[3];\r
-  __IO uint32_t WDTC;\r
-  __O  uint8_t  WDFEED;\r
-       uint8_t  RESERVED1[3];\r
-  __I  uint32_t WDTV;\r
-  __IO uint32_t WDCLKSEL;\r
-} LPC_WDT_TypeDef;\r
-\r
-/*------------- Analog-to-Digital Converter (ADC) ----------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t ADCR;\r
-  __IO uint32_t ADGDR;\r
-       uint32_t RESERVED0;\r
-  __IO uint32_t ADINTEN;\r
-  __I  uint32_t ADDR0;\r
-  __I  uint32_t ADDR1;\r
-  __I  uint32_t ADDR2;\r
-  __I  uint32_t ADDR3;\r
-  __I  uint32_t ADDR4;\r
-  __I  uint32_t ADDR5;\r
-  __I  uint32_t ADDR6;\r
-  __I  uint32_t ADDR7;\r
-  __I  uint32_t ADSTAT;\r
-  __IO uint32_t ADTRM;\r
-} LPC_ADC_TypeDef;\r
-\r
-/*------------- Digital-to-Analog Converter (DAC) ----------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t DACR;\r
-  __IO uint32_t DACCTRL;\r
-  __IO uint16_t DACCNTVAL;\r
-} LPC_DAC_TypeDef;\r
-\r
-/*------------- Motor Control Pulse-Width Modulation (MCPWM) -----------------*/\r
-typedef struct\r
-{\r
-  __I  uint32_t MCCON;\r
-  __O  uint32_t MCCON_SET;\r
-  __O  uint32_t MCCON_CLR;\r
-  __I  uint32_t MCCAPCON;\r
-  __O  uint32_t MCCAPCON_SET;\r
-  __O  uint32_t MCCAPCON_CLR;\r
-  __IO uint32_t MCTIM0;\r
-  __IO uint32_t MCTIM1;\r
-  __IO uint32_t MCTIM2;\r
-  __IO uint32_t MCPER0;\r
-  __IO uint32_t MCPER1;\r
-  __IO uint32_t MCPER2;\r
-  __IO uint32_t MCPW0;\r
-  __IO uint32_t MCPW1;\r
-  __IO uint32_t MCPW2;\r
-  __IO uint32_t MCDEADTIME;\r
-  __IO uint32_t MCCCP;\r
-  __IO uint32_t MCCR0;\r
-  __IO uint32_t MCCR1;\r
-  __IO uint32_t MCCR2;\r
-  __I  uint32_t MCINTEN;\r
-  __O  uint32_t MCINTEN_SET;\r
-  __O  uint32_t MCINTEN_CLR;\r
-  __I  uint32_t MCCNTCON;\r
-  __O  uint32_t MCCNTCON_SET;\r
-  __O  uint32_t MCCNTCON_CLR;\r
-  __I  uint32_t MCINTFLAG;\r
-  __O  uint32_t MCINTFLAG_SET;\r
-  __O  uint32_t MCINTFLAG_CLR;\r
-  __O  uint32_t MCCAP_CLR;\r
-} LPC_MCPWM_TypeDef;\r
-\r
-/*------------- Quadrature Encoder Interface (QEI) ---------------------------*/\r
-typedef struct\r
-{\r
-  __O  uint32_t QEICON;\r
-  __I  uint32_t QEISTAT;\r
-  __IO uint32_t QEICONF;\r
-  __I  uint32_t QEIPOS;\r
-  __IO uint32_t QEIMAXPOS;\r
-  __IO uint32_t CMPOS0;\r
-  __IO uint32_t CMPOS1;\r
-  __IO uint32_t CMPOS2;\r
-  __I  uint32_t INXCNT;\r
-  __IO uint32_t INXCMP;\r
-  __IO uint32_t QEILOAD;\r
-  __I  uint32_t QEITIME;\r
-  __I  uint32_t QEIVEL;\r
-  __I  uint32_t QEICAP;\r
-  __IO uint32_t VELCOMP;\r
-  __IO uint32_t FILTER;\r
-       uint32_t RESERVED0[998];\r
-  __O  uint32_t QEIIEC;\r
-  __O  uint32_t QEIIES;\r
-  __I  uint32_t QEIINTSTAT;\r
-  __I  uint32_t QEIIE;\r
-  __O  uint32_t QEICLR;\r
-  __O  uint32_t QEISET;\r
-} LPC_QEI_TypeDef;\r
-\r
-/*------------- Controller Area Network (CAN) --------------------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t mask[512];              /* ID Masks                           */\r
-} LPC_CANAF_RAM_TypeDef;\r
-\r
-typedef struct                          /* Acceptance Filter Registers        */\r
-{\r
-  __IO uint32_t AFMR;\r
-  __IO uint32_t SFF_sa;\r
-  __IO uint32_t SFF_GRP_sa;\r
-  __IO uint32_t EFF_sa;\r
-  __IO uint32_t EFF_GRP_sa;\r
-  __IO uint32_t ENDofTable;\r
-  __I  uint32_t LUTerrAd;\r
-  __I  uint32_t LUTerr;\r
-  __IO uint32_t FCANIE;\r
-  __IO uint32_t FCANIC0;\r
-  __IO uint32_t FCANIC1;\r
-} LPC_CANAF_TypeDef;\r
-\r
-typedef struct                          /* Central Registers                  */\r
-{\r
-  __I  uint32_t CANTxSR;\r
-  __I  uint32_t CANRxSR;\r
-  __I  uint32_t CANMSR;\r
-} LPC_CANCR_TypeDef;\r
-\r
-typedef struct                          /* Controller Registers               */\r
-{\r
-  __IO uint32_t MOD;\r
-  __O  uint32_t CMR;\r
-  __IO uint32_t GSR;\r
-  __I  uint32_t ICR;\r
-  __IO uint32_t IER;\r
-  __IO uint32_t BTR;\r
-  __IO uint32_t EWL;\r
-  __I  uint32_t SR;\r
-  __IO uint32_t RFS;\r
-  __IO uint32_t RID;\r
-  __IO uint32_t RDA;\r
-  __IO uint32_t RDB;\r
-  __IO uint32_t TFI1;\r
-  __IO uint32_t TID1;\r
-  __IO uint32_t TDA1;\r
-  __IO uint32_t TDB1;\r
-  __IO uint32_t TFI2;\r
-  __IO uint32_t TID2;\r
-  __IO uint32_t TDA2;\r
-  __IO uint32_t TDB2;\r
-  __IO uint32_t TFI3;\r
-  __IO uint32_t TID3;\r
-  __IO uint32_t TDA3;\r
-  __IO uint32_t TDB3;\r
-} LPC_CAN_TypeDef;\r
-\r
-/*------------- General Purpose Direct Memory Access (GPDMA) -----------------*/\r
-typedef struct                          /* Common Registers                   */\r
-{\r
-  __I  uint32_t DMACIntStat;\r
-  __I  uint32_t DMACIntTCStat;\r
-  __O  uint32_t DMACIntTCClear;\r
-  __I  uint32_t DMACIntErrStat;\r
-  __O  uint32_t DMACIntErrClr;\r
-  __I  uint32_t DMACRawIntTCStat;\r
-  __I  uint32_t DMACRawIntErrStat;\r
-  __I  uint32_t DMACEnbldChns;\r
-  __IO uint32_t DMACSoftBReq;\r
-  __IO uint32_t DMACSoftSReq;\r
-  __IO uint32_t DMACSoftLBReq;\r
-  __IO uint32_t DMACSoftLSReq;\r
-  __IO uint32_t DMACConfig;\r
-  __IO uint32_t DMACSync;\r
-} LPC_GPDMA_TypeDef;\r
-\r
-typedef struct                          /* Channel Registers                  */\r
-{\r
-  __IO uint32_t DMACCSrcAddr;\r
-  __IO uint32_t DMACCDestAddr;\r
-  __IO uint32_t DMACCLLI;\r
-  __IO uint32_t DMACCControl;\r
-  __IO uint32_t DMACCConfig;\r
-} LPC_GPDMACH_TypeDef;\r
-\r
-/*------------- Universal Serial Bus (USB) -----------------------------------*/\r
-typedef struct\r
-{\r
-  __I  uint32_t HcRevision;             /* USB Host Registers                 */\r
-  __IO uint32_t HcControl;\r
-  __IO uint32_t HcCommandStatus;\r
-  __IO uint32_t HcInterruptStatus;\r
-  __IO uint32_t HcInterruptEnable;\r
-  __IO uint32_t HcInterruptDisable;\r
-  __IO uint32_t HcHCCA;\r
-  __I  uint32_t HcPeriodCurrentED;\r
-  __IO uint32_t HcControlHeadED;\r
-  __IO uint32_t HcControlCurrentED;\r
-  __IO uint32_t HcBulkHeadED;\r
-  __IO uint32_t HcBulkCurrentED;\r
-  __I  uint32_t HcDoneHead;\r
-  __IO uint32_t HcFmInterval;\r
-  __I  uint32_t HcFmRemaining;\r
-  __I  uint32_t HcFmNumber;\r
-  __IO uint32_t HcPeriodicStart;\r
-  __IO uint32_t HcLSTreshold;\r
-  __IO uint32_t HcRhDescriptorA;\r
-  __IO uint32_t HcRhDescriptorB;\r
-  __IO uint32_t HcRhStatus;\r
-  __IO uint32_t HcRhPortStatus1;\r
-  __IO uint32_t HcRhPortStatus2;\r
-       uint32_t RESERVED0[40];\r
-  __I  uint32_t Module_ID;\r
-\r
-  __I  uint32_t OTGIntSt;               /* USB On-The-Go Registers            */\r
-  __IO uint32_t OTGIntEn;\r
-  __O  uint32_t OTGIntSet;\r
-  __O  uint32_t OTGIntClr;\r
-  __IO uint32_t OTGStCtrl;\r
-  __IO uint32_t OTGTmr;\r
-       uint32_t RESERVED1[58];\r
-\r
-  __I  uint32_t USBDevIntSt;            /* USB Device Interrupt Registers     */\r
-  __IO uint32_t USBDevIntEn;\r
-  __O  uint32_t USBDevIntClr;\r
-  __O  uint32_t USBDevIntSet;\r
-\r
-  __O  uint32_t USBCmdCode;             /* USB Device SIE Command Registers   */\r
-  __I  uint32_t USBCmdData;\r
-\r
-  __I  uint32_t USBRxData;              /* USB Device Transfer Registers      */\r
-  __O  uint32_t USBTxData;\r
-  __I  uint32_t USBRxPLen;\r
-  __O  uint32_t USBTxPLen;\r
-  __IO uint32_t USBCtrl;\r
-  __O  uint32_t USBDevIntPri;\r
-\r
-  __I  uint32_t USBEpIntSt;             /* USB Device Endpoint Interrupt Regs */\r
-  __IO uint32_t USBEpIntEn;\r
-  __O  uint32_t USBEpIntClr;\r
-  __O  uint32_t USBEpIntSet;\r
-  __O  uint32_t USBEpIntPri;\r
-\r
-  __IO uint32_t USBReEp;                /* USB Device Endpoint Realization Reg*/\r
-  __O  uint32_t USBEpInd;\r
-  __IO uint32_t USBMaxPSize;\r
-\r
-  __I  uint32_t USBDMARSt;              /* USB Device DMA Registers           */\r
-  __O  uint32_t USBDMARClr;\r
-  __O  uint32_t USBDMARSet;\r
-       uint32_t RESERVED2[9];\r
-  __IO uint32_t USBUDCAH;\r
-  __I  uint32_t USBEpDMASt;\r
-  __O  uint32_t USBEpDMAEn;\r
-  __O  uint32_t USBEpDMADis;\r
-  __I  uint32_t USBDMAIntSt;\r
-  __IO uint32_t USBDMAIntEn;\r
-       uint32_t RESERVED3[2];\r
-  __I  uint32_t USBEoTIntSt;\r
-  __O  uint32_t USBEoTIntClr;\r
-  __O  uint32_t USBEoTIntSet;\r
-  __I  uint32_t USBNDDRIntSt;\r
-  __O  uint32_t USBNDDRIntClr;\r
-  __O  uint32_t USBNDDRIntSet;\r
-  __I  uint32_t USBSysErrIntSt;\r
-  __O  uint32_t USBSysErrIntClr;\r
-  __O  uint32_t USBSysErrIntSet;\r
-       uint32_t RESERVED4[15];\r
-\r
-  __I  uint32_t I2C_RX;                 /* USB OTG I2C Registers              */\r
-  __O  uint32_t I2C_WO;\r
-  __I  uint32_t I2C_STS;\r
-  __IO uint32_t I2C_CTL;\r
-  __IO uint32_t I2C_CLKHI;\r
-  __O  uint32_t I2C_CLKLO;\r
-       uint32_t RESERVED5[823];\r
-\r
-  union {\r
-  __IO uint32_t USBClkCtrl;             /* USB Clock Control Registers        */\r
-  __IO uint32_t OTGClkCtrl;\r
-  };\r
-  union {\r
-  __I  uint32_t USBClkSt;\r
-  __I  uint32_t OTGClkSt;\r
-  };\r
-} LPC_USB_TypeDef;\r
-\r
-/*------------- Ethernet Media Access Controller (EMAC) ----------------------*/\r
-typedef struct\r
-{\r
-  __IO uint32_t MAC1;                   /* MAC Registers                      */\r
-  __IO uint32_t MAC2;\r
-  __IO uint32_t IPGT;\r
-  __IO uint32_t IPGR;\r
-  __IO uint32_t CLRT;\r
-  __IO uint32_t MAXF;\r
-  __IO uint32_t SUPP;\r
-  __IO uint32_t TEST;\r
-  __IO uint32_t MCFG;\r
-  __IO uint32_t MCMD;\r
-  __IO uint32_t MADR;\r
-  __O  uint32_t MWTD;\r
-  __I  uint32_t MRDD;\r
-  __I  uint32_t MIND;\r
-       uint32_t RESERVED0[2];\r
-  __IO uint32_t SA0;\r
-  __IO uint32_t SA1;\r
-  __IO uint32_t SA2;\r
-       uint32_t RESERVED1[45];\r
-  __IO uint32_t Command;                /* Control Registers                  */\r
-  __I  uint32_t Status;\r
-  __IO uint32_t RxDescriptor;\r
-  __IO uint32_t RxStatus;\r
-  __IO uint32_t RxDescriptorNumber;\r
-  __I  uint32_t RxProduceIndex;\r
-  __IO uint32_t RxConsumeIndex;\r
-  __IO uint32_t TxDescriptor;\r
-  __IO uint32_t TxStatus;\r
-  __IO uint32_t TxDescriptorNumber;\r
-  __IO uint32_t TxProduceIndex;\r
-  __I  uint32_t TxConsumeIndex;\r
-       uint32_t RESERVED2[10];\r
-  __I  uint32_t TSV0;\r
-  __I  uint32_t TSV1;\r
-  __I  uint32_t RSV;\r
-       uint32_t RESERVED3[3];\r
-  __IO uint32_t FlowControlCounter;\r
-  __I  uint32_t FlowControlStatus;\r
-       uint32_t RESERVED4[34];\r
-  __IO uint32_t RxFilterCtrl;           /* Rx Filter Registers                */\r
-  __IO uint32_t RxFilterWoLStatus;\r
-  __IO uint32_t RxFilterWoLClear;\r
-       uint32_t RESERVED5;\r
-  __IO uint32_t HashFilterL;\r
-  __IO uint32_t HashFilterH;\r
-       uint32_t RESERVED6[882];\r
-  __I  uint32_t IntStatus;              /* Module Control Registers           */\r
-  __IO uint32_t IntEnable;\r
-  __O  uint32_t IntClear;\r
-  __O  uint32_t IntSet;\r
-       uint32_t RESERVED7;\r
-  __IO uint32_t PowerDown;\r
-       uint32_t RESERVED8;\r
-  __IO uint32_t Module_ID;\r
-} LPC_EMAC_TypeDef;\r
-\r
-#if defined ( __CC_ARM   )\r
-#pragma anon_unions\r
-#endif\r
-\r
-\r
-/******************************************************************************/\r
-/*                         Peripheral memory map                              */\r
-/******************************************************************************/\r
-/* Base addresses                                                             */\r
-#define LPC_FLASH_BASE        (0x00000000UL)\r
-#define LPC_RAM_BASE          (0x10000000UL)\r
-#define LPC_GPIO_BASE         (0x2009C000UL)\r
-#define LPC_APB0_BASE         (0x40000000UL)\r
-#define LPC_APB1_BASE         (0x40080000UL)\r
-#define LPC_AHB_BASE          (0x50000000UL)\r
-#define LPC_CM3_BASE          (0xE0000000UL)\r
-\r
-/* APB0 peripherals                                                           */\r
-#define LPC_WDT_BASE          (LPC_APB0_BASE + 0x00000)\r
-#define LPC_TIM0_BASE         (LPC_APB0_BASE + 0x04000)\r
-#define LPC_TIM1_BASE         (LPC_APB0_BASE + 0x08000)\r
-#define LPC_UART0_BASE        (LPC_APB0_BASE + 0x0C000)\r
-#define LPC_UART1_BASE        (LPC_APB0_BASE + 0x10000)\r
-#define LPC_PWM1_BASE         (LPC_APB0_BASE + 0x18000)\r
-#define LPC_I2C0_BASE         (LPC_APB0_BASE + 0x1C000)\r
-#define LPC_SPI_BASE          (LPC_APB0_BASE + 0x20000)\r
-#define LPC_RTC_BASE          (LPC_APB0_BASE + 0x24000)\r
-#define LPC_GPIOINT_BASE      (LPC_APB0_BASE + 0x28080)\r
-#define LPC_PINCON_BASE       (LPC_APB0_BASE + 0x2C000)\r
-#define LPC_SSP1_BASE         (LPC_APB0_BASE + 0x30000)\r
-#define LPC_ADC_BASE          (LPC_APB0_BASE + 0x34000)\r
-#define LPC_CANAF_RAM_BASE    (LPC_APB0_BASE + 0x38000)\r
-#define LPC_CANAF_BASE        (LPC_APB0_BASE + 0x3C000)\r
-#define LPC_CANCR_BASE        (LPC_APB0_BASE + 0x40000)\r
-#define LPC_CAN1_BASE         (LPC_APB0_BASE + 0x44000)\r
-#define LPC_CAN2_BASE         (LPC_APB0_BASE + 0x48000)\r
-#define LPC_I2C1_BASE         (LPC_APB0_BASE + 0x5C000)\r
-\r
-/* APB1 peripherals                                                           */\r
-#define LPC_SSP0_BASE         (LPC_APB1_BASE + 0x08000)\r
-#define LPC_DAC_BASE          (LPC_APB1_BASE + 0x0C000)\r
-#define LPC_TIM2_BASE         (LPC_APB1_BASE + 0x10000)\r
-#define LPC_TIM3_BASE         (LPC_APB1_BASE + 0x14000)\r
-#define LPC_UART2_BASE        (LPC_APB1_BASE + 0x18000)\r
-#define LPC_UART3_BASE        (LPC_APB1_BASE + 0x1C000)\r
-#define LPC_I2C2_BASE         (LPC_APB1_BASE + 0x20000)\r
-#define LPC_I2S_BASE          (LPC_APB1_BASE + 0x28000)\r
-#define LPC_RIT_BASE          (LPC_APB1_BASE + 0x30000)\r
-#define LPC_MCPWM_BASE        (LPC_APB1_BASE + 0x38000)\r
-#define LPC_QEI_BASE          (LPC_APB1_BASE + 0x3C000)\r
-#define LPC_SC_BASE           (LPC_APB1_BASE + 0x7C000)\r
-\r
-/* AHB peripherals                                                            */\r
-#define LPC_EMAC_BASE         (LPC_AHB_BASE  + 0x00000)\r
-#define LPC_GPDMA_BASE        (LPC_AHB_BASE  + 0x04000)\r
-#define LPC_GPDMACH0_BASE     (LPC_AHB_BASE  + 0x04100)\r
-#define LPC_GPDMACH1_BASE     (LPC_AHB_BASE  + 0x04120)\r
-#define LPC_GPDMACH2_BASE     (LPC_AHB_BASE  + 0x04140)\r
-#define LPC_GPDMACH3_BASE     (LPC_AHB_BASE  + 0x04160)\r
-#define LPC_GPDMACH4_BASE     (LPC_AHB_BASE  + 0x04180)\r
-#define LPC_GPDMACH5_BASE     (LPC_AHB_BASE  + 0x041A0)\r
-#define LPC_GPDMACH6_BASE     (LPC_AHB_BASE  + 0x041C0)\r
-#define LPC_GPDMACH7_BASE     (LPC_AHB_BASE  + 0x041E0)\r
-#define LPC_USB_BASE          (LPC_AHB_BASE  + 0x0C000)\r
-\r
-/* GPIOs                                                                      */\r
-#define LPC_GPIO0_BASE        (LPC_GPIO_BASE + 0x00000)\r
-#define LPC_GPIO1_BASE        (LPC_GPIO_BASE + 0x00020)\r
-#define LPC_GPIO2_BASE        (LPC_GPIO_BASE + 0x00040)\r
-#define LPC_GPIO3_BASE        (LPC_GPIO_BASE + 0x00060)\r
-#define LPC_GPIO4_BASE        (LPC_GPIO_BASE + 0x00080)\r
-\r
-\r
-/******************************************************************************/\r
-/*                         Peripheral declaration                             */\r
-/******************************************************************************/\r
-#define LPC_SC                ((LPC_SC_TypeDef        *) LPC_SC_BASE       )\r
-#define LPC_GPIO0             ((LPC_GPIO_TypeDef      *) LPC_GPIO0_BASE    )\r
-#define LPC_GPIO1             ((LPC_GPIO_TypeDef      *) LPC_GPIO1_BASE    )\r
-#define LPC_GPIO2             ((LPC_GPIO_TypeDef      *) LPC_GPIO2_BASE    )\r
-#define LPC_GPIO3             ((LPC_GPIO_TypeDef      *) LPC_GPIO3_BASE    )\r
-#define LPC_GPIO4             ((LPC_GPIO_TypeDef      *) LPC_GPIO4_BASE    )\r
-#define LPC_WDT               ((LPC_WDT_TypeDef       *) LPC_WDT_BASE      )\r
-#define LPC_TIM0              ((LPC_TIM_TypeDef       *) LPC_TIM0_BASE     )\r
-#define LPC_TIM1              ((LPC_TIM_TypeDef       *) LPC_TIM1_BASE     )\r
-#define LPC_TIM2              ((LPC_TIM_TypeDef       *) LPC_TIM2_BASE     )\r
-#define LPC_TIM3              ((LPC_TIM_TypeDef       *) LPC_TIM3_BASE     )\r
-#define LPC_RIT               ((LPC_RIT_TypeDef       *) LPC_RIT_BASE      )\r
-#define LPC_UART0             ((LPC_UART0_TypeDef     *) LPC_UART0_BASE    )\r
-#define LPC_UART1             ((LPC_UART1_TypeDef     *) LPC_UART1_BASE    )\r
-#define LPC_UART2             ((LPC_UART_TypeDef      *) LPC_UART2_BASE    )\r
-#define LPC_UART3             ((LPC_UART_TypeDef      *) LPC_UART3_BASE    )\r
-#define LPC_PWM1              ((LPC_PWM_TypeDef       *) LPC_PWM1_BASE     )\r
-#define LPC_I2C0              ((LPC_I2C_TypeDef       *) LPC_I2C0_BASE     )\r
-#define LPC_I2C1              ((LPC_I2C_TypeDef       *) LPC_I2C1_BASE     )\r
-#define LPC_I2C2              ((LPC_I2C_TypeDef       *) LPC_I2C2_BASE     )\r
-#define LPC_I2S               ((LPC_I2S_TypeDef       *) LPC_I2S_BASE      )\r
-#define LPC_SPI               ((LPC_SPI_TypeDef       *) LPC_SPI_BASE      )\r
-#define LPC_RTC               ((LPC_RTC_TypeDef       *) LPC_RTC_BASE      )\r
-#define LPC_GPIOINT           ((LPC_GPIOINT_TypeDef   *) LPC_GPIOINT_BASE  )\r
-#define LPC_PINCON            ((LPC_PINCON_TypeDef    *) LPC_PINCON_BASE   )\r
-#define LPC_SSP0              ((LPC_SSP_TypeDef       *) LPC_SSP0_BASE     )\r
-#define LPC_SSP1              ((LPC_SSP_TypeDef       *) LPC_SSP1_BASE     )\r
-#define LPC_ADC               ((LPC_ADC_TypeDef       *) LPC_ADC_BASE      )\r
-#define LPC_DAC               ((LPC_DAC_TypeDef       *) LPC_DAC_BASE      )\r
-#define LPC_CANAF_RAM         ((LPC_CANAF_RAM_TypeDef *) LPC_CANAF_RAM_BASE)\r
-#define LPC_CANAF             ((LPC_CANAF_TypeDef     *) LPC_CANAF_BASE    )\r
-#define LPC_CANCR             ((LPC_CANCR_TypeDef     *) LPC_CANCR_BASE    )\r
-#define LPC_CAN1              ((LPC_CAN_TypeDef       *) LPC_CAN1_BASE     )\r
-#define LPC_CAN2              ((LPC_CAN_TypeDef       *) LPC_CAN2_BASE     )\r
-#define LPC_MCPWM             ((LPC_MCPWM_TypeDef     *) LPC_MCPWM_BASE    )\r
-#define LPC_QEI               ((LPC_QEI_TypeDef       *) LPC_QEI_BASE      )\r
-#define LPC_EMAC              ((LPC_EMAC_TypeDef      *) LPC_EMAC_BASE     )\r
-#define LPC_GPDMA             ((LPC_GPDMA_TypeDef     *) LPC_GPDMA_BASE    )\r
-#define LPC_GPDMACH0          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH0_BASE )\r
-#define LPC_GPDMACH1          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH1_BASE )\r
-#define LPC_GPDMACH2          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH2_BASE )\r
-#define LPC_GPDMACH3          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH3_BASE )\r
-#define LPC_GPDMACH4          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH4_BASE )\r
-#define LPC_GPDMACH5          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH5_BASE )\r
-#define LPC_GPDMACH6          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH6_BASE )\r
-#define LPC_GPDMACH7          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH7_BASE )\r
-#define LPC_USB               ((LPC_USB_TypeDef       *) LPC_USB_BASE      )\r
-\r
-#endif  // __LPC17xx_H__\r
+/******************************************************************************
+ * @file:    LPC17xx.h
+ * @purpose: CMSIS Cortex-M3 Core Peripheral Access Layer Header File for
+ *           NXP LPC17xx Device Series
+ * @version: V1.04
+ * @date:    2. July 2009
+ *----------------------------------------------------------------------------
+ *
+ * Copyright (C) 2008 ARM Limited. All rights reserved.
+ *
+ * ARM Limited (ARM) is supplying this software for use with Cortex-M3
+ * processor based microcontrollers.  This file can be freely distributed
+ * within development tools that are supporting such ARM based processors.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS".  NO WARRANTIES, WHETHER EXPRESS, IMPLIED
+ * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
+ * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
+ * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
+ *
+ ******************************************************************************/
+\r
+\r
+#ifndef __LPC17xx_H__
+#define __LPC17xx_H__
+\r
+/*
+ * ==========================================================================
+ * ---------- Interrupt Number Definition -----------------------------------
+ * ==========================================================================
+ */
+\r
+typedef enum IRQn
+{
+/******  Cortex-M3 Processor Exceptions Numbers ***************************************************/
+  NonMaskableInt_IRQn           = -14,      /*!< 2 Non Maskable Interrupt                         */
+  MemoryManagement_IRQn         = -12,      /*!< 4 Cortex-M3 Memory Management Interrupt          */
+  BusFault_IRQn                 = -11,      /*!< 5 Cortex-M3 Bus Fault Interrupt                  */
+  UsageFault_IRQn               = -10,      /*!< 6 Cortex-M3 Usage Fault Interrupt                */
+  SVCall_IRQn                   = -5,       /*!< 11 Cortex-M3 SV Call Interrupt                   */
+  DebugMonitor_IRQn             = -4,       /*!< 12 Cortex-M3 Debug Monitor Interrupt             */
+  PendSV_IRQn                   = -2,       /*!< 14 Cortex-M3 Pend SV Interrupt                   */
+  SysTick_IRQn                  = -1,       /*!< 15 Cortex-M3 System Tick Interrupt               */
+\r
+/******  LPC17xx Specific Interrupt Numbers *******************************************************/
+  WDT_IRQn                      = 0,        /*!< Watchdog Timer Interrupt                         */
+  TIMER0_IRQn                   = 1,        /*!< Timer0 Interrupt                                 */
+  TIMER1_IRQn                   = 2,        /*!< Timer1 Interrupt                                 */
+  TIMER2_IRQn                   = 3,        /*!< Timer2 Interrupt                                 */
+  TIMER3_IRQn                   = 4,        /*!< Timer3 Interrupt                                 */
+  UART0_IRQn                    = 5,        /*!< UART0 Interrupt                                  */
+  UART1_IRQn                    = 6,        /*!< UART1 Interrupt                                  */
+  UART2_IRQn                    = 7,        /*!< UART2 Interrupt                                  */
+  UART3_IRQn                    = 8,        /*!< UART3 Interrupt                                  */
+  PWM1_IRQn                     = 9,        /*!< PWM1 Interrupt                                   */
+  I2C0_IRQn                     = 10,       /*!< I2C0 Interrupt                                   */
+  I2C1_IRQn                     = 11,       /*!< I2C1 Interrupt                                   */
+  I2C2_IRQn                     = 12,       /*!< I2C2 Interrupt                                   */
+  SPI_IRQn                      = 13,       /*!< SPI Interrupt                                    */
+  SSP0_IRQn                     = 14,       /*!< SSP0 Interrupt                                   */
+  SSP1_IRQn                     = 15,       /*!< SSP1 Interrupt                                   */
+  PLL0_IRQn                     = 16,       /*!< PLL0 Lock (Main PLL) Interrupt                   */
+  RTC_IRQn                      = 17,       /*!< Real Time Clock Interrupt                        */
+  EINT0_IRQn                    = 18,       /*!< External Interrupt 0 Interrupt                   */
+  EINT1_IRQn                    = 19,       /*!< External Interrupt 1 Interrupt                   */
+  EINT2_IRQn                    = 20,       /*!< External Interrupt 2 Interrupt                   */
+  EINT3_IRQn                    = 21,       /*!< External Interrupt 3 Interrupt                   */
+  ADC_IRQn                      = 22,       /*!< A/D Converter Interrupt                          */
+  BOD_IRQn                      = 23,       /*!< Brown-Out Detect Interrupt                       */
+  USB_IRQn                      = 24,       /*!< USB Interrupt                                    */
+  CAN_IRQn                      = 25,       /*!< CAN Interrupt                                    */
+  DMA_IRQn                      = 26,       /*!< General Purpose DMA Interrupt                    */
+  I2S_IRQn                      = 27,       /*!< I2S Interrupt                                    */
+  ENET_IRQn                     = 28,       /*!< Ethernet Interrupt                               */
+  RIT_IRQn                      = 29,       /*!< Repetitive Interrupt Timer Interrupt             */
+  MCPWM_IRQn                    = 30,       /*!< Motor Control PWM Interrupt                      */
+  QEI_IRQn                      = 31,       /*!< Quadrature Encoder Interface Interrupt           */
+  PLL1_IRQn                     = 32,       /*!< PLL1 Lock (USB PLL) Interrupt                    */
+} IRQn_Type;
+\r
+\r
+/*
+ * ==========================================================================
+ * ----------- Processor and Core Peripheral Section ------------------------
+ * ==========================================================================
+ */
+\r
+/* Configuration of the Cortex-M3 Processor and Core Peripherals */
+#define __MPU_PRESENT             1         /*!< MPU present or not                               */
+#define __NVIC_PRIO_BITS          5         /*!< Number of Bits used for Priority Levels          */
+#define __Vendor_SysTickConfig    0         /*!< Set to 1 if different SysTick Config is used     */
+\r
+\r
+#include "score_cm3.h"                       /* Cortex-M3 processor and core peripherals           */
+//#include "system_LPC17xx.h"                 /* System Header                                      */
+\r
+\r
+/******************************************************************************/
+/*                Device Specific Peripheral registers structures             */
+/******************************************************************************/
+\r
+#if defined ( __CC_ARM   )
+#pragma anon_unions
+#endif
+\r
+/*------------- System Control (SC) ------------------------------------------*/
+typedef struct
+{
+  __IO uint32_t FLASHCFG;               /* Flash Accelerator Module           */
+       uint32_t RESERVED0[31];
+  __IO uint32_t PLL0CON;                /* Clocking and Power Control         */
+  __IO uint32_t PLL0CFG;
+  __I  uint32_t PLL0STAT;
+  __O  uint32_t PLL0FEED;
+       uint32_t RESERVED1[4];
+  __IO uint32_t PLL1CON;
+  __IO uint32_t PLL1CFG;
+  __I  uint32_t PLL1STAT;
+  __O  uint32_t PLL1FEED;
+       uint32_t RESERVED2[4];
+  __IO uint32_t PCON;
+  __IO uint32_t PCONP;
+       uint32_t RESERVED3[15];
+  __IO uint32_t CCLKCFG;
+  __IO uint32_t USBCLKCFG;
+  __IO uint32_t CLKSRCSEL;
+       uint32_t RESERVED4[12];
+  __IO uint32_t EXTINT;                 /* External Interrupts                */
+       uint32_t RESERVED5;
+  __IO uint32_t EXTMODE;
+  __IO uint32_t EXTPOLAR;
+       uint32_t RESERVED6[12];
+  __IO uint32_t RSID;                   /* Reset                              */
+       uint32_t RESERVED7[7];
+  __IO uint32_t SCS;                    /* Syscon Miscellaneous Registers     */
+  __IO uint32_t IRCTRIM;                /* Clock Dividers                     */
+  __IO uint32_t PCLKSEL0;
+  __IO uint32_t PCLKSEL1;
+       uint32_t RESERVED8[4];
+  __IO uint32_t USBIntSt;               /* USB Device/OTG Interrupt Register  */
+       uint32_t RESERVED9;
+  __IO uint32_t CLKOUTCFG;              /* Clock Output Configuration         */
+ } LPC_SC_TypeDef;
+\r
+/*------------- Pin Connect Block (PINCON) -----------------------------------*/
+typedef struct
+{
+  __IO uint32_t PINSEL0;
+  __IO uint32_t PINSEL1;
+  __IO uint32_t PINSEL2;
+  __IO uint32_t PINSEL3;
+  __IO uint32_t PINSEL4;
+  __IO uint32_t PINSEL5;
+  __IO uint32_t PINSEL6;
+  __IO uint32_t PINSEL7;
+  __IO uint32_t PINSEL8;
+  __IO uint32_t PINSEL9;
+  __IO uint32_t PINSEL10;
+       uint32_t RESERVED0[5];
+  __IO uint32_t PINMODE0;
+  __IO uint32_t PINMODE1;
+  __IO uint32_t PINMODE2;
+  __IO uint32_t PINMODE3;
+  __IO uint32_t PINMODE4;
+  __IO uint32_t PINMODE5;
+  __IO uint32_t PINMODE6;
+  __IO uint32_t PINMODE7;
+  __IO uint32_t PINMODE8;
+  __IO uint32_t PINMODE9;
+  __IO uint32_t PINMODE_OD0;
+  __IO uint32_t PINMODE_OD1;
+  __IO uint32_t PINMODE_OD2;
+  __IO uint32_t PINMODE_OD3;
+  __IO uint32_t PINMODE_OD4;
+  __IO uint32_t I2CPADCFG;
+} LPC_PINCON_TypeDef;
+\r
+/*------------- General Purpose Input/Output (GPIO) --------------------------*/
+typedef struct
+{
+  __IO uint32_t FIODIR;
+       uint32_t RESERVED0[3];
+  __IO uint32_t FIOMASK;
+  __IO uint32_t FIOPIN;
+  __IO uint32_t FIOSET;
+  __O  uint32_t FIOCLR;
+} LPC_GPIO_TypeDef;
+\r
+typedef struct
+{
+  __I  uint32_t IntStatus;
+  __I  uint32_t IO0IntStatR;
+  __I  uint32_t IO0IntStatF;
+  __O  uint32_t IO0IntClr;
+  __IO uint32_t IO0IntEnR;
+  __IO uint32_t IO0IntEnF;
+       uint32_t RESERVED0[3];
+  __I  uint32_t IO2IntStatR;
+  __I  uint32_t IO2IntStatF;
+  __O  uint32_t IO2IntClr;
+  __IO uint32_t IO2IntEnR;
+  __IO uint32_t IO2IntEnF;
+} LPC_GPIOINT_TypeDef;
+\r
+/*------------- Timer (TIM) --------------------------------------------------*/
+typedef struct
+{
+  __IO uint32_t IR;
+  __IO uint32_t TCR;
+  __IO uint32_t TC;
+  __IO uint32_t PR;
+  __IO uint32_t PC;
+  __IO uint32_t MCR;
+  __IO uint32_t MR0;
+  __IO uint32_t MR1;
+  __IO uint32_t MR2;
+  __IO uint32_t MR3;
+  __IO uint32_t CCR;
+  __I  uint32_t CR0;
+  __I  uint32_t CR1;
+       uint32_t RESERVED0[2];
+  __IO uint32_t EMR;
+       uint32_t RESERVED1[12];
+  __IO uint32_t CTCR;
+} LPC_TIM_TypeDef;
+\r
+/*------------- Pulse-Width Modulation (PWM) ---------------------------------*/
+typedef struct
+{
+  __IO uint32_t IR;
+  __IO uint32_t TCR;
+  __IO uint32_t TC;
+  __IO uint32_t PR;
+  __IO uint32_t PC;
+  __IO uint32_t MCR;
+  __IO uint32_t MR0;
+  __IO uint32_t MR1;
+  __IO uint32_t MR2;
+  __IO uint32_t MR3;
+  __IO uint32_t CCR;
+  __I  uint32_t CR0;
+  __I  uint32_t CR1;
+  __I  uint32_t CR2;
+  __I  uint32_t CR3;
+       uint32_t RESERVED0;
+  __IO uint32_t MR4;
+  __IO uint32_t MR5;
+  __IO uint32_t MR6;
+  __IO uint32_t PCR;
+  __IO uint32_t LER;
+       uint32_t RESERVED1[7];
+  __IO uint32_t CTCR;
+} LPC_PWM_TypeDef;
+\r
+/*------------- Universal Asynchronous Receiver Transmitter (UART) -----------*/
+typedef struct
+{
+  union {
+  __I  uint8_t  RBR;
+  __O  uint8_t  THR;
+  __IO uint8_t  DLL;
+       uint32_t RESERVED0;
+  };
+  union {
+  __IO uint8_t  DLM;
+  __IO uint32_t IER;
+  };
+  union {
+  __I  uint32_t IIR;
+  __O  uint8_t  FCR;
+  };
+  __IO uint8_t  LCR;
+       uint8_t  RESERVED1[7];
+  __I  uint8_t  LSR;
+       uint8_t  RESERVED2[7];
+  __IO uint8_t  SCR;
+       uint8_t  RESERVED3[3];
+  __IO uint32_t ACR;
+  __IO uint8_t  ICR;
+       uint8_t  RESERVED4[3];
+  __IO uint8_t  FDR;
+       uint8_t  RESERVED5[7];
+  __IO uint8_t  TER;
+       uint8_t  RESERVED6[39];
+  __I  uint8_t  FIFOLVL;
+} LPC_UART_TypeDef;
+\r
+typedef struct
+{
+  union {
+  __I  uint8_t  RBR;
+  __O  uint8_t  THR;
+  __IO uint8_t  DLL;
+       uint32_t RESERVED0;
+  };
+  union {
+  __IO uint8_t  DLM;
+  __IO uint32_t IER;
+  };
+  union {
+  __I  uint32_t IIR;
+  __O  uint8_t  FCR;
+  };
+  __IO uint8_t  LCR;
+       uint8_t  RESERVED1[7];
+  __I  uint8_t  LSR;
+       uint8_t  RESERVED2[7];
+  __IO uint8_t  SCR;
+       uint8_t  RESERVED3[3];
+  __IO uint32_t ACR;
+  __IO uint8_t  ICR;
+       uint8_t  RESERVED4[3];
+  __IO uint8_t  FDR;
+       uint8_t  RESERVED5[7];
+  __IO uint8_t  TER;
+       uint8_t  RESERVED6[39];
+  __I  uint8_t  FIFOLVL;
+       uint8_t  RESERVED7[363];
+  __IO uint32_t DMAREQSEL;
+} LPC_UART0_TypeDef;
+\r
+typedef struct
+{
+  union {
+  __I  uint8_t  RBR;
+  __O  uint8_t  THR;
+  __IO uint8_t  DLL;
+       uint32_t RESERVED0;
+  };
+  union {
+  __IO uint8_t  DLM;
+  __IO uint32_t IER;
+  };
+  union {
+  __I  uint32_t IIR;
+  __O  uint8_t  FCR;
+  };
+  __IO uint8_t  LCR;
+       uint8_t  RESERVED1[3];
+  __IO uint8_t  MCR;
+       uint8_t  RESERVED2[3];
+  __I  uint8_t  LSR;
+       uint8_t  RESERVED3[3];
+  __I  uint8_t  MSR;
+       uint8_t  RESERVED4[3];
+  __IO uint8_t  SCR;
+       uint8_t  RESERVED5[3];
+  __IO uint32_t ACR;
+       uint32_t RESERVED6;
+  __IO uint32_t FDR;
+       uint32_t RESERVED7;
+  __IO uint8_t  TER;
+       uint8_t  RESERVED8[27];
+  __IO uint8_t  RS485CTRL;
+       uint8_t  RESERVED9[3];
+  __IO uint8_t  ADRMATCH;
+       uint8_t  RESERVED10[3];
+  __IO uint8_t  RS485DLY;
+       uint8_t  RESERVED11[3];
+  __I  uint8_t  FIFOLVL;
+} LPC_UART1_TypeDef;
+\r
+/*------------- Serial Peripheral Interface (SPI) ----------------------------*/
+typedef struct
+{
+  __IO uint32_t SPCR;
+  __I  uint32_t SPSR;
+  __IO uint32_t SPDR;
+  __IO uint32_t SPCCR;
+       uint32_t RESERVED0[3];
+  __IO uint32_t SPINT;
+} LPC_SPI_TypeDef;
+\r
+/*------------- Synchronous Serial Communication (SSP) -----------------------*/
+typedef struct
+{
+  __IO uint32_t CR0;
+  __IO uint32_t CR1;
+  __IO uint32_t DR;
+  __I  uint32_t SR;
+  __IO uint32_t CPSR;
+  __IO uint32_t IMSC;
+  __IO uint32_t RIS;
+  __IO uint32_t MIS;
+  __IO uint32_t ICR;
+  __IO uint32_t DMACR;
+} LPC_SSP_TypeDef;
+\r
+/*------------- Inter-Integrated Circuit (I2C) -------------------------------*/
+typedef struct
+{
+  __IO uint32_t I2CONSET;
+  __I  uint32_t I2STAT;
+  __IO uint32_t I2DAT;
+  __IO uint32_t I2ADR0;
+  __IO uint32_t I2SCLH;
+  __IO uint32_t I2SCLL;
+  __O  uint32_t I2CONCLR;
+  __IO uint32_t MMCTRL;
+  __IO uint32_t I2ADR1;
+  __IO uint32_t I2ADR2;
+  __IO uint32_t I2ADR3;
+  __I  uint32_t I2DATA_BUFFER;
+  __IO uint32_t I2MASK0;
+  __IO uint32_t I2MASK1;
+  __IO uint32_t I2MASK2;
+  __IO uint32_t I2MASK3;
+} LPC_I2C_TypeDef;
+\r
+/*------------- Inter IC Sound (I2S) -----------------------------------------*/
+typedef struct
+{
+  __IO uint32_t I2SDAO;
+  __IO uint32_t I2SDAI;
+  __O  uint32_t I2STXFIFO;
+  __I  uint32_t I2SRXFIFO;
+  __I  uint32_t I2SSTATE;
+  __IO uint32_t I2SDMA1;
+  __IO uint32_t I2SDMA2;
+  __IO uint32_t I2SIRQ;
+  __IO uint32_t I2STXRATE;
+  __IO uint32_t I2SRXRATE;
+  __IO uint32_t I2STXBITRATE;
+  __IO uint32_t I2SRXBITRATE;
+  __IO uint32_t I2STXMODE;
+  __IO uint32_t I2SRXMODE;
+} LPC_I2S_TypeDef;
+\r
+/*------------- Repetitive Interrupt Timer (RIT) -----------------------------*/
+typedef struct
+{
+  __IO uint32_t RICOMPVAL;
+  __IO uint32_t RIMASK;
+  __IO uint8_t  RICTRL;
+       uint8_t  RESERVED0[3];
+  __IO uint32_t RICOUNTER;
+} LPC_RIT_TypeDef;
+\r
+/*------------- Real-Time Clock (RTC) ----------------------------------------*/
+typedef struct
+{
+  __IO uint8_t  ILR;
+       uint8_t  RESERVED0[7];
+  __IO uint8_t  CCR;
+       uint8_t  RESERVED1[3];
+  __IO uint8_t  CIIR;
+       uint8_t  RESERVED2[3];
+  __IO uint8_t  AMR;
+       uint8_t  RESERVED3[3];
+  __I  uint32_t CTIME0;
+  __I  uint32_t CTIME1;
+  __I  uint32_t CTIME2;
+  __IO uint8_t  SEC;
+       uint8_t  RESERVED4[3];
+  __IO uint8_t  MIN;
+       uint8_t  RESERVED5[3];
+  __IO uint8_t  HOUR;
+       uint8_t  RESERVED6[3];
+  __IO uint8_t  DOM;
+       uint8_t  RESERVED7[3];
+  __IO uint8_t  DOW;
+       uint8_t  RESERVED8[3];
+  __IO uint16_t DOY;
+       uint16_t RESERVED9;
+  __IO uint8_t  MONTH;
+       uint8_t  RESERVED10[3];
+  __IO uint16_t YEAR;
+       uint16_t RESERVED11;
+  __IO uint32_t CALIBRATION;
+  __IO uint32_t GPREG0;
+  __IO uint32_t GPREG1;
+  __IO uint32_t GPREG2;
+  __IO uint32_t GPREG3;
+  __IO uint32_t GPREG4;
+  __IO uint8_t  RTC_AUXEN;
+       uint8_t  RESERVED12[3];
+  __IO uint8_t  RTC_AUX;
+       uint8_t  RESERVED13[3];
+  __IO uint8_t  ALSEC;
+       uint8_t  RESERVED14[3];
+  __IO uint8_t  ALMIN;
+       uint8_t  RESERVED15[3];
+  __IO uint8_t  ALHOUR;
+       uint8_t  RESERVED16[3];
+  __IO uint8_t  ALDOM;
+       uint8_t  RESERVED17[3];
+  __IO uint8_t  ALDOW;
+       uint8_t  RESERVED18[3];
+  __IO uint16_t ALDOY;
+       uint16_t RESERVED19;
+  __IO uint8_t  ALMON;
+       uint8_t  RESERVED20[3];
+  __IO uint16_t ALYEAR;
+       uint16_t RESERVED21;
+} LPC_RTC_TypeDef;
+\r
+/*------------- Watchdog Timer (WDT) -----------------------------------------*/
+typedef struct
+{
+  __IO uint8_t  WDMOD;
+       uint8_t  RESERVED0[3];
+  __IO uint32_t WDTC;
+  __O  uint8_t  WDFEED;
+       uint8_t  RESERVED1[3];
+  __I  uint32_t WDTV;
+  __IO uint32_t WDCLKSEL;
+} LPC_WDT_TypeDef;
+\r
+/*------------- Analog-to-Digital Converter (ADC) ----------------------------*/
+typedef struct
+{
+  __IO uint32_t ADCR;
+  __IO uint32_t ADGDR;
+       uint32_t RESERVED0;
+  __IO uint32_t ADINTEN;
+  __I  uint32_t ADDR0;
+  __I  uint32_t ADDR1;
+  __I  uint32_t ADDR2;
+  __I  uint32_t ADDR3;
+  __I  uint32_t ADDR4;
+  __I  uint32_t ADDR5;
+  __I  uint32_t ADDR6;
+  __I  uint32_t ADDR7;
+  __I  uint32_t ADSTAT;
+  __IO uint32_t ADTRM;
+} LPC_ADC_TypeDef;
+\r
+/*------------- Digital-to-Analog Converter (DAC) ----------------------------*/
+typedef struct
+{
+  __IO uint32_t DACR;
+  __IO uint32_t DACCTRL;
+  __IO uint16_t DACCNTVAL;
+} LPC_DAC_TypeDef;
+\r
+/*------------- Motor Control Pulse-Width Modulation (MCPWM) -----------------*/
+typedef struct
+{
+  __I  uint32_t MCCON;
+  __O  uint32_t MCCON_SET;
+  __O  uint32_t MCCON_CLR;
+  __I  uint32_t MCCAPCON;
+  __O  uint32_t MCCAPCON_SET;
+  __O  uint32_t MCCAPCON_CLR;
+  __IO uint32_t MCTIM0;
+  __IO uint32_t MCTIM1;
+  __IO uint32_t MCTIM2;
+  __IO uint32_t MCPER0;
+  __IO uint32_t MCPER1;
+  __IO uint32_t MCPER2;
+  __IO uint32_t MCPW0;
+  __IO uint32_t MCPW1;
+  __IO uint32_t MCPW2;
+  __IO uint32_t MCDEADTIME;
+  __IO uint32_t MCCCP;
+  __IO uint32_t MCCR0;
+  __IO uint32_t MCCR1;
+  __IO uint32_t MCCR2;
+  __I  uint32_t MCINTEN;
+  __O  uint32_t MCINTEN_SET;
+  __O  uint32_t MCINTEN_CLR;
+  __I  uint32_t MCCNTCON;
+  __O  uint32_t MCCNTCON_SET;
+  __O  uint32_t MCCNTCON_CLR;
+  __I  uint32_t MCINTFLAG;
+  __O  uint32_t MCINTFLAG_SET;
+  __O  uint32_t MCINTFLAG_CLR;
+  __O  uint32_t MCCAP_CLR;
+} LPC_MCPWM_TypeDef;
+\r
+/*------------- Quadrature Encoder Interface (QEI) ---------------------------*/
+typedef struct
+{
+  __O  uint32_t QEICON;
+  __I  uint32_t QEISTAT;
+  __IO uint32_t QEICONF;
+  __I  uint32_t QEIPOS;
+  __IO uint32_t QEIMAXPOS;
+  __IO uint32_t CMPOS0;
+  __IO uint32_t CMPOS1;
+  __IO uint32_t CMPOS2;
+  __I  uint32_t INXCNT;
+  __IO uint32_t INXCMP;
+  __IO uint32_t QEILOAD;
+  __I  uint32_t QEITIME;
+  __I  uint32_t QEIVEL;
+  __I  uint32_t QEICAP;
+  __IO uint32_t VELCOMP;
+  __IO uint32_t FILTER;
+       uint32_t RESERVED0[998];
+  __O  uint32_t QEIIEC;
+  __O  uint32_t QEIIES;
+  __I  uint32_t QEIINTSTAT;
+  __I  uint32_t QEIIE;
+  __O  uint32_t QEICLR;
+  __O  uint32_t QEISET;
+} LPC_QEI_TypeDef;
+\r
+/*------------- Controller Area Network (CAN) --------------------------------*/
+typedef struct
+{
+  __IO uint32_t mask[512];              /* ID Masks                           */
+} LPC_CANAF_RAM_TypeDef;
+\r
+typedef struct                          /* Acceptance Filter Registers        */
+{
+  __IO uint32_t AFMR;
+  __IO uint32_t SFF_sa;
+  __IO uint32_t SFF_GRP_sa;
+  __IO uint32_t EFF_sa;
+  __IO uint32_t EFF_GRP_sa;
+  __IO uint32_t ENDofTable;
+  __I  uint32_t LUTerrAd;
+  __I  uint32_t LUTerr;
+  __IO uint32_t FCANIE;
+  __IO uint32_t FCANIC0;
+  __IO uint32_t FCANIC1;
+} LPC_CANAF_TypeDef;
+\r
+typedef struct                          /* Central Registers                  */
+{
+  __I  uint32_t CANTxSR;
+  __I  uint32_t CANRxSR;
+  __I  uint32_t CANMSR;
+} LPC_CANCR_TypeDef;
+\r
+typedef struct                          /* Controller Registers               */
+{
+  __IO uint32_t MOD;
+  __O  uint32_t CMR;
+  __IO uint32_t GSR;
+  __I  uint32_t ICR;
+  __IO uint32_t IER;
+  __IO uint32_t BTR;
+  __IO uint32_t EWL;
+  __I  uint32_t SR;
+  __IO uint32_t RFS;
+  __IO uint32_t RID;
+  __IO uint32_t RDA;
+  __IO uint32_t RDB;
+  __IO uint32_t TFI1;
+  __IO uint32_t TID1;
+  __IO uint32_t TDA1;
+  __IO uint32_t TDB1;
+  __IO uint32_t TFI2;
+  __IO uint32_t TID2;
+  __IO uint32_t TDA2;
+  __IO uint32_t TDB2;
+  __IO uint32_t TFI3;
+  __IO uint32_t TID3;
+  __IO uint32_t TDA3;
+  __IO uint32_t TDB3;
+} LPC_CAN_TypeDef;
+\r
+/*------------- General Purpose Direct Memory Access (GPDMA) -----------------*/
+typedef struct                          /* Common Registers                   */
+{
+  __I  uint32_t DMACIntStat;
+  __I  uint32_t DMACIntTCStat;
+  __O  uint32_t DMACIntTCClear;
+  __I  uint32_t DMACIntErrStat;
+  __O  uint32_t DMACIntErrClr;
+  __I  uint32_t DMACRawIntTCStat;
+  __I  uint32_t DMACRawIntErrStat;
+  __I  uint32_t DMACEnbldChns;
+  __IO uint32_t DMACSoftBReq;
+  __IO uint32_t DMACSoftSReq;
+  __IO uint32_t DMACSoftLBReq;
+  __IO uint32_t DMACSoftLSReq;
+  __IO uint32_t DMACConfig;
+  __IO uint32_t DMACSync;
+} LPC_GPDMA_TypeDef;
+\r
+typedef struct                          /* Channel Registers                  */
+{
+  __IO uint32_t DMACCSrcAddr;
+  __IO uint32_t DMACCDestAddr;
+  __IO uint32_t DMACCLLI;
+  __IO uint32_t DMACCControl;
+  __IO uint32_t DMACCConfig;
+} LPC_GPDMACH_TypeDef;
+\r
+/*------------- Universal Serial Bus (USB) -----------------------------------*/
+typedef struct
+{
+  __I  uint32_t HcRevision;             /* USB Host Registers                 */
+  __IO uint32_t HcControl;
+  __IO uint32_t HcCommandStatus;
+  __IO uint32_t HcInterruptStatus;
+  __IO uint32_t HcInterruptEnable;
+  __IO uint32_t HcInterruptDisable;
+  __IO uint32_t HcHCCA;
+  __I  uint32_t HcPeriodCurrentED;
+  __IO uint32_t HcControlHeadED;
+  __IO uint32_t HcControlCurrentED;
+  __IO uint32_t HcBulkHeadED;
+  __IO uint32_t HcBulkCurrentED;
+  __I  uint32_t HcDoneHead;
+  __IO uint32_t HcFmInterval;
+  __I  uint32_t HcFmRemaining;
+  __I  uint32_t HcFmNumber;
+  __IO uint32_t HcPeriodicStart;
+  __IO uint32_t HcLSTreshold;
+  __IO uint32_t HcRhDescriptorA;
+  __IO uint32_t HcRhDescriptorB;
+  __IO uint32_t HcRhStatus;
+  __IO uint32_t HcRhPortStatus1;
+  __IO uint32_t HcRhPortStatus2;
+       uint32_t RESERVED0[40];
+  __I  uint32_t Module_ID;
+\r
+  __I  uint32_t OTGIntSt;               /* USB On-The-Go Registers            */
+  __IO uint32_t OTGIntEn;
+  __O  uint32_t OTGIntSet;
+  __O  uint32_t OTGIntClr;
+  __IO uint32_t OTGStCtrl;
+  __IO uint32_t OTGTmr;
+       uint32_t RESERVED1[58];
+\r
+  __I  uint32_t USBDevIntSt;            /* USB Device Interrupt Registers     */
+  __IO uint32_t USBDevIntEn;
+  __O  uint32_t USBDevIntClr;
+  __O  uint32_t USBDevIntSet;
+\r
+  __O  uint32_t USBCmdCode;             /* USB Device SIE Command Registers   */
+  __I  uint32_t USBCmdData;
+\r
+  __I  uint32_t USBRxData;              /* USB Device Transfer Registers      */
+  __O  uint32_t USBTxData;
+  __I  uint32_t USBRxPLen;
+  __O  uint32_t USBTxPLen;
+  __IO uint32_t USBCtrl;
+  __O  uint32_t USBDevIntPri;
+\r
+  __I  uint32_t USBEpIntSt;             /* USB Device Endpoint Interrupt Regs */
+  __IO uint32_t USBEpIntEn;
+  __O  uint32_t USBEpIntClr;
+  __O  uint32_t USBEpIntSet;
+  __O  uint32_t USBEpIntPri;
+\r
+  __IO uint32_t USBReEp;                /* USB Device Endpoint Realization Reg*/
+  __O  uint32_t USBEpInd;
+  __IO uint32_t USBMaxPSize;
+\r
+  __I  uint32_t USBDMARSt;              /* USB Device DMA Registers           */
+  __O  uint32_t USBDMARClr;
+  __O  uint32_t USBDMARSet;
+       uint32_t RESERVED2[9];
+  __IO uint32_t USBUDCAH;
+  __I  uint32_t USBEpDMASt;
+  __O  uint32_t USBEpDMAEn;
+  __O  uint32_t USBEpDMADis;
+  __I  uint32_t USBDMAIntSt;
+  __IO uint32_t USBDMAIntEn;
+       uint32_t RESERVED3[2];
+  __I  uint32_t USBEoTIntSt;
+  __O  uint32_t USBEoTIntClr;
+  __O  uint32_t USBEoTIntSet;
+  __I  uint32_t USBNDDRIntSt;
+  __O  uint32_t USBNDDRIntClr;
+  __O  uint32_t USBNDDRIntSet;
+  __I  uint32_t USBSysErrIntSt;
+  __O  uint32_t USBSysErrIntClr;
+  __O  uint32_t USBSysErrIntSet;
+       uint32_t RESERVED4[15];
+\r
+  __I  uint32_t I2C_RX;                 /* USB OTG I2C Registers              */
+  __O  uint32_t I2C_WO;
+  __I  uint32_t I2C_STS;
+  __IO uint32_t I2C_CTL;
+  __IO uint32_t I2C_CLKHI;
+  __O  uint32_t I2C_CLKLO;
+       uint32_t RESERVED5[823];
+\r
+  union {
+  __IO uint32_t USBClkCtrl;             /* USB Clock Control Registers        */
+  __IO uint32_t OTGClkCtrl;
+  };
+  union {
+  __I  uint32_t USBClkSt;
+  __I  uint32_t OTGClkSt;
+  };
+} LPC_USB_TypeDef;
+\r
+/*------------- Ethernet Media Access Controller (EMAC) ----------------------*/
+typedef struct
+{
+  __IO uint32_t MAC1;                   /* MAC Registers                      */
+  __IO uint32_t MAC2;
+  __IO uint32_t IPGT;
+  __IO uint32_t IPGR;
+  __IO uint32_t CLRT;
+  __IO uint32_t MAXF;
+  __IO uint32_t SUPP;
+  __IO uint32_t TEST;
+  __IO uint32_t MCFG;
+  __IO uint32_t MCMD;
+  __IO uint32_t MADR;
+  __O  uint32_t MWTD;
+  __I  uint32_t MRDD;
+  __I  uint32_t MIND;
+       uint32_t RESERVED0[2];
+  __IO uint32_t SA0;
+  __IO uint32_t SA1;
+  __IO uint32_t SA2;
+       uint32_t RESERVED1[45];
+  __IO uint32_t Command;                /* Control Registers                  */
+  __I  uint32_t Status;
+  __IO uint32_t RxDescriptor;
+  __IO uint32_t RxStatus;
+  __IO uint32_t RxDescriptorNumber;
+  __I  uint32_t RxProduceIndex;
+  __IO uint32_t RxConsumeIndex;
+  __IO uint32_t TxDescriptor;
+  __IO uint32_t TxStatus;
+  __IO uint32_t TxDescriptorNumber;
+  __IO uint32_t TxProduceIndex;
+  __I  uint32_t TxConsumeIndex;
+       uint32_t RESERVED2[10];
+  __I  uint32_t TSV0;
+  __I  uint32_t TSV1;
+  __I  uint32_t RSV;
+       uint32_t RESERVED3[3];
+  __IO uint32_t FlowControlCounter;
+  __I  uint32_t FlowControlStatus;
+       uint32_t RESERVED4[34];
+  __IO uint32_t RxFilterCtrl;           /* Rx Filter Registers                */
+  __IO uint32_t RxFilterWoLStatus;
+  __IO uint32_t RxFilterWoLClear;
+       uint32_t RESERVED5;
+  __IO uint32_t HashFilterL;
+  __IO uint32_t HashFilterH;
+       uint32_t RESERVED6[882];
+  __I  uint32_t IntStatus;              /* Module Control Registers           */
+  __IO uint32_t IntEnable;
+  __O  uint32_t IntClear;
+  __O  uint32_t IntSet;
+       uint32_t RESERVED7;
+  __IO uint32_t PowerDown;
+       uint32_t RESERVED8;
+  __IO uint32_t Module_ID;
+} LPC_EMAC_TypeDef;
+\r
+#if defined ( __CC_ARM   )
+#pragma anon_unions
+#endif
+\r
+\r
+/******************************************************************************/
+/*                         Peripheral memory map                              */
+/******************************************************************************/
+/* Base addresses                                                             */
+#define LPC_FLASH_BASE        (0x00000000UL)
+#define LPC_RAM_BASE          (0x10000000UL)
+#define LPC_GPIO_BASE         (0x2009C000UL)
+#define LPC_APB0_BASE         (0x40000000UL)
+#define LPC_APB1_BASE         (0x40080000UL)
+#define LPC_AHB_BASE          (0x50000000UL)
+#define LPC_CM3_BASE          (0xE0000000UL)
+\r
+/* APB0 peripherals                                                           */
+#define LPC_WDT_BASE          (LPC_APB0_BASE + 0x00000)
+#define LPC_TIM0_BASE         (LPC_APB0_BASE + 0x04000)
+#define LPC_TIM1_BASE         (LPC_APB0_BASE + 0x08000)
+#define LPC_UART0_BASE        (LPC_APB0_BASE + 0x0C000)
+#define LPC_UART1_BASE        (LPC_APB0_BASE + 0x10000)
+#define LPC_PWM1_BASE         (LPC_APB0_BASE + 0x18000)
+#define LPC_I2C0_BASE         (LPC_APB0_BASE + 0x1C000)
+#define LPC_SPI_BASE          (LPC_APB0_BASE + 0x20000)
+#define LPC_RTC_BASE          (LPC_APB0_BASE + 0x24000)
+#define LPC_GPIOINT_BASE      (LPC_APB0_BASE + 0x28080)
+#define LPC_PINCON_BASE       (LPC_APB0_BASE + 0x2C000)
+#define LPC_SSP1_BASE         (LPC_APB0_BASE + 0x30000)
+#define LPC_ADC_BASE          (LPC_APB0_BASE + 0x34000)
+#define LPC_CANAF_RAM_BASE    (LPC_APB0_BASE + 0x38000)
+#define LPC_CANAF_BASE        (LPC_APB0_BASE + 0x3C000)
+#define LPC_CANCR_BASE        (LPC_APB0_BASE + 0x40000)
+#define LPC_CAN1_BASE         (LPC_APB0_BASE + 0x44000)
+#define LPC_CAN2_BASE         (LPC_APB0_BASE + 0x48000)
+#define LPC_I2C1_BASE         (LPC_APB0_BASE + 0x5C000)
+\r
+/* APB1 peripherals                                                           */
+#define LPC_SSP0_BASE         (LPC_APB1_BASE + 0x08000)
+#define LPC_DAC_BASE          (LPC_APB1_BASE + 0x0C000)
+#define LPC_TIM2_BASE         (LPC_APB1_BASE + 0x10000)
+#define LPC_TIM3_BASE         (LPC_APB1_BASE + 0x14000)
+#define LPC_UART2_BASE        (LPC_APB1_BASE + 0x18000)
+#define LPC_UART3_BASE        (LPC_APB1_BASE + 0x1C000)
+#define LPC_I2C2_BASE         (LPC_APB1_BASE + 0x20000)
+#define LPC_I2S_BASE          (LPC_APB1_BASE + 0x28000)
+#define LPC_RIT_BASE          (LPC_APB1_BASE + 0x30000)
+#define LPC_MCPWM_BASE        (LPC_APB1_BASE + 0x38000)
+#define LPC_QEI_BASE          (LPC_APB1_BASE + 0x3C000)
+#define LPC_SC_BASE           (LPC_APB1_BASE + 0x7C000)
+\r
+/* AHB peripherals                                                            */
+#define LPC_EMAC_BASE         (LPC_AHB_BASE  + 0x00000)
+#define LPC_GPDMA_BASE        (LPC_AHB_BASE  + 0x04000)
+#define LPC_GPDMACH0_BASE     (LPC_AHB_BASE  + 0x04100)
+#define LPC_GPDMACH1_BASE     (LPC_AHB_BASE  + 0x04120)
+#define LPC_GPDMACH2_BASE     (LPC_AHB_BASE  + 0x04140)
+#define LPC_GPDMACH3_BASE     (LPC_AHB_BASE  + 0x04160)
+#define LPC_GPDMACH4_BASE     (LPC_AHB_BASE  + 0x04180)
+#define LPC_GPDMACH5_BASE     (LPC_AHB_BASE  + 0x041A0)
+#define LPC_GPDMACH6_BASE     (LPC_AHB_BASE  + 0x041C0)
+#define LPC_GPDMACH7_BASE     (LPC_AHB_BASE  + 0x041E0)
+#define LPC_USB_BASE          (LPC_AHB_BASE  + 0x0C000)
+\r
+/* GPIOs                                                                      */
+#define LPC_GPIO0_BASE        (LPC_GPIO_BASE + 0x00000)
+#define LPC_GPIO1_BASE        (LPC_GPIO_BASE + 0x00020)
+#define LPC_GPIO2_BASE        (LPC_GPIO_BASE + 0x00040)
+#define LPC_GPIO3_BASE        (LPC_GPIO_BASE + 0x00060)
+#define LPC_GPIO4_BASE        (LPC_GPIO_BASE + 0x00080)
+\r
+\r
+/******************************************************************************/
+/*                         Peripheral declaration                             */
+/******************************************************************************/
+#define LPC_SC                ((LPC_SC_TypeDef        *) LPC_SC_BASE       )
+#define LPC_GPIO0             ((LPC_GPIO_TypeDef      *) LPC_GPIO0_BASE    )
+#define LPC_GPIO1             ((LPC_GPIO_TypeDef      *) LPC_GPIO1_BASE    )
+#define LPC_GPIO2             ((LPC_GPIO_TypeDef      *) LPC_GPIO2_BASE    )
+#define LPC_GPIO3             ((LPC_GPIO_TypeDef      *) LPC_GPIO3_BASE    )
+#define LPC_GPIO4             ((LPC_GPIO_TypeDef      *) LPC_GPIO4_BASE    )
+#define LPC_WDT               ((LPC_WDT_TypeDef       *) LPC_WDT_BASE      )
+#define LPC_TIM0              ((LPC_TIM_TypeDef       *) LPC_TIM0_BASE     )
+#define LPC_TIM1              ((LPC_TIM_TypeDef       *) LPC_TIM1_BASE     )
+#define LPC_TIM2              ((LPC_TIM_TypeDef       *) LPC_TIM2_BASE     )
+#define LPC_TIM3              ((LPC_TIM_TypeDef       *) LPC_TIM3_BASE     )
+#define LPC_RIT               ((LPC_RIT_TypeDef       *) LPC_RIT_BASE      )
+#define LPC_UART0             ((LPC_UART0_TypeDef     *) LPC_UART0_BASE    )
+#define LPC_UART1             ((LPC_UART1_TypeDef     *) LPC_UART1_BASE    )
+#define LPC_UART2             ((LPC_UART_TypeDef      *) LPC_UART2_BASE    )
+#define LPC_UART3             ((LPC_UART_TypeDef      *) LPC_UART3_BASE    )
+#define LPC_PWM1              ((LPC_PWM_TypeDef       *) LPC_PWM1_BASE     )
+#define LPC_I2C0              ((LPC_I2C_TypeDef       *) LPC_I2C0_BASE     )
+#define LPC_I2C1              ((LPC_I2C_TypeDef       *) LPC_I2C1_BASE     )
+#define LPC_I2C2              ((LPC_I2C_TypeDef       *) LPC_I2C2_BASE     )
+#define LPC_I2S               ((LPC_I2S_TypeDef       *) LPC_I2S_BASE      )
+#define LPC_SPI               ((LPC_SPI_TypeDef       *) LPC_SPI_BASE      )
+#define LPC_RTC               ((LPC_RTC_TypeDef       *) LPC_RTC_BASE      )
+#define LPC_GPIOINT           ((LPC_GPIOINT_TypeDef   *) LPC_GPIOINT_BASE  )
+#define LPC_PINCON            ((LPC_PINCON_TypeDef    *) LPC_PINCON_BASE   )
+#define LPC_SSP0              ((LPC_SSP_TypeDef       *) LPC_SSP0_BASE     )
+#define LPC_SSP1              ((LPC_SSP_TypeDef       *) LPC_SSP1_BASE     )
+#define LPC_ADC               ((LPC_ADC_TypeDef       *) LPC_ADC_BASE      )
+#define LPC_DAC               ((LPC_DAC_TypeDef       *) LPC_DAC_BASE      )
+#define LPC_CANAF_RAM         ((LPC_CANAF_RAM_TypeDef *) LPC_CANAF_RAM_BASE)
+#define LPC_CANAF             ((LPC_CANAF_TypeDef     *) LPC_CANAF_BASE    )
+#define LPC_CANCR             ((LPC_CANCR_TypeDef     *) LPC_CANCR_BASE    )
+#define LPC_CAN1              ((LPC_CAN_TypeDef       *) LPC_CAN1_BASE     )
+#define LPC_CAN2              ((LPC_CAN_TypeDef       *) LPC_CAN2_BASE     )
+#define LPC_MCPWM             ((LPC_MCPWM_TypeDef     *) LPC_MCPWM_BASE    )
+#define LPC_QEI               ((LPC_QEI_TypeDef       *) LPC_QEI_BASE      )
+#define LPC_EMAC              ((LPC_EMAC_TypeDef      *) LPC_EMAC_BASE     )
+#define LPC_GPDMA             ((LPC_GPDMA_TypeDef     *) LPC_GPDMA_BASE    )
+#define LPC_GPDMACH0          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH0_BASE )
+#define LPC_GPDMACH1          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH1_BASE )
+#define LPC_GPDMACH2          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH2_BASE )
+#define LPC_GPDMACH3          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH3_BASE )
+#define LPC_GPDMACH4          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH4_BASE )
+#define LPC_GPDMACH5          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH5_BASE )
+#define LPC_GPDMACH6          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH6_BASE )
+#define LPC_GPDMACH7          ((LPC_GPDMACH_TypeDef   *) LPC_GPDMACH7_BASE )
+#define LPC_USB               ((LPC_USB_TypeDef       *) LPC_USB_BASE      )
+\r
+#endif  // __LPC17xx_H__
index 978a75f..6e350b1 100644 (file)
-/******************************************************************************\r
- * @file:    core_cm3.h\r
- * @purpose: CMSIS Cortex-M3 Core Peripheral Access Layer Header File\r
- * @version: V1.30 PRE-RELEASE\r
- * @date:    30. July 2009\r
- *----------------------------------------------------------------------------\r
- *\r
- * Copyright (C) 2009 ARM Limited. All rights reserved.\r
- *\r
- * ARM Limited (ARM) is supplying this software for use with Cortex-Mx \r
- * processor based microcontrollers.  This file can be freely distributed \r
- * within development tools that are supporting such ARM based processors. \r
- *\r
- * THIS SOFTWARE IS PROVIDED "AS IS".  NO WARRANTIES, WHETHER EXPRESS, IMPLIED\r
- * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF\r
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.\r
- * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR\r
- * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.\r
- *\r
- ******************************************************************************/\r
-\r
-#ifndef __CM3_CORE_H__\r
-#define __CM3_CORE_H__\r
-\r
-#ifdef __cplusplus\r
- extern "C" {\r
-#endif \r
-\r
-#define __CM3_CMSIS_VERSION_MAIN  (0x01)                                                       /*!< [31:16] CMSIS HAL main version */\r
-#define __CM3_CMSIS_VERSION_SUB   (0x30)                                                       /*!< [15:0]  CMSIS HAL sub version  */\r
-#define __CM3_CMSIS_VERSION       ((__CM3_CMSIS_VERSION_MAIN << 16) | __CM3_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number       */\r
-\r
-#define __CORTEX_M                (0x03)                                                       /*!< Cortex core                    */\r
-\r
-/**\r
- *  Lint configuration \n\r
- *  ----------------------- \n\r
- *\r
- *  The following Lint messages will be suppressed and not shown: \n\r
- *  \n\r
- *    --- Error 10: --- \n\r
- *    register uint32_t __regBasePri         __asm("basepri"); \n\r
- *    Error 10: Expecting ';' \n\r
- *     \n\r
- *    --- Error 530: --- \n\r
- *    return(__regBasePri); \n\r
- *    Warning 530: Symbol '__regBasePri' (line 264) not initialized \n\r
- *     \n\r
- *    --- Error 550: --- \n\r
- *      __regBasePri = (basePri & 0x1ff); \n\r
- *    } \n\r
- *    Warning 550: Symbol '__regBasePri' (line 271) not accessed \n\r
- *     \n\r
- *    --- Error 754: --- \n\r
- *    uint32_t RESERVED0[24]; \n\r
- *    Info 754: local structure member '<some, not used in the HAL>' (line 109, file ./cm3_core.h) not referenced \n\r
- *     \n\r
- *    --- Error 750: --- \n\r
- *    #define __CM3_CORE_H__ \n\r
- *    Info 750: local macro '__CM3_CORE_H__' (line 43, file./cm3_core.h) not referenced \n\r
- *     \n\r
- *    --- Error 528: --- \n\r
- *    static __INLINE void NVIC_DisableIRQ(uint32_t IRQn) \n\r
- *    Warning 528: Symbol 'NVIC_DisableIRQ(unsigned int)' (line 419, file ./cm3_core.h) not referenced \n\r
- *     \n\r
- *    --- Error 751: --- \n\r
- *    } InterruptType_Type; \n\r
- *    Info 751: local typedef 'InterruptType_Type' (line 170, file ./cm3_core.h) not referenced \n\r
- * \n\r
- * \n\r
- *    Note:  To re-enable a Message, insert a space before 'lint' * \n\r
- *\r
- */\r
-\r
-/*lint -save */\r
-/*lint -e10  */\r
-/*lint -e530 */\r
-/*lint -e550 */\r
-/*lint -e754 */\r
-/*lint -e750 */\r
-/*lint -e528 */\r
-/*lint -e751 */\r
-\r
-\r
-#include <stdint.h>                           /* Include standard types */\r
-\r
-#if defined (__ICCARM__)\r
-  #include <intrinsics.h>                     /* IAR Intrinsics   */\r
-#endif\r
-\r
-\r
-#ifndef __NVIC_PRIO_BITS\r
-  #define __NVIC_PRIO_BITS    4               /*!< standard definition for NVIC Priority Bits */\r
-#endif\r
-\r
-\r
-\r
-\r
-/**\r
- * IO definitions\r
- *\r
- * define access restrictions to peripheral registers\r
- */\r
-\r
-#ifdef __cplusplus\r
-#define     __I     volatile                  /*!< defines 'read only' permissions      */\r
-#else\r
-#define     __I     volatile const            /*!< defines 'read only' permissions      */\r
-#endif\r
-#define     __O     volatile                  /*!< defines 'write only' permissions     */\r
-#define     __IO    volatile                  /*!< defines 'read / write' permissions   */\r
-\r
-\r
-\r
-/*******************************************************************************\r
- *                 Register Abstraction\r
- ******************************************************************************/\r
-\r
-\r
-/* System Reset */\r
-#define NVIC_VECTRESET              0         /*!< Vector Reset Bit             */\r
-#define NVIC_SYSRESETREQ            2         /*!< System Reset Request         */\r
-#define NVIC_AIRCR_VECTKEY    (0x5FA << 16)   /*!< AIRCR Key for write access   */\r
-#define NVIC_AIRCR_ENDIANESS        15        /*!< Endianess                    */\r
-\r
-/* Core Debug */\r
-#define CoreDebug_DEMCR_TRCENA (1 << 24)      /*!< DEMCR TRCENA enable          */\r
-#define ITM_TCR_ITMENA              1         /*!< ITM enable                   */\r
-\r
-\r
-\r
-\r
-/* memory mapping struct for Nested Vectored Interrupt Controller (NVIC) */\r
-typedef struct\r
-{\r
-  __IO uint32_t ISER[8];                      /*!< Interrupt Set Enable Register            */\r
-       uint32_t RESERVED0[24];\r
-  __IO uint32_t ICER[8];                      /*!< Interrupt Clear Enable Register          */\r
-       uint32_t RSERVED1[24];\r
-  __IO uint32_t ISPR[8];                      /*!< Interrupt Set Pending Register           */\r
-       uint32_t RESERVED2[24];\r
-  __IO uint32_t ICPR[8];                      /*!< Interrupt Clear Pending Register         */\r
-       uint32_t RESERVED3[24];\r
-  __IO uint32_t IABR[8];                      /*!< Interrupt Active bit Register            */\r
-       uint32_t RESERVED4[56];\r
-  __IO uint8_t  IP[240];                      /*!< Interrupt Priority Register, 8Bit wide   */\r
-       uint32_t RESERVED5[644];\r
-  __O  uint32_t STIR;                         /*!< Software Trigger Interrupt Register      */\r
-}  NVIC_Type;\r
-\r
-\r
-/* memory mapping struct for System Control Block */\r
-typedef struct\r
-{\r
-  __I  uint32_t CPUID;                        /*!< CPU ID Base Register                                     */\r
-  __IO uint32_t ICSR;                         /*!< Interrupt Control State Register                         */\r
-  __IO uint32_t VTOR;                         /*!< Vector Table Offset Register                             */\r
-  __IO uint32_t AIRCR;                        /*!< Application Interrupt / Reset Control Register           */\r
-  __IO uint32_t SCR;                          /*!< System Control Register                                  */\r
-  __IO uint32_t CCR;                          /*!< Configuration Control Register                           */\r
-  __IO uint8_t  SHP[12];                      /*!< System Handlers Priority Registers (4-7, 8-11, 12-15)    */\r
-  __IO uint32_t SHCSR;                        /*!< System Handler Control and State Register                */\r
-  __IO uint32_t CFSR;                         /*!< Configurable Fault Status Register                       */\r
-  __IO uint32_t HFSR;                         /*!< Hard Fault Status Register                               */\r
-  __IO uint32_t DFSR;                         /*!< Debug Fault Status Register                              */\r
-  __IO uint32_t MMFAR;                        /*!< Mem Manage Address Register                              */\r
-  __IO uint32_t BFAR;                         /*!< Bus Fault Address Register                               */\r
-  __IO uint32_t AFSR;                         /*!< Auxiliary Fault Status Register                          */\r
-  __I  uint32_t PFR[2];                       /*!< Processor Feature Register                               */\r
-  __I  uint32_t DFR;                          /*!< Debug Feature Register                                   */\r
-  __I  uint32_t ADR;                          /*!< Auxiliary Feature Register                               */\r
-  __I  uint32_t MMFR[4];                      /*!< Memory Model Feature Register                            */\r
-  __I  uint32_t ISAR[5];                      /*!< ISA Feature Register                                     */\r
-} SCB_Type;\r
-\r
-\r
-/* memory mapping struct for SysTick */\r
-typedef struct\r
-{\r
-  __IO uint32_t CTRL;                         /*!< SysTick Control and Status Register */\r
-  __IO uint32_t LOAD;                         /*!< SysTick Reload Value Register       */\r
-  __IO uint32_t VAL;                          /*!< SysTick Current Value Register      */\r
-  __I  uint32_t CALIB;                        /*!< SysTick Calibration Register        */\r
-} SysTick_Type;\r
-\r
-\r
-/* memory mapping structur for ITM */\r
-typedef struct\r
-{\r
-  __O  union  \r
-  {\r
-    __O  uint8_t    u8;                       /*!< ITM Stimulus Port 8-bit               */\r
-    __O  uint16_t   u16;                      /*!< ITM Stimulus Port 16-bit              */\r
-    __O  uint32_t   u32;                      /*!< ITM Stimulus Port 32-bit              */\r
-  }  PORT [32];                               /*!< ITM Stimulus Port Registers           */\r
-       uint32_t RESERVED0[864];\r
-  __IO uint32_t TER;                          /*!< ITM Trace Enable Register             */\r
-       uint32_t RESERVED1[15];\r
-  __IO uint32_t TPR;                          /*!< ITM Trace Privilege Register          */\r
-       uint32_t RESERVED2[15];\r
-  __IO uint32_t TCR;                          /*!< ITM Trace Control Register            */\r
-       uint32_t RESERVED3[29];\r
-  __IO uint32_t IWR;                          /*!< ITM Integration Write Register        */\r
-  __IO uint32_t IRR;                          /*!< ITM Integration Read Register         */\r
-  __IO uint32_t IMCR;                         /*!< ITM Integration Mode Control Register */\r
-       uint32_t RESERVED4[43];\r
-  __IO uint32_t LAR;                          /*!< ITM Lock Access Register              */\r
-  __IO uint32_t LSR;                          /*!< ITM Lock Status Register              */\r
-       uint32_t RESERVED5[6];\r
-  __I  uint32_t PID4;                         /*!< ITM Product ID Registers              */\r
-  __I  uint32_t PID5;\r
-  __I  uint32_t PID6;\r
-  __I  uint32_t PID7;\r
-  __I  uint32_t PID0;\r
-  __I  uint32_t PID1;\r
-  __I  uint32_t PID2;\r
-  __I  uint32_t PID3;\r
-  __I  uint32_t CID0;\r
-  __I  uint32_t CID1;\r
-  __I  uint32_t CID2;\r
-  __I  uint32_t CID3;\r
-} ITM_Type;\r
-\r
-\r
-/* memory mapped struct for Interrupt Type */\r
-typedef struct\r
-{\r
-       uint32_t RESERVED0;\r
-  __I  uint32_t ICTR;                         /*!< Interrupt Control Type Register  */\r
-#if ((defined __CM3_REV) && (__CM3_REV >= 0x200))\r
-  __IO uint32_t ACTLR;                        /*!< Auxiliary Control Register       */\r
-#else\r
-       uint32_t RESERVED1;\r
-#endif\r
-} InterruptType_Type;\r
-\r
-\r
-/* Memory Protection Unit */\r
-#if defined (__MPU_PRESENT) && (__MPU_PRESENT == 1)\r
-typedef struct\r
-{\r
-  __I  uint32_t TYPE;                         /*!< MPU Type Register                               */\r
-  __IO uint32_t CTRL;                         /*!< MPU Control Register                            */\r
-  __IO uint32_t RNR;                          /*!< MPU Region RNRber Register                      */\r
-  __IO uint32_t RBAR;                         /*!< MPU Region Base Address Register                */\r
-  __IO uint32_t RASR;                         /*!< MPU Region Attribute and Size Register          */\r
-  __IO uint32_t RBAR_A1;                      /*!< MPU Alias 1 Region Base Address Register        */\r
-  __IO uint32_t RASR_A1;                      /*!< MPU Alias 1 Region Attribute and Size Register  */\r
-  __IO uint32_t RBAR_A2;                      /*!< MPU Alias 2 Region Base Address Register        */\r
-  __IO uint32_t RASR_A2;                      /*!< MPU Alias 2 Region Attribute and Size Register  */\r
-  __IO uint32_t RBAR_A3;                      /*!< MPU Alias 3 Region Base Address Register        */\r
-  __IO uint32_t RASR_A3;                      /*!< MPU Alias 3 Region Attribute and Size Register  */\r
-} MPU_Type;\r
-#endif\r
-\r
-\r
-/* Core Debug Register */\r
-typedef struct\r
-{\r
-  __IO uint32_t DHCSR;                        /*!< Debug Halting Control and Status Register       */\r
-  __O  uint32_t DCRSR;                        /*!< Debug Core Register Selector Register           */\r
-  __IO uint32_t DCRDR;                        /*!< Debug Core Register Data Register               */\r
-  __IO uint32_t DEMCR;                        /*!< Debug Exception and Monitor Control Register    */\r
-} CoreDebug_Type;\r
-\r
-\r
-/* Memory mapping of Cortex-M3 Hardware */\r
-#define SCS_BASE            (0xE000E000)                              /*!< System Control Space Base Address    */\r
-#define ITM_BASE            (0xE0000000)                              /*!< ITM Base Address                     */\r
-#define CoreDebug_BASE      (0xE000EDF0)                              /*!< Core Debug Base Address              */\r
-#define SysTick_BASE        (SCS_BASE +  0x0010)                      /*!< SysTick Base Address                 */\r
-#define NVIC_BASE           (SCS_BASE +  0x0100)                      /*!< NVIC Base Address                    */\r
-#define SCB_BASE            (SCS_BASE +  0x0D00)                      /*!< System Control Block Base Address    */\r
-\r
-#define InterruptType       ((InterruptType_Type *) SCS_BASE)         /*!< Interrupt Type Register              */\r
-#define SCB                 ((SCB_Type *)           SCB_BASE)         /*!< SCB configuration struct             */\r
-#define SysTick             ((SysTick_Type *)       SysTick_BASE)     /*!< SysTick configuration struct         */\r
-#define NVIC                ((NVIC_Type *)          NVIC_BASE)        /*!< NVIC configuration struct            */\r
-#define ITM                 ((ITM_Type *)           ITM_BASE)         /*!< ITM configuration struct             */\r
-#define CoreDebug           ((CoreDebug_Type *)     CoreDebug_BASE)   /*!< Core Debug configuration struct      */\r
-\r
-#if defined (__MPU_PRESENT) && (__MPU_PRESENT == 1)\r
-  #define MPU_BASE          (SCS_BASE +  0x0D90)                      /*!< Memory Protection Unit               */\r
-  #define MPU               ((MPU_Type*)            MPU_BASE)         /*!< Memory Protection Unit               */\r
-#endif\r
-\r
-\r
-/*******************************************************************************\r
- *                Hardware Abstraction Layer\r
- ******************************************************************************/\r
-\r
-\r
-#if defined ( __CC_ARM   )\r
-  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */\r
-  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */\r
-\r
-#elif defined ( __ICCARM__ )\r
-  #define __ASM           __asm                                       /*!< asm keyword for IAR Compiler           */\r
-  #define __INLINE        inline                                      /*!< inline keyword for IAR Compiler. Only avaiable in High optimization mode! */\r
-\r
-#elif defined   (  __GNUC__  )\r
-  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */\r
-  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */\r
-\r
-#elif defined   (  __TASKING__  )\r
-  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler          */\r
-  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler       */\r
-\r
-#endif\r
-\r
-\r
-/* ###################  Compiler specific Intrinsics  ########################### */\r
-\r
-#if defined ( __CC_ARM   ) /*------------------RealView Compiler -----------------*/\r
-/* ARM armcc specific functions */\r
-\r
-#define __enable_fault_irq                __enable_fiq\r
-#define __disable_fault_irq               __disable_fiq\r
-\r
-#define __NOP                             __nop\r
-#define __WFI                             __wfi\r
-#define __WFE                             __wfe\r
-#define __SEV                             __sev\r
-#define __ISB()                           __isb(0)\r
-#define __DSB()                           __dsb(0)\r
-#define __DMB()                           __dmb(0)\r
-#define __REV                             __rev\r
-#define __RBIT                            __rbit\r
-#define __LDREXB(ptr)                     ((unsigned char ) __ldrex(ptr))\r
-#define __LDREXH(ptr)                     ((unsigned short) __ldrex(ptr))\r
-#define __LDREXW(ptr)                     ((unsigned int  ) __ldrex(ptr))\r
-#define __STREXB(value, ptr)              __strex(value, ptr)\r
-#define __STREXH(value, ptr)              __strex(value, ptr)\r
-#define __STREXW(value, ptr)              __strex(value, ptr)\r
-\r
-\r
-/* intrinsic unsigned long long __ldrexd(volatile void *ptr) */\r
-/* intrinsic int __strexd(unsigned long long val, volatile void *ptr) */\r
-/* intrinsic void __enable_irq();     */\r
-/* intrinsic void __disable_irq();    */\r
-\r
-\r
-#if (__ARMCC_VERSION < 400000)\r
-\r
-#else  /* (__ARMCC_VERSION >= 400000)  */\r
-\r
-\r
-/**\r
- * @brief  Remove the exclusive lock created by ldrex\r
- *\r
- * @param  none\r
- * @return none\r
- *\r
- * Removes the exclusive lock which is created by ldrex.\r
- */\r
-#define __CLREX                           __clrex\r
-\r
-/**\r
- * @brief  Return the Base Priority value\r
- *\r
- * @param  none\r
- * @return uint32_t BasePriority\r
- *\r
- * Return the content of the base priority register\r
- */\r
-static __INLINE uint32_t  __get_BASEPRI(void)\r
-{\r
-  register uint32_t __regBasePri         __ASM("basepri");\r
-  return(__regBasePri);\r
-}\r
-\r
-/**\r
- * @brief  Set the Base Priority value\r
- *\r
- * @param  uint32_t BasePriority\r
- * @return none\r
- *\r
- * Set the base priority register\r
- */\r
-static __INLINE void __set_BASEPRI(uint32_t basePri)\r
-{\r
-  register uint32_t __regBasePri         __ASM("basepri");\r
-  __regBasePri = (basePri & 0xff);\r
-}\r
-\r
-/**\r
- * @brief  Return the Priority Mask value\r
- *\r
- * @param  none\r
- * @return uint32_t PriMask\r
- *\r
- * Return the state of the priority mask bit from the priority mask\r
- * register\r
- */\r
-static __INLINE uint32_t __get_PRIMASK(void)\r
-{\r
-  register uint32_t __regPriMask         __ASM("primask");\r
-  return(__regPriMask);\r
-}\r
-\r
-/**\r
- * @brief  Set the Priority Mask value\r
- *\r
- * @param  uint32_t PriMask\r
- * @return none\r
- *\r
- * Set the priority mask bit in the priority mask register\r
- */\r
-static __INLINE void __set_PRIMASK(uint32_t priMask)\r
-{\r
-  register uint32_t __regPriMask         __ASM("primask");\r
-  __regPriMask = (priMask);\r
-}\r
-\r
-/**\r
- * @brief  Return the Fault Mask value\r
- *\r
- * @param  none\r
- * @return uint32_t FaultMask\r
- *\r
- * Return the content of the fault mask register\r
- */\r
-static __INLINE uint32_t __get_FAULTMASK(void)\r
-{\r
-  register uint32_t __regFaultMask       __ASM("faultmask");\r
-  return(__regFaultMask);\r
-}\r
-\r
-/**\r
- * @brief  Set the Fault Mask value\r
- *\r
- * @param  uint32_t faultMask value\r
- * @return none\r
- *\r
- * Set the fault mask register\r
- */\r
-static __INLINE void __set_FAULTMASK(uint32_t faultMask)\r
-{\r
-  register uint32_t __regFaultMask       __ASM("faultmask");\r
-  __regFaultMask = (faultMask & 1);\r
-}\r
-\r
-/**\r
- * @brief  Return the Control Register value\r
- * \r
- * @param  none\r
- * @return uint32_t Control value\r
- *\r
- * Return the content of the control register\r
- */\r
-static __INLINE uint32_t __get_CONTROL(void)\r
-{\r
-  register uint32_t __regControl         __ASM("control");\r
-  return(__regControl);\r
-}\r
-\r
-/**\r
- * @brief  Set the Control Register value\r
- *\r
- * @param  uint32_t Control value\r
- * @return none\r
- *\r
- * Set the control register\r
- */\r
-static __INLINE void __set_CONTROL(uint32_t control)\r
-{\r
-  register uint32_t __regControl         __ASM("control");\r
-  __regControl = control;\r
-}\r
-\r
-#endif /* __ARMCC_VERSION  */ \r
-\r
-\r
-\r
-#elif (defined (__ICCARM__)) /*------------------ ICC Compiler -------------------*/\r
-/* IAR iccarm specific functions */\r
-\r
-#define __enable_irq                              __enable_interrupt        /*!< global Interrupt enable */\r
-#define __disable_irq                             __disable_interrupt       /*!< global Interrupt disable */\r
-\r
-static __INLINE void __enable_fault_irq()         { __ASM ("cpsie f"); }\r
-static __INLINE void __disable_fault_irq()        { __ASM ("cpsid f"); }\r
-\r
-#define __NOP                                     __no_operation()          /*!< no operation intrinsic in IAR Compiler */ \r
-static __INLINE  void __WFI()                     { __ASM ("wfi"); }\r
-static __INLINE  void __WFE()                     { __ASM ("wfe"); }\r
-static __INLINE  void __SEV()                     { __ASM ("sev"); }\r
-static __INLINE  void __CLREX()                   { __ASM ("clrex"); }\r
-\r
-/* intrinsic void __ISB(void)                                     */\r
-/* intrinsic void __DSB(void)                                     */\r
-/* intrinsic void __DMB(void)                                     */\r
-/* intrinsic void __set_PRIMASK();                                */\r
-/* intrinsic void __get_PRIMASK();                                */\r
-/* intrinsic void __set_FAULTMASK();                              */\r
-/* intrinsic void __get_FAULTMASK();                              */\r
-/* intrinsic uint32_t __REV(uint32_t value);                      */\r
-/* intrinsic uint32_t __REVSH(uint32_t value);                    */\r
-/* intrinsic unsigned long __STREX(unsigned long, unsigned long); */\r
-/* intrinsic unsigned long __LDREX(unsigned long *);              */\r
-\r
-\r
-#elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/\r
-/* GNU gcc specific functions */\r
-\r
-static __INLINE void __enable_irq()               { __ASM volatile ("cpsie i"); }\r
-static __INLINE void __disable_irq()              { __ASM volatile ("cpsid i"); }\r
-\r
-static __INLINE void __enable_fault_irq()         { __ASM volatile ("cpsie f"); }\r
-static __INLINE void __disable_fault_irq()        { __ASM volatile ("cpsid f"); }\r
-\r
-static __INLINE void __NOP()                      { __ASM volatile ("nop"); }\r
-static __INLINE void __WFI()                      { __ASM volatile ("wfi"); }\r
-static __INLINE void __WFE()                      { __ASM volatile ("wfe"); }\r
-static __INLINE void __SEV()                      { __ASM volatile ("sev"); }\r
-static __INLINE void __ISB()                      { __ASM volatile ("isb"); }\r
-static __INLINE void __DSB()                      { __ASM volatile ("dsb"); }\r
-static __INLINE void __DMB()                      { __ASM volatile ("dmb"); }\r
-static __INLINE void __CLREX()                    { __ASM volatile ("clrex"); }\r
-\r
-\r
-#elif (defined (__TASKING__)) /*------------------ TASKING Compiler ---------------------*/\r
-/* TASKING carm specific functions */\r
-\r
-/*\r
- * The CMSIS functions have been implemented as intrinsics in the compiler.\r
- * Please use "carm -?i" to get an up to date list of all instrinsics,\r
- * Including the CMSIS ones.\r
- */\r
-\r
-#endif\r
-\r
-\r
-\r
-/* ##########################   NVIC functions  #################################### */\r
-\r
-\r
-/**\r
- * @brief  Set the Priority Grouping in NVIC Interrupt Controller\r
- *\r
- * @param  uint32_t priority_grouping is priority grouping field\r
- * @return none \r
- *\r
- * Set the priority grouping field using the required unlock sequence.\r
- * The parameter priority_grouping is assigned to the field \r
- * SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used.\r
- * In case of a conflict between priority grouping and available\r
- * priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set.\r
- */\r
-static __INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup)\r
-{\r
-  uint32_t reg_value;\r
-  uint32_t PriorityGroupTmp = (PriorityGroup & 0x07);                         /* only values 0..7 are used          */\r
+/******************************************************************************
+ * @file:    core_cm3.h
+ * @purpose: CMSIS Cortex-M3 Core Peripheral Access Layer Header File
+ * @version: V1.30 PRE-RELEASE
+ * @date:    30. July 2009
+ *----------------------------------------------------------------------------
+ *
+ * Copyright (C) 2009 ARM Limited. All rights reserved.
+ *
+ * ARM Limited (ARM) is supplying this software for use with Cortex-Mx
+ * processor based microcontrollers.  This file can be freely distributed
+ * within development tools that are supporting such ARM based processors.
+ *
+ * THIS SOFTWARE IS PROVIDED "AS IS".  NO WARRANTIES, WHETHER EXPRESS, IMPLIED
+ * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
+ * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
+ * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
+ *
+ ******************************************************************************/
+\r
+#ifndef __CM3_CORE_H__
+#define __CM3_CORE_H__
+\r
+#ifdef __cplusplus
+ extern "C" {
+#endif
+\r
+#define __CM3_CMSIS_VERSION_MAIN  (0x01)                                                       /*!< [31:16] CMSIS HAL main version */
+#define __CM3_CMSIS_VERSION_SUB   (0x30)                                                       /*!< [15:0]  CMSIS HAL sub version  */
+#define __CM3_CMSIS_VERSION       ((__CM3_CMSIS_VERSION_MAIN << 16) | __CM3_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number       */
+\r
+#define __CORTEX_M                (0x03)                                                       /*!< Cortex core                    */
+\r
+/**
+ *  Lint configuration \n
+ *  ----------------------- \n
+ *
+ *  The following Lint messages will be suppressed and not shown: \n
+ *  \n
+ *    --- Error 10: --- \n
+ *    register uint32_t __regBasePri         __asm("basepri"); \n
+ *    Error 10: Expecting ';' \n
+ *     \n
+ *    --- Error 530: --- \n
+ *    return(__regBasePri); \n
+ *    Warning 530: Symbol '__regBasePri' (line 264) not initialized \n
+ *     \n
+ *    --- Error 550: --- \n
+ *      __regBasePri = (basePri & 0x1ff); \n
+ *    } \n
+ *    Warning 550: Symbol '__regBasePri' (line 271) not accessed \n
+ *     \n
+ *    --- Error 754: --- \n
+ *    uint32_t RESERVED0[24]; \n
+ *    Info 754: local structure member '<some, not used in the HAL>' (line 109, file ./cm3_core.h) not referenced \n
+ *     \n
+ *    --- Error 750: --- \n
+ *    #define __CM3_CORE_H__ \n
+ *    Info 750: local macro '__CM3_CORE_H__' (line 43, file./cm3_core.h) not referenced \n
+ *     \n
+ *    --- Error 528: --- \n
+ *    static __INLINE void NVIC_DisableIRQ(uint32_t IRQn) \n
+ *    Warning 528: Symbol 'NVIC_DisableIRQ(unsigned int)' (line 419, file ./cm3_core.h) not referenced \n
+ *     \n
+ *    --- Error 751: --- \n
+ *    } InterruptType_Type; \n
+ *    Info 751: local typedef 'InterruptType_Type' (line 170, file ./cm3_core.h) not referenced \n
+ * \n
+ * \n
+ *    Note:  To re-enable a Message, insert a space before 'lint' * \n
+ *
+ */
+\r
+/*lint -save */
+/*lint -e10  */
+/*lint -e530 */
+/*lint -e550 */
+/*lint -e754 */
+/*lint -e750 */
+/*lint -e528 */
+/*lint -e751 */
+\r
+\r
+#include <stdint.h>                           /* Include standard types */
+\r
+#if defined (__ICCARM__)
+  #include <intrinsics.h>                     /* IAR Intrinsics   */
+#endif
+\r
+\r
+#ifndef __NVIC_PRIO_BITS
+  #define __NVIC_PRIO_BITS    4               /*!< standard definition for NVIC Priority Bits */
+#endif
+\r
+\r
+\r
+\r
+/**
+ * IO definitions
+ *
+ * define access restrictions to peripheral registers
+ */
+\r
+#ifdef __cplusplus
+#define     __I     volatile                  /*!< defines 'read only' permissions      */
+#else
+#define     __I     volatile const            /*!< defines 'read only' permissions      */
+#endif
+#define     __O     volatile                  /*!< defines 'write only' permissions     */
+#define     __IO    volatile                  /*!< defines 'read / write' permissions   */
+\r
+\r
+\r
+/*******************************************************************************
+ *                 Register Abstraction
+ ******************************************************************************/
+\r
+\r
+/* System Reset */
+#define NVIC_VECTRESET              0         /*!< Vector Reset Bit             */
+#define NVIC_SYSRESETREQ            2         /*!< System Reset Request         */
+#define NVIC_AIRCR_VECTKEY    (0x5FA << 16)   /*!< AIRCR Key for write access   */
+#define NVIC_AIRCR_ENDIANESS        15        /*!< Endianess                    */
+\r
+/* Core Debug */
+#define CoreDebug_DEMCR_TRCENA (1 << 24)      /*!< DEMCR TRCENA enable          */
+#define ITM_TCR_ITMENA              1         /*!< ITM enable                   */
+\r
+\r
+\r
+\r
+/* memory mapping struct for Nested Vectored Interrupt Controller (NVIC) */
+typedef struct
+{
+  __IO uint32_t ISER[8];                      /*!< Interrupt Set Enable Register            */
+       uint32_t RESERVED0[24];
+  __IO uint32_t ICER[8];                      /*!< Interrupt Clear Enable Register          */
+       uint32_t RSERVED1[24];
+  __IO uint32_t ISPR[8];                      /*!< Interrupt Set Pending Register           */
+       uint32_t RESERVED2[24];
+  __IO uint32_t ICPR[8];                      /*!< Interrupt Clear Pending Register         */
+       uint32_t RESERVED3[24];
+  __IO uint32_t IABR[8];                      /*!< Interrupt Active bit Register            */
+       uint32_t RESERVED4[56];
+  __IO uint8_t  IP[240];                      /*!< Interrupt Priority Register, 8Bit wide   */
+       uint32_t RESERVED5[644];
+  __O  uint32_t STIR;                         /*!< Software Trigger Interrupt Register      */
+}  NVIC_Type;
+\r
+\r
+/* memory mapping struct for System Control Block */
+typedef struct
+{
+  __I  uint32_t CPUID;                        /*!< CPU ID Base Register                                     */
+  __IO uint32_t ICSR;                         /*!< Interrupt Control State Register                         */
+  __IO uint32_t VTOR;                         /*!< Vector Table Offset Register                             */
+  __IO uint32_t AIRCR;                        /*!< Application Interrupt / Reset Control Register           */
+  __IO uint32_t SCR;                          /*!< System Control Register                                  */
+  __IO uint32_t CCR;                          /*!< Configuration Control Register                           */
+  __IO uint8_t  SHP[12];                      /*!< System Handlers Priority Registers (4-7, 8-11, 12-15)    */
+  __IO uint32_t SHCSR;                        /*!< System Handler Control and State Register                */
+  __IO uint32_t CFSR;                         /*!< Configurable Fault Status Register                       */
+  __IO uint32_t HFSR;                         /*!< Hard Fault Status Register                               */
+  __IO uint32_t DFSR;                         /*!< Debug Fault Status Register                              */
+  __IO uint32_t MMFAR;                        /*!< Mem Manage Address Register                              */
+  __IO uint32_t BFAR;                         /*!< Bus Fault Address Register                               */
+  __IO uint32_t AFSR;                         /*!< Auxiliary Fault Status Register                          */
+  __I  uint32_t PFR[2];                       /*!< Processor Feature Register                               */
+  __I  uint32_t DFR;                          /*!< Debug Feature Register                                   */
+  __I  uint32_t ADR;                          /*!< Auxiliary Feature Register                               */
+  __I  uint32_t MMFR[4];                      /*!< Memory Model Feature Register                            */
+  __I  uint32_t ISAR[5];                      /*!< ISA Feature Register                                     */
+} SCB_Type;
+\r
+\r
+/* memory mapping struct for SysTick */
+typedef struct
+{
+  __IO uint32_t CTRL;                         /*!< SysTick Control and Status Register */
+  __IO uint32_t LOAD;                         /*!< SysTick Reload Value Register       */
+  __IO uint32_t VAL;                          /*!< SysTick Current Value Register      */
+  __I  uint32_t CALIB;                        /*!< SysTick Calibration Register        */
+} SysTick_Type;
+\r
+\r
+/* memory mapping structur for ITM */
+typedef struct
+{
+  __O  union
+  {
+    __O  uint8_t    u8;                       /*!< ITM Stimulus Port 8-bit               */
+    __O  uint16_t   u16;                      /*!< ITM Stimulus Port 16-bit              */
+    __O  uint32_t   u32;                      /*!< ITM Stimulus Port 32-bit              */
+  }  PORT [32];                               /*!< ITM Stimulus Port Registers           */
+       uint32_t RESERVED0[864];
+  __IO uint32_t TER;                          /*!< ITM Trace Enable Register             */
+       uint32_t RESERVED1[15];
+  __IO uint32_t TPR;                          /*!< ITM Trace Privilege Register          */
+       uint32_t RESERVED2[15];
+  __IO uint32_t TCR;                          /*!< ITM Trace Control Register            */
+       uint32_t RESERVED3[29];
+  __IO uint32_t IWR;                          /*!< ITM Integration Write Register        */
+  __IO uint32_t IRR;                          /*!< ITM Integration Read Register         */
+  __IO uint32_t IMCR;                         /*!< ITM Integration Mode Control Register */
+       uint32_t RESERVED4[43];
+  __IO uint32_t LAR;                          /*!< ITM Lock Access Register              */
+  __IO uint32_t LSR;                          /*!< ITM Lock Status Register              */
+       uint32_t RESERVED5[6];
+  __I  uint32_t PID4;                         /*!< ITM Product ID Registers              */
+  __I  uint32_t PID5;
+  __I  uint32_t PID6;
+  __I  uint32_t PID7;
+  __I  uint32_t PID0;
+  __I  uint32_t PID1;
+  __I  uint32_t PID2;
+  __I  uint32_t PID3;
+  __I  uint32_t CID0;
+  __I  uint32_t CID1;
+  __I  uint32_t CID2;
+  __I  uint32_t CID3;
+} ITM_Type;
+\r
+\r
+/* memory mapped struct for Interrupt Type */
+typedef struct
+{
+       uint32_t RESERVED0;
+  __I  uint32_t ICTR;                         /*!< Interrupt Control Type Register  */
+#if ((defined __CM3_REV) && (__CM3_REV >= 0x200))
+  __IO uint32_t ACTLR;                        /*!< Auxiliary Control Register       */
+#else
+       uint32_t RESERVED1;
+#endif
+} InterruptType_Type;
+\r
+\r
+/* Memory Protection Unit */
+#if defined (__MPU_PRESENT) && (__MPU_PRESENT == 1)
+typedef struct
+{
+  __I  uint32_t TYPE;                         /*!< MPU Type Register                               */
+  __IO uint32_t CTRL;                         /*!< MPU Control Register                            */
+  __IO uint32_t RNR;                          /*!< MPU Region RNRber Register                      */
+  __IO uint32_t RBAR;                         /*!< MPU Region Base Address Register                */
+  __IO uint32_t RASR;                         /*!< MPU Region Attribute and Size Register          */
+  __IO uint32_t RBAR_A1;                      /*!< MPU Alias 1 Region Base Address Register        */
+  __IO uint32_t RASR_A1;                      /*!< MPU Alias 1 Region Attribute and Size Register  */
+  __IO uint32_t RBAR_A2;                      /*!< MPU Alias 2 Region Base Address Register        */
+  __IO uint32_t RASR_A2;                      /*!< MPU Alias 2 Region Attribute and Size Register  */
+  __IO uint32_t RBAR_A3;                      /*!< MPU Alias 3 Region Base Address Register        */
+  __IO uint32_t RASR_A3;                      /*!< MPU Alias 3 Region Attribute and Size Register  */
+} MPU_Type;
+#endif
+\r
+\r
+/* Core Debug Register */
+typedef struct
+{
+  __IO uint32_t DHCSR;                        /*!< Debug Halting Control and Status Register       */
+  __O  uint32_t DCRSR;                        /*!< Debug Core Register Selector Register           */
+  __IO uint32_t DCRDR;                        /*!< Debug Core Register Data Register               */
+  __IO uint32_t DEMCR;                        /*!< Debug Exception and Monitor Control Register    */
+} CoreDebug_Type;
+\r
+\r
+/* Memory mapping of Cortex-M3 Hardware */
+#define SCS_BASE            (0xE000E000)                              /*!< System Control Space Base Address    */
+#define ITM_BASE            (0xE0000000)                              /*!< ITM Base Address                     */
+#define CoreDebug_BASE      (0xE000EDF0)                              /*!< Core Debug Base Address              */
+#define SysTick_BASE        (SCS_BASE +  0x0010)                      /*!< SysTick Base Address                 */
+#define NVIC_BASE           (SCS_BASE +  0x0100)                      /*!< NVIC Base Address                    */
+#define SCB_BASE            (SCS_BASE +  0x0D00)                      /*!< System Control Block Base Address    */
+\r
+#define InterruptType       ((InterruptType_Type *) SCS_BASE)         /*!< Interrupt Type Register              */
+#define SCB                 ((SCB_Type *)           SCB_BASE)         /*!< SCB configuration struct             */
+#define SysTick             ((SysTick_Type *)       SysTick_BASE)     /*!< SysTick configuration struct         */
+#define NVIC                ((NVIC_Type *)          NVIC_BASE)        /*!< NVIC configuration struct            */
+#define ITM                 ((ITM_Type *)           ITM_BASE)         /*!< ITM configuration struct             */
+#define CoreDebug           ((CoreDebug_Type *)     CoreDebug_BASE)   /*!< Core Debug configuration struct      */
+\r
+#if defined (__MPU_PRESENT) && (__MPU_PRESENT == 1)
+  #define MPU_BASE          (SCS_BASE +  0x0D90)                      /*!< Memory Protection Unit               */
+  #define MPU               ((MPU_Type*)            MPU_BASE)         /*!< Memory Protection Unit               */
+#endif
+\r
+\r
+/*******************************************************************************
+ *                Hardware Abstraction Layer
+ ******************************************************************************/
+\r
+\r
+#if defined ( __CC_ARM   )
+  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
+  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
+\r
+#elif defined ( __ICCARM__ )
+  #define __ASM           __asm                                       /*!< asm keyword for IAR Compiler           */
+  #define __INLINE        inline                                      /*!< inline keyword for IAR Compiler. Only avaiable in High optimization mode! */
+\r
+#elif defined   (  __GNUC__  )
+  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
+\r
+#elif defined   (  __TASKING__  )
+  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler       */
+\r
+#endif
+\r
+\r
+/* ###################  Compiler specific Intrinsics  ########################### */
+\r
+#if defined ( __CC_ARM   ) /*------------------RealView Compiler -----------------*/
+/* ARM armcc specific functions */
+\r
+#define __enable_fault_irq                __enable_fiq
+#define __disable_fault_irq               __disable_fiq
+\r
+#define __NOP                             __nop
+#define __WFI                             __wfi
+#define __WFE                             __wfe
+#define __SEV                             __sev
+#define __ISB()                           __isb(0)
+#define __DSB()                           __dsb(0)
+#define __DMB()                           __dmb(0)
+#define __REV                             __rev
+#define __RBIT                            __rbit
+#define __LDREXB(ptr)                     ((unsigned char ) __ldrex(ptr))
+#define __LDREXH(ptr)                     ((unsigned short) __ldrex(ptr))
+#define __LDREXW(ptr)                     ((unsigned int  ) __ldrex(ptr))
+#define __STREXB(value, ptr)              __strex(value, ptr)
+#define __STREXH(value, ptr)              __strex(value, ptr)
+#define __STREXW(value, ptr)              __strex(value, ptr)
+\r
+\r
+/* intrinsic unsigned long long __ldrexd(volatile void *ptr) */
+/* intrinsic int __strexd(unsigned long long val, volatile void *ptr) */
+/* intrinsic void __enable_irq();     */
+/* intrinsic void __disable_irq();    */
+\r
+\r
+#if (__ARMCC_VERSION < 400000)
+\r
+#else  /* (__ARMCC_VERSION >= 400000)  */
+\r
+\r
+/**
+ * @brief  Remove the exclusive lock created by ldrex
+ *
+ * @param  none
+ * @return none
+ *
+ * Removes the exclusive lock which is created by ldrex.
+ */
+#define __CLREX                           __clrex
+\r
+/**
+ * @brief  Return the Base Priority value
+ *
+ * @param  none
+ * @return uint32_t BasePriority
+ *
+ * Return the content of the base priority register
+ */
+static __INLINE uint32_t  __get_BASEPRI(void)
+{
+  register uint32_t __regBasePri         __ASM("basepri");
+  return(__regBasePri);
+}
+\r
+/**
+ * @brief  Set the Base Priority value
+ *
+ * @param  uint32_t BasePriority
+ * @return none
+ *
+ * Set the base priority register
+ */
+static __INLINE void __set_BASEPRI(uint32_t basePri)
+{
+  register uint32_t __regBasePri         __ASM("basepri");
+  __regBasePri = (basePri & 0xff);
+}
+\r
+/**
+ * @brief  Return the Priority Mask value
+ *
+ * @param  none
+ * @return uint32_t PriMask
+ *
+ * Return the state of the priority mask bit from the priority mask
+ * register
+ */
+static __INLINE uint32_t __get_PRIMASK(void)
+{
+  register uint32_t __regPriMask         __ASM("primask");
+  return(__regPriMask);
+}
+\r
+/**
+ * @brief  Set the Priority Mask value
+ *
+ * @param  uint32_t PriMask
+ * @return none
+ *
+ * Set the priority mask bit in the priority mask register
+ */
+static __INLINE void __set_PRIMASK(uint32_t priMask)
+{
+  register uint32_t __regPriMask         __ASM("primask");
+  __regPriMask = (priMask);
+}
+\r
+/**
+ * @brief  Return the Fault Mask value
+ *
+ * @param  none
+ * @return uint32_t FaultMask
+ *
+ * Return the content of the fault mask register
+ */
+static __INLINE uint32_t __get_FAULTMASK(void)
+{
+  register uint32_t __regFaultMask       __ASM("faultmask");
+  return(__regFaultMask);
+}
+\r
+/**
+ * @brief  Set the Fault Mask value
+ *
+ * @param  uint32_t faultMask value
+ * @return none
+ *
+ * Set the fault mask register
+ */
+static __INLINE void __set_FAULTMASK(uint32_t faultMask)
+{
+  register uint32_t __regFaultMask       __ASM("faultmask");
+  __regFaultMask = (faultMask & 1);
+}
+\r
+/**
+ * @brief  Return the Control Register value
+ *
+ * @param  none
+ * @return uint32_t Control value
+ *
+ * Return the content of the control register
+ */
+static __INLINE uint32_t __get_CONTROL(void)
+{
+  register uint32_t __regControl         __ASM("control");
+  return(__regControl);
+}
+\r
+/**
+ * @brief  Set the Control Register value
+ *
+ * @param  uint32_t Control value
+ * @return none
+ *
+ * Set the control register
+ */
+static __INLINE void __set_CONTROL(uint32_t control)
+{
+  register uint32_t __regControl         __ASM("control");
+  __regControl = control;
+}
+\r
+#endif /* __ARMCC_VERSION  */
+\r
+\r
+\r
+#elif (defined (__ICCARM__)) /*------------------ ICC Compiler -------------------*/
+/* IAR iccarm specific functions */
+\r
+#define __enable_irq                              __enable_interrupt        /*!< global Interrupt enable */
+#define __disable_irq                             __disable_interrupt       /*!< global Interrupt disable */
+\r
+static __INLINE void __enable_fault_irq()         { __ASM ("cpsie f"); }
+static __INLINE void __disable_fault_irq()        { __ASM ("cpsid f"); }
+\r
+#define __NOP                                     __no_operation()          /*!< no operation intrinsic in IAR Compiler */
+static __INLINE  void __WFI()                     { __ASM ("wfi"); }
+static __INLINE  void __WFE()                     { __ASM ("wfe"); }
+static __INLINE  void __SEV()                     { __ASM ("sev"); }
+static __INLINE  void __CLREX()                   { __ASM ("clrex"); }
+\r
+/* intrinsic void __ISB(void)                                     */
+/* intrinsic void __DSB(void)                                     */
+/* intrinsic void __DMB(void)                                     */
+/* intrinsic void __set_PRIMASK();                                */
+/* intrinsic void __get_PRIMASK();                                */
+/* intrinsic void __set_FAULTMASK();                              */
+/* intrinsic void __get_FAULTMASK();                              */
+/* intrinsic uint32_t __REV(uint32_t value);                      */
+/* intrinsic uint32_t __REVSH(uint32_t value);                    */
+/* intrinsic unsigned long __STREX(unsigned long, unsigned long); */
+/* intrinsic unsigned long __LDREX(unsigned long *);              */
+\r
+\r
+#elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/
+/* GNU gcc specific functions */
+\r
+static __INLINE void __enable_irq()               { __ASM volatile ("cpsie i"); }
+static __INLINE void __disable_irq()              { __ASM volatile ("cpsid i"); }
+\r
+static __INLINE void __enable_fault_irq()         { __ASM volatile ("cpsie f"); }
+static __INLINE void __disable_fault_irq()        { __ASM volatile ("cpsid f"); }
+\r
+static __INLINE void __NOP()                      { __ASM volatile ("nop"); }
+static __INLINE void __WFI()                      { __ASM volatile ("wfi"); }
+static __INLINE void __WFE()                      { __ASM volatile ("wfe"); }
+static __INLINE void __SEV()                      { __ASM volatile ("sev"); }
+static __INLINE void __ISB()                      { __ASM volatile ("isb"); }
+static __INLINE void __DSB()                      { __ASM volatile ("dsb"); }
+static __INLINE void __DMB()                      { __ASM volatile ("dmb"); }
+static __INLINE void __CLREX()                    { __ASM volatile ("clrex"); }
+\r
+\r
+#elif (defined (__TASKING__)) /*------------------ TASKING Compiler ---------------------*/
+/* TASKING carm specific functions */
+\r
+/*
+ * The CMSIS functions have been implemented as intrinsics in the compiler.
+ * Please use "carm -?i" to get an up to date list of all instrinsics,
+ * Including the CMSIS ones.
+ */
+\r
+#endif
+\r
+\r
+\r
+/* ##########################   NVIC functions  #################################### */
+\r
+\r
+/**
+ * @brief  Set the Priority Grouping in NVIC Interrupt Controller
+ *
+ * @param  uint32_t priority_grouping is priority grouping field
+ * @return none
+ *
+ * Set the priority grouping field using the required unlock sequence.
+ * The parameter priority_grouping is assigned to the field
+ * SCB->AIRCR [10:8] PRIGROUP field. Only values from 0..7 are used.
+ * In case of a conflict between priority grouping and available
+ * priority bits (__NVIC_PRIO_BITS) the smallest possible priority group is set.
+ */
+static __INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
+{
+  uint32_t reg_value;
+  uint32_t PriorityGroupTmp = (PriorityGroup & 0x07);                         /* only values 0..7 are used          */
   \r
-  reg_value  = SCB->AIRCR;                                                    /* read old register configuration    */\r
-  reg_value &= ~((0xFFFFU << 16) | (0x0F << 8));                              /* clear bits to change               */\r
-  reg_value  = ((reg_value | NVIC_AIRCR_VECTKEY | (PriorityGroupTmp << 8)));  /* Insert write key and priorty group */\r
-  SCB->AIRCR = reg_value;\r
-}\r
-\r
-/**\r
- * @brief  Get the Priority Grouping from NVIC Interrupt Controller\r
- *\r
- * @param  none\r
- * @return uint32_t   priority grouping field \r
- *\r
- * Get the priority grouping from NVIC Interrupt Controller.\r
- * priority grouping is SCB->AIRCR [10:8] PRIGROUP field.\r
- */\r
-static __INLINE uint32_t NVIC_GetPriorityGrouping(void)\r
-{\r
-  return ((SCB->AIRCR >> 8) & 0x07);                                          /* read priority grouping field */\r
-}\r
-\r
-/**\r
- * @brief  Enable Interrupt in NVIC Interrupt Controller\r
- *\r
- * @param  IRQn_Type IRQn specifies the interrupt number\r
- * @return none \r
- *\r
- * Enable a device specific interupt in the NVIC interrupt controller.\r
- * The interrupt number cannot be a negative value.\r
- */\r
-static __INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)\r
-{\r
-  NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */\r
-}\r
-\r
-/**\r
- * @brief  Disable the interrupt line for external interrupt specified\r
- * \r
- * @param  IRQn_Type IRQn is the positive number of the external interrupt\r
- * @return none\r
- * \r
- * Disable a device specific interupt in the NVIC interrupt controller.\r
- * The interrupt number cannot be a negative value.\r
- */\r
-static __INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)\r
-{\r
-  NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */\r
-}\r
-\r
-/**\r
- * @brief  Read the interrupt pending bit for a device specific interrupt source\r
- * \r
- * @param  IRQn_Type IRQn is the number of the device specifc interrupt\r
- * @return uint32_t 1 if pending interrupt else 0\r
- *\r
- * Read the pending register in NVIC and return 1 if its status is pending, \r
- * otherwise it returns 0\r
- */\r
-static __INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)\r
-{\r
-  return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */\r
-}\r
-\r
-/**\r
- * @brief  Set the pending bit for an external interrupt\r
- * \r
- * @param  IRQn_Type IRQn is the Number of the interrupt\r
- * @return none\r
- *\r
- * Set the pending bit for the specified interrupt.\r
- * The interrupt number cannot be a negative value.\r
- */\r
-static __INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)\r
-{\r
-  NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */\r
-}\r
-\r
-/**\r
- * @brief  Clear the pending bit for an external interrupt\r
- *\r
- * @param  IRQn_Type IRQn is the Number of the interrupt\r
- * @return none\r
- *\r
- * Clear the pending bit for the specified interrupt. \r
- * The interrupt number cannot be a negative value.\r
- */\r
-static __INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)\r
-{\r
-  NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */\r
-}\r
-\r
-/**\r
- * @brief  Read the active bit for an external interrupt\r
- *\r
- * @param  IRQn_Type  IRQn is the Number of the interrupt\r
- * @return uint32_t   1 if active else 0\r
- *\r
- * Read the active register in NVIC and returns 1 if its status is active, \r
- * otherwise it returns 0.\r
- */\r
-static __INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn)\r
-{\r
-  return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */\r
-}\r
-\r
-/**\r
- * @brief  Set the priority for an interrupt\r
- *\r
- * @param  IRQn_Type IRQn is the Number of the interrupt\r
- * @param  priority is the priority for the interrupt\r
- * @return none\r
- *\r
- * Set the priority for the specified interrupt. The interrupt \r
- * number can be positive to specify an external (device specific) \r
- * interrupt, or negative to specify an internal (core) interrupt. \n\r
- *\r
- * Note: The priority cannot be set for every core interrupt.\r
- */\r
-static __INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)\r
-{\r
-  if(IRQn < 0) {\r
-    SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M3 System Interrupts */\r
-  else {\r
-    NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff);    }        /* set Priority for device specific Interrupts      */\r
-}\r
-\r
-/**\r
- * @brief  Read the priority for an interrupt\r
- *\r
- * @param  IRQn_Type IRQn is the Number of the interrupt\r
- * @return uint32_t  priority is the priority for the interrupt\r
- *\r
- * Read the priority for the specified interrupt. The interrupt \r
- * number can be positive to specify an external (device specific) \r
- * interrupt, or negative to specify an internal (core) interrupt.\r
- *\r
- * The returned priority value is automatically aligned to the implemented\r
- * priority bits of the microcontroller.\r
- *\r
- * Note: The priority cannot be set for every core interrupt.\r
- */\r
-static __INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)\r
-{\r
-\r
-  if(IRQn < 0) {\r
-    return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for Cortex-M3 system interrupts */\r
-  else {\r
-    return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)]           >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for device specific interrupts  */\r
-}\r
-\r
-\r
-/**\r
- * @brief  Encode the priority for an interrupt\r
- *\r
- * @param  uint32_t PriorityGroup   is the used priority group\r
- * @param  uint32_t PreemptPriority is the preemptive priority value (starting from 0)\r
- * @param  uint32_t SubPriority     is the sub priority value (starting from 0)\r
- * @return uint32_t                    the priority for the interrupt\r
- *\r
- * Encode the priority for an interrupt with the given priority group,\r
- * preemptive priority value and sub priority value.\r
- * In case of a conflict between priority grouping and available\r
- * priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set.\r
- *\r
- * The returned priority value can be used for NVIC_SetPriority(...) function\r
- */\r
-static __INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority)\r
-{\r
-  uint32_t PriorityGroupTmp = (PriorityGroup & 0x07);                         /* only values 0..7 are used          */\r
-  uint32_t PreemptPriorityBits;\r
-  uint32_t SubPriorityBits;\r
-\r
-  PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;\r
-  SubPriorityBits     = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;\r
+  reg_value  = SCB->AIRCR;                                                    /* read old register configuration    */
+  reg_value &= ~((0xFFFFU << 16) | (0x0F << 8));                              /* clear bits to change               */
+  reg_value  = ((reg_value | NVIC_AIRCR_VECTKEY | (PriorityGroupTmp << 8)));  /* Insert write key and priorty group */
+  SCB->AIRCR = reg_value;
+}
+\r
+/**
+ * @brief  Get the Priority Grouping from NVIC Interrupt Controller
+ *
+ * @param  none
+ * @return uint32_t   priority grouping field
+ *
+ * Get the priority grouping from NVIC Interrupt Controller.
+ * priority grouping is SCB->AIRCR [10:8] PRIGROUP field.
+ */
+static __INLINE uint32_t NVIC_GetPriorityGrouping(void)
+{
+  return ((SCB->AIRCR >> 8) & 0x07);                                          /* read priority grouping field */
+}
+\r
+/**
+ * @brief  Enable Interrupt in NVIC Interrupt Controller
+ *
+ * @param  IRQn_Type IRQn specifies the interrupt number
+ * @return none
+ *
+ * Enable a device specific interupt in the NVIC interrupt controller.
+ * The interrupt number cannot be a negative value.
+ */
+static __INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
+{
+  NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */
+}
+\r
+/**
+ * @brief  Disable the interrupt line for external interrupt specified
+ *
+ * @param  IRQn_Type IRQn is the positive number of the external interrupt
+ * @return none
+ *
+ * Disable a device specific interupt in the NVIC interrupt controller.
+ * The interrupt number cannot be a negative value.
+ */
+static __INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
+{
+  NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */
+}
+\r
+/**
+ * @brief  Read the interrupt pending bit for a device specific interrupt source
+ *
+ * @param  IRQn_Type IRQn is the number of the device specifc interrupt
+ * @return uint32_t 1 if pending interrupt else 0
+ *
+ * Read the pending register in NVIC and return 1 if its status is pending,
+ * otherwise it returns 0
+ */
+static __INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
+{
+  return((uint32_t) ((NVIC->ISPR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if pending else 0 */
+}
+\r
+/**
+ * @brief  Set the pending bit for an external interrupt
+ *
+ * @param  IRQn_Type IRQn is the Number of the interrupt
+ * @return none
+ *
+ * Set the pending bit for the specified interrupt.
+ * The interrupt number cannot be a negative value.
+ */
+static __INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
+{
+  NVIC->ISPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* set interrupt pending */
+}
+\r
+/**
+ * @brief  Clear the pending bit for an external interrupt
+ *
+ * @param  IRQn_Type IRQn is the Number of the interrupt
+ * @return none
+ *
+ * Clear the pending bit for the specified interrupt.
+ * The interrupt number cannot be a negative value.
+ */
+static __INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
+{
+  NVIC->ICPR[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */
+}
+\r
+/**
+ * @brief  Read the active bit for an external interrupt
+ *
+ * @param  IRQn_Type  IRQn is the Number of the interrupt
+ * @return uint32_t   1 if active else 0
+ *
+ * Read the active register in NVIC and returns 1 if its status is active,
+ * otherwise it returns 0.
+ */
+static __INLINE uint32_t NVIC_GetActive(IRQn_Type IRQn)
+{
+  return((uint32_t)((NVIC->IABR[(uint32_t)(IRQn) >> 5] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0)); /* Return 1 if active else 0 */
+}
+\r
+/**
+ * @brief  Set the priority for an interrupt
+ *
+ * @param  IRQn_Type IRQn is the Number of the interrupt
+ * @param  priority is the priority for the interrupt
+ * @return none
+ *
+ * Set the priority for the specified interrupt. The interrupt
+ * number can be positive to specify an external (device specific)
+ * interrupt, or negative to specify an internal (core) interrupt. \n
+ *
+ * Note: The priority cannot be set for every core interrupt.
+ */
+static __INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
+{
+  if(IRQn < 0) {
+    SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff); } /* set Priority for Cortex-M3 System Interrupts */
+  else {
+    NVIC->IP[(uint32_t)(IRQn)] = ((priority << (8 - __NVIC_PRIO_BITS)) & 0xff);    }        /* set Priority for device specific Interrupts      */
+}
+\r
+/**
+ * @brief  Read the priority for an interrupt
+ *
+ * @param  IRQn_Type IRQn is the Number of the interrupt
+ * @return uint32_t  priority is the priority for the interrupt
+ *
+ * Read the priority for the specified interrupt. The interrupt
+ * number can be positive to specify an external (device specific)
+ * interrupt, or negative to specify an internal (core) interrupt.
+ *
+ * The returned priority value is automatically aligned to the implemented
+ * priority bits of the microcontroller.
+ *
+ * Note: The priority cannot be set for every core interrupt.
+ */
+static __INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
+{
+\r
+  if(IRQn < 0) {
+    return((uint32_t)(SCB->SHP[((uint32_t)(IRQn) & 0xF)-4] >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for Cortex-M3 system interrupts */
+  else {
+    return((uint32_t)(NVIC->IP[(uint32_t)(IRQn)]           >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for device specific interrupts  */
+}
+\r
+\r
+/**
+ * @brief  Encode the priority for an interrupt
+ *
+ * @param  uint32_t PriorityGroup   is the used priority group
+ * @param  uint32_t PreemptPriority is the preemptive priority value (starting from 0)
+ * @param  uint32_t SubPriority     is the sub priority value (starting from 0)
+ * @return uint32_t                    the priority for the interrupt
+ *
+ * Encode the priority for an interrupt with the given priority group,
+ * preemptive priority value and sub priority value.
+ * In case of a conflict between priority grouping and available
+ * priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set.
+ *
+ * The returned priority value can be used for NVIC_SetPriority(...) function
+ */
+static __INLINE uint32_t NVIC_EncodePriority (uint32_t PriorityGroup, uint32_t PreemptPriority, uint32_t SubPriority)
+{
+  uint32_t PriorityGroupTmp = (PriorityGroup & 0x07);                         /* only values 0..7 are used          */
+  uint32_t PreemptPriorityBits;
+  uint32_t SubPriorityBits;
+\r
+  PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;
+  SubPriorityBits     = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;
  \r
-  return (\r
-           ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) |\r
-           ((SubPriority     & ((1 << (SubPriorityBits    )) - 1)))\r
-         );\r
-}\r
-\r
-\r
-/**\r
- * @brief  Decode the priority of an interrupt\r
- *\r
- * @param  uint32_t   Priority       the priority for the interrupt\r
- * @param  uint32_t   PrioGroup   is the used priority group\r
- * @param  uint32_t* pPreemptPrio is the preemptive priority value (starting from 0)\r
- * @param  uint32_t* pSubPrio     is the sub priority value (starting from 0)\r
- * @return none\r
- *\r
- * Decode an interrupt priority value with the given priority group to \r
- * preemptive priority value and sub priority value.\r
- * In case of a conflict between priority grouping and available\r
- * priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set.\r
- *\r
- * The priority value can be retrieved with NVIC_GetPriority(...) function\r
- */\r
-static __INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority)\r
-{\r
-  uint32_t PriorityGroupTmp = (PriorityGroup & 0x07);                         /* only values 0..7 are used          */\r
-  uint32_t PreemptPriorityBits;\r
-  uint32_t SubPriorityBits;\r
-\r
-  PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;\r
-  SubPriorityBits     = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;\r
+  return (
+           ((PreemptPriority & ((1 << (PreemptPriorityBits)) - 1)) << SubPriorityBits) |
+           ((SubPriority     & ((1 << (SubPriorityBits    )) - 1)))
+         );
+}
+\r
+\r
+/**
+ * @brief  Decode the priority of an interrupt
+ *
+ * @param  uint32_t   Priority       the priority for the interrupt
+ * @param  uint32_t   PrioGroup   is the used priority group
+ * @param  uint32_t* pPreemptPrio is the preemptive priority value (starting from 0)
+ * @param  uint32_t* pSubPrio     is the sub priority value (starting from 0)
+ * @return none
+ *
+ * Decode an interrupt priority value with the given priority group to
+ * preemptive priority value and sub priority value.
+ * In case of a conflict between priority grouping and available
+ * priority bits (__NVIC_PRIO_BITS) the samllest possible priority group is set.
+ *
+ * The priority value can be retrieved with NVIC_GetPriority(...) function
+ */
+static __INLINE void NVIC_DecodePriority (uint32_t Priority, uint32_t PriorityGroup, uint32_t* pPreemptPriority, uint32_t* pSubPriority)
+{
+  uint32_t PriorityGroupTmp = (PriorityGroup & 0x07);                         /* only values 0..7 are used          */
+  uint32_t PreemptPriorityBits;
+  uint32_t SubPriorityBits;
+\r
+  PreemptPriorityBits = ((7 - PriorityGroupTmp) > __NVIC_PRIO_BITS) ? __NVIC_PRIO_BITS : 7 - PriorityGroupTmp;
+  SubPriorityBits     = ((PriorityGroupTmp + __NVIC_PRIO_BITS) < 7) ? 0 : PriorityGroupTmp - 7 + __NVIC_PRIO_BITS;
   \r
-  *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1);\r
-  *pSubPriority     = (Priority                   ) & ((1 << (SubPriorityBits    )) - 1);\r
-}\r
-\r
-\r
-\r
-/* ##################################    SysTick function  ############################################ */\r
-\r
-#if (!defined (__Vendor_SysTickConfig)) || (__Vendor_SysTickConfig == 0)\r
-\r
-/* SysTick constants */\r
-#define SYSTICK_ENABLE              0                                          /* Config-Bit to start or stop the SysTick Timer                         */\r
-#define SYSTICK_TICKINT             1                                          /* Config-Bit to enable or disable the SysTick interrupt                 */\r
-#define SYSTICK_CLKSOURCE           2                                          /* Clocksource has the offset 2 in SysTick Control and Status Register   */\r
-#define SYSTICK_MAXCOUNT       ((1<<24) -1)                                    /* SysTick MaxCount                                                      */\r
-\r
-/**\r
- * @brief  Initialize and start the SysTick counter and its interrupt.\r
- *\r
- * @param  uint32_t ticks is the number of ticks between two interrupts\r
- * @return  none\r
- *\r
- * Initialise the system tick timer and its interrupt and start the\r
- * system tick timer / counter in free running mode to generate \r
- * periodical interrupts.\r
- */\r
-static __INLINE uint32_t SysTick_Config(uint32_t ticks)\r
-{ \r
-  if (ticks > SYSTICK_MAXCOUNT)  return (1);                                             /* Reload value impossible */\r
-\r
-  SysTick->LOAD  =  (ticks & SYSTICK_MAXCOUNT) - 1;                                      /* set reload register */\r
-  NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);                            /* set Priority for Cortex-M0 System Interrupts */\r
-  SysTick->VAL   =  (0x00);                                                              /* Load the SysTick Counter Value */\r
-  SysTick->CTRL = (1 << SYSTICK_CLKSOURCE) | (1<<SYSTICK_ENABLE) | (1<<SYSTICK_TICKINT); /* Enable SysTick IRQ and SysTick Timer */\r
-  return (0);                                                                            /* Function successful */\r
-}\r
-\r
-#endif\r
-\r
-\r
-\r
-\r
-\r
-/* ##################################    Reset function  ############################################ */\r
-\r
-/**\r
- * @brief  Initiate a system reset request.\r
- *\r
- * @param   none\r
- * @return  none\r
- *\r
- * Initialize a system reset request to reset the MCU\r
- */\r
-static __INLINE void NVIC_SystemReset(void)\r
-{\r
-  SCB->AIRCR  = (NVIC_AIRCR_VECTKEY | (SCB->AIRCR & (0x700)) | (1<<NVIC_SYSRESETREQ)); /* Keep priority group unchanged */\r
-  __DSB();                                                                             /* Ensure completion of memory access */              \r
-  while(1);                                                                            /* wait until reset */\r
-}\r
-\r
-\r
-/* ##################################### Debug In/Output function ########################################### */\r
-\r
-extern volatile int ITM_RxBuffer;                    /* variable to receive characters                             */\r
-#define             ITM_RXBUFFER_EMPTY    0x5AA55AA5 /* value identifying ITM_RxBuffer is ready for next character */\r
-\r
-\r
-/**\r
- * @brief  Outputs a character via the ITM channel 0\r
- *\r
- * @param   uint32_t character to output\r
- * @return  uint32_t input character\r
- *\r
- * The function outputs a character via the ITM channel 0. \r
- * The function returns when no debugger is connected that has booked the output.  \r
- * It is blocking when a debugger is connected, but the previous character send is not transmitted. \r
- */\r
-static __INLINE uint32_t ITM_SendChar (uint32_t ch)\r
-{\r
-  if ((CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA)  &&\r
-      (ITM->TCR & ITM_TCR_ITMENA)                  &&\r
-      (ITM->TER & (1UL << 0))  ) \r
-  {\r
-    while (ITM->PORT[0].u32 == 0);\r
-    ITM->PORT[0].u8 = (uint8_t) ch;\r
-  }  \r
-  return (ch);\r
-}\r
-\r
-\r
-/**\r
- * @brief  Inputs a character via variable ITM_RxBuffer\r
- *\r
- * @param   none\r
- * @return  uint32_t input character\r
- *\r
- * The function inputs a character via variable ITM_RxBuffer. \r
- * The function returns when no debugger is connected that has booked the output.  \r
- * It is blocking when a debugger is connected, but the previous character send is not transmitted. \r
- */\r
-static __INLINE int ITM_ReceiveChar (void) {\r
-  int ch = -1;                               /* no character available */\r
-\r
-  if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) {\r
-    ch = ITM_RxBuffer;\r
-    ITM_RxBuffer = ITM_RXBUFFER_EMPTY;       /* ready for next character */\r
-  }\r
+  *pPreemptPriority = (Priority >> SubPriorityBits) & ((1 << (PreemptPriorityBits)) - 1);
+  *pSubPriority     = (Priority                   ) & ((1 << (SubPriorityBits    )) - 1);
+}
+\r
+\r
+\r
+/* ##################################    SysTick function  ############################################ */
+\r
+#if (!defined (__Vendor_SysTickConfig)) || (__Vendor_SysTickConfig == 0)
+\r
+/* SysTick constants */
+#define SYSTICK_ENABLE              0                                          /* Config-Bit to start or stop the SysTick Timer                         */
+#define SYSTICK_TICKINT             1                                          /* Config-Bit to enable or disable the SysTick interrupt                 */
+#define SYSTICK_CLKSOURCE           2                                          /* Clocksource has the offset 2 in SysTick Control and Status Register   */
+#define SYSTICK_MAXCOUNT       ((1<<24) -1)                                    /* SysTick MaxCount                                                      */
+\r
+/**
+ * @brief  Initialize and start the SysTick counter and its interrupt.
+ *
+ * @param  uint32_t ticks is the number of ticks between two interrupts
+ * @return  none
+ *
+ * Initialise the system tick timer and its interrupt and start the
+ * system tick timer / counter in free running mode to generate
+ * periodical interrupts.
+ */
+static __INLINE uint32_t SysTick_Config(uint32_t ticks)
+{
+  if (ticks > SYSTICK_MAXCOUNT)  return (1);                                             /* Reload value impossible */
+\r
+  SysTick->LOAD  =  (ticks & SYSTICK_MAXCOUNT) - 1;                                      /* set reload register */
+  NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);                            /* set Priority for Cortex-M0 System Interrupts */
+  SysTick->VAL   =  (0x00);                                                              /* Load the SysTick Counter Value */
+  SysTick->CTRL = (1 << SYSTICK_CLKSOURCE) | (1<<SYSTICK_ENABLE) | (1<<SYSTICK_TICKINT); /* Enable SysTick IRQ and SysTick Timer */
+  return (0);                                                                            /* Function successful */
+}
+\r
+#endif
+\r
+\r
+\r
+\r
+\r
+/* ##################################    Reset function  ############################################ */
+\r
+/**
+ * @brief  Initiate a system reset request.
+ *
+ * @param   none
+ * @return  none
+ *
+ * Initialize a system reset request to reset the MCU
+ */
+static __INLINE void NVIC_SystemReset(void)
+{
+  SCB->AIRCR  = (NVIC_AIRCR_VECTKEY | (SCB->AIRCR & (0x700)) | (1<<NVIC_SYSRESETREQ)); /* Keep priority group unchanged */
+  __DSB();                                                                             /* Ensure completion of memory access */
+  while(1);                                                                            /* wait until reset */
+}
+\r
+\r
+/* ##################################### Debug In/Output function ########################################### */
+\r
+extern volatile int ITM_RxBuffer;                    /* variable to receive characters                             */
+#define             ITM_RXBUFFER_EMPTY    0x5AA55AA5 /* value identifying ITM_RxBuffer is ready for next character */
+\r
+\r
+/**
+ * @brief  Outputs a character via the ITM channel 0
+ *
+ * @param   uint32_t character to output
+ * @return  uint32_t input character
+ *
+ * The function outputs a character via the ITM channel 0.
+ * The function returns when no debugger is connected that has booked the output.
+ * It is blocking when a debugger is connected, but the previous character send is not transmitted.
+ */
+static __INLINE uint32_t ITM_SendChar (uint32_t ch)
+{
+  if ((CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA)  &&
+      (ITM->TCR & ITM_TCR_ITMENA)                  &&
+      (ITM->TER & (1UL << 0))  )
+  {
+    while (ITM->PORT[0].u32 == 0);
+    ITM->PORT[0].u8 = (uint8_t) ch;
+  }
+  return (ch);
+}
+\r
+\r
+/**
+ * @brief  Inputs a character via variable ITM_RxBuffer
+ *
+ * @param   none
+ * @return  uint32_t input character
+ *
+ * The function inputs a character via variable ITM_RxBuffer.
+ * The function returns when no debugger is connected that has booked the output.
+ * It is blocking when a debugger is connected, but the previous character send is not transmitted.
+ */
+static __INLINE int ITM_ReceiveChar (void) {
+  int ch = -1;                               /* no character available */
+\r
+  if (ITM_RxBuffer != ITM_RXBUFFER_EMPTY) {
+    ch = ITM_RxBuffer;
+    ITM_RxBuffer = ITM_RXBUFFER_EMPTY;       /* ready for next character */
+  }
   \r
-  return (ch); \r
-}\r
+  return (ch);
+}
 \r
 \r
-/**\r
- * @brief  Check if  a character via variable ITM_RxBuffer is available\r
- *\r
- * @param   none\r
- * @return  int  1 = character available, 0 = no character available\r
- *\r
- * The function checks  variable ITM_RxBuffer whether a character is available or not. \r
- * The function returns '1' if a character is available and '0' if no character is available. \r
- */\r
-static __INLINE int ITM_CheckChar (void) {\r
+/**
+ * @brief  Check if  a character via variable ITM_RxBuffer is available
+ *
+ * @param   none
+ * @return  int  1 = character available, 0 = no character available
+ *
+ * The function checks  variable ITM_RxBuffer whether a character is available or not.
+ * The function returns '1' if a character is available and '0' if no character is available.
+ */
+static __INLINE int ITM_CheckChar (void) {
 \r
-  if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) {\r
-    return (0);                                 /* no character available */\r
-  } else {\r
-    return (1);                                 /*    character available */\r
-  }\r
-}\r
+  if (ITM_RxBuffer == ITM_RXBUFFER_EMPTY) {
+    return (0);                                 /* no character available */
+  } else {
+    return (1);                                 /*    character available */
+  }
+}
 \r
 \r
 \r
-#ifdef __cplusplus\r
-}\r
-#endif\r
+#ifdef __cplusplus
+}
+#endif
 \r
-#endif /* __CM3_CORE_H__ */\r
+#endif /* __CM3_CORE_H__ */
 \r
-/*lint -restore */\r
+/*lint -restore */
index e8335c2..1ab7c82 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "libs/Module.h"
index 6f62682..8347839 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef MODULE_H
@@ -12,7 +12,7 @@
 using std::string;
 
 // Module base class
-// All modules must extend this class, see http://smoothieware.org/moduleexample 
+// All modules must extend this class, see http://smoothieware.org/moduleexample
 class Kernel;
 class Module {
     public:
index 17bbd8b..bebc215 100644 (file)
@@ -14,16 +14,16 @@ class Pin{
         Pin* from_string(std::string value){
             LPC_GPIO_TypeDef* gpios[5] ={LPC_GPIO0,LPC_GPIO1,LPC_GPIO2,LPC_GPIO3,LPC_GPIO4};
             if( value.find_first_of("n")!=string::npos ? true : false ){
-                this->port_number = 0;  
-                this->port = gpios[(unsigned int) this->port_number]; 
+                this->port_number = 0;
+                this->port = gpios[(unsigned int) this->port_number];
                 this->inverting = false;
                 this->pin = 255;;
             }else{
-                this->port_number =  atoi(value.substr(0,1).c_str());  
-                this->port = gpios[(unsigned int) this->port_number]; 
+                this->port_number =  atoi(value.substr(0,1).c_str());
+                this->port = gpios[(unsigned int) this->port_number];
                 this->inverting = ( value.find_first_of("!")!=string::npos ? true : false );
                 this->pin  = atoi( value.substr(2, value.size()-2-(this->inverting?1:0)).c_str() );
-            } 
+            }
             return this;
         }
 
@@ -35,12 +35,12 @@ class Pin{
         inline Pin* as_output(){
             this->port->FIODIR |= 1<<this->pin;
             return this;
-        }  
+        }
 
         inline Pin* as_input(){
             this->port->FIODIR &= ~(1<<this->pin);
             return this;
-        }  
+        }
 
         inline Pin* as_open_drain(){
             if( this->port_number == 0 ){ LPC_PINCON->PINMODE_OD0 |= (1<<this->pin); }
@@ -60,13 +60,13 @@ class Pin{
                 this->port->FIOSET = 1 << this->pin;
             }else{
                 this->port->FIOCLR = 1 << this->pin;
-            }        
+            }
         }
 
-        bool inverting; 
+        bool inverting;
         LPC_GPIO_TypeDef* port;
         char port_number;
-        char pin; 
+        char pin;
 };
 
 
index 4e650e4..65a6d81 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
       
       With chucks taken from http://en.wikipedia.org/wiki/Circular_buffer, see licence there also
 */
@@ -67,9 +67,9 @@ template<class kind, int length> void RingBuffer<kind, length>::get(int index, k
         j++;
         k= (k + 1) & (length - 1);
     }
-    // TODO : this checks wether we are asked a value out of range 
+    // TODO : this checks wether we are asked a value out of range
     //if (k == this->tail){
-    //    return NULL; 
+    //    return NULL;
     //}
     object = this->buffer[k];
 }
@@ -83,7 +83,7 @@ template<class kind, int length> kind* RingBuffer<kind, length>::get_ref(int ind
         j++;
         k= (k + 1) & (length - 1);
     }
-    // TODO : this checks wether we are asked a value out of range 
+    // TODO : this checks wether we are asked a value out of range
     if (k == this->tail){
         return NULL;
     }
@@ -91,7 +91,7 @@ template<class kind, int length> kind* RingBuffer<kind, length>::get_ref(int ind
 }
 
 template<class kind, int length> void RingBuffer<kind, length>::pop_front(kind &object){
-    object = this->buffer[this->head]; 
+    object = this->buffer[this->head];
     this->head = (this->head+1)&(length-1);
 }
 
index 0b69a17..e9aeffb 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 using namespace std;
@@ -38,13 +38,13 @@ void SlowTicker::tick(){
     LPC_GPIO1->FIODIR |= 1<<20;
     LPC_GPIO1->FIOSET = 1<<20;
 
-    for (unsigned int i=0; i<this->hooks.size(); i++){ 
+    for (unsigned int i=0; i<this->hooks.size(); i++){
         Hook* hook = this->hooks.at(i);
         hook->counter += ( hook->frequency / this->max_frequency );
         if( hook->counter > 0 ){
             hook->counter-=1;
             hook->call();
-        } 
+        }
     }
 
     LPC_GPIO1->FIOCLR = 1<<20;
@@ -53,8 +53,8 @@ void SlowTicker::tick(){
 
 extern "C" void TIMER2_IRQHandler (void){
     if((LPC_TIM2->IR >> 0) & 1){  // If interrupt register set for MR0
-        LPC_TIM2->IR |= 1 << 0;   // Reset it 
+        LPC_TIM2->IR |= 1 << 0;   // Reset it
     }
-    global_slow_ticker->tick(); 
+    global_slow_ticker->tick();
 }
 
index b2fa321..68bcb3e 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 
@@ -24,19 +24,19 @@ class SlowTicker : public Module{
         void tick();
         // For some reason this can't go in the .cpp, see :  http://mbed.org/forum/mbed/topic/2774/?page=1#comment-14221
         template<typename T> Hook* attach( double frequency, T *optr, uint32_t ( T::*fptr )( uint32_t ) ){
-            Hook* hook = new Hook(); 
+            Hook* hook = new Hook();
             hook->frequency = frequency;
             hook->attach(optr, fptr);
             hook->counter = -1.5;
-            if( frequency > this->max_frequency ){ 
-                this->max_frequency = frequency; 
-            } 
-            this->set_frequency(this->max_frequency); 
+            if( frequency > this->max_frequency ){
+                this->max_frequency = frequency;
+            }
+            this->set_frequency(this->max_frequency);
             this->hooks.push_back(hook);
             return hook;
         }
 
-        vector<Hook*> hooks; 
+        vector<Hook*> hooks;
         double max_frequency;
 };
 
index 266cd80..5eb0750 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 
@@ -30,7 +30,7 @@ class StepTicker{
         void remove_motor_from_active_list(StepperMotor* motor);
 
         double frequency;
-        vector<StepperMotor*> stepper_motors; 
+        vector<StepperMotor*> stepper_motors;
         uint32_t delay;
         uint32_t period;
         uint32_t debug;
index c7da6d4..ec115eb 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef STREAMOUTPUT_H
index 7712f6a..174cd6f 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#include "stdint.h"\r
-#include "stdarg.h"\r
-#include "USBCDCMSC.h"\r
-#include "USBBusInterface.h"\r
-#include "libs/SerialMessage.h"\r
-\r
-#include "libs/StreamOutput.h"\r
-#include "libs/RingBuffer.h"\r
-\r
-static uint8_t cdc_line_coding[7]= {0x80, 0x25, 0x00, 0x00, 0x00, 0x00, 0x08};\r
-\r
-#define DEFAULT_CONFIGURATION (1)\r
-\r
-#define CDC_SET_LINE_CODING        0x20\r
-#define CDC_GET_LINE_CODING        0x21\r
-#define CDC_SET_CONTROL_LINE_STATE 0x22\r
-#define CDC_SEND_BREAK             0x23\r
-\r
-#define MAX_CDC_REPORT_SIZE MAX_PACKET_SIZE_EPBULK\r
-\r
-\r
-\r
-#define DISK_OK         0x00\r
-#define NO_INIT         0x01\r
-#define NO_DISK         0x02\r
-#define WRITE_PROTECT   0x04\r
-\r
-#define CBW_Signature   0x43425355\r
-#define CSW_Signature   0x53425355\r
-\r
-// SCSI Commands\r
-#define TEST_UNIT_READY            0x00\r
-#define REQUEST_SENSE              0x03\r
-#define FORMAT_UNIT                0x04\r
-#define INQUIRY                    0x12\r
-#define MODE_SELECT6               0x15\r
-#define MODE_SENSE6                0x1A\r
-#define START_STOP_UNIT            0x1B\r
-#define MEDIA_REMOVAL              0x1E\r
-#define READ_FORMAT_CAPACITIES     0x23\r
-#define READ_CAPACITY              0x25\r
-#define READ10                     0x28\r
-#define WRITE10                    0x2A\r
-#define VERIFY10                   0x2F\r
-#define READ12                     0xA8\r
-#define WRITE12                    0xAA\r
-#define MODE_SELECT10              0x55\r
-#define MODE_SENSE10               0x5A\r
-\r
-// MSC class specific requests\r
-#define MSC_REQUEST_RESET          0xFF\r
-#define MSC_REQUEST_GET_MAX_LUN    0xFE\r
-\r
-#define DEFAULT_CONFIGURATION (1)\r
-\r
-// Sense codes\r
-#define SENSE_NO_SENSE          0x00\r
-#define SENSE_RECOVERED_ERROR   0x01\r
-#define SENSE_NOT_READY         0x02\r
-#define SENSE_MEDIUM_ERROR      0x03\r
-#define SENSE_HARDWARE_ERROR    0x04\r
-#define SENSE_ILLEGAL_REQUEST   0x05\r
-#define SENSE_UNIT_ATTENTION    0x06\r
-#define SENSE_DATA_PROTECT      0x07\r
-#define SENSE_BLANK_CHECK       0x08\r
-#define SENSE_ABORTED_COMMAND   0x0B\r
-#define SENSE_VOLUME_OVERFLOW   0x0D\r
-#define SENSE_MISCOMPARE        0x0E\r
-\r
-// max packet size\r
-#define MAX_PACKET  MAX_PACKET_SIZE_EPBULK\r
-\r
-// CSW Status\r
-enum Status {\r
-    CSW_PASSED,\r
-    CSW_FAILED,\r
-    CSW_ERROR,\r
-};\r
-\r
-\r
-USBCDCMSC::USBCDCMSC(SDFileSystem *sd, uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release), cdcbuf(128), _sd(sd) {\r
-    cdcbreak = 0;\r
-    _status = NO_INIT;\r
-    connect();\r
-//    USBDevice::connect();\r
-    setSense(SENSE_NO_SENSE, 0x00, 0x00);\r
-    USBHAL::connect();\r
-}\r
-\r
-bool USBCDCMSC::USBCallback_request(void) {\r
-    /* Called in ISR context */\r
-\r
-    bool success = false;\r
-    CONTROL_TRANSFER * transfer = getTransferPtr();\r
-    static uint8_t maxLUN[1] = {0};\r
-\r
-    /* Process class-specific requests */\r
-\r
-    if (transfer->setup.bmRequestType.Type == CLASS_TYPE) {\r
-        switch (transfer->setup.bRequest) {\r
-            case CDC_GET_LINE_CODING:\r
-                transfer->remaining = 7;\r
-                transfer->ptr = cdc_line_coding;\r
-                transfer->direction = DEVICE_TO_HOST;\r
-                success = true;\r
-                break;\r
-            case CDC_SET_LINE_CODING:\r
-                transfer->remaining = 7;\r
-                success = true;\r
-                break;\r
-            case CDC_SET_CONTROL_LINE_STATE:\r
-                success = true;\r
-                break;\r
-            case CDC_SEND_BREAK:\r
-                cdcbreak = 1;\r
-                success = true;\r
-                break;\r
-            case MSC_REQUEST_RESET:\r
-                reset();\r
-                success = true;\r
-                break;\r
-            case MSC_REQUEST_GET_MAX_LUN:\r
-                transfer->remaining = 1;\r
-                transfer->ptr = maxLUN;\r
-                transfer->direction = DEVICE_TO_HOST;\r
-                success = true;\r
-                break;\r
-            default:\r
-                break;\r
-        }\r
-    }\r
-\r
-    return success;\r
-}\r
-\r
-\r
-// Called in ISR context\r
-// Set configuration. Return false if the\r
-// configuration is not supported.\r
-bool USBCDCMSC::USBCallback_setConfiguration(uint8_t configuration) {\r
-    if (configuration != DEFAULT_CONFIGURATION) {\r
-        return false;\r
-    }\r
-\r
-    // Configure endpoints > 0\r
-    addEndpoint(EPINT_IN, MAX_PACKET_SIZE_EPINT);\r
-    addEndpoint(EPBULK_IN, MAX_PACKET_SIZE_EPBULK);\r
-    addEndpoint(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-\r
-    // Configure endpoints > 0\r
-    addEndpoint(MSDBULK_IN, MAX_PACKET_SIZE_MSDBULK);\r
-    addEndpoint(MSDBULK_OUT, MAX_PACKET_SIZE_MSDBULK);\r
-\r
-    // We activate the endpoint to be able to recceive data\r
-    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-\r
-    //activate readings\r
-    readStart(MSDBULK_OUT, MAX_PACKET_SIZE_MSDBULK);\r
-    return true;\r
-}\r
-\r
-bool USBCDCMSC::send(uint8_t * buffer, uint16_t size) {\r
-    return USBDevice::write(EPBULK_IN, buffer, size, MAX_CDC_REPORT_SIZE);\r
-}\r
-\r
-bool USBCDCMSC::readEP(uint8_t * buffer, uint16_t * size) {\r
-    if (!USBDevice::readEP(EPBULK_OUT, buffer, size, MAX_CDC_REPORT_SIZE))\r
-        return false;\r
-    if (!readStart(EPBULK_OUT, MAX_CDC_REPORT_SIZE))\r
-        return false;\r
-    return true;\r
-}\r
-\r
-bool USBCDCMSC::readEP_NB(uint8_t * buffer, uint16_t * size) {\r
-    if (!USBDevice::readEP_NB(EPBULK_OUT, buffer, size, MAX_CDC_REPORT_SIZE))\r
-        return false;\r
-    if (!readStart(EPBULK_OUT, MAX_CDC_REPORT_SIZE))\r
-        return false;\r
-    return true;\r
-}\r
-\r
-\r
-uint8_t * USBCDCMSC::deviceDesc() {\r
-    static uint8_t deviceDescriptor[] = {\r
-        18,                   // bLength\r
-        1,                    // bDescriptorType\r
-        0x10, 0x01,           // bcdUSB\r
-        0xef,                    // bDeviceClass\r
-        0x02,                    // bDeviceSubClass\r
-        0x01,                    // bDeviceProtocol\r
-        MAX_PACKET_SIZE_EP0,  // bMaxPacketSize0\r
-        LSB(VENDOR_ID), MSB(VENDOR_ID),  // idVendor\r
-        LSB(PRODUCT_ID), MSB(PRODUCT_ID),// idProduct\r
-        0x00, 0x01,           // bcdDevice\r
-        1,                    // iManufacturer\r
-        2,                    // iProduct\r
-        3,                    // iSerialNumber\r
-        1                     // bNumConfigurations\r
-    };\r
-    return deviceDescriptor;\r
-}\r
-\r
-uint8_t * USBCDCMSC::stringIinterfaceDesc() {\r
-    static uint8_t stringIinterfaceDescriptor[] = {\r
-        0x0e,\r
-        STRING_DESCRIPTOR,\r
-        'C',0,'D',0,'C',0,'M',0,'S',0,'C',0,\r
-    };\r
-    return stringIinterfaceDescriptor;\r
-}\r
-\r
-uint8_t * USBCDCMSC::stringIproductDesc() {\r
-    static uint8_t stringIproductDescriptor[] = {\r
-        0x1c,\r
-        STRING_DESCRIPTOR,\r
-        'C',0,'D',0,'C',0,'M',0,'S',0,'C',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0\r
-    };\r
-    return stringIproductDescriptor;\r
-}\r
-\r
-\r
-uint8_t * USBCDCMSC::configurationDesc() {\r
-    static uint8_t configDescriptor[] = {\r
-        9,                      // bLength;\r
-        2,                      // bDescriptorType;\r
-        LSB(0x62),              // wTotalLength\r
-        MSB(0x62),\r
-        3,                      // bNumInterfaces\r
-        1,                      // bConfigurationValue\r
-        0,                      // iConfiguration\r
-        0xc0,                   // bmAttributes\r
-        50,                     // bMaxPower\r
-\r
-        // IAD\r
-//        0x08, 0x0B, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00,\r
-        0x08, 0x0B, 0x00, 0x02, 0x02, 0x02, 0x01, 0x00,\r
-\r
-        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12\r
-        9,                      // bLength\r
-        4,                      // bDescriptorType\r
-        0,                      // bInterfaceNumber\r
-        0,                      // bAlternateSetting\r
-        1,                      // bNumEndpoints\r
-        0x02,                   // bInterfaceClass\r
-        0x02,                   // bInterfaceSubClass\r
-        0x01,                   // bInterfaceProtocol\r
-        0,                      // iInterface\r
-\r
-        // CDC Header Functional Descriptor, CDC Spec 5.2.3.1, Table 26\r
-        5,                      // bFunctionLength\r
-        0x24,                   // bDescriptorType\r
-        0x00,                   // bDescriptorSubtype\r
-        0x10, 0x01,             // bcdCDC\r
-\r
-        // Call Management Functional Descriptor, CDC Spec 5.2.3.2, Table 27\r
-        5,                      // bFunctionLength\r
-        0x24,                   // bDescriptorType\r
-        0x01,                   // bDescriptorSubtype\r
-        0x03,                   // bmCapabilities\r
-        1,                      // bDataInterface\r
-\r
-        // Abstract Control Management Functional Descriptor, CDC Spec 5.2.3.3, Table 28\r
-        4,                      // bFunctionLength\r
-        0x24,                   // bDescriptorType\r
-        0x02,                   // bDescriptorSubtype\r
-        0x06,                   // bmCapabilities\r
-\r
-        // Union Functional Descriptor, CDC Spec 5.2.3.8, Table 33\r
-        5,                      // bFunctionLength\r
-        0x24,                   // bDescriptorType\r
-        0x06,                   // bDescriptorSubtype\r
-        0,                      // bMasterInterface\r
-        1,                      // bSlaveInterface0\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        ENDPOINT_DESCRIPTOR_LENGTH,     // bLength\r
-        ENDPOINT_DESCRIPTOR,            // bDescriptorType\r
-        PHY_TO_DESC(EPINT_IN),          // bEndpointAddress\r
-        E_INTERRUPT,                    // bmAttributes (0x03=intr)\r
-        LSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (MSB)\r
-        16,                             // bInterval\r
-\r
-\r
-\r
-\r
-        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12\r
-        9,          // bLength\r
-        4,          // bDescriptorType\r
-        1,          // bInterfaceNumber\r
-        0,          // bAlternateSetting\r
-        2,          // bNumEndpoints\r
-        0x0A,       // bInterfaceClass\r
-        0x00,       // bInterfaceSubClass\r
-        0x00,       // bInterfaceProtocol\r
-        0,          // iInterface\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        7,                      // bLength\r
-        5,                      // bDescriptorType\r
-        PHY_TO_DESC(EPBULK_IN), // bEndpointAddress\r
-        0x02,                   // bmAttributes (0x02=bulk)\r
-        LSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (MSB)\r
-        0,                      // bInterval\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        7,                      // bLength\r
-        5,                      // bDescriptorType\r
-        PHY_TO_DESC(EPBULK_OUT),// bEndpointAddress\r
-        0x02,                   // bmAttributes (0x02=bulk)\r
-        LSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPBULK),     // wMaxPacketSize (MSB)\r
-        0,                       // bInterval\r
-\r
-        // Interface 2, Alternate Setting 0, MSC Class\r
-        9,      // bLength\r
-        4,      // bDescriptorType\r
-        0x02,   // bInterfaceNumber\r
-        0x00,   // bAlternateSetting\r
-        0x02,   // bNumEndpoints\r
-        0x08,   // bInterfaceClass\r
-        0x06,   // bInterfaceSubClass\r
-        0x50,   // bInterfaceProtocol\r
-        0x04,   // iInterface\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        7,                          // bLength\r
-        5,                          // bDescriptorType\r
-        PHY_TO_DESC(MSDBULK_IN),     // bEndpointAddress\r
-        0x02,                       // bmAttributes (0x02=bulk)\r
-        LSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (MSB)\r
-        0,                          // bInterval\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        7,                          // bLength\r
-        5,                          // bDescriptorType\r
-        PHY_TO_DESC(MSDBULK_OUT),    // bEndpointAddress\r
-        0x02,                       // bmAttributes (0x02=bulk)\r
-        LSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (MSB)\r
-        0                           // bInterval\r
-    };\r
-    return configDescriptor;\r
-}\r
-\r
-int USBCDCMSC::_putc(int c) {\r
-    send((uint8_t *)&c, 1);\r
-    return 1;\r
-}\r
-\r
-int USBCDCMSC::_getc() {\r
-    uint8_t c = 0;\r
-    while (cdcbuf.isEmpty());\r
-    cdcbuf.dequeue(&c);\r
-    return c;\r
-}\r
-\r
-int USBCDCMSC::printf(const char* format, ...) {\r
-    va_list args;\r
-    int slen;\r
-    uint8_t *result, *current;\r
-\r
-    va_start (args, format);\r
-    slen = vasprintf ((char **)&result, format, args);\r
-    va_end (args);\r
-\r
-    current = result;\r
-\r
-    // Send full-size packets as many times as needed\r
-    while(slen > MAX_CDC_REPORT_SIZE) {\r
-        send(current, MAX_CDC_REPORT_SIZE);\r
-        current += MAX_CDC_REPORT_SIZE;\r
-        slen -= MAX_CDC_REPORT_SIZE;\r
-    }\r
-\r
-    // send a full packet followed by Zero Length Packet\r
-    if(slen == MAX_CDC_REPORT_SIZE) {\r
-        send(current, MAX_CDC_REPORT_SIZE);\r
-        send(current, 0);\r
-    }\r
-\r
-    // send a partial packet if needed to finish\r
-    if(slen < MAX_CDC_REPORT_SIZE) {\r
-        send(current, slen);\r
-    }\r
-    free(result);\r
-    return 0;\r
-}\r
-\r
-bool USBCDCMSC::writeBlock(uint8_t * buf, uint16_t size) {\r
-    if(size > MAX_PACKET_SIZE_EPBULK) {\r
-        return false;\r
-    }\r
-    if(!send(buf, size)) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-\r
-\r
-bool USBCDCMSC::EP2_OUT_callback() {\r
-    uint8_t c[65];\r
-    uint16_t size = 0;\r
-\r
-    //we read the packet received and put it on the circular buffer\r
-    readEP(c, &size);\r
-    for (int i = 0; i < size; i++) {\r
-        cdcbuf.queue(c[i]);\r
-    }\r
-\r
-    //call a potential handler\r
-    rx.call();\r
-\r
-    // We reactivate the endpoint to receive next characters\r
-    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-    return true;\r
-}\r
-\r
-uint8_t USBCDCMSC::available() {\r
-    return cdcbuf.available();\r
-}\r
-\r
-\r
-bool USBCDCMSC::connect() {\r
-\r
-    //disk initialization\r
-    if (disk_status() & NO_INIT) {\r
-        if (disk_initialize()) {\r
-            return false;\r
-        }\r
-    }\r
-\r
-    // get number of blocks\r
-    BlockCount = disk_sectors();\r
-\r
-    // get memory size\r
-    MemorySize = disk_size();\r
-\r
-    if (BlockCount >= 0) {\r
-        BlockSize = MemorySize / BlockCount;\r
-        if (BlockSize != 0) {\r
-            page = (uint8_t *)malloc(BlockSize * sizeof(uint8_t));\r
-            if (page == NULL)\r
-                return false;\r
-        }\r
-    } else {\r
-        return false;\r
-    }\r
-\r
-    //connect the device\r
-//    USBDevice::connect();\r
-    return true;\r
-}\r
-\r
-\r
-void USBCDCMSC::reset() {\r
-    stage = READ_CBW;\r
-}\r
-\r
-\r
-// Called in ISR context called when a data is received\r
-bool USBCDCMSC::EP5_OUT_callback() {\r
-    uint16_t size = 0;\r
-    uint8_t buf[MAX_PACKET_SIZE_EPBULK];\r
-    USBDevice::readEP(MSDBULK_OUT, buf, &size, MAX_PACKET_SIZE_EPBULK);\r
-    switch (stage) {\r
-            // the device has to decode the CBW received\r
-        case READ_CBW:\r
-            CBWDecode(buf, size);\r
-            break;\r
-\r
-            // the device has to receive data from the host\r
-        case PROCESS_CBW:\r
-            switch (cbw.CB[0]) {\r
-                case WRITE10:\r
-                case WRITE12:\r
-                    memoryWrite(buf, size);\r
-                    break;\r
-                case VERIFY10:\r
-                    memoryVerify(buf, size);\r
-                    break;\r
-            }\r
-            break;\r
-\r
-            // an error has occured: stall endpoint and send CSW\r
-        default:\r
-            stallEndpoint(MSDBULK_OUT);\r
-            csw.Status = CSW_ERROR;\r
-            sendCSW();\r
-            break;\r
-    }\r
-\r
-    //reactivate readings on the OUT bulk endpoint\r
-    readStart(MSDBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-    return true;\r
-}\r
-\r
-// Called in ISR context when a data has been transferred\r
-bool USBCDCMSC::EP5_IN_callback() {\r
-    switch (stage) {\r
-\r
-            // the device has to send data to the host\r
-        case PROCESS_CBW:\r
-            switch (cbw.CB[0]) {\r
-                case READ10:\r
-                case READ12:\r
-                    memoryRead();\r
-                    break;\r
-            }\r
-            break;\r
-\r
-            //the device has to send a CSW\r
-        case SEND_CSW:\r
-            sendCSW();\r
-            break;\r
-\r
-            // an error has occured\r
-        case ERROR:\r
-            stallEndpoint(MSDBULK_IN);\r
-            sendCSW();\r
-            break;\r
-\r
-            // the host has received the CSW -> we wait a CBW\r
-        case WAIT_CSW:\r
-            stage = READ_CBW;\r
-            break;\r
-    }\r
-    return true;\r
-}\r
-\r
-\r
-void USBCDCMSC::memoryWrite (uint8_t * buf, uint16_t size) {\r
-\r
-    if ((addr + size) > MemorySize) {\r
-        size = MemorySize - addr;\r
-        stage = ERROR;\r
-        stallEndpoint(MSDBULK_OUT);\r
-    }\r
-\r
-    // we fill an array in RAM of 1 block before writing it in memory\r
-    for (int i = 0; i < size; i++)\r
-        page[addr%BlockSize + i] = buf[i];\r
-\r
-    // if the array is filled, write it in memory\r
-    if (!((addr + size)%BlockSize)) {\r
-        if (!(disk_status() & WRITE_PROTECT)) {\r
-            disk_write((const char *)page, addr/BlockSize);\r
-        }\r
-    }\r
-\r
-    addr += size;\r
-    length -= size;\r
-    csw.DataResidue -= size;\r
-\r
-    if ((!length) || (stage != PROCESS_CBW)) {\r
-        csw.Status = (stage == ERROR) ? CSW_FAILED : CSW_PASSED;\r
-        sendCSW();\r
-    }\r
-}\r
-\r
-void USBCDCMSC::memoryVerify (uint8_t * buf, uint16_t size) {\r
-    uint32_t n;\r
-\r
-    if ((addr + size) > MemorySize) {\r
-        size = MemorySize - addr;\r
-        stage = ERROR;\r
-        stallEndpoint(MSDBULK_OUT);\r
-    }\r
-\r
-    // beginning of a new block -> load a whole block in RAM\r
-    if (!(addr%BlockSize))\r
-        disk_read((char *)page, addr/BlockSize);\r
-\r
-    // info are in RAM -> no need to re-read memory\r
-    for (n = 0; n < size; n++) {\r
-        if (page[addr%BlockSize + n] != buf[n]) {\r
-            memOK = false;\r
-            break;\r
-        }\r
-    }\r
-\r
-    addr += size;\r
-    length -= size;\r
-    csw.DataResidue -= size;\r
-\r
-    if ( !length || (stage != PROCESS_CBW)) {\r
-        csw.Status = (memOK && (stage == PROCESS_CBW)) ? CSW_PASSED : CSW_FAILED;\r
-        sendCSW();\r
-    }\r
-}\r
-\r
-\r
-bool USBCDCMSC::inquiryRequest (void) {\r
-    uint8_t inquiry[] = { 0x00, 0x80, 0x00, 0x01,\r
-                          36 - 4, 0x80, 0x00, 0x00,\r
-                          'M', 'B', 'E', 'D', '.', 'O', 'R', 'G',\r
-                          'M', 'B', 'E', 'D', ' ', 'U', 'S', 'B', ' ', 'D', 'I', 'S', 'K', ' ', ' ', ' ',\r
-                          '1', '.', '0', ' ',\r
-                        };\r
-    if (!msd_write(inquiry, sizeof(inquiry))) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-\r
-bool USBCDCMSC::readFormatCapacity() {\r
-    uint8_t capacity[] = { 0x00, 0x00, 0x00, 0x08,\r
-                        ((uint8_t) ((BlockCount >> 24) & 0xff)),\r
-                        ((uint8_t) ((BlockCount >> 16) & 0xff)),\r
-                        ((uint8_t) ((BlockCount >> 8) & 0xff)),\r
-                        ((uint8_t) ((BlockCount >> 0) & 0xff)),\r
-\r
-                        0x02,\r
-                        ((uint8_t) ((BlockSize >> 16) & 0xff)),\r
-                        ((uint8_t) ((BlockSize >> 8) & 0xff)),\r
-                        ((uint8_t) ((BlockSize >> 0) & 0xff)),\r
-                        };\r
-    if (!msd_write(capacity, sizeof(capacity))) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-\r
-bool USBCDCMSC::readCapacity (void) {\r
-    uint8_t capacity[] = {\r
-        ((uint8_t) (((BlockCount - 1) >> 24) & 0xff)),\r
-        ((uint8_t) (((BlockCount - 1) >> 16) & 0xff)),\r
-        ((uint8_t) (((BlockCount - 1) >>  8) & 0xff)),\r
-        ((uint8_t) (((BlockCount - 1) >>  0) & 0xff)),\r
-\r
-        ((uint8_t) ((BlockSize >> 24) & 0xff)),\r
-        ((uint8_t) ((BlockSize >> 16) & 0xff)),\r
-        ((uint8_t) ((BlockSize >>  8) & 0xff)),\r
-        ((uint8_t) ((BlockSize >>  0) & 0xff)),\r
-    };\r
-    if (!msd_write(capacity, sizeof(capacity))) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-bool USBCDCMSC::msd_write (uint8_t * buf, uint16_t size) {\r
-\r
-    if (size >= cbw.DataLength) {\r
-        size = cbw.DataLength;\r
-    }\r
-    stage = SEND_CSW;\r
-\r
-    if (!writeNB(MSDBULK_IN, buf, size, MAX_PACKET_SIZE_EPBULK)) {\r
-        return false;\r
-    }\r
-\r
-    csw.DataResidue -= size;\r
-    csw.Status = CSW_PASSED;\r
-    return true;\r
-}\r
-\r
-\r
-bool USBCDCMSC::modeSense6 (void) {\r
-    uint8_t sense6[] = { 0x03, 0x00, 0x00, 0x00 };\r
-    if (!msd_write(sense6, sizeof(sense6))) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-void USBCDCMSC::sendCSW() {\r
-    csw.Signature = CSW_Signature;\r
-    writeNB(MSDBULK_IN, (uint8_t *)&csw, sizeof(CSW), MAX_PACKET_SIZE_EPBULK);\r
-    stage = WAIT_CSW;\r
-}\r
-\r
-void USBCDCMSC::setSense (uint8_t sense_key, uint8_t asc, uint8_t ascq) {\r
-    sense.error = 0x70;\r
-    sense.sense_key = sense_key;\r
-    sense.additional_sense_length = 0x0a;\r
-    sense.asc = asc;\r
-    sense.ascq = ascq;\r
-}\r
-\r
-bool USBCDCMSC::requestSense (void) {\r
-    if (!msd_write((uint8_t *)&sense, sizeof(sense))) {\r
-        return false;\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-void USBCDCMSC::mediaRemoval() {\r
-    csw.Status = CSW_PASSED;\r
-    sendCSW();\r
-}\r
-\r
-void USBCDCMSC::fail() {\r
-    csw.Status = CSW_FAILED;\r
-    sendCSW();\r
-}\r
-\r
-\r
-void USBCDCMSC::CBWDecode(uint8_t * buf, uint16_t size) {\r
-    if (size == sizeof(cbw)) {\r
-        memcpy((uint8_t *)&cbw, buf, size);\r
-        if (cbw.Signature == CBW_Signature) {\r
-            csw.Tag = cbw.Tag;\r
-            csw.DataResidue = cbw.DataLength;\r
-            if ((cbw.CBLength <  1) || (cbw.CBLength > 16) ) {\r
-                fail();\r
-            } else {\r
-                switch (cbw.CB[0]) {\r
-                    case TEST_UNIT_READY:\r
-                        testUnitReady();\r
-                        break;\r
-                    case REQUEST_SENSE:\r
-                        requestSense();\r
-                        break;\r
-                    case INQUIRY:\r
-                        inquiryRequest();\r
-                        break;\r
-                    case MODE_SENSE6:\r
-                        modeSense6();\r
-                        break;\r
-                    case READ_FORMAT_CAPACITIES:\r
-                        readFormatCapacity();\r
-                        break;\r
-                    case MEDIA_REMOVAL:\r
-                        mediaRemoval();\r
-                        break;\r
-                    case READ_CAPACITY:\r
-                        readCapacity();\r
-                        break;\r
-                    case READ10:\r
-                    case READ12:\r
-                        if (infoTransfer()) {\r
-                            if ((cbw.Flags & 0x80)) {\r
-                                stage = PROCESS_CBW;\r
-                                memoryRead();\r
-                            } else {\r
-                                stallEndpoint(MSDBULK_OUT);\r
-                                csw.Status = CSW_ERROR;\r
-                                sendCSW();\r
-                            }\r
-                        }\r
-                        break;\r
-                    case WRITE10:\r
-                    case WRITE12:\r
-                        if (infoTransfer()) {\r
-                            if (!(cbw.Flags & 0x80)) {\r
-                                stage = PROCESS_CBW;\r
-                            } else {\r
-                                stallEndpoint(MSDBULK_IN);\r
-                                csw.Status = CSW_ERROR;\r
-                                sendCSW();\r
-                            }\r
-                        }\r
-                        break;\r
-                    case VERIFY10:\r
-                        if (!(cbw.CB[1] & 0x02)) {\r
-                            csw.Status = CSW_PASSED;\r
-                            sendCSW();\r
-                            break;\r
-                        }\r
-                        if (infoTransfer()) {\r
-                            if (!(cbw.Flags & 0x80)) {\r
-                                stage = PROCESS_CBW;\r
-                                memOK = true;\r
-                            } else {\r
-                                stallEndpoint(MSDBULK_IN);\r
-                                csw.Status = CSW_ERROR;\r
-                                sendCSW();\r
-                            }\r
-                        }\r
-                        break;\r
-                    default:\r
-                        fail();\r
-                        break;\r
-                }\r
-            }\r
-        }\r
-    }\r
-}\r
-\r
-void USBCDCMSC::testUnitReady (void) {\r
-\r
-    if (cbw.DataLength != 0) {\r
-        if ((cbw.Flags & 0x80) != 0) {\r
-            stallEndpoint(MSDBULK_IN);\r
-        } else {\r
-            stallEndpoint(MSDBULK_OUT);\r
-        }\r
-    }\r
-\r
-    csw.Status = CSW_PASSED;\r
-    sendCSW();\r
-}\r
-\r
-\r
-void USBCDCMSC::memoryRead (void) {\r
-    uint32_t n;\r
-\r
-    n = (length > MAX_PACKET) ? MAX_PACKET : length;\r
-\r
-    if ((addr + n) > MemorySize) {\r
-        n = MemorySize - addr;\r
-        stage = ERROR;\r
-    }\r
-\r
-    // we read an entire block\r
-    if (!(addr%BlockSize))\r
-        disk_read((char *)page, addr/BlockSize);\r
-\r
-    // write data which are in RAM\r
-    writeNB(MSDBULK_IN, &page[addr%BlockSize], n, MAX_PACKET_SIZE_EPBULK);\r
-\r
-    addr += n;\r
-    length -= n;\r
-\r
-    csw.DataResidue -= n;\r
-\r
-    if ( !length || (stage != PROCESS_CBW)) {\r
-        csw.Status = (stage == PROCESS_CBW) ? CSW_PASSED : CSW_FAILED;\r
-        stage = (stage == PROCESS_CBW) ? SEND_CSW : stage;\r
-    }\r
-}\r
-\r
-\r
-bool USBCDCMSC::infoTransfer (void) {\r
-    uint32_t n;\r
-\r
-    // Logical Block Address of First Block\r
-    n = (cbw.CB[2] << 24) | (cbw.CB[3] << 16) | (cbw.CB[4] <<  8) | (cbw.CB[5] <<  0);\r
-\r
-    addr = n * BlockSize;\r
-\r
-    // Number of Blocks to transfer\r
-    switch (cbw.CB[0]) {\r
-        case READ10:\r
-        case WRITE10:\r
-        case VERIFY10:\r
-            n = (cbw.CB[7] <<  8) | (cbw.CB[8] <<  0);\r
-            break;\r
-\r
-        case READ12:\r
-        case WRITE12:\r
-            n = (cbw.CB[6] << 24) | (cbw.CB[7] << 16) | (cbw.CB[8] <<  8) | (cbw.CB[9] <<  0);\r
-            break;\r
-    }\r
-\r
-    length = n * BlockSize;\r
-\r
-    if (!cbw.DataLength) {              // host requests no data\r
-        csw.Status = CSW_FAILED;\r
-        sendCSW();\r
-        return false;\r
-    }\r
-\r
-    if (cbw.DataLength != length) {\r
-        if ((cbw.Flags & 0x80) != 0) {\r
-            stallEndpoint(MSDBULK_IN);\r
-        } else {\r
-            stallEndpoint(MSDBULK_OUT);\r
-        }\r
-\r
-        csw.Status = CSW_FAILED;\r
-        sendCSW();\r
-        return false;\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-int USBCDCMSC::isBreak () {\r
-    int ret = cdcbreak;\r
-    cdcbreak = 0;\r
-    return ret;\r
-}\r
-\r
-int USBCDCMSC::disk_initialize() {\r
-    if (_sd->disk_initialize()) {\r
-        _status |= NO_DISK;\r
-        return 1;\r
-    } else {\r
-        _status = DISK_OK;\r
-        return 0;\r
-    }\r
-}\r
-\r
-int USBCDCMSC::disk_write(const char *buffer, int block_number) {\r
-    return _sd->disk_write(buffer, block_number);\r
-}\r
-\r
-int USBCDCMSC::disk_read(char *buffer, int block_number) {\r
-    return _sd->disk_read(buffer, block_number);\r
-}\r
-\r
-int USBCDCMSC::disk_status() {\r
-    return _status;\r
-}\r
-\r
-int USBCDCMSC::disk_sectors() {\r
-    return _sd->disk_sectors();\r
-}\r
-int USBCDCMSC::disk_size() {\r
-    return _sd->disk_sectors() * 512;\r
-}\r
-\r
-\r
-void USBCDCMSC::on_module_loaded(){\r
-    // We want to be called every time a new char is received\r
-    this->attach(this, &USBCDCMSC::on_serial_char_received);\r
-\r
-    // We only call the command dispatcher in the main loop, nowhere else\r
-    this->register_for_event(ON_MAIN_LOOP);\r
-\r
-    // Add to the pack of streams kernel can call to, for example for broadcasting\r
-    this->kernel->streams->append_stream(this);\r
-\r
-}\r
-\r
-\r
-\r
-\r
-\r
-\r
-void USBCDCMSC::on_main_loop(void* argument){\r
-    if( this->has_char('\n') ){\r
-        string received;\r
-        while(1){\r
-            char c;\r
-            this->buffer.pop_front(c);\r
-            if( c == '\n' ){\r
-                struct SerialMessage message;\r
-                message.message = received;\r
-                message.stream = this;\r
-                this->kernel->call_event(ON_CONSOLE_LINE_RECEIVED, &message );\r
-                return;\r
-            }else{\r
-                received += c;\r
-            }\r
-        }\r
-    }\r
-}\r
-\r
-void USBCDCMSC::on_serial_char_received(){\r
-    while(this->available()){\r
-        char received = this->_getc();\r
-        // convert CR to NL (for host OSs that don't send NL)\r
-        if( received == '\r' ){ received = '\n'; }\r
-        this->buffer.push_back(received);\r
-    }\r
-\r
-}\r
-\r
-\r
-bool USBCDCMSC::has_char(char letter){\r
-    int index = this->buffer.head;\r
-    while( index != this->buffer.tail ){\r
-        if( this->buffer.buffer[index] == letter ){\r
-            return true;\r
-        }\r
-        index = this->buffer.next_block_index(index);\r
-    }\r
-    return false;\r
-}\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#include "stdint.h"
+#include "stdarg.h"
+#include "USBCDCMSC.h"
+#include "USBBusInterface.h"
+#include "libs/SerialMessage.h"
+\r
+#include "libs/StreamOutput.h"
+#include "libs/RingBuffer.h"
+\r
+static uint8_t cdc_line_coding[7]= {0x80, 0x25, 0x00, 0x00, 0x00, 0x00, 0x08};
+\r
+#define DEFAULT_CONFIGURATION (1)
+\r
+#define CDC_SET_LINE_CODING        0x20
+#define CDC_GET_LINE_CODING        0x21
+#define CDC_SET_CONTROL_LINE_STATE 0x22
+#define CDC_SEND_BREAK             0x23
+\r
+#define MAX_CDC_REPORT_SIZE MAX_PACKET_SIZE_EPBULK
+\r
+\r
+\r
+#define DISK_OK         0x00
+#define NO_INIT         0x01
+#define NO_DISK         0x02
+#define WRITE_PROTECT   0x04
+\r
+#define CBW_Signature   0x43425355
+#define CSW_Signature   0x53425355
+\r
+// SCSI Commands
+#define TEST_UNIT_READY            0x00
+#define REQUEST_SENSE              0x03
+#define FORMAT_UNIT                0x04
+#define INQUIRY                    0x12
+#define MODE_SELECT6               0x15
+#define MODE_SENSE6                0x1A
+#define START_STOP_UNIT            0x1B
+#define MEDIA_REMOVAL              0x1E
+#define READ_FORMAT_CAPACITIES     0x23
+#define READ_CAPACITY              0x25
+#define READ10                     0x28
+#define WRITE10                    0x2A
+#define VERIFY10                   0x2F
+#define READ12                     0xA8
+#define WRITE12                    0xAA
+#define MODE_SELECT10              0x55
+#define MODE_SENSE10               0x5A
+\r
+// MSC class specific requests
+#define MSC_REQUEST_RESET          0xFF
+#define MSC_REQUEST_GET_MAX_LUN    0xFE
+\r
+#define DEFAULT_CONFIGURATION (1)
+\r
+// Sense codes
+#define SENSE_NO_SENSE          0x00
+#define SENSE_RECOVERED_ERROR   0x01
+#define SENSE_NOT_READY         0x02
+#define SENSE_MEDIUM_ERROR      0x03
+#define SENSE_HARDWARE_ERROR    0x04
+#define SENSE_ILLEGAL_REQUEST   0x05
+#define SENSE_UNIT_ATTENTION    0x06
+#define SENSE_DATA_PROTECT      0x07
+#define SENSE_BLANK_CHECK       0x08
+#define SENSE_ABORTED_COMMAND   0x0B
+#define SENSE_VOLUME_OVERFLOW   0x0D
+#define SENSE_MISCOMPARE        0x0E
+\r
+// max packet size
+#define MAX_PACKET  MAX_PACKET_SIZE_EPBULK
+\r
+// CSW Status
+enum Status {
+    CSW_PASSED,
+    CSW_FAILED,
+    CSW_ERROR,
+};
+\r
+\r
+USBCDCMSC::USBCDCMSC(SDFileSystem *sd, uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release), cdcbuf(128), _sd(sd) {
+    cdcbreak = 0;
+    _status = NO_INIT;
+    connect();
+//    USBDevice::connect();
+    setSense(SENSE_NO_SENSE, 0x00, 0x00);
+    USBHAL::connect();
+}
+\r
+bool USBCDCMSC::USBCallback_request(void) {
+    /* Called in ISR context */
+\r
+    bool success = false;
+    CONTROL_TRANSFER * transfer = getTransferPtr();
+    static uint8_t maxLUN[1] = {0};
+\r
+    /* Process class-specific requests */
+\r
+    if (transfer->setup.bmRequestType.Type == CLASS_TYPE) {
+        switch (transfer->setup.bRequest) {
+            case CDC_GET_LINE_CODING:
+                transfer->remaining = 7;
+                transfer->ptr = cdc_line_coding;
+                transfer->direction = DEVICE_TO_HOST;
+                success = true;
+                break;
+            case CDC_SET_LINE_CODING:
+                transfer->remaining = 7;
+                success = true;
+                break;
+            case CDC_SET_CONTROL_LINE_STATE:
+                success = true;
+                break;
+            case CDC_SEND_BREAK:
+                cdcbreak = 1;
+                success = true;
+                break;
+            case MSC_REQUEST_RESET:
+                reset();
+                success = true;
+                break;
+            case MSC_REQUEST_GET_MAX_LUN:
+                transfer->remaining = 1;
+                transfer->ptr = maxLUN;
+                transfer->direction = DEVICE_TO_HOST;
+                success = true;
+                break;
+            default:
+                break;
+        }
+    }
+\r
+    return success;
+}
+\r
+\r
+// Called in ISR context
+// Set configuration. Return false if the
+// configuration is not supported.
+bool USBCDCMSC::USBCallback_setConfiguration(uint8_t configuration) {
+    if (configuration != DEFAULT_CONFIGURATION) {
+        return false;
+    }
+\r
+    // Configure endpoints > 0
+    addEndpoint(EPINT_IN, MAX_PACKET_SIZE_EPINT);
+    addEndpoint(EPBULK_IN, MAX_PACKET_SIZE_EPBULK);
+    addEndpoint(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+\r
+    // Configure endpoints > 0
+    addEndpoint(MSDBULK_IN, MAX_PACKET_SIZE_MSDBULK);
+    addEndpoint(MSDBULK_OUT, MAX_PACKET_SIZE_MSDBULK);
+\r
+    // We activate the endpoint to be able to recceive data
+    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+\r
+    //activate readings
+    readStart(MSDBULK_OUT, MAX_PACKET_SIZE_MSDBULK);
+    return true;
+}
+\r
+bool USBCDCMSC::send(uint8_t * buffer, uint16_t size) {
+    return USBDevice::write(EPBULK_IN, buffer, size, MAX_CDC_REPORT_SIZE);
+}
+\r
+bool USBCDCMSC::readEP(uint8_t * buffer, uint16_t * size) {
+    if (!USBDevice::readEP(EPBULK_OUT, buffer, size, MAX_CDC_REPORT_SIZE))
+        return false;
+    if (!readStart(EPBULK_OUT, MAX_CDC_REPORT_SIZE))
+        return false;
+    return true;
+}
+\r
+bool USBCDCMSC::readEP_NB(uint8_t * buffer, uint16_t * size) {
+    if (!USBDevice::readEP_NB(EPBULK_OUT, buffer, size, MAX_CDC_REPORT_SIZE))
+        return false;
+    if (!readStart(EPBULK_OUT, MAX_CDC_REPORT_SIZE))
+        return false;
+    return true;
+}
+\r
+\r
+uint8_t * USBCDCMSC::deviceDesc() {
+    static uint8_t deviceDescriptor[] = {
+        18,                   // bLength
+        1,                    // bDescriptorType
+        0x10, 0x01,           // bcdUSB
+        0xef,                    // bDeviceClass
+        0x02,                    // bDeviceSubClass
+        0x01,                    // bDeviceProtocol
+        MAX_PACKET_SIZE_EP0,  // bMaxPacketSize0
+        LSB(VENDOR_ID), MSB(VENDOR_ID),  // idVendor
+        LSB(PRODUCT_ID), MSB(PRODUCT_ID),// idProduct
+        0x00, 0x01,           // bcdDevice
+        1,                    // iManufacturer
+        2,                    // iProduct
+        3,                    // iSerialNumber
+        1                     // bNumConfigurations
+    };
+    return deviceDescriptor;
+}
+\r
+uint8_t * USBCDCMSC::stringIinterfaceDesc() {
+    static uint8_t stringIinterfaceDescriptor[] = {
+        0x0e,
+        STRING_DESCRIPTOR,
+        'C',0,'D',0,'C',0,'M',0,'S',0,'C',0,
+    };
+    return stringIinterfaceDescriptor;
+}
+\r
+uint8_t * USBCDCMSC::stringIproductDesc() {
+    static uint8_t stringIproductDescriptor[] = {
+        0x1c,
+        STRING_DESCRIPTOR,
+        'C',0,'D',0,'C',0,'M',0,'S',0,'C',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0
+    };
+    return stringIproductDescriptor;
+}
+\r
+\r
+uint8_t * USBCDCMSC::configurationDesc() {
+    static uint8_t configDescriptor[] = {
+        9,                      // bLength;
+        2,                      // bDescriptorType;
+        LSB(0x62),              // wTotalLength
+        MSB(0x62),
+        3,                      // bNumInterfaces
+        1,                      // bConfigurationValue
+        0,                      // iConfiguration
+        0xc0,                   // bmAttributes
+        50,                     // bMaxPower
+\r
+        // IAD
+//        0x08, 0x0B, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00,
+        0x08, 0x0B, 0x00, 0x02, 0x02, 0x02, 0x01, 0x00,
+\r
+        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+        9,                      // bLength
+        4,                      // bDescriptorType
+        0,                      // bInterfaceNumber
+        0,                      // bAlternateSetting
+        1,                      // bNumEndpoints
+        0x02,                   // bInterfaceClass
+        0x02,                   // bInterfaceSubClass
+        0x01,                   // bInterfaceProtocol
+        0,                      // iInterface
+\r
+        // CDC Header Functional Descriptor, CDC Spec 5.2.3.1, Table 26
+        5,                      // bFunctionLength
+        0x24,                   // bDescriptorType
+        0x00,                   // bDescriptorSubtype
+        0x10, 0x01,             // bcdCDC
+\r
+        // Call Management Functional Descriptor, CDC Spec 5.2.3.2, Table 27
+        5,                      // bFunctionLength
+        0x24,                   // bDescriptorType
+        0x01,                   // bDescriptorSubtype
+        0x03,                   // bmCapabilities
+        1,                      // bDataInterface
+\r
+        // Abstract Control Management Functional Descriptor, CDC Spec 5.2.3.3, Table 28
+        4,                      // bFunctionLength
+        0x24,                   // bDescriptorType
+        0x02,                   // bDescriptorSubtype
+        0x06,                   // bmCapabilities
+\r
+        // Union Functional Descriptor, CDC Spec 5.2.3.8, Table 33
+        5,                      // bFunctionLength
+        0x24,                   // bDescriptorType
+        0x06,                   // bDescriptorSubtype
+        0,                      // bMasterInterface
+        1,                      // bSlaveInterface0
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        ENDPOINT_DESCRIPTOR_LENGTH,     // bLength
+        ENDPOINT_DESCRIPTOR,            // bDescriptorType
+        PHY_TO_DESC(EPINT_IN),          // bEndpointAddress
+        E_INTERRUPT,                    // bmAttributes (0x03=intr)
+        LSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (MSB)
+        16,                             // bInterval
+\r
+\r
+\r
+\r
+        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+        9,          // bLength
+        4,          // bDescriptorType
+        1,          // bInterfaceNumber
+        0,          // bAlternateSetting
+        2,          // bNumEndpoints
+        0x0A,       // bInterfaceClass
+        0x00,       // bInterfaceSubClass
+        0x00,       // bInterfaceProtocol
+        0,          // iInterface
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                      // bLength
+        5,                      // bDescriptorType
+        PHY_TO_DESC(EPBULK_IN), // bEndpointAddress
+        0x02,                   // bmAttributes (0x02=bulk)
+        LSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (MSB)
+        0,                      // bInterval
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                      // bLength
+        5,                      // bDescriptorType
+        PHY_TO_DESC(EPBULK_OUT),// bEndpointAddress
+        0x02,                   // bmAttributes (0x02=bulk)
+        LSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPBULK),     // wMaxPacketSize (MSB)
+        0,                       // bInterval
+\r
+        // Interface 2, Alternate Setting 0, MSC Class
+        9,      // bLength
+        4,      // bDescriptorType
+        0x02,   // bInterfaceNumber
+        0x00,   // bAlternateSetting
+        0x02,   // bNumEndpoints
+        0x08,   // bInterfaceClass
+        0x06,   // bInterfaceSubClass
+        0x50,   // bInterfaceProtocol
+        0x04,   // iInterface
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                          // bLength
+        5,                          // bDescriptorType
+        PHY_TO_DESC(MSDBULK_IN),     // bEndpointAddress
+        0x02,                       // bmAttributes (0x02=bulk)
+        LSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (MSB)
+        0,                          // bInterval
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                          // bLength
+        5,                          // bDescriptorType
+        PHY_TO_DESC(MSDBULK_OUT),    // bEndpointAddress
+        0x02,                       // bmAttributes (0x02=bulk)
+        LSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (MSB)
+        0                           // bInterval
+    };
+    return configDescriptor;
+}
+\r
+int USBCDCMSC::_putc(int c) {
+    send((uint8_t *)&c, 1);
+    return 1;
+}
+\r
+int USBCDCMSC::_getc() {
+    uint8_t c = 0;
+    while (cdcbuf.isEmpty());
+    cdcbuf.dequeue(&c);
+    return c;
+}
+\r
+int USBCDCMSC::printf(const char* format, ...) {
+    va_list args;
+    int slen;
+    uint8_t *result, *current;
+\r
+    va_start (args, format);
+    slen = vasprintf ((char **)&result, format, args);
+    va_end (args);
+\r
+    current = result;
+\r
+    // Send full-size packets as many times as needed
+    while(slen > MAX_CDC_REPORT_SIZE) {
+        send(current, MAX_CDC_REPORT_SIZE);
+        current += MAX_CDC_REPORT_SIZE;
+        slen -= MAX_CDC_REPORT_SIZE;
+    }
+\r
+    // send a full packet followed by Zero Length Packet
+    if(slen == MAX_CDC_REPORT_SIZE) {
+        send(current, MAX_CDC_REPORT_SIZE);
+        send(current, 0);
+    }
+\r
+    // send a partial packet if needed to finish
+    if(slen < MAX_CDC_REPORT_SIZE) {
+        send(current, slen);
+    }
+    free(result);
+    return 0;
+}
+\r
+bool USBCDCMSC::writeBlock(uint8_t * buf, uint16_t size) {
+    if(size > MAX_PACKET_SIZE_EPBULK) {
+        return false;
+    }
+    if(!send(buf, size)) {
+        return false;
+    }
+    return true;
+}
+\r
+\r
+\r
+bool USBCDCMSC::EP2_OUT_callback() {
+    uint8_t c[65];
+    uint16_t size = 0;
+\r
+    //we read the packet received and put it on the circular buffer
+    readEP(c, &size);
+    for (int i = 0; i < size; i++) {
+        cdcbuf.queue(c[i]);
+    }
+\r
+    //call a potential handler
+    rx.call();
+\r
+    // We reactivate the endpoint to receive next characters
+    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+    return true;
+}
+\r
+uint8_t USBCDCMSC::available() {
+    return cdcbuf.available();
+}
+\r
+\r
+bool USBCDCMSC::connect() {
+\r
+    //disk initialization
+    if (disk_status() & NO_INIT) {
+        if (disk_initialize()) {
+            return false;
+        }
+    }
+\r
+    // get number of blocks
+    BlockCount = disk_sectors();
+\r
+    // get memory size
+    MemorySize = disk_size();
+\r
+    if (BlockCount >= 0) {
+        BlockSize = MemorySize / BlockCount;
+        if (BlockSize != 0) {
+            page = (uint8_t *)malloc(BlockSize * sizeof(uint8_t));
+            if (page == NULL)
+                return false;
+        }
+    } else {
+        return false;
+    }
+\r
+    //connect the device
+//    USBDevice::connect();
+    return true;
+}
+\r
+\r
+void USBCDCMSC::reset() {
+    stage = READ_CBW;
+}
+\r
+\r
+// Called in ISR context called when a data is received
+bool USBCDCMSC::EP5_OUT_callback() {
+    uint16_t size = 0;
+    uint8_t buf[MAX_PACKET_SIZE_EPBULK];
+    USBDevice::readEP(MSDBULK_OUT, buf, &size, MAX_PACKET_SIZE_EPBULK);
+    switch (stage) {
+            // the device has to decode the CBW received
+        case READ_CBW:
+            CBWDecode(buf, size);
+            break;
+\r
+            // the device has to receive data from the host
+        case PROCESS_CBW:
+            switch (cbw.CB[0]) {
+                case WRITE10:
+                case WRITE12:
+                    memoryWrite(buf, size);
+                    break;
+                case VERIFY10:
+                    memoryVerify(buf, size);
+                    break;
+            }
+            break;
+\r
+            // an error has occured: stall endpoint and send CSW
+        default:
+            stallEndpoint(MSDBULK_OUT);
+            csw.Status = CSW_ERROR;
+            sendCSW();
+            break;
+    }
+\r
+    //reactivate readings on the OUT bulk endpoint
+    readStart(MSDBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+    return true;
+}
+\r
+// Called in ISR context when a data has been transferred
+bool USBCDCMSC::EP5_IN_callback() {
+    switch (stage) {
+\r
+            // the device has to send data to the host
+        case PROCESS_CBW:
+            switch (cbw.CB[0]) {
+                case READ10:
+                case READ12:
+                    memoryRead();
+                    break;
+            }
+            break;
+\r
+            //the device has to send a CSW
+        case SEND_CSW:
+            sendCSW();
+            break;
+\r
+            // an error has occured
+        case ERROR:
+            stallEndpoint(MSDBULK_IN);
+            sendCSW();
+            break;
+\r
+            // the host has received the CSW -> we wait a CBW
+        case WAIT_CSW:
+            stage = READ_CBW;
+            break;
+    }
+    return true;
+}
+\r
+\r
+void USBCDCMSC::memoryWrite (uint8_t * buf, uint16_t size) {
+\r
+    if ((addr + size) > MemorySize) {
+        size = MemorySize - addr;
+        stage = ERROR;
+        stallEndpoint(MSDBULK_OUT);
+    }
+\r
+    // we fill an array in RAM of 1 block before writing it in memory
+    for (int i = 0; i < size; i++)
+        page[addr%BlockSize + i] = buf[i];
+\r
+    // if the array is filled, write it in memory
+    if (!((addr + size)%BlockSize)) {
+        if (!(disk_status() & WRITE_PROTECT)) {
+            disk_write((const char *)page, addr/BlockSize);
+        }
+    }
+\r
+    addr += size;
+    length -= size;
+    csw.DataResidue -= size;
+\r
+    if ((!length) || (stage != PROCESS_CBW)) {
+        csw.Status = (stage == ERROR) ? CSW_FAILED : CSW_PASSED;
+        sendCSW();
+    }
+}
+\r
+void USBCDCMSC::memoryVerify (uint8_t * buf, uint16_t size) {
+    uint32_t n;
+\r
+    if ((addr + size) > MemorySize) {
+        size = MemorySize - addr;
+        stage = ERROR;
+        stallEndpoint(MSDBULK_OUT);
+    }
+\r
+    // beginning of a new block -> load a whole block in RAM
+    if (!(addr%BlockSize))
+        disk_read((char *)page, addr/BlockSize);
+\r
+    // info are in RAM -> no need to re-read memory
+    for (n = 0; n < size; n++) {
+        if (page[addr%BlockSize + n] != buf[n]) {
+            memOK = false;
+            break;
+        }
+    }
+\r
+    addr += size;
+    length -= size;
+    csw.DataResidue -= size;
+\r
+    if ( !length || (stage != PROCESS_CBW)) {
+        csw.Status = (memOK && (stage == PROCESS_CBW)) ? CSW_PASSED : CSW_FAILED;
+        sendCSW();
+    }
+}
+\r
+\r
+bool USBCDCMSC::inquiryRequest (void) {
+    uint8_t inquiry[] = { 0x00, 0x80, 0x00, 0x01,
+                          36 - 4, 0x80, 0x00, 0x00,
+                          'M', 'B', 'E', 'D', '.', 'O', 'R', 'G',
+                          'M', 'B', 'E', 'D', ' ', 'U', 'S', 'B', ' ', 'D', 'I', 'S', 'K', ' ', ' ', ' ',
+                          '1', '.', '0', ' ',
+                        };
+    if (!msd_write(inquiry, sizeof(inquiry))) {
+        return false;
+    }
+    return true;
+}
+\r
+\r
+bool USBCDCMSC::readFormatCapacity() {
+    uint8_t capacity[] = { 0x00, 0x00, 0x00, 0x08,
+                        ((uint8_t) ((BlockCount >> 24) & 0xff)),
+                        ((uint8_t) ((BlockCount >> 16) & 0xff)),
+                        ((uint8_t) ((BlockCount >> 8) & 0xff)),
+                        ((uint8_t) ((BlockCount >> 0) & 0xff)),
+\r
+                        0x02,
+                        ((uint8_t) ((BlockSize >> 16) & 0xff)),
+                        ((uint8_t) ((BlockSize >> 8) & 0xff)),
+                        ((uint8_t) ((BlockSize >> 0) & 0xff)),
+                        };
+    if (!msd_write(capacity, sizeof(capacity))) {
+        return false;
+    }
+    return true;
+}
+\r
+\r
+bool USBCDCMSC::readCapacity (void) {
+    uint8_t capacity[] = {
+        ((uint8_t) (((BlockCount - 1) >> 24) & 0xff)),
+        ((uint8_t) (((BlockCount - 1) >> 16) & 0xff)),
+        ((uint8_t) (((BlockCount - 1) >>  8) & 0xff)),
+        ((uint8_t) (((BlockCount - 1) >>  0) & 0xff)),
+\r
+        ((uint8_t) ((BlockSize >> 24) & 0xff)),
+        ((uint8_t) ((BlockSize >> 16) & 0xff)),
+        ((uint8_t) ((BlockSize >>  8) & 0xff)),
+        ((uint8_t) ((BlockSize >>  0) & 0xff)),
+    };
+    if (!msd_write(capacity, sizeof(capacity))) {
+        return false;
+    }
+    return true;
+}
+\r
+bool USBCDCMSC::msd_write (uint8_t * buf, uint16_t size) {
+\r
+    if (size >= cbw.DataLength) {
+        size = cbw.DataLength;
+    }
+    stage = SEND_CSW;
+\r
+    if (!writeNB(MSDBULK_IN, buf, size, MAX_PACKET_SIZE_EPBULK)) {
+        return false;
+    }
+\r
+    csw.DataResidue -= size;
+    csw.Status = CSW_PASSED;
+    return true;
+}
+\r
+\r
+bool USBCDCMSC::modeSense6 (void) {
+    uint8_t sense6[] = { 0x03, 0x00, 0x00, 0x00 };
+    if (!msd_write(sense6, sizeof(sense6))) {
+        return false;
+    }
+    return true;
+}
+\r
+void USBCDCMSC::sendCSW() {
+    csw.Signature = CSW_Signature;
+    writeNB(MSDBULK_IN, (uint8_t *)&csw, sizeof(CSW), MAX_PACKET_SIZE_EPBULK);
+    stage = WAIT_CSW;
+}
+\r
+void USBCDCMSC::setSense (uint8_t sense_key, uint8_t asc, uint8_t ascq) {
+    sense.error = 0x70;
+    sense.sense_key = sense_key;
+    sense.additional_sense_length = 0x0a;
+    sense.asc = asc;
+    sense.ascq = ascq;
+}
+\r
+bool USBCDCMSC::requestSense (void) {
+    if (!msd_write((uint8_t *)&sense, sizeof(sense))) {
+        return false;
+    }
+\r
+    return true;
+}
+\r
+void USBCDCMSC::mediaRemoval() {
+    csw.Status = CSW_PASSED;
+    sendCSW();
+}
+\r
+void USBCDCMSC::fail() {
+    csw.Status = CSW_FAILED;
+    sendCSW();
+}
+\r
+\r
+void USBCDCMSC::CBWDecode(uint8_t * buf, uint16_t size) {
+    if (size == sizeof(cbw)) {
+        memcpy((uint8_t *)&cbw, buf, size);
+        if (cbw.Signature == CBW_Signature) {
+            csw.Tag = cbw.Tag;
+            csw.DataResidue = cbw.DataLength;
+            if ((cbw.CBLength <  1) || (cbw.CBLength > 16) ) {
+                fail();
+            } else {
+                switch (cbw.CB[0]) {
+                    case TEST_UNIT_READY:
+                        testUnitReady();
+                        break;
+                    case REQUEST_SENSE:
+                        requestSense();
+                        break;
+                    case INQUIRY:
+                        inquiryRequest();
+                        break;
+                    case MODE_SENSE6:
+                        modeSense6();
+                        break;
+                    case READ_FORMAT_CAPACITIES:
+                        readFormatCapacity();
+                        break;
+                    case MEDIA_REMOVAL:
+                        mediaRemoval();
+                        break;
+                    case READ_CAPACITY:
+                        readCapacity();
+                        break;
+                    case READ10:
+                    case READ12:
+                        if (infoTransfer()) {
+                            if ((cbw.Flags & 0x80)) {
+                                stage = PROCESS_CBW;
+                                memoryRead();
+                            } else {
+                                stallEndpoint(MSDBULK_OUT);
+                                csw.Status = CSW_ERROR;
+                                sendCSW();
+                            }
+                        }
+                        break;
+                    case WRITE10:
+                    case WRITE12:
+                        if (infoTransfer()) {
+                            if (!(cbw.Flags & 0x80)) {
+                                stage = PROCESS_CBW;
+                            } else {
+                                stallEndpoint(MSDBULK_IN);
+                                csw.Status = CSW_ERROR;
+                                sendCSW();
+                            }
+                        }
+                        break;
+                    case VERIFY10:
+                        if (!(cbw.CB[1] & 0x02)) {
+                            csw.Status = CSW_PASSED;
+                            sendCSW();
+                            break;
+                        }
+                        if (infoTransfer()) {
+                            if (!(cbw.Flags & 0x80)) {
+                                stage = PROCESS_CBW;
+                                memOK = true;
+                            } else {
+                                stallEndpoint(MSDBULK_IN);
+                                csw.Status = CSW_ERROR;
+                                sendCSW();
+                            }
+                        }
+                        break;
+                    default:
+                        fail();
+                        break;
+                }
+            }
+        }
+    }
+}
+\r
+void USBCDCMSC::testUnitReady (void) {
+\r
+    if (cbw.DataLength != 0) {
+        if ((cbw.Flags & 0x80) != 0) {
+            stallEndpoint(MSDBULK_IN);
+        } else {
+            stallEndpoint(MSDBULK_OUT);
+        }
+    }
+\r
+    csw.Status = CSW_PASSED;
+    sendCSW();
+}
+\r
+\r
+void USBCDCMSC::memoryRead (void) {
+    uint32_t n;
+\r
+    n = (length > MAX_PACKET) ? MAX_PACKET : length;
+\r
+    if ((addr + n) > MemorySize) {
+        n = MemorySize - addr;
+        stage = ERROR;
+    }
+\r
+    // we read an entire block
+    if (!(addr%BlockSize))
+        disk_read((char *)page, addr/BlockSize);
+\r
+    // write data which are in RAM
+    writeNB(MSDBULK_IN, &page[addr%BlockSize], n, MAX_PACKET_SIZE_EPBULK);
+\r
+    addr += n;
+    length -= n;
+\r
+    csw.DataResidue -= n;
+\r
+    if ( !length || (stage != PROCESS_CBW)) {
+        csw.Status = (stage == PROCESS_CBW) ? CSW_PASSED : CSW_FAILED;
+        stage = (stage == PROCESS_CBW) ? SEND_CSW : stage;
+    }
+}
+\r
+\r
+bool USBCDCMSC::infoTransfer (void) {
+    uint32_t n;
+\r
+    // Logical Block Address of First Block
+    n = (cbw.CB[2] << 24) | (cbw.CB[3] << 16) | (cbw.CB[4] <<  8) | (cbw.CB[5] <<  0);
+\r
+    addr = n * BlockSize;
+\r
+    // Number of Blocks to transfer
+    switch (cbw.CB[0]) {
+        case READ10:
+        case WRITE10:
+        case VERIFY10:
+            n = (cbw.CB[7] <<  8) | (cbw.CB[8] <<  0);
+            break;
+\r
+        case READ12:
+        case WRITE12:
+            n = (cbw.CB[6] << 24) | (cbw.CB[7] << 16) | (cbw.CB[8] <<  8) | (cbw.CB[9] <<  0);
+            break;
+    }
+\r
+    length = n * BlockSize;
+\r
+    if (!cbw.DataLength) {              // host requests no data
+        csw.Status = CSW_FAILED;
+        sendCSW();
+        return false;
+    }
+\r
+    if (cbw.DataLength != length) {
+        if ((cbw.Flags & 0x80) != 0) {
+            stallEndpoint(MSDBULK_IN);
+        } else {
+            stallEndpoint(MSDBULK_OUT);
+        }
+\r
+        csw.Status = CSW_FAILED;
+        sendCSW();
+        return false;
+    }
+\r
+    return true;
+}
+\r
+int USBCDCMSC::isBreak () {
+    int ret = cdcbreak;
+    cdcbreak = 0;
+    return ret;
+}
+\r
+int USBCDCMSC::disk_initialize() {
+    if (_sd->disk_initialize()) {
+        _status |= NO_DISK;
+        return 1;
+    } else {
+        _status = DISK_OK;
+        return 0;
+    }
+}
+\r
+int USBCDCMSC::disk_write(const char *buffer, int block_number) {
+    return _sd->disk_write(buffer, block_number);
+}
+\r
+int USBCDCMSC::disk_read(char *buffer, int block_number) {
+    return _sd->disk_read(buffer, block_number);
+}
+\r
+int USBCDCMSC::disk_status() {
+    return _status;
+}
+\r
+int USBCDCMSC::disk_sectors() {
+    return _sd->disk_sectors();
+}
+int USBCDCMSC::disk_size() {
+    return _sd->disk_sectors() * 512;
+}
+\r
+\r
+void USBCDCMSC::on_module_loaded(){
+    // We want to be called every time a new char is received
+    this->attach(this, &USBCDCMSC::on_serial_char_received);
+\r
+    // We only call the command dispatcher in the main loop, nowhere else
+    this->register_for_event(ON_MAIN_LOOP);
+\r
+    // Add to the pack of streams kernel can call to, for example for broadcasting
+    this->kernel->streams->append_stream(this);
+\r
+}
+\r
+\r
+\r
+\r
+\r
+\r
+void USBCDCMSC::on_main_loop(void* argument){
+    if( this->has_char('\n') ){
+        string received;
+        while(1){
+            char c;
+            this->buffer.pop_front(c);
+            if( c == '\n' ){
+                struct SerialMessage message;
+                message.message = received;
+                message.stream = this;
+                this->kernel->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
+                return;
+            }else{
+                received += c;
+            }
+        }
+    }
+}
+\r
+void USBCDCMSC::on_serial_char_received(){
+    while(this->available()){
+        char received = this->_getc();
+        // convert CR to NL (for host OSs that don't send NL)
+        if( received == '\r' ){ received = '\n'; }
+        this->buffer.push_back(received);
+    }
+\r
+}
+\r
+\r
+bool USBCDCMSC::has_char(char letter){
+    int index = this->buffer.head;
+    while( index != this->buffer.tail ){
+        if( this->buffer.buffer[index] == letter ){
+            return true;
+        }
+        index = this->buffer.next_block_index(index);
+    }
+    return false;
+}
index b9450f1..cc52ea5 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#ifndef USBCDCMSC_H\r
-#define USBCDCMSC_H\r
-\r
-#include <string>\r
-using std::string;\r
-#include "mbed.h"\r
-#include "libs/Module.h"\r
-#include "libs/Kernel.h"\r
-\r
-\r
-/* These headers are included for child class. */\r
-#include "USBEndpoints.h"\r
-#include "USBDescriptor.h"\r
-#include "USBDevice_Types.h"\r
-\r
-#include "USBDevice.h"\r
-\r
-//#include "Stream.h"\r
-#include "CircBuffer.h"\r
-\r
-#include "libs/RingBuffer.h"\r
-\r
-#include "SDFileSystem.h"\r
-\r
-#ifdef __GNUC__\r
-    /* Packing for structs in GCC. */\r
-    #define PACK_STRUCT_STRUCT __attribute__((packed))\r
-    #define PACK_STRUCT_BEGIN\r
-    #define PACK_STRUCT_END\r
-#else /* !__GNUC__ */\r
-    /* Packing for structs in ARM compiler. */\r
-    #define PACK_STRUCT_STRUCT\r
-    #define PACK_STRUCT_BEGIN __packed\r
-    #define PACK_STRUCT_END\r
-#endif /* __GNUC__ */\r
-\r
-#include "libs/StreamOutput.h"\r
-\r
-\r
-\r
-\r
-class USBCDCMSC: public USBDevice, public Module, public StreamOutput {\r
-public:\r
-\r
-    /*\r
-    * Constructor\r
-    *\r
-    * @param vendor_id Your vendor_id\r
-    * @param product_id Your product_id\r
-    * @param product_release Your preoduct_release\r
-    */\r
-    USBCDCMSC(SDFileSystem *sd, uint16_t vendor_id = 0x1f00, uint16_t product_id = 0x2012, uint16_t product_release = 0x0001);\r
-\r
-    /**\r
-    * Send a character. You can use puts, printf.\r
-    *\r
-    * @param c character to be sent\r
-    * @returns true if there is no error, false otherwise\r
-    */\r
-    virtual int _putc(int c);\r
-\r
-    /**\r
-     * Send a formatted string.\r
-     */\r
-    int printf(const char* format, ...);\r
-\r
-    /**\r
-    * Read a character: blocking\r
-    *\r
-    * @returns character read\r
-    */\r
-    virtual int _getc();\r
-\r
-    /**\r
-    * Check the number of bytes available.\r
-    *\r
-    * @returns the number of bytes available\r
-    */\r
-    uint8_t available();\r
-\r
-    /**\r
-    * Write a block of data.\r
-    *\r
-    * For more efficiency, a block of size 64 (maximum size of a bulk endpoint) has to be written.\r
-    *\r
-    * @param buf pointer on data which will be written\r
-    * @param size size of the buffer. The maximum size of a block is limited by the size of the endpoint (64 bytes)\r
-    *\r
-    * @returns true if successfull\r
-    */\r
-    bool writeBlock(uint8_t * buf, uint16_t size);\r
-\r
-    /**\r
-     *  Attach a member function to call when a packet is received.\r
-     *\r
-     *  @param tptr pointer to the object to call the member function on\r
-     *  @param mptr pointer to the member function to be called\r
-     */\r
-    template<typename T>\r
-    void attach(T* tptr, void (T::*mptr)(void)) {\r
-        if((mptr != NULL) && (tptr != NULL)) {\r
-            rx.attach(tptr, mptr);\r
-        }\r
-    }\r
-\r
-    /**\r
-     * Attach a callback called when a packet is received\r
-     *\r
-     * @param fptr function pointer\r
-     */\r
-    void attach(void (*fn)(void)) {\r
-        if(fn != NULL) {\r
-            rx.attach(fn);\r
-        }\r
-    }\r
-\r
-\r
-    /**\r
-    * Connect the USB MSD device. Establish disk initialization before really connect the device.\r
-    *\r
-    * @returns true if successful\r
-    */\r
-    bool connect();\r
-    void on_module_loaded();\r
-    void on_serial_char_received();\r
-    void on_main_loop(void* argument);\r
-    bool has_char(char letter);\r
-\r
-    RingBuffer<char,256> buffer;             // Receive buffer\r
-\r
-protected:\r
-\r
-    /*\r
-    * Get device descriptor. Warning: this method has to store the length of the report descriptor in reportLength.\r
-    *\r
-    * @returns pointer to the device descriptor\r
-    */\r
-    virtual uint8_t * deviceDesc();\r
-\r
-    /*\r
-    * Get string product descriptor\r
-    *\r
-    * @returns pointer to the string product descriptor\r
-    */\r
-    virtual uint8_t * stringIproductDesc();\r
-\r
-    /*\r
-    * Get string interface descriptor\r
-    *\r
-    * @returns pointer to the string interface descriptor\r
-    */\r
-    virtual uint8_t * stringIinterfaceDesc();\r
-\r
-    /*\r
-    * Get configuration descriptor\r
-    *\r
-    * @returns pointer to the configuration descriptor\r
-    */\r
-    virtual uint8_t * configurationDesc();\r
-\r
-    /*\r
-    * Send a buffer\r
-    *\r
-    * @param endpoint endpoint which will be sent the buffer\r
-    * @param buffer buffer to be sent\r
-    * @param size length of the buffer\r
-    * @returns true if successful\r
-    */\r
-    bool send(uint8_t * buffer, uint16_t size);\r
-\r
-    /*\r
-    * Read a buffer from a certain endpoint. Warning: blocking\r
-    *\r
-    * @param endpoint endpoint to read\r
-    * @param buffer buffer where will be stored bytes\r
-    * @param size the number of bytes read will be stored in *size\r
-    * @param maxSize the maximum length that can be read\r
-    * @returns true if successful\r
-    */\r
-    bool readEP(uint8_t * buffer, uint16_t * size);\r
-\r
-    /*\r
-    * Read a buffer from a certain endpoint. Warning: non blocking\r
-    *\r
-    * @param endpoint endpoint to read\r
-    * @param buffer buffer where will be stored bytes\r
-    * @param size the number of bytes read will be stored in *size\r
-    * @param maxSize the maximum length that can be read\r
-    * @returns true if successful\r
-    */\r
-    bool readEP_NB(uint8_t * buffer, uint16_t * size);\r
-\r
-    virtual bool USBCallback_request();\r
-    virtual bool USBCallback_setConfiguration(uint8_t configuration);\r
-\r
-    virtual bool EP2_OUT_callback();\r
-\r
-    /*\r
-    * Callback called when a packet is received\r
-    */\r
-    virtual bool EP5_OUT_callback();\r
-\r
-    /*\r
-    * Callback called when a packet has been sent\r
-    */\r
-    virtual bool EP5_IN_callback();\r
-\r
-private:\r
-\r
-    FunctionPointer rx;\r
-    CircBuffer<uint8_t> cdcbuf;\r
-    int cdcbreak;\r
-\r
-    // MSC Bulk-only Stage\r
-    enum Stage {\r
-        READ_CBW,     // wait a CBW\r
-        ERROR,        // error\r
-        PROCESS_CBW,  // process a CBW request\r
-        SEND_CSW,     // send a CSW\r
-        WAIT_CSW,     // wait that a CSW has been effectively sent\r
-    };\r
-\r
-\r
-    // Bulk-only CBW\r
-    typedef PACK_STRUCT_BEGIN struct {\r
-        uint32_t Signature;\r
-        uint32_t Tag;\r
-        uint32_t DataLength;\r
-        uint8_t  Flags;\r
-        uint8_t  LUN;\r
-        uint8_t  CBLength;\r
-        uint8_t  CB[16];\r
-    } PACK_STRUCT_STRUCT CBW;\r
-\r
-    // Bulk-only CSW\r
-    typedef PACK_STRUCT_BEGIN struct {\r
-        uint32_t Signature;\r
-        uint32_t Tag;\r
-        uint32_t DataResidue;\r
-        uint8_t  Status;\r
-    } PACK_STRUCT_STRUCT CSW;\r
-\r
-    // sense\r
-    typedef PACK_STRUCT_BEGIN struct {\r
-        uint8_t error;\r
-        uint8_t resvd;\r
-        uint8_t sense_key;\r
-        uint8_t information[4];\r
-        uint8_t additional_sense_length;\r
-        uint8_t resvd2[4];\r
-        uint8_t asc;\r
-        uint8_t ascq;\r
-        uint8_t resvd3[4];\r
-    } PACK_STRUCT_STRUCT SENSE;\r
-\r
-    //state of the bulk-only state machine\r
-    Stage stage;\r
-\r
-    // current CBW\r
-    CBW cbw;\r
-\r
-    // CSW which will be sent\r
-    CSW csw;\r
-\r
-    // Current sense\r
-    SENSE sense;\r
-\r
-    // addr where will be read or written data\r
-    uint32_t addr;\r
-\r
-    // length of a reading or writing\r
-    uint32_t length;\r
-\r
-    // memory OK (after a memoryVerify)\r
-    bool memOK;\r
-\r
-    // cache in RAM before writing in memory. Useful also to read a block.\r
-    uint8_t * page;\r
-\r
-    int BlockSize;\r
-    int MemorySize;\r
-    int BlockCount;\r
-\r
-    int _status;\r
-    SDFileSystem *_sd;\r
-\r
-    void CBWDecode(uint8_t * buf, uint16_t size);\r
-    void sendCSW (void);\r
-    bool inquiryRequest (void);\r
-    bool msd_write (uint8_t * buf, uint16_t size);\r
-    bool readFormatCapacity();\r
-    bool readCapacity (void);\r
-    bool infoTransfer (void);\r
-    void memoryRead (void);\r
-    bool modeSense6 (void);\r
-    void testUnitReady (void);\r
-    bool requestSense (void);\r
-    void setSense (uint8_t sense_key, uint8_t asc, uint8_t ascq);\r
-    void memoryVerify (uint8_t * buf, uint16_t size);\r
-    void memoryWrite (uint8_t * buf, uint16_t size);\r
-    void mediaRemoval(void);\r
-    void reset();\r
-    void fail();\r
-\r
-    int isBreak();\r
-\r
-    int disk_initialize();\r
-    int disk_write(const char *buffer, int block_number);\r
-    int disk_read(char *buffer, int block_number);\r
-    int disk_status();\r
-    int disk_sectors();\r
-    int disk_size();\r
-\r
-};\r
-\r
-#endif\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#ifndef USBCDCMSC_H
+#define USBCDCMSC_H
+\r
+#include <string>
+using std::string;
+#include "mbed.h"
+#include "libs/Module.h"
+#include "libs/Kernel.h"
+\r
+\r
+/* These headers are included for child class. */
+#include "USBEndpoints.h"
+#include "USBDescriptor.h"
+#include "USBDevice_Types.h"
+\r
+#include "USBDevice.h"
+\r
+//#include "Stream.h"
+#include "CircBuffer.h"
+\r
+#include "libs/RingBuffer.h"
+\r
+#include "SDFileSystem.h"
+\r
+#ifdef __GNUC__
+    /* Packing for structs in GCC. */
+    #define PACK_STRUCT_STRUCT __attribute__((packed))
+    #define PACK_STRUCT_BEGIN
+    #define PACK_STRUCT_END
+#else /* !__GNUC__ */
+    /* Packing for structs in ARM compiler. */
+    #define PACK_STRUCT_STRUCT
+    #define PACK_STRUCT_BEGIN __packed
+    #define PACK_STRUCT_END
+#endif /* __GNUC__ */
+\r
+#include "libs/StreamOutput.h"
+\r
+\r
+\r
+\r
+class USBCDCMSC: public USBDevice, public Module, public StreamOutput {
+public:
+\r
+    /*
+    * Constructor
+    *
+    * @param vendor_id Your vendor_id
+    * @param product_id Your product_id
+    * @param product_release Your preoduct_release
+    */
+    USBCDCMSC(SDFileSystem *sd, uint16_t vendor_id = 0x1f00, uint16_t product_id = 0x2012, uint16_t product_release = 0x0001);
+\r
+    /**
+    * Send a character. You can use puts, printf.
+    *
+    * @param c character to be sent
+    * @returns true if there is no error, false otherwise
+    */
+    virtual int _putc(int c);
+\r
+    /**
+     * Send a formatted string.
+     */
+    int printf(const char* format, ...);
+\r
+    /**
+    * Read a character: blocking
+    *
+    * @returns character read
+    */
+    virtual int _getc();
+\r
+    /**
+    * Check the number of bytes available.
+    *
+    * @returns the number of bytes available
+    */
+    uint8_t available();
+\r
+    /**
+    * Write a block of data.
+    *
+    * For more efficiency, a block of size 64 (maximum size of a bulk endpoint) has to be written.
+    *
+    * @param buf pointer on data which will be written
+    * @param size size of the buffer. The maximum size of a block is limited by the size of the endpoint (64 bytes)
+    *
+    * @returns true if successfull
+    */
+    bool writeBlock(uint8_t * buf, uint16_t size);
+\r
+    /**
+     *  Attach a member function to call when a packet is received.
+     *
+     *  @param tptr pointer to the object to call the member function on
+     *  @param mptr pointer to the member function to be called
+     */
+    template<typename T>
+    void attach(T* tptr, void (T::*mptr)(void)) {
+        if((mptr != NULL) && (tptr != NULL)) {
+            rx.attach(tptr, mptr);
+        }
+    }
+\r
+    /**
+     * Attach a callback called when a packet is received
+     *
+     * @param fptr function pointer
+     */
+    void attach(void (*fn)(void)) {
+        if(fn != NULL) {
+            rx.attach(fn);
+        }
+    }
+\r
+\r
+    /**
+    * Connect the USB MSD device. Establish disk initialization before really connect the device.
+    *
+    * @returns true if successful
+    */
+    bool connect();
+    void on_module_loaded();
+    void on_serial_char_received();
+    void on_main_loop(void* argument);
+    bool has_char(char letter);
+\r
+    RingBuffer<char,256> buffer;             // Receive buffer
+\r
+protected:
+\r
+    /*
+    * Get device descriptor. Warning: this method has to store the length of the report descriptor in reportLength.
+    *
+    * @returns pointer to the device descriptor
+    */
+    virtual uint8_t * deviceDesc();
+\r
+    /*
+    * Get string product descriptor
+    *
+    * @returns pointer to the string product descriptor
+    */
+    virtual uint8_t * stringIproductDesc();
+\r
+    /*
+    * Get string interface descriptor
+    *
+    * @returns pointer to the string interface descriptor
+    */
+    virtual uint8_t * stringIinterfaceDesc();
+\r
+    /*
+    * Get configuration descriptor
+    *
+    * @returns pointer to the configuration descriptor
+    */
+    virtual uint8_t * configurationDesc();
+\r
+    /*
+    * Send a buffer
+    *
+    * @param endpoint endpoint which will be sent the buffer
+    * @param buffer buffer to be sent
+    * @param size length of the buffer
+    * @returns true if successful
+    */
+    bool send(uint8_t * buffer, uint16_t size);
+\r
+    /*
+    * Read a buffer from a certain endpoint. Warning: blocking
+    *
+    * @param endpoint endpoint to read
+    * @param buffer buffer where will be stored bytes
+    * @param size the number of bytes read will be stored in *size
+    * @param maxSize the maximum length that can be read
+    * @returns true if successful
+    */
+    bool readEP(uint8_t * buffer, uint16_t * size);
+\r
+    /*
+    * Read a buffer from a certain endpoint. Warning: non blocking
+    *
+    * @param endpoint endpoint to read
+    * @param buffer buffer where will be stored bytes
+    * @param size the number of bytes read will be stored in *size
+    * @param maxSize the maximum length that can be read
+    * @returns true if successful
+    */
+    bool readEP_NB(uint8_t * buffer, uint16_t * size);
+\r
+    virtual bool USBCallback_request();
+    virtual bool USBCallback_setConfiguration(uint8_t configuration);
+\r
+    virtual bool EP2_OUT_callback();
+\r
+    /*
+    * Callback called when a packet is received
+    */
+    virtual bool EP5_OUT_callback();
+\r
+    /*
+    * Callback called when a packet has been sent
+    */
+    virtual bool EP5_IN_callback();
+\r
+private:
+\r
+    FunctionPointer rx;
+    CircBuffer<uint8_t> cdcbuf;
+    int cdcbreak;
+\r
+    // MSC Bulk-only Stage
+    enum Stage {
+        READ_CBW,     // wait a CBW
+        ERROR,        // error
+        PROCESS_CBW,  // process a CBW request
+        SEND_CSW,     // send a CSW
+        WAIT_CSW,     // wait that a CSW has been effectively sent
+    };
+\r
+\r
+    // Bulk-only CBW
+    typedef PACK_STRUCT_BEGIN struct {
+        uint32_t Signature;
+        uint32_t Tag;
+        uint32_t DataLength;
+        uint8_t  Flags;
+        uint8_t  LUN;
+        uint8_t  CBLength;
+        uint8_t  CB[16];
+    } PACK_STRUCT_STRUCT CBW;
+\r
+    // Bulk-only CSW
+    typedef PACK_STRUCT_BEGIN struct {
+        uint32_t Signature;
+        uint32_t Tag;
+        uint32_t DataResidue;
+        uint8_t  Status;
+    } PACK_STRUCT_STRUCT CSW;
+\r
+    // sense
+    typedef PACK_STRUCT_BEGIN struct {
+        uint8_t error;
+        uint8_t resvd;
+        uint8_t sense_key;
+        uint8_t information[4];
+        uint8_t additional_sense_length;
+        uint8_t resvd2[4];
+        uint8_t asc;
+        uint8_t ascq;
+        uint8_t resvd3[4];
+    } PACK_STRUCT_STRUCT SENSE;
+\r
+    //state of the bulk-only state machine
+    Stage stage;
+\r
+    // current CBW
+    CBW cbw;
+\r
+    // CSW which will be sent
+    CSW csw;
+\r
+    // Current sense
+    SENSE sense;
+\r
+    // addr where will be read or written data
+    uint32_t addr;
+\r
+    // length of a reading or writing
+    uint32_t length;
+\r
+    // memory OK (after a memoryVerify)
+    bool memOK;
+\r
+    // cache in RAM before writing in memory. Useful also to read a block.
+    uint8_t * page;
+\r
+    int BlockSize;
+    int MemorySize;
+    int BlockCount;
+\r
+    int _status;
+    SDFileSystem *_sd;
+\r
+    void CBWDecode(uint8_t * buf, uint16_t size);
+    void sendCSW (void);
+    bool inquiryRequest (void);
+    bool msd_write (uint8_t * buf, uint16_t size);
+    bool readFormatCapacity();
+    bool readCapacity (void);
+    bool infoTransfer (void);
+    void memoryRead (void);
+    bool modeSense6 (void);
+    void testUnitReady (void);
+    bool requestSense (void);
+    void setSense (uint8_t sense_key, uint8_t asc, uint8_t ascq);
+    void memoryVerify (uint8_t * buf, uint16_t size);
+    void memoryWrite (uint8_t * buf, uint16_t size);
+    void mediaRemoval(void);
+    void reset();
+    void fail();
+\r
+    int isBreak();
+\r
+    int disk_initialize();
+    int disk_write(const char *buffer, int block_number);
+    int disk_read(char *buffer, int block_number);
+    int disk_status();
+    int disk_sectors();
+    int disk_size();
+\r
+};
+\r
+#endif
index fadf509..bfce6d4 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#include "stdint.h"\r
-#include "USBAudio.h"\r
-#include "USBBusInterface.h"\r
-#include "USBAudio_Types.h"\r
-\r
-\r
-\r
-USBAudio::USBAudio(uint32_t frequency, uint8_t channel_nb, uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release) {\r
-    mute = 0;\r
-    volCur = 0x0080;\r
-    volMin = 0x0000;\r
-    volMax = 0x0100;\r
-    volRes = 0x0004;\r
-    available = false;\r
-\r
-    FREQ = frequency;\r
-\r
-    this->channel_nb = channel_nb;\r
-\r
-    // stereo -> *2, mono -> *1\r
-    PACKET_SIZE_ISO = (FREQ / 500) * channel_nb;\r
-\r
-    // STEREO -> left and right\r
-    channel_config = (channel_nb == 1) ? CHANNEL_M : CHANNEL_L + CHANNEL_R;\r
-\r
-    SOF_handler = false;\r
-\r
-    buf_stream = NULL;\r
-\r
-    // connect the device\r
-    USBDevice::connect();\r
-}\r
-\r
-bool USBAudio::read(uint8_t * buf) {\r
-    buf_stream = buf;\r
-    while (!available);\r
-    available = false;\r
-    buf_stream = NULL;\r
-    return true;\r
-}\r
-\r
-bool USBAudio::readNB(uint8_t * buf) {\r
-    buf_stream = buf;\r
-    SOF_handler = false;\r
-    while (!SOF_handler);\r
-    if (available) {\r
-        available = false;\r
-        buf_stream = NULL;\r
-        return true;\r
-    }\r
-    buf_stream = NULL;\r
-    return false;\r
-}\r
-\r
-\r
-float USBAudio::getVolume() {\r
-    return (mute) ? 0.0 : (float)volCur/(float)volMax;\r
-}\r
-\r
-\r
-// Called in ISR context on each start of frame\r
-void USBAudio::SOF(int frameNumber) {\r
-    uint16_t size = 0;\r
-\r
-    // read the isochronous endpoint\r
-    if (buf_stream != NULL) {\r
-        USBDevice::readEP_NB(EP3OUT, buf_stream, &size, PACKET_SIZE_ISO);\r
-    }\r
-\r
-    // if we read something, modify the flag "available"\r
-    available = (size) ? true : false;\r
-\r
-    // activate readings on the isochronous\r
-    readStart(EP3OUT, PACKET_SIZE_ISO);\r
-\r
-    SOF_handler = true;\r
-}\r
-\r
-\r
-// Called in ISR context\r
-// Set configuration. Return false if the configuration is not supported.\r
-bool USBAudio::USBCallback_setConfiguration(uint8_t configuration) {\r
-    if (configuration != DEFAULT_CONFIGURATION) {\r
-        return false;\r
-    }\r
-\r
-    // Configure isochronous endpoint\r
-    realiseEndpoint(EP3OUT, PACKET_SIZE_ISO, ISOCHRONOUS);\r
-\r
-    // activate readings on this endpoint\r
-    readStart(EP3OUT, PACKET_SIZE_ISO);\r
-    return true;\r
-}\r
-\r
-\r
-// Called in ISR context\r
-// Set alternate setting. Return false if the alternate setting is not supported\r
-bool USBAudio::USBCallback_setInterface(uint16_t interface, uint8_t alternate) {\r
-    if (interface == 0 && alternate == 0) {\r
-        return true;\r
-    }\r
-    if (interface == 1 && (alternate == 0 || alternate == 1)) {\r
-        return true;\r
-    }\r
-    return false;\r
-}\r
-\r
-\r
-\r
-// Called in ISR context\r
-// Called by USBDevice on Endpoint0 request\r
-// This is used to handle extensions to standard requests and class specific requests.\r
-// Return true if class handles this request\r
-bool USBAudio::USBCallback_request() {\r
-    bool success = false;\r
-    CONTROL_TRANSFER * transfer = getTransferPtr();\r
-\r
-    // Process class-specific requests\r
-    if (transfer->setup.bmRequestType.Type == CLASS_TYPE) {\r
-\r
-        // Feature Unit: Interface = 0, ID = 2\r
-        if (transfer->setup.wIndex == 0x0200) {\r
-\r
-            // Master Channel\r
-            if ((transfer->setup.wValue & 0xff) == 0) {\r
-\r
-                switch (transfer->setup.wValue >> 8) {\r
-                    case MUTE_CONTROL:\r
-                        switch (transfer->setup.bRequest) {\r
-                            case REQUEST_GET_CUR:\r
-                                transfer->remaining = 1;\r
-                                transfer->ptr = &mute;\r
-                                transfer->direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break;\r
-\r
-                            case REQUEST_SET_CUR:\r
-                                transfer->remaining = 1;\r
-                                transfer->notify = true;\r
-                                transfer->direction = HOST_TO_DEVICE;\r
-                                success = true;\r
-                                break;\r
-                            default:\r
-                                break;\r
-                        }\r
-                        break;\r
-                    case VOLUME_CONTROL:\r
-                        switch (transfer->setup.bRequest) {\r
-                            case REQUEST_GET_CUR:\r
-                                transfer->remaining = 2;\r
-                                transfer->ptr = (uint8_t *)&volCur;\r
-                                transfer->direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break;\r
-                            case REQUEST_GET_MIN:\r
-                                transfer->remaining = 2;\r
-                                transfer->ptr = (uint8_t *)&volMin;\r
-                                transfer->direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break;\r
-                            case REQUEST_GET_MAX:\r
-                                transfer->remaining = 2;\r
-                                transfer->ptr = (uint8_t *)&volMax;\r
-                                transfer->direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break;\r
-                            case REQUEST_GET_RES:\r
-                                transfer->remaining = 2;\r
-                                transfer->ptr = (uint8_t *)&volRes;\r
-                                transfer->direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break;\r
-\r
-                            case REQUEST_SET_CUR:\r
-                                transfer->remaining = 2;\r
-                                transfer->notify = true;\r
-                                transfer->direction = HOST_TO_DEVICE;\r
-                                success = true;\r
-                                break;\r
-                            case REQUEST_SET_MIN:\r
-                                transfer->remaining = 2;\r
-                                transfer->notify = true;\r
-                                transfer->direction = HOST_TO_DEVICE;\r
-                                success = true;\r
-                                break;\r
-                            case REQUEST_SET_MAX:\r
-                                transfer->remaining = 2;\r
-                                transfer->notify = true;\r
-                                transfer->direction = HOST_TO_DEVICE;\r
-                                success = true;\r
-                                break;\r
-                            case REQUEST_SET_RES:\r
-                                transfer->remaining = 2;\r
-                                transfer->notify = true;\r
-                                transfer->direction = HOST_TO_DEVICE;\r
-                                success = true;\r
-                                break;\r
-                        }\r
-                        break;\r
-                    default:\r
-                        break;\r
-                }\r
-            }\r
-        }\r
-    }\r
-    return success;\r
-}\r
-\r
-\r
-// Called in ISR context when a data OUT stage has been performed\r
-void USBAudio::USBCallback_requestCompleted(uint8_t * buf, uint16_t length) {\r
-    uint16_t data = *((uint16_t *)buf);\r
-    CONTROL_TRANSFER * transfer = getTransferPtr();\r
-    switch (transfer->setup.wValue >> 8) {\r
-        case MUTE_CONTROL:\r
-            switch (transfer->setup.bRequest) {\r
-                case REQUEST_SET_CUR:\r
-                    mute = data & 0xff;\r
-                    updateVol.call();\r
-                    break;\r
-                default:\r
-                    break;\r
-            }\r
-            break;\r
-        case VOLUME_CONTROL:\r
-            switch (transfer->setup.bRequest) {\r
-                case REQUEST_SET_CUR:\r
-                    volCur = data;\r
-                    updateVol.call();\r
-                    break;\r
-                default:\r
-                    break;\r
-            }\r
-            break;\r
-        default:\r
-            break;\r
-    }\r
-}\r
-\r
-\r
-\r
-#define TOTAL_DESCRIPTOR_LENGTH ((1 * CONFIGURATION_DESCRIPTOR_LENGTH) \\r
-                               + (3 * INTERFACE_DESCRIPTOR_LENGTH) \\r
-                               + (1 * CONTROL_INTERFACE_DESCRIPTOR_LENGTH) \\r
-                               + (1 * INPUT_TERMINAL_DESCRIPTOR_LENGTH) \\r
-                               + (1 * FEATURE_UNIT_DESCRIPTOR_LENGTH) \\r
-                               + (1 * OUTPUT_TERMINAL_DESCRIPTOR_LENGTH) \\r
-                               + (1 * STREAMING_INTERFACE_DESCRIPTOR_LENGTH) \\r
-                               + (1 * FORMAT_TYPE_I_DESCRIPTOR_LENGTH) \\r
-                               + (1 * (ENDPOINT_DESCRIPTOR_LENGTH + 2)) \\r
-                               + (1 * STREAMING_ENDPOINT_DESCRIPTOR_LENGTH) )\r
-\r
-#define TOTAL_CONTROL_INTF_LENGTH    (CONTROL_INTERFACE_DESCRIPTOR_LENGTH + \\r
-                                      INPUT_TERMINAL_DESCRIPTOR_LENGTH     + \\r
-                                      FEATURE_UNIT_DESCRIPTOR_LENGTH    + \\r
-                                      OUTPUT_TERMINAL_DESCRIPTOR_LENGTH)\r
-\r
-uint8_t * USBAudio::configurationDesc() {\r
-    static uint8_t configDescriptor[] = {\r
-        // Configuration 1\r
-        CONFIGURATION_DESCRIPTOR_LENGTH,        // bLength\r
-        CONFIGURATION_DESCRIPTOR,               // bDescriptorType\r
-        LSB(TOTAL_DESCRIPTOR_LENGTH),           // wTotalLength (LSB)\r
-        MSB(TOTAL_DESCRIPTOR_LENGTH),           // wTotalLength (MSB)\r
-        0x02,                                   // bNumInterfaces\r
-        DEFAULT_CONFIGURATION,                  // bConfigurationValue\r
-        0x00,                                   // iConfiguration\r
-        0x80,                                   // bmAttributes\r
-        50,                                     // bMaxPower\r
-\r
-        // Interface 0, Alternate Setting 0, Audio Control\r
-        INTERFACE_DESCRIPTOR_LENGTH,            // bLength\r
-        INTERFACE_DESCRIPTOR,                   // bDescriptorType\r
-        0x00,                                   // bInterfaceNumber\r
-        0x00,                                   // bAlternateSetting\r
-        0x00,                                   // bNumEndpoints\r
-        AUDIO_CLASS,                            // bInterfaceClass\r
-        SUBCLASS_AUDIOCONTROL,                  // bInterfaceSubClass\r
-        0x00,                                   // bInterfaceProtocol\r
-        0x00,                                   // iInterface\r
-\r
-\r
-        // Audio Control Interface\r
-        CONTROL_INTERFACE_DESCRIPTOR_LENGTH,    // bLength\r
-        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType\r
-        CONTROL_HEADER,                         // bDescriptorSubtype\r
-        LSB(0x0100),                            // bcdADC (LSB)\r
-        MSB(0x0100),                            // bcdADC (MSB)\r
-        LSB(TOTAL_CONTROL_INTF_LENGTH),         // wTotalLength\r
-        MSB(TOTAL_CONTROL_INTF_LENGTH),         // wTotalLength\r
-        0x01,                                   // bInCollection\r
-        0x01,                                   // baInterfaceNr\r
-\r
-        // Audio Input Terminal\r
-        INPUT_TERMINAL_DESCRIPTOR_LENGTH,       // bLength\r
-        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType\r
-        CONTROL_INPUT_TERMINAL,                 // bDescriptorSubtype\r
-        0x01,                                   // bTerminalID\r
-        LSB(TERMINAL_USB_STREAMING),            // wTerminalType\r
-        MSB(TERMINAL_USB_STREAMING),            // wTerminalType\r
-        0x00,                                   // bAssocTerminal\r
-        channel_nb,                             // bNrChannels\r
-        LSB(channel_config),                    // wChannelConfig\r
-        MSB(channel_config),                    // wChannelConfig\r
-        0x00,                                   // iChannelNames\r
-        0x00,                                   // iTerminal\r
-\r
-        // Audio Feature Unit\r
-        FEATURE_UNIT_DESCRIPTOR_LENGTH,         // bLength\r
-        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType\r
-        CONTROL_FEATURE_UNIT,                   // bDescriptorSubtype\r
-        0x02,                                   // bUnitID\r
-        0x01,                                   // bSourceID\r
-        0x01,                                   // bControlSize\r
-        CONTROL_MUTE |\r
-        CONTROL_VOLUME,                         // bmaControls(0)\r
-        0x00,                                   // bmaControls(1)\r
-        0x00,                                   // iTerminal\r
-\r
-        // Audio Output Terminal\r
-        OUTPUT_TERMINAL_DESCRIPTOR_LENGTH,      // bLength\r
-        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType\r
-        CONTROL_OUTPUT_TERMINAL,                // bDescriptorSubtype\r
-        0x03,                                   // bTerminalID\r
-        LSB(TERMINAL_SPEAKER),                  // wTerminalType\r
-        MSB(TERMINAL_SPEAKER),                  // wTerminalType\r
-        0x00,                                   // bAssocTerminal\r
-        0x02,                                   // bSourceID\r
-        0x00,                                   // iTerminal\r
-\r
-\r
-        // Interface 1, Alternate Setting 0, Audio Streaming - Zero Bandwith\r
-        INTERFACE_DESCRIPTOR_LENGTH,            // bLength\r
-        INTERFACE_DESCRIPTOR,                   // bDescriptorType\r
-        0x01,                                   // bInterfaceNumber\r
-        0x00,                                   // bAlternateSetting\r
-        0x00,                                   // bNumEndpoints\r
-        AUDIO_CLASS,                            // bInterfaceClass\r
-        SUBCLASS_AUDIOSTREAMING,                // bInterfaceSubClass\r
-        0x00,                                   // bInterfaceProtocol\r
-        0x00,                                   // iInterface\r
-\r
-        // Interface 1, Alternate Setting 1, Audio Streaming - Operational\r
-        INTERFACE_DESCRIPTOR_LENGTH,            // bLength\r
-        INTERFACE_DESCRIPTOR,                   // bDescriptorType\r
-        0x01,                                   // bInterfaceNumber\r
-        0x01,                                   // bAlternateSetting\r
-        0x01,                                   // bNumEndpoints\r
-        AUDIO_CLASS,                            // bInterfaceClass\r
-        SUBCLASS_AUDIOSTREAMING,                // bInterfaceSubClass\r
-        0x00,                                   // bInterfaceProtocol\r
-        0x00,                                   // iInterface\r
-\r
-        // Audio Streaming Interface\r
-        STREAMING_INTERFACE_DESCRIPTOR_LENGTH,  // bLength\r
-        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType\r
-        STREAMING_GENERAL,                      // bDescriptorSubtype\r
-        0x01,                                   // bTerminalLink\r
-        0x00,                                   // bDelay\r
-        LSB(FORMAT_PCM),                        // wFormatTag\r
-        MSB(FORMAT_PCM),                        // wFormatTag\r
-\r
-        // Audio Type I Format\r
-        FORMAT_TYPE_I_DESCRIPTOR_LENGTH,        // bLength\r
-        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType\r
-        STREAMING_FORMAT_TYPE,                  // bDescriptorSubtype\r
-        FORMAT_TYPE_I,                          // bFormatType\r
-        channel_nb,                             // bNrChannels\r
-        0x02,                                   // bSubFrameSize\r
-        16,                                     // bBitResolution\r
-        0x01,                                   // bSamFreqType\r
-        LSB(FREQ),                              // tSamFreq\r
-        ((uint8_t) ((FREQ >> 8) & 0xff)),       // tSamFreq\r
-        ((uint8_t) ((FREQ >> 16) & 0xff)),      // tSamFreq\r
-\r
-        // Endpoint - Standard Descriptor\r
-        ENDPOINT_DESCRIPTOR_LENGTH + 2,         // bLength\r
-        ENDPOINT_DESCRIPTOR,                    // bDescriptorType\r
-        PHY_TO_DESC(EPISO_OUT),                 // bEndpointAddress\r
-        E_ISOCHRONOUS,                          // bmAttributes\r
-        LSB(PACKET_SIZE_ISO),                   // wMaxPacketSize\r
-        MSB(PACKET_SIZE_ISO),                   // wMaxPacketSize\r
-        0x01,                                   // bInterval\r
-        0x00,                                   // bRefresh\r
-        0x00,                                   // bSynchAddress\r
-\r
-        // Endpoint - Audio Streaming\r
-        STREAMING_ENDPOINT_DESCRIPTOR_LENGTH,   // bLength\r
-        ENDPOINT_DESCRIPTOR_TYPE,               // bDescriptorType\r
-        ENDPOINT_GENERAL,                       // bDescriptor\r
-        0x00,                                   // bmAttributes\r
-        0x00,                                   // bLockDelayUnits\r
-        LSB(0x0000),                            // wLockDelay\r
-        MSB(0x0000),                            // wLockDelay\r
-\r
-        // Terminator\r
-        0                                       // bLength\r
-    };\r
-    return configDescriptor;\r
-}\r
-\r
-uint8_t * USBAudio::stringIinterfaceDesc() {\r
-    static uint8_t stringIinterfaceDescriptor[] = {\r
-        0x0c,                           //bLength\r
-        STRING_DESCRIPTOR,              //bDescriptorType 0x03\r
-        'A',0,'u',0,'d',0,'i',0,'o',0   //bString iInterface - Audio\r
-    };\r
-    return stringIinterfaceDescriptor;\r
-}\r
-\r
-uint8_t * USBAudio::stringIproductDesc() {\r
-    static uint8_t stringIproductDescriptor[] = {\r
-        0x16,                                                       //bLength\r
-        STRING_DESCRIPTOR,                                          //bDescriptorType 0x03\r
-        'M',0,'b',0,'e',0,'d',0,' ',0,'A',0,'u',0,'d',0,'i',0,'o',0 //bString iProduct - Mbed Audio\r
-    };\r
-    return stringIproductDescriptor;\r
-}\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#include "stdint.h"
+#include "USBAudio.h"
+#include "USBBusInterface.h"
+#include "USBAudio_Types.h"
+\r
+\r
+\r
+USBAudio::USBAudio(uint32_t frequency, uint8_t channel_nb, uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release) {
+    mute = 0;
+    volCur = 0x0080;
+    volMin = 0x0000;
+    volMax = 0x0100;
+    volRes = 0x0004;
+    available = false;
+\r
+    FREQ = frequency;
+\r
+    this->channel_nb = channel_nb;
+\r
+    // stereo -> *2, mono -> *1
+    PACKET_SIZE_ISO = (FREQ / 500) * channel_nb;
+\r
+    // STEREO -> left and right
+    channel_config = (channel_nb == 1) ? CHANNEL_M : CHANNEL_L + CHANNEL_R;
+\r
+    SOF_handler = false;
+\r
+    buf_stream = NULL;
+\r
+    // connect the device
+    USBDevice::connect();
+}
+\r
+bool USBAudio::read(uint8_t * buf) {
+    buf_stream = buf;
+    while (!available);
+    available = false;
+    buf_stream = NULL;
+    return true;
+}
+\r
+bool USBAudio::readNB(uint8_t * buf) {
+    buf_stream = buf;
+    SOF_handler = false;
+    while (!SOF_handler);
+    if (available) {
+        available = false;
+        buf_stream = NULL;
+        return true;
+    }
+    buf_stream = NULL;
+    return false;
+}
+\r
+\r
+float USBAudio::getVolume() {
+    return (mute) ? 0.0 : (float)volCur/(float)volMax;
+}
+\r
+\r
+// Called in ISR context on each start of frame
+void USBAudio::SOF(int frameNumber) {
+    uint16_t size = 0;
+\r
+    // read the isochronous endpoint
+    if (buf_stream != NULL) {
+        USBDevice::readEP_NB(EP3OUT, buf_stream, &size, PACKET_SIZE_ISO);
+    }
+\r
+    // if we read something, modify the flag "available"
+    available = (size) ? true : false;
+\r
+    // activate readings on the isochronous
+    readStart(EP3OUT, PACKET_SIZE_ISO);
+\r
+    SOF_handler = true;
+}
+\r
+\r
+// Called in ISR context
+// Set configuration. Return false if the configuration is not supported.
+bool USBAudio::USBCallback_setConfiguration(uint8_t configuration) {
+    if (configuration != DEFAULT_CONFIGURATION) {
+        return false;
+    }
+\r
+    // Configure isochronous endpoint
+    realiseEndpoint(EP3OUT, PACKET_SIZE_ISO, ISOCHRONOUS);
+\r
+    // activate readings on this endpoint
+    readStart(EP3OUT, PACKET_SIZE_ISO);
+    return true;
+}
+\r
+\r
+// Called in ISR context
+// Set alternate setting. Return false if the alternate setting is not supported
+bool USBAudio::USBCallback_setInterface(uint16_t interface, uint8_t alternate) {
+    if (interface == 0 && alternate == 0) {
+        return true;
+    }
+    if (interface == 1 && (alternate == 0 || alternate == 1)) {
+        return true;
+    }
+    return false;
+}
+\r
+\r
+\r
+// Called in ISR context
+// Called by USBDevice on Endpoint0 request
+// This is used to handle extensions to standard requests and class specific requests.
+// Return true if class handles this request
+bool USBAudio::USBCallback_request() {
+    bool success = false;
+    CONTROL_TRANSFER * transfer = getTransferPtr();
+\r
+    // Process class-specific requests
+    if (transfer->setup.bmRequestType.Type == CLASS_TYPE) {
+\r
+        // Feature Unit: Interface = 0, ID = 2
+        if (transfer->setup.wIndex == 0x0200) {
+\r
+            // Master Channel
+            if ((transfer->setup.wValue & 0xff) == 0) {
+\r
+                switch (transfer->setup.wValue >> 8) {
+                    case MUTE_CONTROL:
+                        switch (transfer->setup.bRequest) {
+                            case REQUEST_GET_CUR:
+                                transfer->remaining = 1;
+                                transfer->ptr = &mute;
+                                transfer->direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+\r
+                            case REQUEST_SET_CUR:
+                                transfer->remaining = 1;
+                                transfer->notify = true;
+                                transfer->direction = HOST_TO_DEVICE;
+                                success = true;
+                                break;
+                            default:
+                                break;
+                        }
+                        break;
+                    case VOLUME_CONTROL:
+                        switch (transfer->setup.bRequest) {
+                            case REQUEST_GET_CUR:
+                                transfer->remaining = 2;
+                                transfer->ptr = (uint8_t *)&volCur;
+                                transfer->direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+                            case REQUEST_GET_MIN:
+                                transfer->remaining = 2;
+                                transfer->ptr = (uint8_t *)&volMin;
+                                transfer->direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+                            case REQUEST_GET_MAX:
+                                transfer->remaining = 2;
+                                transfer->ptr = (uint8_t *)&volMax;
+                                transfer->direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+                            case REQUEST_GET_RES:
+                                transfer->remaining = 2;
+                                transfer->ptr = (uint8_t *)&volRes;
+                                transfer->direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+\r
+                            case REQUEST_SET_CUR:
+                                transfer->remaining = 2;
+                                transfer->notify = true;
+                                transfer->direction = HOST_TO_DEVICE;
+                                success = true;
+                                break;
+                            case REQUEST_SET_MIN:
+                                transfer->remaining = 2;
+                                transfer->notify = true;
+                                transfer->direction = HOST_TO_DEVICE;
+                                success = true;
+                                break;
+                            case REQUEST_SET_MAX:
+                                transfer->remaining = 2;
+                                transfer->notify = true;
+                                transfer->direction = HOST_TO_DEVICE;
+                                success = true;
+                                break;
+                            case REQUEST_SET_RES:
+                                transfer->remaining = 2;
+                                transfer->notify = true;
+                                transfer->direction = HOST_TO_DEVICE;
+                                success = true;
+                                break;
+                        }
+                        break;
+                    default:
+                        break;
+                }
+            }
+        }
+    }
+    return success;
+}
+\r
+\r
+// Called in ISR context when a data OUT stage has been performed
+void USBAudio::USBCallback_requestCompleted(uint8_t * buf, uint16_t length) {
+    uint16_t data = *((uint16_t *)buf);
+    CONTROL_TRANSFER * transfer = getTransferPtr();
+    switch (transfer->setup.wValue >> 8) {
+        case MUTE_CONTROL:
+            switch (transfer->setup.bRequest) {
+                case REQUEST_SET_CUR:
+                    mute = data & 0xff;
+                    updateVol.call();
+                    break;
+                default:
+                    break;
+            }
+            break;
+        case VOLUME_CONTROL:
+            switch (transfer->setup.bRequest) {
+                case REQUEST_SET_CUR:
+                    volCur = data;
+                    updateVol.call();
+                    break;
+                default:
+                    break;
+            }
+            break;
+        default:
+            break;
+    }
+}
+\r
+\r
+\r
+#define TOTAL_DESCRIPTOR_LENGTH ((1 * CONFIGURATION_DESCRIPTOR_LENGTH) \
+                               + (3 * INTERFACE_DESCRIPTOR_LENGTH) \
+                               + (1 * CONTROL_INTERFACE_DESCRIPTOR_LENGTH) \
+                               + (1 * INPUT_TERMINAL_DESCRIPTOR_LENGTH) \
+                               + (1 * FEATURE_UNIT_DESCRIPTOR_LENGTH) \
+                               + (1 * OUTPUT_TERMINAL_DESCRIPTOR_LENGTH) \
+                               + (1 * STREAMING_INTERFACE_DESCRIPTOR_LENGTH) \
+                               + (1 * FORMAT_TYPE_I_DESCRIPTOR_LENGTH) \
+                               + (1 * (ENDPOINT_DESCRIPTOR_LENGTH + 2)) \
+                               + (1 * STREAMING_ENDPOINT_DESCRIPTOR_LENGTH) )
+\r
+#define TOTAL_CONTROL_INTF_LENGTH    (CONTROL_INTERFACE_DESCRIPTOR_LENGTH + \
+                                      INPUT_TERMINAL_DESCRIPTOR_LENGTH     + \
+                                      FEATURE_UNIT_DESCRIPTOR_LENGTH    + \
+                                      OUTPUT_TERMINAL_DESCRIPTOR_LENGTH)
+\r
+uint8_t * USBAudio::configurationDesc() {
+    static uint8_t configDescriptor[] = {
+        // Configuration 1
+        CONFIGURATION_DESCRIPTOR_LENGTH,        // bLength
+        CONFIGURATION_DESCRIPTOR,               // bDescriptorType
+        LSB(TOTAL_DESCRIPTOR_LENGTH),           // wTotalLength (LSB)
+        MSB(TOTAL_DESCRIPTOR_LENGTH),           // wTotalLength (MSB)
+        0x02,                                   // bNumInterfaces
+        DEFAULT_CONFIGURATION,                  // bConfigurationValue
+        0x00,                                   // iConfiguration
+        0x80,                                   // bmAttributes
+        50,                                     // bMaxPower
+\r
+        // Interface 0, Alternate Setting 0, Audio Control
+        INTERFACE_DESCRIPTOR_LENGTH,            // bLength
+        INTERFACE_DESCRIPTOR,                   // bDescriptorType
+        0x00,                                   // bInterfaceNumber
+        0x00,                                   // bAlternateSetting
+        0x00,                                   // bNumEndpoints
+        AUDIO_CLASS,                            // bInterfaceClass
+        SUBCLASS_AUDIOCONTROL,                  // bInterfaceSubClass
+        0x00,                                   // bInterfaceProtocol
+        0x00,                                   // iInterface
+\r
+\r
+        // Audio Control Interface
+        CONTROL_INTERFACE_DESCRIPTOR_LENGTH,    // bLength
+        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType
+        CONTROL_HEADER,                         // bDescriptorSubtype
+        LSB(0x0100),                            // bcdADC (LSB)
+        MSB(0x0100),                            // bcdADC (MSB)
+        LSB(TOTAL_CONTROL_INTF_LENGTH),         // wTotalLength
+        MSB(TOTAL_CONTROL_INTF_LENGTH),         // wTotalLength
+        0x01,                                   // bInCollection
+        0x01,                                   // baInterfaceNr
+\r
+        // Audio Input Terminal
+        INPUT_TERMINAL_DESCRIPTOR_LENGTH,       // bLength
+        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType
+        CONTROL_INPUT_TERMINAL,                 // bDescriptorSubtype
+        0x01,                                   // bTerminalID
+        LSB(TERMINAL_USB_STREAMING),            // wTerminalType
+        MSB(TERMINAL_USB_STREAMING),            // wTerminalType
+        0x00,                                   // bAssocTerminal
+        channel_nb,                             // bNrChannels
+        LSB(channel_config),                    // wChannelConfig
+        MSB(channel_config),                    // wChannelConfig
+        0x00,                                   // iChannelNames
+        0x00,                                   // iTerminal
+\r
+        // Audio Feature Unit
+        FEATURE_UNIT_DESCRIPTOR_LENGTH,         // bLength
+        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType
+        CONTROL_FEATURE_UNIT,                   // bDescriptorSubtype
+        0x02,                                   // bUnitID
+        0x01,                                   // bSourceID
+        0x01,                                   // bControlSize
+        CONTROL_MUTE |
+        CONTROL_VOLUME,                         // bmaControls(0)
+        0x00,                                   // bmaControls(1)
+        0x00,                                   // iTerminal
+\r
+        // Audio Output Terminal
+        OUTPUT_TERMINAL_DESCRIPTOR_LENGTH,      // bLength
+        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType
+        CONTROL_OUTPUT_TERMINAL,                // bDescriptorSubtype
+        0x03,                                   // bTerminalID
+        LSB(TERMINAL_SPEAKER),                  // wTerminalType
+        MSB(TERMINAL_SPEAKER),                  // wTerminalType
+        0x00,                                   // bAssocTerminal
+        0x02,                                   // bSourceID
+        0x00,                                   // iTerminal
+\r
+\r
+        // Interface 1, Alternate Setting 0, Audio Streaming - Zero Bandwith
+        INTERFACE_DESCRIPTOR_LENGTH,            // bLength
+        INTERFACE_DESCRIPTOR,                   // bDescriptorType
+        0x01,                                   // bInterfaceNumber
+        0x00,                                   // bAlternateSetting
+        0x00,                                   // bNumEndpoints
+        AUDIO_CLASS,                            // bInterfaceClass
+        SUBCLASS_AUDIOSTREAMING,                // bInterfaceSubClass
+        0x00,                                   // bInterfaceProtocol
+        0x00,                                   // iInterface
+\r
+        // Interface 1, Alternate Setting 1, Audio Streaming - Operational
+        INTERFACE_DESCRIPTOR_LENGTH,            // bLength
+        INTERFACE_DESCRIPTOR,                   // bDescriptorType
+        0x01,                                   // bInterfaceNumber
+        0x01,                                   // bAlternateSetting
+        0x01,                                   // bNumEndpoints
+        AUDIO_CLASS,                            // bInterfaceClass
+        SUBCLASS_AUDIOSTREAMING,                // bInterfaceSubClass
+        0x00,                                   // bInterfaceProtocol
+        0x00,                                   // iInterface
+\r
+        // Audio Streaming Interface
+        STREAMING_INTERFACE_DESCRIPTOR_LENGTH,  // bLength
+        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType
+        STREAMING_GENERAL,                      // bDescriptorSubtype
+        0x01,                                   // bTerminalLink
+        0x00,                                   // bDelay
+        LSB(FORMAT_PCM),                        // wFormatTag
+        MSB(FORMAT_PCM),                        // wFormatTag
+\r
+        // Audio Type I Format
+        FORMAT_TYPE_I_DESCRIPTOR_LENGTH,        // bLength
+        INTERFACE_DESCRIPTOR_TYPE,              // bDescriptorType
+        STREAMING_FORMAT_TYPE,                  // bDescriptorSubtype
+        FORMAT_TYPE_I,                          // bFormatType
+        channel_nb,                             // bNrChannels
+        0x02,                                   // bSubFrameSize
+        16,                                     // bBitResolution
+        0x01,                                   // bSamFreqType
+        LSB(FREQ),                              // tSamFreq
+        ((uint8_t) ((FREQ >> 8) & 0xff)),       // tSamFreq
+        ((uint8_t) ((FREQ >> 16) & 0xff)),      // tSamFreq
+\r
+        // Endpoint - Standard Descriptor
+        ENDPOINT_DESCRIPTOR_LENGTH + 2,         // bLength
+        ENDPOINT_DESCRIPTOR,                    // bDescriptorType
+        PHY_TO_DESC(EPISO_OUT),                 // bEndpointAddress
+        E_ISOCHRONOUS,                          // bmAttributes
+        LSB(PACKET_SIZE_ISO),                   // wMaxPacketSize
+        MSB(PACKET_SIZE_ISO),                   // wMaxPacketSize
+        0x01,                                   // bInterval
+        0x00,                                   // bRefresh
+        0x00,                                   // bSynchAddress
+\r
+        // Endpoint - Audio Streaming
+        STREAMING_ENDPOINT_DESCRIPTOR_LENGTH,   // bLength
+        ENDPOINT_DESCRIPTOR_TYPE,               // bDescriptorType
+        ENDPOINT_GENERAL,                       // bDescriptor
+        0x00,                                   // bmAttributes
+        0x00,                                   // bLockDelayUnits
+        LSB(0x0000),                            // wLockDelay
+        MSB(0x0000),                            // wLockDelay
+\r
+        // Terminator
+        0                                       // bLength
+    };
+    return configDescriptor;
+}
+\r
+uint8_t * USBAudio::stringIinterfaceDesc() {
+    static uint8_t stringIinterfaceDescriptor[] = {
+        0x0c,                           //bLength
+        STRING_DESCRIPTOR,              //bDescriptorType 0x03
+        'A',0,'u',0,'d',0,'i',0,'o',0   //bString iInterface - Audio
+    };
+    return stringIinterfaceDescriptor;
+}
+\r
+uint8_t * USBAudio::stringIproductDesc() {
+    static uint8_t stringIproductDescriptor[] = {
+        0x16,                                                       //bLength
+        STRING_DESCRIPTOR,                                          //bDescriptorType 0x03
+        'M',0,'b',0,'e',0,'d',0,' ',0,'A',0,'u',0,'d',0,'i',0,'o',0 //bString iProduct - Mbed Audio
+    };
+    return stringIproductDescriptor;
+}
index b923ffb..6e357ec 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#ifndef USBAudio_H\r
-#define USBAudio_H\r
-\r
-/* These headers are included for child class. */\r
-#include "USBEndpoints.h"\r
-#include "USBDescriptor.h"\r
-#include "USBDevice_Types.h"\r
-\r
-#include "USBDevice.h"\r
-\r
-\r
-/**\r
-* USBAudio example\r
-*\r
-* #include "mbed.h"\r
-* #include "USBAudio.h"\r
-*\r
-* Serial pc(USBTX, USBRX);\r
-*\r
-* // frequency: 48 kHz\r
-* #define FREQ 48000\r
-*\r
-* // 1 channel: mono\r
-* #define NB_CHA 1\r
-*\r
-* // length of an audio packet: each ms, we receive 48 * 16bits ->48 * 2 bytes. as there is one channel, the length will be 48 * 2 * 1\r
-* #define AUDIO_LENGTH_PACKET 48 * 2 * 1\r
-*\r
-* // USBAudio\r
-* USBAudio audio(FREQ, NB_CHA);\r
-*\r
-* int main() {\r
-*    int16_t buf[AUDIO_LENGTH_PACKET/2];\r
-*    \r
-*    while (1) {\r
-*        // read an audio packet\r
-*        audio.read((uint8_t *)buf);\r
-*\r
-*\r
-*        // print packet received\r
-*        pc.printf("recv: ");\r
-*        for(int i = 0; i < AUDIO_LENGTH_PACKET/2; i++) {\r
-*            pc.printf("%d ", buf[i]);\r
-*        }\r
-*        pc.printf("\r\n");\r
-*    }\r
-* }\r
-* @endcode\r
-*/\r
-class USBAudio: public USBDevice {\r
-public:\r
-\r
-    /**\r
-    * Constructor\r
-    *\r
-    * @param frequency frequency in Hz (default: 48000)\r
-    * @param channel_nb channel number (1 or 2) (default: 1)\r
-    * @param vendor_id Your vendor_id\r
-    * @param product_id Your product_id\r
-    * @param product_release Your preoduct_release\r
-    */\r
-    USBAudio(uint32_t frequency = 48000, uint8_t channel_nb = 1, uint16_t vendor_id = 0x7bb8, uint16_t product_id = 0x1111, uint16_t product_release = 0x0100);\r
-\r
-    /**\r
-    * Get current volume between 0.0 and 1.0\r
-    *\r
-    * @returns volume\r
-    */\r
-    float getVolume();\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#ifndef USBAudio_H
+#define USBAudio_H
+\r
+/* These headers are included for child class. */
+#include "USBEndpoints.h"
+#include "USBDescriptor.h"
+#include "USBDevice_Types.h"
+\r
+#include "USBDevice.h"
+\r
+\r
+/**
+* USBAudio example
+*
+* #include "mbed.h"
+* #include "USBAudio.h"
+*
+* Serial pc(USBTX, USBRX);
+*
+* // frequency: 48 kHz
+* #define FREQ 48000
+*
+* // 1 channel: mono
+* #define NB_CHA 1
+*
+* // length of an audio packet: each ms, we receive 48 * 16bits ->48 * 2 bytes. as there is one channel, the length will be 48 * 2 * 1
+* #define AUDIO_LENGTH_PACKET 48 * 2 * 1
+*
+* // USBAudio
+* USBAudio audio(FREQ, NB_CHA);
+*
+* int main() {
+*    int16_t buf[AUDIO_LENGTH_PACKET/2];
+*
+*    while (1) {
+*        // read an audio packet
+*        audio.read((uint8_t *)buf);
+*
+*
+*        // print packet received
+*        pc.printf("recv: ");
+*        for(int i = 0; i < AUDIO_LENGTH_PACKET/2; i++) {
+*            pc.printf("%d ", buf[i]);
+*        }
+*        pc.printf("\r\n");
+*    }
+* }
+* @endcode
+*/
+class USBAudio: public USBDevice {
+public:
+\r
+    /**
+    * Constructor
+    *
+    * @param frequency frequency in Hz (default: 48000)
+    * @param channel_nb channel number (1 or 2) (default: 1)
+    * @param vendor_id Your vendor_id
+    * @param product_id Your product_id
+    * @param product_release Your preoduct_release
+    */
+    USBAudio(uint32_t frequency = 48000, uint8_t channel_nb = 1, uint16_t vendor_id = 0x7bb8, uint16_t product_id = 0x1111, uint16_t product_release = 0x0100);
+\r
+    /**
+    * Get current volume between 0.0 and 1.0
+    *
+    * @returns volume
+    */
+    float getVolume();
     \r
-    /**\r
-    * Read an audio packet. warning: blocking\r
-    *\r
-    * @param buf pointer on a buffer which will be filled with an audio packet\r
-    *\r
-    * @returns true if successfull\r
-    */\r
-    bool read(uint8_t * buf);\r
+    /**
+    * Read an audio packet. warning: blocking
+    *
+    * @param buf pointer on a buffer which will be filled with an audio packet
+    *
+    * @returns true if successfull
+    */
+    bool read(uint8_t * buf);
     \r
-    /**\r
-    * Try to read an audio packet. warning: non blocking\r
-    *\r
-    * @param buf pointer on a buffer which will be filled if an audio packet is available\r
-    *\r
-    * @returns true if successfull\r
-    */\r
-    bool readNB(uint8_t * buf);\r
+    /**
+    * Try to read an audio packet. warning: non blocking
+    *
+    * @param buf pointer on a buffer which will be filled if an audio packet is available
+    *
+    * @returns true if successfull
+    */
+    bool readNB(uint8_t * buf);
     \r
 \r
-    /** attach a handler to update the volume\r
-     *\r
-     * @param function Function to attach\r
-     *\r
-     */\r
-    void attach(void(*fptr)(void)) {\r
-        updateVol.attach(fptr);\r
-    }\r
-\r
-    /** Attach a nonstatic void/void member function to update the volume\r
-     *\r
-     * @param tptr Object pointer\r
-     * @param mptr Member function pointer\r
-     *\r
-     */\r
-    template<typename T>\r
-    void attach(T *tptr, void(T::*mptr)(void)) {\r
-        updateVol.attach(tptr, mptr);\r
-    }\r
-\r
-\r
-protected:\r
-\r
-    /*\r
-    * Called by USBDevice layer. Set configuration of the device.\r
-    * For instance, you can add all endpoints that you need on this function.\r
-    *\r
-    * @param configuration Number of the configuration\r
-    * @returns true if class handles this request\r
-    */\r
-    virtual bool USBCallback_setConfiguration(uint8_t configuration);\r
-\r
-    /*\r
-    * Called by USBDevice on Endpoint0 request. Warning: Called in ISR context\r
-    * This is used to handle extensions to standard requests\r
-    * and class specific requests\r
-    *\r
-    * @returns true if class handles this request\r
-    */\r
-    virtual bool USBCallback_request();\r
-\r
-    /*\r
-    * Get string product descriptor\r
-    *\r
-    * @returns pointer to the string product descriptor\r
-    */\r
-    virtual uint8_t * stringIproductDesc();\r
-\r
-    /*\r
-    * Get string interface descriptor\r
-    *\r
-    * @returns pointer to the string interface descriptor\r
-    */\r
-    virtual uint8_t * stringIinterfaceDesc();\r
-\r
-    /*\r
-    * Get configuration descriptor\r
-    *\r
-    * @returns pointer to the configuration descriptor\r
-    */\r
-    virtual uint8_t * configurationDesc();\r
-\r
-    /*\r
-     * Called by USBDevice layer. Set interface/alternate of the device.\r
-     *\r
-     * @param interface Number of the interface to be configured\r
-     * @param alternate Number of the alternate to be configured\r
-     * @returns true if class handles this request\r
-     */\r
-    virtual bool USBCallback_setInterface(uint16_t interface, uint8_t alternate);\r
-\r
-    /*\r
-    * Called by USBDevice on Endpoint0 request completion\r
-    * if the 'notify' flag has been set to true. Warning: Called in ISR context\r
-    *\r
-    * In this case it is used to indicate that a HID report has\r
-    * been received from the host on endpoint 0\r
-    *\r
-    * @param buf buffer received on endpoint 0\r
-    * @param length length of this buffer\r
-    */\r
-    virtual void USBCallback_requestCompleted(uint8_t * buf, uint16_t length);\r
-\r
-    /*\r
-    * Callback called on each Start of Frame event\r
-    */\r
-    virtual void SOF(int frameNumber);\r
-\r
-private:\r
-\r
-    // stream available ?\r
-    volatile bool available;\r
-\r
-    // FREQ\r
-    uint32_t FREQ;\r
-\r
-    // size of the maximum packet for the isochronous endpoint\r
-    uint32_t PACKET_SIZE_ISO;\r
-\r
-    // mono, stereo,...\r
-    uint8_t channel_nb;\r
+    /** attach a handler to update the volume
+     *
+     * @param function Function to attach
+     *
+     */
+    void attach(void(*fptr)(void)) {
+        updateVol.attach(fptr);
+    }
+\r
+    /** Attach a nonstatic void/void member function to update the volume
+     *
+     * @param tptr Object pointer
+     * @param mptr Member function pointer
+     *
+     */
+    template<typename T>
+    void attach(T *tptr, void(T::*mptr)(void)) {
+        updateVol.attach(tptr, mptr);
+    }
+\r
+\r
+protected:
+\r
+    /*
+    * Called by USBDevice layer. Set configuration of the device.
+    * For instance, you can add all endpoints that you need on this function.
+    *
+    * @param configuration Number of the configuration
+    * @returns true if class handles this request
+    */
+    virtual bool USBCallback_setConfiguration(uint8_t configuration);
+\r
+    /*
+    * Called by USBDevice on Endpoint0 request. Warning: Called in ISR context
+    * This is used to handle extensions to standard requests
+    * and class specific requests
+    *
+    * @returns true if class handles this request
+    */
+    virtual bool USBCallback_request();
+\r
+    /*
+    * Get string product descriptor
+    *
+    * @returns pointer to the string product descriptor
+    */
+    virtual uint8_t * stringIproductDesc();
+\r
+    /*
+    * Get string interface descriptor
+    *
+    * @returns pointer to the string interface descriptor
+    */
+    virtual uint8_t * stringIinterfaceDesc();
+\r
+    /*
+    * Get configuration descriptor
+    *
+    * @returns pointer to the configuration descriptor
+    */
+    virtual uint8_t * configurationDesc();
+\r
+    /*
+     * Called by USBDevice layer. Set interface/alternate of the device.
+     *
+     * @param interface Number of the interface to be configured
+     * @param alternate Number of the alternate to be configured
+     * @returns true if class handles this request
+     */
+    virtual bool USBCallback_setInterface(uint16_t interface, uint8_t alternate);
+\r
+    /*
+    * Called by USBDevice on Endpoint0 request completion
+    * if the 'notify' flag has been set to true. Warning: Called in ISR context
+    *
+    * In this case it is used to indicate that a HID report has
+    * been received from the host on endpoint 0
+    *
+    * @param buf buffer received on endpoint 0
+    * @param length length of this buffer
+    */
+    virtual void USBCallback_requestCompleted(uint8_t * buf, uint16_t length);
+\r
+    /*
+    * Callback called on each Start of Frame event
+    */
+    virtual void SOF(int frameNumber);
+\r
+private:
+\r
+    // stream available ?
+    volatile bool available;
+\r
+    // FREQ
+    uint32_t FREQ;
+\r
+    // size of the maximum packet for the isochronous endpoint
+    uint32_t PACKET_SIZE_ISO;
+\r
+    // mono, stereo,...
+    uint8_t channel_nb;
     \r
-    // channel config: master, left, right\r
-    uint8_t channel_config;\r
+    // channel config: master, left, right
+    uint8_t channel_config;
 \r
-    // mute state\r
-    uint8_t mute;\r
+    // mute state
+    uint8_t mute;
 \r
-    // Volume Current Value\r
-    uint16_t volCur;\r
+    // Volume Current Value
+    uint16_t volCur;
 \r
-    // Volume Minimum Value\r
-    uint16_t volMin;\r
+    // Volume Minimum Value
+    uint16_t volMin;
 \r
-    // Volume Maximum Value\r
-    uint16_t volMax;\r
+    // Volume Maximum Value
+    uint16_t volMax;
 \r
-    // Volume Resolution\r
-    uint16_t volRes;\r
+    // Volume Resolution
+    uint16_t volRes;
 \r
-    // Buffer containing one audio packet\r
-    uint8_t * buf_stream;\r
+    // Buffer containing one audio packet
+    uint8_t * buf_stream;
     \r
-    // callback to update volume\r
-    FunctionPointer updateVol;\r
+    // callback to update volume
+    FunctionPointer updateVol;
     \r
-    // boolean showing that the SOF handler has been called. Useful for readNB.\r
-    volatile bool SOF_handler;\r
+    // boolean showing that the SOF handler has been called. Useful for readNB.
+    volatile bool SOF_handler;
 \r
-};\r
+};
 \r
-#endif\r
+#endif
index c7f7058..453519c 100644 (file)
@@ -1,94 +1,94 @@
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#ifndef USBAUDIO_TYPES_H\r
-#define USBAUDIO_TYPES_H\r
-\r
-\r
-#define DEFAULT_CONFIGURATION (1)\r
-\r
-// Audio Request Codes\r
-#define REQUEST_SET_CUR     0x01\r
-#define REQUEST_GET_CUR     0x81\r
-#define REQUEST_SET_MIN     0x02\r
-#define REQUEST_GET_MIN     0x82\r
-#define REQUEST_SET_MAX     0x03\r
-#define REQUEST_GET_MAX     0x83\r
-#define REQUEST_SET_RES     0x04\r
-#define REQUEST_GET_RES     0x84\r
-\r
-#define MUTE_CONTROL        0x01\r
-#define VOLUME_CONTROL      0x02\r
-\r
-\r
-// Audio Descriptor Sizes\r
-#define CONTROL_INTERFACE_DESCRIPTOR_LENGTH       0x09\r
-#define STREAMING_INTERFACE_DESCRIPTOR_LENGTH     0x07\r
-#define INPUT_TERMINAL_DESCRIPTOR_LENGTH          0x0C\r
-#define OUTPUT_TERMINAL_DESCRIPTOR_LENGTH         0x09\r
-#define FEATURE_UNIT_DESCRIPTOR_LENGTH            0x09\r
-#define STREAMING_ENDPOINT_DESCRIPTOR_LENGTH      0x07\r
-\r
-// Audio Format Type Descriptor Sizes\r
-#define FORMAT_TYPE_I_DESCRIPTOR_LENGTH   0x0b\r
-\r
-#define AUDIO_CLASS                       0x01\r
-#define SUBCLASS_AUDIOCONTROL             0x01\r
-#define SUBCLASS_AUDIOSTREAMING           0x02\r
-\r
-// Audio Descriptor Types\r
-#define INTERFACE_DESCRIPTOR_TYPE         0x24\r
-#define ENDPOINT_DESCRIPTOR_TYPE          0x25\r
-\r
-// Audio Control Interface Descriptor Subtypes\r
-#define CONTROL_HEADER                    0x01\r
-#define CONTROL_INPUT_TERMINAL            0x02\r
-#define CONTROL_OUTPUT_TERMINAL           0x03\r
-#define CONTROL_FEATURE_UNIT              0x06\r
-\r
-// USB Terminal Types\r
-#define TERMINAL_USB_STREAMING            0x0101\r
-\r
-// Predefined Audio Channel Configuration Bits\r
-// Mono\r
-#define CHANNEL_M                         0x0000\r
-#define CHANNEL_L                         0x0001  /* Left Front */\r
-#define CHANNEL_R                         0x0002  /* Right Front */\r
-\r
-// Feature Unit Control Bits\r
-#define CONTROL_MUTE                      0x0001\r
-#define CONTROL_VOLUME                    0x0002\r
-\r
-// Output Terminal Types\r
-#define TERMINAL_SPEAKER                  0x0301\r
-#define TERMINAL_HEADPHONES               0x0302\r
-\r
-// Audio Streaming Interface Descriptor Subtypes\r
-#define STREAMING_GENERAL                 0x01\r
-#define STREAMING_FORMAT_TYPE             0x02\r
-\r
-// Audio Data Format Type I Codes\r
-#define FORMAT_PCM                        0x0001\r
-\r
-// Audio Format Types\r
-#define FORMAT_TYPE_I                     0x01\r
-\r
-// Audio Endpoint Descriptor Subtypes\r
-#define ENDPOINT_GENERAL                  0x01\r
-\r
-#endif\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#ifndef USBAUDIO_TYPES_H
+#define USBAUDIO_TYPES_H
+\r
+\r
+#define DEFAULT_CONFIGURATION (1)
+\r
+// Audio Request Codes
+#define REQUEST_SET_CUR     0x01
+#define REQUEST_GET_CUR     0x81
+#define REQUEST_SET_MIN     0x02
+#define REQUEST_GET_MIN     0x82
+#define REQUEST_SET_MAX     0x03
+#define REQUEST_GET_MAX     0x83
+#define REQUEST_SET_RES     0x04
+#define REQUEST_GET_RES     0x84
+\r
+#define MUTE_CONTROL        0x01
+#define VOLUME_CONTROL      0x02
+\r
+\r
+// Audio Descriptor Sizes
+#define CONTROL_INTERFACE_DESCRIPTOR_LENGTH       0x09
+#define STREAMING_INTERFACE_DESCRIPTOR_LENGTH     0x07
+#define INPUT_TERMINAL_DESCRIPTOR_LENGTH          0x0C
+#define OUTPUT_TERMINAL_DESCRIPTOR_LENGTH         0x09
+#define FEATURE_UNIT_DESCRIPTOR_LENGTH            0x09
+#define STREAMING_ENDPOINT_DESCRIPTOR_LENGTH      0x07
+\r
+// Audio Format Type Descriptor Sizes
+#define FORMAT_TYPE_I_DESCRIPTOR_LENGTH   0x0b
+\r
+#define AUDIO_CLASS                       0x01
+#define SUBCLASS_AUDIOCONTROL             0x01
+#define SUBCLASS_AUDIOSTREAMING           0x02
+\r
+// Audio Descriptor Types
+#define INTERFACE_DESCRIPTOR_TYPE         0x24
+#define ENDPOINT_DESCRIPTOR_TYPE          0x25
+\r
+// Audio Control Interface Descriptor Subtypes
+#define CONTROL_HEADER                    0x01
+#define CONTROL_INPUT_TERMINAL            0x02
+#define CONTROL_OUTPUT_TERMINAL           0x03
+#define CONTROL_FEATURE_UNIT              0x06
+\r
+// USB Terminal Types
+#define TERMINAL_USB_STREAMING            0x0101
+\r
+// Predefined Audio Channel Configuration Bits
+// Mono
+#define CHANNEL_M                         0x0000
+#define CHANNEL_L                         0x0001  /* Left Front */
+#define CHANNEL_R                         0x0002  /* Right Front */
+\r
+// Feature Unit Control Bits
+#define CONTROL_MUTE                      0x0001
+#define CONTROL_VOLUME                    0x0002
+\r
+// Output Terminal Types
+#define TERMINAL_SPEAKER                  0x0301
+#define TERMINAL_HEADPHONES               0x0302
+\r
+// Audio Streaming Interface Descriptor Subtypes
+#define STREAMING_GENERAL                 0x01
+#define STREAMING_FORMAT_TYPE             0x02
+\r
+// Audio Data Format Type I Codes
+#define FORMAT_PCM                        0x0001
+\r
+// Audio Format Types
+#define FORMAT_TYPE_I                     0x01
+\r
+// Audio Endpoint Descriptor Subtypes
+#define ENDPOINT_GENERAL                  0x01
+\r
+#endif
index 57d63f8..a3a6d9a 100644 (file)
@@ -1,66 +1,66 @@
-/* USBBusInterface.h */\r
-/* USB Bus Interface */\r
-/* Copyright (c) 2011 ARM Limited. All rights reserved. */\r
+/* USBBusInterface.h */
+/* USB Bus Interface */
+/* Copyright (c) 2011 ARM Limited. All rights reserved. */
 \r
-#ifndef USBBUSINTERFACE_H\r
-#define USBBUSINTERFACE_H\r
+#ifndef USBBUSINTERFACE_H
+#define USBBUSINTERFACE_H
 \r
-#include "mbed.h"\r
-#include "USBEndpoints.h"\r
+#include "mbed.h"
+#include "USBEndpoints.h"
 \r
-class USBHAL {\r
-public:\r
-    /* Configuration */\r
-    USBHAL();\r
-    ~USBHAL();\r
-    void connect(void);\r
-    void disconnect(void);\r
-    void configureDevice(void);\r
-    void unconfigureDevice(void);\r
-    void setAddress(uint8_t address);\r
-    void remoteWakeup(void);\r
+class USBHAL {
+public:
+    /* Configuration */
+    USBHAL();
+    ~USBHAL();
+    void connect(void);
+    void disconnect(void);
+    void configureDevice(void);
+    void unconfigureDevice(void);
+    void setAddress(uint8_t address);
+    void remoteWakeup(void);
 \r
-    /* Endpoint 0 */\r
-    void EP0setup(uint8_t *buffer);\r
-    void EP0read(void);\r
-    uint32_t EP0getReadResult(uint8_t *buffer);\r
-    void EP0write(uint8_t *buffer, uint32_t size);\r
-    void EP0getWriteResult(void);\r
-    void EP0stall(void);\r
+    /* Endpoint 0 */
+    void EP0setup(uint8_t *buffer);
+    void EP0read(void);
+    uint32_t EP0getReadResult(uint8_t *buffer);
+    void EP0write(uint8_t *buffer, uint32_t size);
+    void EP0getWriteResult(void);
+    void EP0stall(void);
 \r
-    /* Other endpoints */\r
-    EP_STATUS endpointRead(uint8_t endpoint, uint32_t maximumSize);\r
-    EP_STATUS endpointReadResult(uint8_t endpoint, uint8_t *data, uint32_t *bytesRead);\r
-    EP_STATUS endpointWrite(uint8_t endpoint, uint8_t *data, uint32_t size);\r
-    EP_STATUS endpointWriteResult(uint8_t endpoint);\r
-    void stallEndpoint(uint8_t endpoint);\r
-    void unstallEndpoint(uint8_t endpoint);\r
-    bool realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, uint32_t options);\r
-    bool getEndpointStallState(unsigned char endpoint);\r
-    uint32_t endpointReadcore(uint8_t endpoint, uint8_t *buffer);\r
+    /* Other endpoints */
+    EP_STATUS endpointRead(uint8_t endpoint, uint32_t maximumSize);
+    EP_STATUS endpointReadResult(uint8_t endpoint, uint8_t *data, uint32_t *bytesRead);
+    EP_STATUS endpointWrite(uint8_t endpoint, uint8_t *data, uint32_t size);
+    EP_STATUS endpointWriteResult(uint8_t endpoint);
+    void stallEndpoint(uint8_t endpoint);
+    void unstallEndpoint(uint8_t endpoint);
+    bool realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, uint32_t options);
+    bool getEndpointStallState(unsigned char endpoint);
+    uint32_t endpointReadcore(uint8_t endpoint, uint8_t *buffer);
     \r
-protected:\r
-    virtual void busReset(void){};\r
-    virtual void EP0setupCallback(void){};\r
-    virtual void EP0out(void){};\r
-    virtual void EP0in(void){};\r
-    virtual void connectStateChanged(unsigned int connected){};\r
-    virtual void suspendStateChanged(unsigned int suspended){};\r
-    virtual void SOF(int frameNumber){};\r
-    virtual bool EP1_OUT_callback(){return false;};\r
-    virtual bool EP1_IN_callback(){return false;};\r
-    virtual bool EP2_OUT_callback(){return false;};\r
-    virtual bool EP2_IN_callback(){return false;};\r
-    virtual bool EP3_OUT_callback(){return false;};\r
-    virtual bool EP3_IN_callback(){return false;};\r
-    virtual bool EP5_OUT_callback(){return false;};\r
-    virtual bool EP5_IN_callback(){return false;};\r
+protected:
+    virtual void busReset(void){};
+    virtual void EP0setupCallback(void){};
+    virtual void EP0out(void){};
+    virtual void EP0in(void){};
+    virtual void connectStateChanged(unsigned int connected){};
+    virtual void suspendStateChanged(unsigned int suspended){};
+    virtual void SOF(int frameNumber){};
+    virtual bool EP1_OUT_callback(){return false;};
+    virtual bool EP1_IN_callback(){return false;};
+    virtual bool EP2_OUT_callback(){return false;};
+    virtual bool EP2_IN_callback(){return false;};
+    virtual bool EP3_OUT_callback(){return false;};
+    virtual bool EP3_IN_callback(){return false;};
+    virtual bool EP5_OUT_callback(){return false;};
+    virtual bool EP5_IN_callback(){return false;};
     \r
-private:\r
-    void usbisr(void);\r
-    static void _usbisr(void);\r
-    static USBHAL * instance;\r
-};\r
-#endif\r
+private:
+    void usbisr(void);
+    static void _usbisr(void);
+    static USBHAL * instance;
+};
+#endif
 \r
 \r
index 6b07528..835110d 100644 (file)
-// USBBusInterface_LPC11U.c\r
-// USB Bus Interface for NXP LPC11Uxx\r
-// Copyright (c) 2011 ARM Limited. All rights reserved.\r
-\r
-// Reference:\r
-// NXP UM10462 LPC11U1x User manual Rev. 1 &#65533; 14 April 2011\r
+// USBBusInterface_LPC11U.c
+// USB Bus Interface for NXP LPC11Uxx
+// Copyright (c) 2011 ARM Limited. All rights reserved.
+\r
+// Reference:
+// NXP UM10462 LPC11U1x User manual Rev. 1 &#65533; 14 April 2011
 \r
-#ifdef TARGET_LPC11U24\r
+#ifdef TARGET_LPC11U24
 \r
-#include "USBBusInterface.h"\r
+#include "USBBusInterface.h"
 \r
-USBHAL * USBHAL::instance;\r
-\r
-\r
-// Valid physical endpoint numbers are 0 to (NUMBER_OF_PHYSICAL_ENDPOINTS-1)\r
-#define LAST_PHYSICAL_ENDPOINT (NUMBER_OF_PHYSICAL_ENDPOINTS-1)\r
-\r
-// Convert physical endpoint number to register bit\r
-#define EP(endpoint) (1UL<<endpoint)\r
-\r
-// Convert physical to logical\r
-#define PHY_TO_LOG(endpoint)    ((endpoint)>>1)\r
+USBHAL * USBHAL::instance;
+\r
+\r
+// Valid physical endpoint numbers are 0 to (NUMBER_OF_PHYSICAL_ENDPOINTS-1)
+#define LAST_PHYSICAL_ENDPOINT (NUMBER_OF_PHYSICAL_ENDPOINTS-1)
+\r
+// Convert physical endpoint number to register bit
+#define EP(endpoint) (1UL<<endpoint)
+\r
+// Convert physical to logical
+#define PHY_TO_LOG(endpoint)    ((endpoint)>>1)
 \r
-// Get endpoint direction\r
-#define IN_EP(endpoint)     ((endpoint) & 1U ? true : false)\r
-#define OUT_EP(endpoint)    ((endpoint) & 1U ? false : true)\r
+// Get endpoint direction
+#define IN_EP(endpoint)     ((endpoint) & 1U ? true : false)
+#define OUT_EP(endpoint)    ((endpoint) & 1U ? false : true)
 \r
-// USB RAM\r
-#define USB_RAM_START (0x20004000)\r
-#define USB_RAM_SIZE  (0x00000800)\r
+// USB RAM
+#define USB_RAM_START (0x20004000)
+#define USB_RAM_SIZE  (0x00000800)
 \r
-// SYSAHBCLKCTRL\r
-#define CLK_USB     (1UL<<14)\r
-#define CLK_USBRAM  (1UL<<27)\r
+// SYSAHBCLKCTRL
+#define CLK_USB     (1UL<<14)
+#define CLK_USBRAM  (1UL<<27)
 \r
-// USB Information register\r
-#define FRAME_NR(a)     ((a) & 0x7ff)   // Frame number\r
+// USB Information register
+#define FRAME_NR(a)     ((a) & 0x7ff)   // Frame number
 \r
-// USB Device Command/Status register\r
-#define DEV_ADDR_MASK   (0x7f)          // Device address\r
-#define DEV_ADDR(a)     ((a) & DEV_ADDR_MASK)\r
-#define DEV_EN          (1UL<<7)        // Device enable\r
-#define SETUP           (1UL<<8)        // SETUP token received\r
-#define PLL_ON          (1UL<<9)        // PLL enabled in suspend\r
-#define DCON            (1UL<<16)       // Device status - connect\r
-#define DSUS            (1UL<<17)       // Device status - suspend\r
-#define DCON_C          (1UL<<24)       // Connect change\r
-#define DSUS_C          (1UL<<25)       // Suspend change\r
-#define DRES_C          (1UL<<26)       // Reset change\r
-#define VBUSDEBOUNCED   (1UL<<28)       // Vbus detected\r
-\r
-// Endpoint Command/Status list\r
-#define CMDSTS_A                 (1UL<<31)          // Active\r
-#define CMDSTS_D                 (1UL<<30)          // Disable\r
-#define CMDSTS_S                 (1UL<<29)          // Stall\r
-#define CMDSTS_TR                (1UL<<28)          // Toggle Reset\r
-#define CMDSTS_RF                (1UL<<27)          // Rate Feedback mode\r
-#define CMDSTS_TV                (1UL<<27)          // Toggle Value\r
-#define CMDSTS_T                 (1UL<<26)          // Endpoint Type\r
-#define CMDSTS_NBYTES(n)         (((n)&0x3ff)<<16)  // Number of bytes\r
-#define CMDSTS_ADDRESS_OFFSET(a) (((a)>>6)&0xffff)  // Buffer start address\r
-\r
-#define BYTES_REMAINING(s)       (((s)>>16)&0x3ff)  // Bytes remaining after transfer\r
-\r
-// USB Non-endpoint interrupt sources\r
-#define FRAME_INT   (1UL<<30)\r
-#define DEV_INT     (1UL<<31)\r
-\r
-static volatile int epComplete = 0;\r
-\r
-// One entry for a double-buffered logical endpoint in the endpoint\r
-// command/status list. Endpoint 0 is single buffered, out[1] is used\r
-// for the SETUP packet and in[1] is not used\r
-typedef __packed struct {\r
-    uint32_t out[2];\r
-    uint32_t in[2];\r
-} EP_COMMAND_STATUS;\r
-\r
-typedef __packed struct {\r
-    uint8_t out[MAX_PACKET_SIZE_EP0];\r
-    uint8_t in[MAX_PACKET_SIZE_EP0];\r
-    uint8_t setup[SETUP_PACKET_SIZE];\r
-} CONTROL_TRANSFER;\r
-\r
-typedef __packed struct {\r
-    uint32_t    maxPacket;\r
-    uint32_t    buffer[2];\r
-    uint32_t    options;\r
-} EP_STATE;\r
-\r
-static volatile EP_STATE endpointState[NUMBER_OF_PHYSICAL_ENDPOINTS];\r
-\r
-// Pointer to the endpoint command/status list\r
-static EP_COMMAND_STATUS *ep = NULL;\r
-\r
-// Pointer to endpoint 0 data (IN/OUT and SETUP)\r
-static CONTROL_TRANSFER *ct = NULL;\r
-\r
-// Shadow DEVCMDSTAT register to avoid accidentally clearing flags or\r
-// initiating a remote wakeup event.\r
-static volatile uint32_t devCmdStat;\r
-\r
-// Pointers used to allocate USB RAM\r
-static uint32_t usbRamPtr = USB_RAM_START;\r
-static uint32_t epRamPtr = 0; // Buffers for endpoints > 0 start here\r
-\r
-#define ROUND_UP_TO_MULTIPLE(x, m) ((((x)+((m)-1))/(m))*(m))\r
-\r
-void USBMemCopy(uint8_t *dst, uint8_t *src, uint32_t size);\r
-void USBMemCopy(uint8_t *dst, uint8_t *src, uint32_t size) {\r
-    if (size > 0) {\r
-        do {\r
-            *dst++ = *src++;\r
-        } while (--size > 0);\r
-    }\r
-}\r
-\r
-\r
-USBHAL::USBHAL(void) {\r
-    NVIC_DisableIRQ(USB_IRQn);\r
-\r
-    // nUSB_CONNECT output\r
-    LPC_IOCON->PIO0_6 = 0x00000001;\r
-\r
-    // Enable clocks (USB registers, USB RAM)\r
-    LPC_SYSCON->SYSAHBCLKCTRL |= CLK_USB | CLK_USBRAM;\r
-\r
-    // Ensure device disconnected (DCON not set)\r
-    LPC_USB->DEVCMDSTAT = 0;\r
-\r
-    // to ensure that the USB host sees the device as\r
-    // disconnected if the target CPU is reset.\r
-    wait(0.3);\r
-\r
-    // Reserve space in USB RAM for endpoint command/status list\r
-    // Must be 256 byte aligned\r
-    usbRamPtr = ROUND_UP_TO_MULTIPLE(usbRamPtr, 256);\r
-    ep = (EP_COMMAND_STATUS *)usbRamPtr;\r
-    usbRamPtr += (sizeof(EP_COMMAND_STATUS) * NUMBER_OF_LOGICAL_ENDPOINTS);\r
-    LPC_USB->EPLISTSTART = (uint32_t)(ep) & 0xffffff00;\r
-\r
-    // Reserve space in USB RAM for Endpoint 0\r
-    // Must be 64 byte aligned\r
-    usbRamPtr = ROUND_UP_TO_MULTIPLE(usbRamPtr, 64);\r
-    ct = (CONTROL_TRANSFER *)usbRamPtr;\r
-    usbRamPtr += sizeof(CONTROL_TRANSFER);\r
-    LPC_USB->DATABUFSTART =(uint32_t)(ct) & 0xffc00000;\r
-\r
-    // Setup command/status list for EP0\r
-    ep[0].out[0] = 0;\r
-    ep[0].in[0] =  0;\r
-    ep[0].out[1] = CMDSTS_ADDRESS_OFFSET((uint32_t)ct->setup);\r
-\r
-    // Route all interrupts to IRQ, some can be routed to\r
-    // USB_FIQ if you wish.\r
-    LPC_USB->INTROUTING = 0;\r
-\r
-    // Set device address 0, enable USB device, no remote wakeup\r
-    devCmdStat = DEV_ADDR(0) | DEV_EN | DSUS;\r
-    LPC_USB->DEVCMDSTAT = devCmdStat;\r
-\r
-    // Enable interrupts for device events and EP0\r
-    LPC_USB->INTEN = DEV_INT | EP(EP0IN) | EP(EP0OUT) | FRAME_INT;\r
-    instance = this;\r
-\r
-    //attach IRQ handler and enable interrupts\r
-    NVIC_SetVector(USB_IRQn, (uint32_t)&_usbisr);\r
-    NVIC_EnableIRQ(USB_IRQn);\r
-}\r
-\r
-USBHAL::~USBHAL(void) {\r
-    // Ensure device disconnected (DCON not set)\r
-    LPC_USB->DEVCMDSTAT = 0;\r
-\r
-    // Disable USB interrupts\r
-    NVIC_DisableIRQ(USB_IRQn);\r
-}\r
-\r
-void USBHAL::connect(void) {\r
-    devCmdStat |= DCON;\r
-    LPC_USB->DEVCMDSTAT = devCmdStat;\r
-}\r
-\r
-void USBHAL::disconnect(void) {\r
-    devCmdStat &= ~DCON;\r
-    LPC_USB->DEVCMDSTAT = devCmdStat;\r
-}\r
-\r
-void USBHAL::configureDevice(void) {\r
-}\r
-\r
-void USBHAL::unconfigureDevice(void) {\r
-}\r
-\r
-void USBHAL::EP0setup(uint8_t *buffer) {\r
-    // Copy setup packet data\r
-    USBMemCopy(buffer, ct->setup, SETUP_PACKET_SIZE);\r
-}\r
-\r
-void USBHAL::EP0read(void) {\r
-    // Start an endpoint 0 read\r
-\r
-    // The USB ISR will call USBDevice_EP0out() when a packet has been read,\r
-    // the USBDevice layer then calls USBBusInterface_EP0getReadResult() to\r
-    // read the data.\r
-\r
-    ep[0].out[0] = CMDSTS_A |CMDSTS_NBYTES(MAX_PACKET_SIZE_EP0) \\r
-                   | CMDSTS_ADDRESS_OFFSET((uint32_t)ct->out);\r
-}\r
-\r
-uint32_t USBHAL::EP0getReadResult(uint8_t *buffer) {\r
-    // Complete an endpoint 0 read\r
-    uint32_t bytesRead;\r
-\r
-    // Find how many bytes were read\r
-    bytesRead = MAX_PACKET_SIZE_EP0 - BYTES_REMAINING(ep[0].out[0]);\r
+// USB Device Command/Status register
+#define DEV_ADDR_MASK   (0x7f)          // Device address
+#define DEV_ADDR(a)     ((a) & DEV_ADDR_MASK)
+#define DEV_EN          (1UL<<7)        // Device enable
+#define SETUP           (1UL<<8)        // SETUP token received
+#define PLL_ON          (1UL<<9)        // PLL enabled in suspend
+#define DCON            (1UL<<16)       // Device status - connect
+#define DSUS            (1UL<<17)       // Device status - suspend
+#define DCON_C          (1UL<<24)       // Connect change
+#define DSUS_C          (1UL<<25)       // Suspend change
+#define DRES_C          (1UL<<26)       // Reset change
+#define VBUSDEBOUNCED   (1UL<<28)       // Vbus detected
+\r
+// Endpoint Command/Status list
+#define CMDSTS_A                 (1UL<<31)          // Active
+#define CMDSTS_D                 (1UL<<30)          // Disable
+#define CMDSTS_S                 (1UL<<29)          // Stall
+#define CMDSTS_TR                (1UL<<28)          // Toggle Reset
+#define CMDSTS_RF                (1UL<<27)          // Rate Feedback mode
+#define CMDSTS_TV                (1UL<<27)          // Toggle Value
+#define CMDSTS_T                 (1UL<<26)          // Endpoint Type
+#define CMDSTS_NBYTES(n)         (((n)&0x3ff)<<16)  // Number of bytes
+#define CMDSTS_ADDRESS_OFFSET(a) (((a)>>6)&0xffff)  // Buffer start address
+\r
+#define BYTES_REMAINING(s)       (((s)>>16)&0x3ff)  // Bytes remaining after transfer
+\r
+// USB Non-endpoint interrupt sources
+#define FRAME_INT   (1UL<<30)
+#define DEV_INT     (1UL<<31)
+\r
+static volatile int epComplete = 0;
+\r
+// One entry for a double-buffered logical endpoint in the endpoint
+// command/status list. Endpoint 0 is single buffered, out[1] is used
+// for the SETUP packet and in[1] is not used
+typedef __packed struct {
+    uint32_t out[2];
+    uint32_t in[2];
+} EP_COMMAND_STATUS;
+\r
+typedef __packed struct {
+    uint8_t out[MAX_PACKET_SIZE_EP0];
+    uint8_t in[MAX_PACKET_SIZE_EP0];
+    uint8_t setup[SETUP_PACKET_SIZE];
+} CONTROL_TRANSFER;
+\r
+typedef __packed struct {
+    uint32_t    maxPacket;
+    uint32_t    buffer[2];
+    uint32_t    options;
+} EP_STATE;
+\r
+static volatile EP_STATE endpointState[NUMBER_OF_PHYSICAL_ENDPOINTS];
+\r
+// Pointer to the endpoint command/status list
+static EP_COMMAND_STATUS *ep = NULL;
+\r
+// Pointer to endpoint 0 data (IN/OUT and SETUP)
+static CONTROL_TRANSFER *ct = NULL;
+\r
+// Shadow DEVCMDSTAT register to avoid accidentally clearing flags or
+// initiating a remote wakeup event.
+static volatile uint32_t devCmdStat;
+\r
+// Pointers used to allocate USB RAM
+static uint32_t usbRamPtr = USB_RAM_START;
+static uint32_t epRamPtr = 0; // Buffers for endpoints > 0 start here
+\r
+#define ROUND_UP_TO_MULTIPLE(x, m) ((((x)+((m)-1))/(m))*(m))
+\r
+void USBMemCopy(uint8_t *dst, uint8_t *src, uint32_t size);
+void USBMemCopy(uint8_t *dst, uint8_t *src, uint32_t size) {
+    if (size > 0) {
+        do {
+            *dst++ = *src++;
+        } while (--size > 0);
+    }
+}
+\r
+\r
+USBHAL::USBHAL(void) {
+    NVIC_DisableIRQ(USB_IRQn);
+\r
+    // nUSB_CONNECT output
+    LPC_IOCON->PIO0_6 = 0x00000001;
+\r
+    // Enable clocks (USB registers, USB RAM)
+    LPC_SYSCON->SYSAHBCLKCTRL |= CLK_USB | CLK_USBRAM;
+\r
+    // Ensure device disconnected (DCON not set)
+    LPC_USB->DEVCMDSTAT = 0;
+\r
+    // to ensure that the USB host sees the device as
+    // disconnected if the target CPU is reset.
+    wait(0.3);
+\r
+    // Reserve space in USB RAM for endpoint command/status list
+    // Must be 256 byte aligned
+    usbRamPtr = ROUND_UP_TO_MULTIPLE(usbRamPtr, 256);
+    ep = (EP_COMMAND_STATUS *)usbRamPtr;
+    usbRamPtr += (sizeof(EP_COMMAND_STATUS) * NUMBER_OF_LOGICAL_ENDPOINTS);
+    LPC_USB->EPLISTSTART = (uint32_t)(ep) & 0xffffff00;
+\r
+    // Reserve space in USB RAM for Endpoint 0
+    // Must be 64 byte aligned
+    usbRamPtr = ROUND_UP_TO_MULTIPLE(usbRamPtr, 64);
+    ct = (CONTROL_TRANSFER *)usbRamPtr;
+    usbRamPtr += sizeof(CONTROL_TRANSFER);
+    LPC_USB->DATABUFSTART =(uint32_t)(ct) & 0xffc00000;
+\r
+    // Setup command/status list for EP0
+    ep[0].out[0] = 0;
+    ep[0].in[0] =  0;
+    ep[0].out[1] = CMDSTS_ADDRESS_OFFSET((uint32_t)ct->setup);
+\r
+    // Route all interrupts to IRQ, some can be routed to
+    // USB_FIQ if you wish.
+    LPC_USB->INTROUTING = 0;
+\r
+    // Set device address 0, enable USB device, no remote wakeup
+    devCmdStat = DEV_ADDR(0) | DEV_EN | DSUS;
+    LPC_USB->DEVCMDSTAT = devCmdStat;
+\r
+    // Enable interrupts for device events and EP0
+    LPC_USB->INTEN = DEV_INT | EP(EP0IN) | EP(EP0OUT) | FRAME_INT;
+    instance = this;
+\r
+    //attach IRQ handler and enable interrupts
+    NVIC_SetVector(USB_IRQn, (uint32_t)&_usbisr);
+    NVIC_EnableIRQ(USB_IRQn);
+}
+\r
+USBHAL::~USBHAL(void) {
+    // Ensure device disconnected (DCON not set)
+    LPC_USB->DEVCMDSTAT = 0;
+\r
+    // Disable USB interrupts
+    NVIC_DisableIRQ(USB_IRQn);
+}
+\r
+void USBHAL::connect(void) {
+    devCmdStat |= DCON;
+    LPC_USB->DEVCMDSTAT = devCmdStat;
+}
+\r
+void USBHAL::disconnect(void) {
+    devCmdStat &= ~DCON;
+    LPC_USB->DEVCMDSTAT = devCmdStat;
+}
+\r
+void USBHAL::configureDevice(void) {
+}
+\r
+void USBHAL::unconfigureDevice(void) {
+}
+\r
+void USBHAL::EP0setup(uint8_t *buffer) {
+    // Copy setup packet data
+    USBMemCopy(buffer, ct->setup, SETUP_PACKET_SIZE);
+}
+\r
+void USBHAL::EP0read(void) {
+    // Start an endpoint 0 read
+\r
+    // The USB ISR will call USBDevice_EP0out() when a packet has been read,
+    // the USBDevice layer then calls USBBusInterface_EP0getReadResult() to
+    // read the data.
+\r
+    ep[0].out[0] = CMDSTS_A |CMDSTS_NBYTES(MAX_PACKET_SIZE_EP0) \
+                   | CMDSTS_ADDRESS_OFFSET((uint32_t)ct->out);
+}
+\r
+uint32_t USBHAL::EP0getReadResult(uint8_t *buffer) {
+    // Complete an endpoint 0 read
+    uint32_t bytesRead;
+\r
+    // Find how many bytes were read
+    bytesRead = MAX_PACKET_SIZE_EP0 - BYTES_REMAINING(ep[0].out[0]);
 \r
-    // Copy data\r
-    USBMemCopy(buffer, ct->out, bytesRead);\r
-    return bytesRead;\r
-}\r
-\r
-void USBHAL::EP0write(uint8_t *buffer, uint32_t size) {\r
-    // Start and endpoint 0 write\r
-\r
-    // The USB ISR will call USBDevice_EP0in() when the data has\r
-    // been written, the USBDevice layer then calls\r
-    // USBBusInterface_EP0getWriteResult() to complete the transaction.\r
-\r
-    // Copy data\r
-    USBMemCopy(ct->in, buffer, size);\r
-\r
-    // Start transfer\r
-    ep[0].in[0] = CMDSTS_A | CMDSTS_NBYTES(size) \\r
-                  | CMDSTS_ADDRESS_OFFSET((uint32_t)ct->in);\r
-}\r
-\r
-\r
-EP_STATUS USBHAL::endpointRead(uint8_t endpoint, uint32_t maximumSize) {\r
-    uint8_t bf = 0;\r
-    uint32_t flags = 0;\r
-\r
-    //check which buffer must be filled\r
-    if (LPC_USB->EPBUFCFG & EP(endpoint)) {\r
-        // Double buffered\r
-        if (LPC_USB->EPINUSE & EP(endpoint)) {\r
-            bf = 1;\r
-        } else {\r
-            bf = 0;\r
-        }\r
-    }\r
+    // Copy data
+    USBMemCopy(buffer, ct->out, bytesRead);
+    return bytesRead;
+}
+\r
+void USBHAL::EP0write(uint8_t *buffer, uint32_t size) {
+    // Start and endpoint 0 write
+\r
+    // The USB ISR will call USBDevice_EP0in() when the data has
+    // been written, the USBDevice layer then calls
+    // USBBusInterface_EP0getWriteResult() to complete the transaction.
+\r
+    // Copy data
+    USBMemCopy(ct->in, buffer, size);
+\r
+    // Start transfer
+    ep[0].in[0] = CMDSTS_A | CMDSTS_NBYTES(size) \
+                  | CMDSTS_ADDRESS_OFFSET((uint32_t)ct->in);
+}
+\r
+\r
+EP_STATUS USBHAL::endpointRead(uint8_t endpoint, uint32_t maximumSize) {
+    uint8_t bf = 0;
+    uint32_t flags = 0;
+\r
+    //check which buffer must be filled
+    if (LPC_USB->EPBUFCFG & EP(endpoint)) {
+        // Double buffered
+        if (LPC_USB->EPINUSE & EP(endpoint)) {
+            bf = 1;
+        } else {
+            bf = 0;
+        }
+    }
     \r
-    // if isochronous endpoint, T = 1\r
-    if(endpointState[endpoint].options & ISOCHRONOUS)\r
-    {\r
-        flags |= CMDSTS_T;\r
-    }\r
+    // if isochronous endpoint, T = 1
+    if(endpointState[endpoint].options & ISOCHRONOUS)
+    {
+        flags |= CMDSTS_T;
+    }
         \r
-    //Active the endpoint for reading\r
-    ep[PHY_TO_LOG(endpoint)].out[bf] = CMDSTS_A | CMDSTS_NBYTES(maximumSize) \\r
-                                       | CMDSTS_ADDRESS_OFFSET((uint32_t)ct->out) | flags;\r
-    return EP_PENDING;\r
-}\r
-\r
-EP_STATUS USBHAL::endpointReadResult(uint8_t endpoint, uint8_t *data, uint32_t *bytesRead) {\r
-\r
-    uint8_t bf = 0;\r
-\r
-    if (!(epComplete & EP(endpoint)))\r
-        return EP_PENDING;\r
-    else {\r
-        epComplete &= ~EP(endpoint);\r
-\r
-        //check which buffer has been filled\r
-        if (LPC_USB->EPBUFCFG & EP(endpoint)) {\r
-            // Double buffered (here we read the previous buffer which was used)\r
-            if (LPC_USB->EPINUSE & EP(endpoint)) {\r
-                bf = 0;\r
-            } else {\r
-                bf = 1;\r
-            }\r
-        }\r
-\r
-        // Find how many bytes were read\r
-        *bytesRead = (uint32_t) (endpointState[endpoint].maxPacket - BYTES_REMAINING(ep[PHY_TO_LOG(endpoint)].out[bf]));\r
-\r
-        // Copy data\r
-        USBMemCopy(data, ct->out, *bytesRead);\r
-        return EP_COMPLETED;\r
-    }\r
-}\r
-\r
-void USBHAL::EP0getWriteResult(void) {\r
-    // Complete an endpoint 0 write\r
-\r
-    // Nothing required for this target\r
-    return;\r
-}\r
-\r
-void USBHAL::EP0stall(void) {\r
-    ep[0].in[0] = CMDSTS_S;\r
-    ep[0].out[0] = CMDSTS_S;\r
-}\r
-\r
-void USBHAL::setAddress(uint8_t address) {\r
-    devCmdStat &= ~DEV_ADDR_MASK;\r
-    devCmdStat |= DEV_ADDR(address);\r
-    LPC_USB->DEVCMDSTAT = devCmdStat;\r
-}\r
-\r
-EP_STATUS USBHAL::endpointWrite(uint8_t endpoint, uint8_t *data, uint32_t size) {\r
-    uint32_t flags = 0;\r
-    uint32_t bf;\r
-\r
-    // Validate parameters\r
-    if (data == NULL) {\r
-        return EP_INVALID;\r
-    }\r
-\r
-    if (endpoint > LAST_PHYSICAL_ENDPOINT) {\r
-        return EP_INVALID;\r
-    }\r
-\r
-    if ((endpoint==EP0IN) || (endpoint==EP0OUT)) {\r
-        return EP_INVALID;\r
-    }\r
-\r
-    if (size > endpointState[endpoint].maxPacket) {\r
-        return EP_INVALID;\r
-    }\r
-\r
-    if (LPC_USB->EPBUFCFG & EP(endpoint)) {\r
-        // Double buffered\r
-        if (LPC_USB->EPINUSE & EP(endpoint)) {\r
-            bf = 1;\r
-        } else {\r
-            bf = 0;\r
-        }\r
-    } else {\r
-        // Single buffered\r
-        bf = 0;\r
-    }\r
-\r
-    // Check if already active\r
-    if (ep[PHY_TO_LOG(endpoint)].in[bf] & CMDSTS_A) {\r
-        return EP_INVALID;\r
-    }\r
-\r
-    // Check if stalled\r
-    if (ep[PHY_TO_LOG(endpoint)].in[bf] & CMDSTS_S) {\r
-        return EP_STALLED;\r
-    }\r
-\r
-    // Copy data to USB RAM\r
-    USBMemCopy((uint8_t *)endpointState[endpoint].buffer[bf], data, size);\r
-\r
-    // Add options\r
-    if (endpointState[endpoint].options & RATE_FEEDBACK_MODE) {\r
-        flags |= CMDSTS_RF;\r
-    }\r
-\r
-    if (endpointState[endpoint].options & ISOCHRONOUS) {\r
-        flags |= CMDSTS_T;\r
-    }\r
-\r
-    // Add transfer\r
-    ep[PHY_TO_LOG(endpoint)].in[bf] = CMDSTS_ADDRESS_OFFSET( \\r
-                                      endpointState[endpoint].buffer[bf]) \\r
-                                      | CMDSTS_NBYTES(size) | CMDSTS_A | flags;\r
-\r
-    return EP_PENDING;\r
-}\r
-\r
-EP_STATUS USBHAL::endpointWriteResult(uint8_t endpoint) {\r
-    uint32_t bf;\r
-    // Validate parameters\r
-\r
-    if (endpoint > LAST_PHYSICAL_ENDPOINT) {\r
-        return EP_INVALID;\r
-    }\r
-\r
-    if (OUT_EP(endpoint)) {\r
-        return EP_INVALID;\r
-    }\r
-\r
-    if (LPC_USB->EPBUFCFG & EP(endpoint)) {\r
-        // Double buffered     // TODO: FIX THIS\r
-        if (LPC_USB->EPINUSE & EP(endpoint)) {\r
-            bf = 1;\r
-        } else {\r
-            bf = 0;\r
-        }\r
-    } else {\r
-        // Single buffered\r
-        bf = 0;\r
-    }\r
-\r
-    // Check if endpoint still active\r
-    if (ep[PHY_TO_LOG(endpoint)].in[bf] & CMDSTS_A) {\r
-        return EP_PENDING;\r
-    }\r
-\r
-    // Check if stalled\r
-    if (ep[PHY_TO_LOG(endpoint)].in[bf] & CMDSTS_S) {\r
-        return EP_STALLED;\r
-    }\r
-\r
-    return EP_COMPLETED;\r
-}\r
-\r
-void USBHAL::stallEndpoint(uint8_t endpoint) {\r
-\r
-    // TODO: should this clear active bit?\r
-\r
-    if (IN_EP(endpoint)) {\r
-        ep[PHY_TO_LOG(endpoint)].in[0] |= CMDSTS_S;\r
-        ep[PHY_TO_LOG(endpoint)].in[1] |= CMDSTS_S;\r
-    } else {\r
-        ep[PHY_TO_LOG(endpoint)].out[0] |= CMDSTS_S;\r
-        ep[PHY_TO_LOG(endpoint)].out[1] |= CMDSTS_S;\r
-    }\r
-}\r
-\r
-void USBHAL::unstallEndpoint(uint8_t endpoint) {\r
-    if (LPC_USB->EPBUFCFG & EP(endpoint)) {\r
-        // Double buffered\r
-        if (IN_EP(endpoint)) {\r
-            ep[PHY_TO_LOG(endpoint)].in[0] = 0; // S = 0\r
-            ep[PHY_TO_LOG(endpoint)].in[1] = 0; // S = 0\r
-\r
-            if (LPC_USB->EPINUSE & EP(endpoint)) {\r
-                ep[PHY_TO_LOG(endpoint)].in[1] = CMDSTS_TR; // S =0, TR=1, TV = 0\r
-            } else {\r
-                ep[PHY_TO_LOG(endpoint)].in[0] = CMDSTS_TR; // S =0, TR=1, TV = 0\r
-            }\r
-        } else {\r
-            ep[PHY_TO_LOG(endpoint)].out[0] = 0; // S = 0\r
-            ep[PHY_TO_LOG(endpoint)].out[1] = 0; // S = 0\r
-\r
-            if (LPC_USB->EPINUSE & EP(endpoint)) {\r
-                ep[PHY_TO_LOG(endpoint)].out[1] = CMDSTS_TR; // S =0, TR=1, TV = 0\r
-            } else {\r
-                ep[PHY_TO_LOG(endpoint)].out[0] = CMDSTS_TR; // S =0, TR=1, TV = 0\r
-            }\r
-        }\r
-    } else {\r
-        // Single buffered\r
-        if (IN_EP(endpoint)) {\r
-            ep[PHY_TO_LOG(endpoint)].in[0] = CMDSTS_TR; // S=0, TR=1, TV = 0\r
-        } else {\r
-            ep[PHY_TO_LOG(endpoint)].out[0] = CMDSTS_TR; // S=0, TR=1, TV = 0\r
-        }\r
-    }\r
-}\r
-\r
-bool USBHAL::getEndpointStallState(unsigned char endpoint) {\r
-    if (IN_EP(endpoint)) {\r
-        if (LPC_USB->EPINUSE & EP(endpoint)) {\r
-            if (ep[PHY_TO_LOG(endpoint)].in[1] & CMDSTS_S) {\r
-                return true;\r
-            }\r
-        } else {\r
-            if (ep[PHY_TO_LOG(endpoint)].in[0] & CMDSTS_S) {\r
-                return true;\r
-            }\r
-        }\r
-    } else {\r
-        if (LPC_USB->EPINUSE & EP(endpoint)) {\r
-            if (ep[PHY_TO_LOG(endpoint)].out[1] & CMDSTS_S) {\r
-                return true;\r
-            }\r
-        } else {\r
-            if (ep[PHY_TO_LOG(endpoint)].out[0] & CMDSTS_S) {\r
-                return true;\r
-            }\r
-        }\r
-    }\r
-\r
-    return false;\r
-}\r
-\r
-bool USBHAL::realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, uint32_t options) {\r
-    uint32_t tmpEpRamPtr;\r
-\r
-    if (endpoint > LAST_PHYSICAL_ENDPOINT) {\r
-        return false;\r
-    }\r
-\r
-    // Not applicable to the control endpoints\r
-    if ((endpoint==EP0IN) || (endpoint==EP0OUT)) {\r
-        return false;\r
-    }\r
-\r
-    // Allocate buffers in USB RAM\r
-    tmpEpRamPtr = epRamPtr;\r
-\r
-    // Must be 64 byte aligned\r
-    tmpEpRamPtr = ROUND_UP_TO_MULTIPLE(tmpEpRamPtr, 64);\r
-\r
-    if ((tmpEpRamPtr + maxPacket) > (USB_RAM_START + USB_RAM_SIZE)) {\r
-        // Out of memory\r
-        return false;\r
-    }\r
-\r
-    // Allocate first buffer\r
-    endpointState[endpoint].buffer[0] = tmpEpRamPtr;\r
-    tmpEpRamPtr += maxPacket;\r
-\r
-    if (!(options & SINGLE_BUFFERED)) {\r
-        // Must be 64 byte aligned\r
-        tmpEpRamPtr = ROUND_UP_TO_MULTIPLE(tmpEpRamPtr, 64);\r
-\r
-        if ((tmpEpRamPtr + maxPacket) > (USB_RAM_START + USB_RAM_SIZE)) {\r
-            // Out of memory\r
-            return false;\r
-        }\r
-\r
-        // Allocate second buffer\r
-        endpointState[endpoint].buffer[1] = tmpEpRamPtr;\r
-        tmpEpRamPtr += maxPacket;\r
-    }\r
-\r
-    // Commit to this USB RAM allocation\r
-    epRamPtr = tmpEpRamPtr;\r
-\r
-    // Remaining endpoint state values\r
-    endpointState[endpoint].maxPacket = maxPacket;\r
-    endpointState[endpoint].options = options;\r
-\r
-    // Enable double buffering if required\r
-    if (options & SINGLE_BUFFERED) {\r
-        LPC_USB->EPBUFCFG &= ~EP(endpoint);\r
-    } else {\r
-        // Double buffered\r
-        LPC_USB->EPBUFCFG |= EP(endpoint);\r
-    }\r
-\r
-    // Enable interrupt\r
-    LPC_USB->INTEN |= EP(endpoint);\r
-\r
-    // Enable endpoint\r
-    unstallEndpoint(endpoint);\r
-    return true;\r
-}\r
-\r
-void USBHAL::remoteWakeup(void) {\r
-    // Clearing DSUS bit initiates a remote wakeup if the\r
-    // device is currently enabled and suspended - otherwise\r
-    // it has no effect.\r
-    LPC_USB->DEVCMDSTAT = devCmdStat & ~DSUS;\r
-}\r
-\r
-\r
-static void disableEndpoints(void) {\r
-    uint32_t logEp;\r
-\r
-    // Ref. Table 158 "When a bus reset is received, software\r
-    // must set the disable bit of all endpoints to 1".\r
-\r
-    for (logEp = 1; logEp < NUMBER_OF_LOGICAL_ENDPOINTS; logEp++) {\r
-        ep[logEp].out[0] = CMDSTS_D;\r
-        ep[logEp].out[1] = CMDSTS_D;\r
-        ep[logEp].in[0] =  CMDSTS_D;\r
-        ep[logEp].in[1] =  CMDSTS_D;\r
-    }\r
-\r
-    // Start of USB RAM for endpoints > 0\r
-    epRamPtr = usbRamPtr;\r
-}\r
-\r
-\r
-\r
-void USBHAL::_usbisr(void) {\r
-    instance->usbisr();\r
-}\r
-\r
-\r
-void USBHAL::usbisr(void) {\r
-    // Start of frame\r
-    if (LPC_USB->INTSTAT & FRAME_INT) {\r
-        // Clear SOF interrupt\r
-        LPC_USB->INTSTAT = FRAME_INT;\r
-\r
-        // SOF event, read frame number\r
-        SOF(FRAME_NR(LPC_USB->INFO));\r
-    }\r
-\r
-    // Device state\r
-    if (LPC_USB->INTSTAT & DEV_INT) {\r
-        LPC_USB->INTSTAT = DEV_INT;\r
-\r
-        if (LPC_USB->DEVCMDSTAT & DCON_C) {\r
-            // Connect status changed\r
-            LPC_USB->DEVCMDSTAT = devCmdStat | DCON_C;\r
-\r
-            connectStateChanged((LPC_USB->DEVCMDSTAT & DCON) != 0);\r
-        }\r
-\r
-        if (LPC_USB->DEVCMDSTAT & DSUS_C) {\r
-            // Suspend status changed\r
-            LPC_USB->DEVCMDSTAT = devCmdStat | DSUS_C;\r
-\r
-            suspendStateChanged((LPC_USB->DEVCMDSTAT & DSUS) != 0);\r
-        }\r
-\r
-        if (LPC_USB->DEVCMDSTAT & DRES_C) {\r
-            // Bus reset\r
-            LPC_USB->DEVCMDSTAT = devCmdStat | DRES_C;\r
-\r
-            // Disable endpoints > 0\r
-            disableEndpoints();\r
-\r
-            // Bus reset event\r
-            busReset();\r
-        }\r
-    }\r
-\r
-    // Endpoint 0\r
-    if (LPC_USB->INTSTAT & EP(EP0OUT)) {\r
-        // Clear EP0OUT/SETUP interrupt\r
-        LPC_USB->INTSTAT = EP(EP0OUT);\r
-\r
-        // Check if SETUP\r
-        if (LPC_USB->DEVCMDSTAT & SETUP) {\r
-            // Clear Active and Stall bits for EP0\r
-            // Documentation does not make it clear if we must use the\r
-            // EPSKIP register to achieve this, Fig. 16 and NXP reference\r
-            // code suggests we can just clear the Active bits - check with\r
-            // NXP to be sure.\r
-            ep[0].in[0] = 0;\r
-            ep[0].out[0] = 0;\r
-\r
-            // Clear EP0IN interrupt\r
-            LPC_USB->INTSTAT = EP(EP0IN);\r
-\r
-            // Clear SETUP (and INTONNAK_CI/O) in device status register\r
-            LPC_USB->DEVCMDSTAT = devCmdStat | SETUP;\r
-\r
-            // EP0 SETUP event (SETUP data received)\r
-            EP0setupCallback();\r
-        } else {\r
-            // EP0OUT ACK event (OUT data received)\r
-            EP0out();\r
-        }\r
-    }\r
-\r
-    if (LPC_USB->INTSTAT & EP(EP0IN)) {\r
-        // Clear EP0IN interrupt\r
-        LPC_USB->INTSTAT = EP(EP0IN);\r
-\r
-        // EP0IN ACK event (IN data sent)\r
-        EP0in();\r
-    }\r
-\r
-    if (LPC_USB->INTSTAT & EP(EP1IN)) {\r
-        // Clear EP1IN interrupt\r
-        LPC_USB->INTSTAT = EP(EP1IN);\r
-        epComplete |= EP(EP1IN);\r
-        if (EP1_IN_callback())\r
-            epComplete &= ~EP(EP1IN);\r
-    }\r
-\r
-    if (LPC_USB->INTSTAT & EP(EP1OUT)) {\r
-        // Clear EP1OUT interrupt\r
-        LPC_USB->INTSTAT = EP(EP1OUT);\r
-        epComplete |= EP(EP1OUT);\r
-        if (EP1_OUT_callback())\r
-            epComplete &= ~EP(EP1OUT);\r
-    }\r
-\r
-    if (LPC_USB->INTSTAT & EP(EP2IN)) {\r
-        // Clear EPBULK_IN interrupt\r
-        LPC_USB->INTSTAT = EP(EP2IN);\r
-        epComplete |= EP(EP2IN);\r
-        if (EP2_IN_callback())\r
-            epComplete &= ~EP(EP2IN);\r
-    }\r
-\r
-    if (LPC_USB->INTSTAT & EP(EP2OUT)) {\r
-        // Clear EPBULK_OUT interrupt\r
-        LPC_USB->INTSTAT = EP(EP2OUT);\r
-        epComplete |= EP(EP2OUT);\r
-        //Call callback function. If true, clear epComplete\r
-        if (EP2_OUT_callback())\r
-            epComplete &= ~EP(EP2OUT);\r
-    }\r
-\r
-    if (LPC_USB->INTSTAT & EP(EP3IN)) {\r
-        // Clear EP3_IN interrupt\r
-        LPC_USB->INTSTAT = EP(EP3IN);\r
-        epComplete |= EP(EP3IN);\r
-        if (EP3_IN_callback())\r
-            epComplete &= ~EP(EP3IN);\r
-    }\r
-\r
-    if (LPC_USB->INTSTAT & EP(EP3OUT)) {\r
-        // Clear EP3_OUT interrupt\r
-        LPC_USB->INTSTAT = EP(EP3OUT);\r
-        epComplete |= EP(EP3OUT);\r
-        //Call callback function. If true, clear epComplete\r
-        if (EP3_OUT_callback())\r
-            epComplete &= ~EP(EP3OUT);\r
-    }\r
-}\r
+    //Active the endpoint for reading
+    ep[PHY_TO_LOG(endpoint)].out[bf] = CMDSTS_A | CMDSTS_NBYTES(maximumSize) \
+                                       | CMDSTS_ADDRESS_OFFSET((uint32_t)ct->out) | flags;
+    return EP_PENDING;
+}
+\r
+EP_STATUS USBHAL::endpointReadResult(uint8_t endpoint, uint8_t *data, uint32_t *bytesRead) {
+\r
+    uint8_t bf = 0;
+\r
+    if (!(epComplete & EP(endpoint)))
+        return EP_PENDING;
+    else {
+        epComplete &= ~EP(endpoint);
+\r
+        //check which buffer has been filled
+        if (LPC_USB->EPBUFCFG & EP(endpoint)) {
+            // Double buffered (here we read the previous buffer which was used)
+            if (LPC_USB->EPINUSE & EP(endpoint)) {
+                bf = 0;
+            } else {
+                bf = 1;
+            }
+        }
+\r
+        // Find how many bytes were read
+        *bytesRead = (uint32_t) (endpointState[endpoint].maxPacket - BYTES_REMAINING(ep[PHY_TO_LOG(endpoint)].out[bf]));
+\r
+        // Copy data
+        USBMemCopy(data, ct->out, *bytesRead);
+        return EP_COMPLETED;
+    }
+}
+\r
+void USBHAL::EP0getWriteResult(void) {
+    // Complete an endpoint 0 write
+\r
+    // Nothing required for this target
+    return;
+}
+\r
+void USBHAL::EP0stall(void) {
+    ep[0].in[0] = CMDSTS_S;
+    ep[0].out[0] = CMDSTS_S;
+}
+\r
+void USBHAL::setAddress(uint8_t address) {
+    devCmdStat &= ~DEV_ADDR_MASK;
+    devCmdStat |= DEV_ADDR(address);
+    LPC_USB->DEVCMDSTAT = devCmdStat;
+}
+\r
+EP_STATUS USBHAL::endpointWrite(uint8_t endpoint, uint8_t *data, uint32_t size) {
+    uint32_t flags = 0;
+    uint32_t bf;
+\r
+    // Validate parameters
+    if (data == NULL) {
+        return EP_INVALID;
+    }
+\r
+    if (endpoint > LAST_PHYSICAL_ENDPOINT) {
+        return EP_INVALID;
+    }
+\r
+    if ((endpoint==EP0IN) || (endpoint==EP0OUT)) {
+        return EP_INVALID;
+    }
+\r
+    if (size > endpointState[endpoint].maxPacket) {
+        return EP_INVALID;
+    }
+\r
+    if (LPC_USB->EPBUFCFG & EP(endpoint)) {
+        // Double buffered
+        if (LPC_USB->EPINUSE & EP(endpoint)) {
+            bf = 1;
+        } else {
+            bf = 0;
+        }
+    } else {
+        // Single buffered
+        bf = 0;
+    }
+\r
+    // Check if already active
+    if (ep[PHY_TO_LOG(endpoint)].in[bf] & CMDSTS_A) {
+        return EP_INVALID;
+    }
+\r
+    // Check if stalled
+    if (ep[PHY_TO_LOG(endpoint)].in[bf] & CMDSTS_S) {
+        return EP_STALLED;
+    }
+\r
+    // Copy data to USB RAM
+    USBMemCopy((uint8_t *)endpointState[endpoint].buffer[bf], data, size);
+\r
+    // Add options
+    if (endpointState[endpoint].options & RATE_FEEDBACK_MODE) {
+        flags |= CMDSTS_RF;
+    }
+\r
+    if (endpointState[endpoint].options & ISOCHRONOUS) {
+        flags |= CMDSTS_T;
+    }
+\r
+    // Add transfer
+    ep[PHY_TO_LOG(endpoint)].in[bf] = CMDSTS_ADDRESS_OFFSET( \
+                                      endpointState[endpoint].buffer[bf]) \
+                                      | CMDSTS_NBYTES(size) | CMDSTS_A | flags;
+\r
+    return EP_PENDING;
+}
+\r
+EP_STATUS USBHAL::endpointWriteResult(uint8_t endpoint) {
+    uint32_t bf;
+    // Validate parameters
+\r
+    if (endpoint > LAST_PHYSICAL_ENDPOINT) {
+        return EP_INVALID;
+    }
+\r
+    if (OUT_EP(endpoint)) {
+        return EP_INVALID;
+    }
+\r
+    if (LPC_USB->EPBUFCFG & EP(endpoint)) {
+        // Double buffered     // TODO: FIX THIS
+        if (LPC_USB->EPINUSE & EP(endpoint)) {
+            bf = 1;
+        } else {
+            bf = 0;
+        }
+    } else {
+        // Single buffered
+        bf = 0;
+    }
+\r
+    // Check if endpoint still active
+    if (ep[PHY_TO_LOG(endpoint)].in[bf] & CMDSTS_A) {
+        return EP_PENDING;
+    }
+\r
+    // Check if stalled
+    if (ep[PHY_TO_LOG(endpoint)].in[bf] & CMDSTS_S) {
+        return EP_STALLED;
+    }
+\r
+    return EP_COMPLETED;
+}
+\r
+void USBHAL::stallEndpoint(uint8_t endpoint) {
+\r
+    // TODO: should this clear active bit?
+\r
+    if (IN_EP(endpoint)) {
+        ep[PHY_TO_LOG(endpoint)].in[0] |= CMDSTS_S;
+        ep[PHY_TO_LOG(endpoint)].in[1] |= CMDSTS_S;
+    } else {
+        ep[PHY_TO_LOG(endpoint)].out[0] |= CMDSTS_S;
+        ep[PHY_TO_LOG(endpoint)].out[1] |= CMDSTS_S;
+    }
+}
+\r
+void USBHAL::unstallEndpoint(uint8_t endpoint) {
+    if (LPC_USB->EPBUFCFG & EP(endpoint)) {
+        // Double buffered
+        if (IN_EP(endpoint)) {
+            ep[PHY_TO_LOG(endpoint)].in[0] = 0; // S = 0
+            ep[PHY_TO_LOG(endpoint)].in[1] = 0; // S = 0
+\r
+            if (LPC_USB->EPINUSE & EP(endpoint)) {
+                ep[PHY_TO_LOG(endpoint)].in[1] = CMDSTS_TR; // S =0, TR=1, TV = 0
+            } else {
+                ep[PHY_TO_LOG(endpoint)].in[0] = CMDSTS_TR; // S =0, TR=1, TV = 0
+            }
+        } else {
+            ep[PHY_TO_LOG(endpoint)].out[0] = 0; // S = 0
+            ep[PHY_TO_LOG(endpoint)].out[1] = 0; // S = 0
+\r
+            if (LPC_USB->EPINUSE & EP(endpoint)) {
+                ep[PHY_TO_LOG(endpoint)].out[1] = CMDSTS_TR; // S =0, TR=1, TV = 0
+            } else {
+                ep[PHY_TO_LOG(endpoint)].out[0] = CMDSTS_TR; // S =0, TR=1, TV = 0
+            }
+        }
+    } else {
+        // Single buffered
+        if (IN_EP(endpoint)) {
+            ep[PHY_TO_LOG(endpoint)].in[0] = CMDSTS_TR; // S=0, TR=1, TV = 0
+        } else {
+            ep[PHY_TO_LOG(endpoint)].out[0] = CMDSTS_TR; // S=0, TR=1, TV = 0
+        }
+    }
+}
+\r
+bool USBHAL::getEndpointStallState(unsigned char endpoint) {
+    if (IN_EP(endpoint)) {
+        if (LPC_USB->EPINUSE & EP(endpoint)) {
+            if (ep[PHY_TO_LOG(endpoint)].in[1] & CMDSTS_S) {
+                return true;
+            }
+        } else {
+            if (ep[PHY_TO_LOG(endpoint)].in[0] & CMDSTS_S) {
+                return true;
+            }
+        }
+    } else {
+        if (LPC_USB->EPINUSE & EP(endpoint)) {
+            if (ep[PHY_TO_LOG(endpoint)].out[1] & CMDSTS_S) {
+                return true;
+            }
+        } else {
+            if (ep[PHY_TO_LOG(endpoint)].out[0] & CMDSTS_S) {
+                return true;
+            }
+        }
+    }
+\r
+    return false;
+}
+\r
+bool USBHAL::realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, uint32_t options) {
+    uint32_t tmpEpRamPtr;
+\r
+    if (endpoint > LAST_PHYSICAL_ENDPOINT) {
+        return false;
+    }
+\r
+    // Not applicable to the control endpoints
+    if ((endpoint==EP0IN) || (endpoint==EP0OUT)) {
+        return false;
+    }
+\r
+    // Allocate buffers in USB RAM
+    tmpEpRamPtr = epRamPtr;
+\r
+    // Must be 64 byte aligned
+    tmpEpRamPtr = ROUND_UP_TO_MULTIPLE(tmpEpRamPtr, 64);
+\r
+    if ((tmpEpRamPtr + maxPacket) > (USB_RAM_START + USB_RAM_SIZE)) {
+        // Out of memory
+        return false;
+    }
+\r
+    // Allocate first buffer
+    endpointState[endpoint].buffer[0] = tmpEpRamPtr;
+    tmpEpRamPtr += maxPacket;
+\r
+    if (!(options & SINGLE_BUFFERED)) {
+        // Must be 64 byte aligned
+        tmpEpRamPtr = ROUND_UP_TO_MULTIPLE(tmpEpRamPtr, 64);
+\r
+        if ((tmpEpRamPtr + maxPacket) > (USB_RAM_START + USB_RAM_SIZE)) {
+            // Out of memory
+            return false;
+        }
+\r
+        // Allocate second buffer
+        endpointState[endpoint].buffer[1] = tmpEpRamPtr;
+        tmpEpRamPtr += maxPacket;
+    }
+\r
+    // Commit to this USB RAM allocation
+    epRamPtr = tmpEpRamPtr;
+\r
+    // Remaining endpoint state values
+    endpointState[endpoint].maxPacket = maxPacket;
+    endpointState[endpoint].options = options;
+\r
+    // Enable double buffering if required
+    if (options & SINGLE_BUFFERED) {
+        LPC_USB->EPBUFCFG &= ~EP(endpoint);
+    } else {
+        // Double buffered
+        LPC_USB->EPBUFCFG |= EP(endpoint);
+    }
+\r
+    // Enable interrupt
+    LPC_USB->INTEN |= EP(endpoint);
+\r
+    // Enable endpoint
+    unstallEndpoint(endpoint);
+    return true;
+}
+\r
+void USBHAL::remoteWakeup(void) {
+    // Clearing DSUS bit initiates a remote wakeup if the
+    // device is currently enabled and suspended - otherwise
+    // it has no effect.
+    LPC_USB->DEVCMDSTAT = devCmdStat & ~DSUS;
+}
+\r
+\r
+static void disableEndpoints(void) {
+    uint32_t logEp;
+\r
+    // Ref. Table 158 "When a bus reset is received, software
+    // must set the disable bit of all endpoints to 1".
+\r
+    for (logEp = 1; logEp < NUMBER_OF_LOGICAL_ENDPOINTS; logEp++) {
+        ep[logEp].out[0] = CMDSTS_D;
+        ep[logEp].out[1] = CMDSTS_D;
+        ep[logEp].in[0] =  CMDSTS_D;
+        ep[logEp].in[1] =  CMDSTS_D;
+    }
+\r
+    // Start of USB RAM for endpoints > 0
+    epRamPtr = usbRamPtr;
+}
+\r
+\r
+\r
+void USBHAL::_usbisr(void) {
+    instance->usbisr();
+}
+\r
+\r
+void USBHAL::usbisr(void) {
+    // Start of frame
+    if (LPC_USB->INTSTAT & FRAME_INT) {
+        // Clear SOF interrupt
+        LPC_USB->INTSTAT = FRAME_INT;
+\r
+        // SOF event, read frame number
+        SOF(FRAME_NR(LPC_USB->INFO));
+    }
+\r
+    // Device state
+    if (LPC_USB->INTSTAT & DEV_INT) {
+        LPC_USB->INTSTAT = DEV_INT;
+\r
+        if (LPC_USB->DEVCMDSTAT & DCON_C) {
+            // Connect status changed
+            LPC_USB->DEVCMDSTAT = devCmdStat | DCON_C;
+\r
+            connectStateChanged((LPC_USB->DEVCMDSTAT & DCON) != 0);
+        }
+\r
+        if (LPC_USB->DEVCMDSTAT & DSUS_C) {
+            // Suspend status changed
+            LPC_USB->DEVCMDSTAT = devCmdStat | DSUS_C;
+\r
+            suspendStateChanged((LPC_USB->DEVCMDSTAT & DSUS) != 0);
+        }
+\r
+        if (LPC_USB->DEVCMDSTAT & DRES_C) {
+            // Bus reset
+            LPC_USB->DEVCMDSTAT = devCmdStat | DRES_C;
+\r
+            // Disable endpoints > 0
+            disableEndpoints();
+\r
+            // Bus reset event
+            busReset();
+        }
+    }
+\r
+    // Endpoint 0
+    if (LPC_USB->INTSTAT & EP(EP0OUT)) {
+        // Clear EP0OUT/SETUP interrupt
+        LPC_USB->INTSTAT = EP(EP0OUT);
+\r
+        // Check if SETUP
+        if (LPC_USB->DEVCMDSTAT & SETUP) {
+            // Clear Active and Stall bits for EP0
+            // Documentation does not make it clear if we must use the
+            // EPSKIP register to achieve this, Fig. 16 and NXP reference
+            // code suggests we can just clear the Active bits - check with
+            // NXP to be sure.
+            ep[0].in[0] = 0;
+            ep[0].out[0] = 0;
+\r
+            // Clear EP0IN interrupt
+            LPC_USB->INTSTAT = EP(EP0IN);
+\r
+            // Clear SETUP (and INTONNAK_CI/O) in device status register
+            LPC_USB->DEVCMDSTAT = devCmdStat | SETUP;
+\r
+            // EP0 SETUP event (SETUP data received)
+            EP0setupCallback();
+        } else {
+            // EP0OUT ACK event (OUT data received)
+            EP0out();
+        }
+    }
+\r
+    if (LPC_USB->INTSTAT & EP(EP0IN)) {
+        // Clear EP0IN interrupt
+        LPC_USB->INTSTAT = EP(EP0IN);
+\r
+        // EP0IN ACK event (IN data sent)
+        EP0in();
+    }
+\r
+    if (LPC_USB->INTSTAT & EP(EP1IN)) {
+        // Clear EP1IN interrupt
+        LPC_USB->INTSTAT = EP(EP1IN);
+        epComplete |= EP(EP1IN);
+        if (EP1_IN_callback())
+            epComplete &= ~EP(EP1IN);
+    }
+\r
+    if (LPC_USB->INTSTAT & EP(EP1OUT)) {
+        // Clear EP1OUT interrupt
+        LPC_USB->INTSTAT = EP(EP1OUT);
+        epComplete |= EP(EP1OUT);
+        if (EP1_OUT_callback())
+            epComplete &= ~EP(EP1OUT);
+    }
+\r
+    if (LPC_USB->INTSTAT & EP(EP2IN)) {
+        // Clear EPBULK_IN interrupt
+        LPC_USB->INTSTAT = EP(EP2IN);
+        epComplete |= EP(EP2IN);
+        if (EP2_IN_callback())
+            epComplete &= ~EP(EP2IN);
+    }
+\r
+    if (LPC_USB->INTSTAT & EP(EP2OUT)) {
+        // Clear EPBULK_OUT interrupt
+        LPC_USB->INTSTAT = EP(EP2OUT);
+        epComplete |= EP(EP2OUT);
+        //Call callback function. If true, clear epComplete
+        if (EP2_OUT_callback())
+            epComplete &= ~EP(EP2OUT);
+    }
+\r
+    if (LPC_USB->INTSTAT & EP(EP3IN)) {
+        // Clear EP3_IN interrupt
+        LPC_USB->INTSTAT = EP(EP3IN);
+        epComplete |= EP(EP3IN);
+        if (EP3_IN_callback())
+            epComplete &= ~EP(EP3IN);
+    }
+\r
+    if (LPC_USB->INTSTAT & EP(EP3OUT)) {
+        // Clear EP3_OUT interrupt
+        LPC_USB->INTSTAT = EP(EP3OUT);
+        epComplete |= EP(EP3OUT);
+        //Call callback function. If true, clear epComplete
+        if (EP3_OUT_callback())
+            epComplete &= ~EP(EP3OUT);
+    }
+}
 \r
 #endif
\ No newline at end of file
index 182bf80..1974876 100644 (file)
-// USBBusInterface_LPC17_LPC23.c\r
-// USB Bus Interface for NXP LPC1768 and LPC2368\r
-// Copyright (c) 2011 ARM Limited. All rights reserved.\r
-\r
-#ifdef TARGET_LPC1768\r
-\r
-#include "USBBusInterface.h"\r
-\r
-\r
-// Get endpoint direction\r
-#define IN_EP(endpoint)     ((endpoint) & 1U ? true : false)\r
-#define OUT_EP(endpoint)    ((endpoint) & 1U ? false : true)\r
-\r
-// Convert physical endpoint number to register bit\r
-#define EP(endpoint) (1UL<<endpoint)\r
-\r
-// Power Control for Peripherals register\r
-#define PCUSB      (1UL<<31)\r
-\r
-// USB Clock Control register\r
-#define DEV_CLK_EN (1UL<<1)\r
-#define AHB_CLK_EN (1UL<<4)\r
-\r
-// USB Clock Status register\r
-#define DEV_CLK_ON (1UL<<1)\r
-#define AHB_CLK_ON (1UL<<4)\r
-\r
-// USB Device Interupt registers\r
-#define FRAME      (1UL<<0)\r
-#define EP_FAST    (1UL<<1)\r
-#define EP_SLOW    (1UL<<2)\r
-#define DEV_STAT   (1UL<<3)\r
-#define CCEMPTY    (1UL<<4)\r
-#define CDFULL     (1UL<<5)\r
-#define RxENDPKT   (1UL<<6)\r
-#define TxENDPKT   (1UL<<7)\r
-#define EP_RLZED   (1UL<<8)\r
-#define ERR_INT    (1UL<<9)\r
-\r
-// USB Control register\r
-#define RD_EN (1<<0)\r
-#define WR_EN (1<<1)\r
-#define LOG_ENDPOINT(endpoint) ((endpoint>>1)<<2)\r
-\r
-// USB Receive Packet Length register\r
-#define DV      (1UL<<10)\r
-#define PKT_RDY (1UL<<11)\r
-#define PKT_LNGTH_MASK (0x3ff)\r
-\r
-// Serial Interface Engine (SIE)\r
-#define SIE_WRITE   (0x01)\r
-#define SIE_READ    (0x02)\r
-#define SIE_COMMAND (0x05)\r
-#define SIE_CMD_CODE(phase, data) ((phase<<8)|(data<<16))\r
-\r
-// SIE Command codes\r
-#define SIE_CMD_SET_ADDRESS        (0xD0)\r
-#define SIE_CMD_CONFIGURE_DEVICE   (0xD8)\r
-#define SIE_CMD_SET_MODE           (0xF3)\r
-#define SIE_CMD_READ_FRAME_NUMBER  (0xF5)\r
-#define SIE_CMD_READ_TEST_REGISTER (0xFD)\r
-#define SIE_CMD_SET_DEVICE_STATUS  (0xFE)\r
-#define SIE_CMD_GET_DEVICE_STATUS  (0xFE)\r
-#define SIE_CMD_GET_ERROR_CODE     (0xFF)\r
-#define SIE_CMD_READ_ERROR_STATUS  (0xFB)\r
-\r
-#define SIE_CMD_SELECT_ENDPOINT(endpoint)                 (0x00+endpoint)\r
-#define SIE_CMD_SELECT_ENDPOINT_CLEAR_INTERRUPT(endpoint) (0x40+endpoint)\r
-#define SIE_CMD_SET_ENDPOINT_STATUS(endpoint)             (0x40+endpoint)\r
-\r
-#define SIE_CMD_CLEAR_BUFFER    (0xF2)\r
-#define SIE_CMD_VALIDATE_BUFFER (0xFA)\r
-\r
-// SIE Device Status register\r
-#define SIE_DS_CON    (1<<0)\r
-#define SIE_DS_CON_CH (1<<1)\r
-#define SIE_DS_SUS    (1<<2)\r
-#define SIE_DS_SUS_CH (1<<3)\r
-#define SIE_DS_RST    (1<<4)\r
-\r
-// SIE Device Set Address register\r
-#define SIE_DSA_DEV_EN  (1<<7)\r
-\r
-// SIE Configue Device register\r
-#define SIE_CONF_DEVICE (1<<0)\r
-\r
-// Select Endpoint register\r
-#define SIE_SE_FE       (1<<0)\r
-#define SIE_SE_ST       (1<<1)\r
-#define SIE_SE_STP      (1<<2)\r
-#define SIE_SE_PO       (1<<3)\r
-#define SIE_SE_EPN      (1<<4)\r
-#define SIE_SE_B_1_FULL (1<<5)\r
-#define SIE_SE_B_2_FULL (1<<6)\r
-\r
-// Set Endpoint Status command\r
-#define SIE_SES_ST      (1<<0)\r
-#define SIE_SES_DA      (1<<5)\r
-#define SIE_SES_RF_MO   (1<<6)\r
-#define SIE_SES_CND_ST  (1<<7)\r
-\r
-\r
-USBHAL * USBHAL::instance;\r
-\r
-volatile int epComplete;\r
-uint32_t endpointStallState;\r
-\r
-static void SIECommand(uint32_t command) {\r
-    // The command phase of a SIE transaction\r
-    LPC_USB->USBDevIntClr = CCEMPTY;\r
-    LPC_USB->USBCmdCode = SIE_CMD_CODE(SIE_COMMAND, command);\r
-    while (!(LPC_USB->USBDevIntSt & CCEMPTY));\r
-}\r
-\r
-static void SIEWriteData(uint8_t data) {\r
-    // The data write phase of a SIE transaction\r
-    LPC_USB->USBDevIntClr = CCEMPTY;\r
-    LPC_USB->USBCmdCode = SIE_CMD_CODE(SIE_WRITE, data);\r
-    while (!(LPC_USB->USBDevIntSt & CCEMPTY));\r
-}\r
-\r
-static uint8_t SIEReadData(uint32_t command) {\r
-    // The data read phase of a SIE transaction\r
-    LPC_USB->USBDevIntClr = CDFULL;\r
-    LPC_USB->USBCmdCode = SIE_CMD_CODE(SIE_READ, command);\r
-    while (!(LPC_USB->USBDevIntSt & CDFULL));\r
-    return (uint8_t)LPC_USB->USBCmdData;\r
-}\r
-\r
-static void SIEsetDeviceStatus(uint8_t status) {\r
-    // Write SIE device status register\r
-    SIECommand(SIE_CMD_SET_DEVICE_STATUS);\r
-    SIEWriteData(status);\r
-}\r
-\r
-static uint8_t SIEgetDeviceStatus(void) {\r
-    // Read SIE device status register\r
-    SIECommand(SIE_CMD_GET_DEVICE_STATUS);\r
-    return SIEReadData(SIE_CMD_GET_DEVICE_STATUS);\r
-}\r
-\r
-void SIEsetAddress(uint8_t address) {\r
-    // Write SIE device address register\r
-    SIECommand(SIE_CMD_SET_ADDRESS);\r
-    SIEWriteData((address & 0x7f) | SIE_DSA_DEV_EN);\r
-}\r
-\r
-static uint8_t SIEselectEndpoint(uint8_t endpoint) {\r
-    // SIE select endpoint command\r
-    SIECommand(SIE_CMD_SELECT_ENDPOINT(endpoint));\r
-    return SIEReadData(SIE_CMD_SELECT_ENDPOINT(endpoint));\r
-}\r
-\r
-static uint8_t SIEclearBuffer(void) {\r
-    // SIE clear buffer command\r
-    SIECommand(SIE_CMD_CLEAR_BUFFER);\r
-    return SIEReadData(SIE_CMD_CLEAR_BUFFER);\r
-}\r
-\r
-static void SIEvalidateBuffer(void) {\r
-    // SIE validate buffer command\r
-    SIECommand(SIE_CMD_VALIDATE_BUFFER);\r
-}\r
-\r
-static void SIEsetEndpointStatus(uint8_t endpoint, uint8_t status) {\r
-    // SIE set endpoint status command\r
-    SIECommand(SIE_CMD_SET_ENDPOINT_STATUS(endpoint));\r
-    SIEWriteData(status);\r
-}\r
-\r
-static uint16_t SIEgetFrameNumber(void) __attribute__ ((unused));\r
-static uint16_t SIEgetFrameNumber(void) {\r
-    // Read current frame number\r
-    uint16_t lowByte;\r
-    uint16_t highByte;\r
-\r
-    SIECommand(SIE_CMD_READ_FRAME_NUMBER);\r
-    lowByte = SIEReadData(SIE_CMD_READ_FRAME_NUMBER);\r
-    highByte = SIEReadData(SIE_CMD_READ_FRAME_NUMBER);\r
-\r
-    return (highByte << 8) | lowByte;\r
-}\r
-\r
-static void SIEconfigureDevice(void) {\r
-    // SIE Configure device command\r
-    SIECommand(SIE_CMD_CONFIGURE_DEVICE);\r
-    SIEWriteData(SIE_CONF_DEVICE);\r
-}\r
-\r
-static void SIEunconfigureDevice(void) {\r
-    // SIE Configure device command\r
-    SIECommand(SIE_CMD_CONFIGURE_DEVICE);\r
-    SIEWriteData(0);\r
-}\r
-\r
-static void SIEconnect(void) {\r
-    // Connect USB device\r
-    uint8_t status;\r
-\r
-    status = SIEgetDeviceStatus();\r
-    SIEsetDeviceStatus(status | SIE_DS_CON);\r
-}\r
-\r
-\r
-static void SIEdisconnect(void) {\r
-    // Disconnect USB device\r
-    uint8_t status;\r
-\r
-    status = SIEgetDeviceStatus();\r
-    SIEsetDeviceStatus(status & ~SIE_DS_CON);\r
-}\r
-\r
-\r
-static uint8_t selectEndpointClearInterrupt(uint8_t endpoint) {\r
-    // Implemented using using EP_INT_CLR.\r
-    LPC_USB->USBEpIntClr = EP(endpoint);\r
-    while (!(LPC_USB->USBDevIntSt & CDFULL));\r
-    return (uint8_t)LPC_USB->USBCmdData;\r
-}\r
-\r
-\r
-\r
-\r
-\r
-static void enableEndpointEvent(uint8_t endpoint) {\r
-    // Enable an endpoint interrupt\r
-    LPC_USB->USBEpIntEn |= EP(endpoint);\r
-}\r
-\r
-static void disableEndpointEvent(uint8_t endpoint) __attribute__ ((unused));\r
-static void disableEndpointEvent(uint8_t endpoint) {\r
-    // Disable an endpoint interrupt\r
-    LPC_USB->USBEpIntEn &= ~EP(endpoint);\r
-}\r
-\r
-static volatile uint32_t __attribute__((used)) dummyRead;\r
+// USBBusInterface_LPC17_LPC23.c
+// USB Bus Interface for NXP LPC1768 and LPC2368
+// Copyright (c) 2011 ARM Limited. All rights reserved.
+\r
+#ifdef TARGET_LPC1768
+\r
+#include "USBBusInterface.h"
+\r
+\r
+// Get endpoint direction
+#define IN_EP(endpoint)     ((endpoint) & 1U ? true : false)
+#define OUT_EP(endpoint)    ((endpoint) & 1U ? false : true)
+\r
+// Convert physical endpoint number to register bit
+#define EP(endpoint) (1UL<<endpoint)
+\r
+// Power Control for Peripherals register
+#define PCUSB      (1UL<<31)
+\r
+// USB Clock Control register
+#define DEV_CLK_EN (1UL<<1)
+#define AHB_CLK_EN (1UL<<4)
+\r
+// USB Clock Status register
+#define DEV_CLK_ON (1UL<<1)
+#define AHB_CLK_ON (1UL<<4)
+\r
+// USB Device Interupt registers
+#define FRAME      (1UL<<0)
+#define EP_FAST    (1UL<<1)
+#define EP_SLOW    (1UL<<2)
+#define DEV_STAT   (1UL<<3)
+#define CCEMPTY    (1UL<<4)
+#define CDFULL     (1UL<<5)
+#define RxENDPKT   (1UL<<6)
+#define TxENDPKT   (1UL<<7)
+#define EP_RLZED   (1UL<<8)
+#define ERR_INT    (1UL<<9)
+\r
+// USB Control register
+#define RD_EN (1<<0)
+#define WR_EN (1<<1)
+#define LOG_ENDPOINT(endpoint) ((endpoint>>1)<<2)
+\r
+// USB Receive Packet Length register
+#define DV      (1UL<<10)
+#define PKT_RDY (1UL<<11)
+#define PKT_LNGTH_MASK (0x3ff)
+\r
+// Serial Interface Engine (SIE)
+#define SIE_WRITE   (0x01)
+#define SIE_READ    (0x02)
+#define SIE_COMMAND (0x05)
+#define SIE_CMD_CODE(phase, data) ((phase<<8)|(data<<16))
+\r
+// SIE Command codes
+#define SIE_CMD_SET_ADDRESS        (0xD0)
+#define SIE_CMD_CONFIGURE_DEVICE   (0xD8)
+#define SIE_CMD_SET_MODE           (0xF3)
+#define SIE_CMD_READ_FRAME_NUMBER  (0xF5)
+#define SIE_CMD_READ_TEST_REGISTER (0xFD)
+#define SIE_CMD_SET_DEVICE_STATUS  (0xFE)
+#define SIE_CMD_GET_DEVICE_STATUS  (0xFE)
+#define SIE_CMD_GET_ERROR_CODE     (0xFF)
+#define SIE_CMD_READ_ERROR_STATUS  (0xFB)
+\r
+#define SIE_CMD_SELECT_ENDPOINT(endpoint)                 (0x00+endpoint)
+#define SIE_CMD_SELECT_ENDPOINT_CLEAR_INTERRUPT(endpoint) (0x40+endpoint)
+#define SIE_CMD_SET_ENDPOINT_STATUS(endpoint)             (0x40+endpoint)
+\r
+#define SIE_CMD_CLEAR_BUFFER    (0xF2)
+#define SIE_CMD_VALIDATE_BUFFER (0xFA)
+\r
+// SIE Device Status register
+#define SIE_DS_CON    (1<<0)
+#define SIE_DS_CON_CH (1<<1)
+#define SIE_DS_SUS    (1<<2)
+#define SIE_DS_SUS_CH (1<<3)
+#define SIE_DS_RST    (1<<4)
+\r
+// SIE Device Set Address register
+#define SIE_DSA_DEV_EN  (1<<7)
+\r
+// SIE Configue Device register
+#define SIE_CONF_DEVICE (1<<0)
+\r
+// Select Endpoint register
+#define SIE_SE_FE       (1<<0)
+#define SIE_SE_ST       (1<<1)
+#define SIE_SE_STP      (1<<2)
+#define SIE_SE_PO       (1<<3)
+#define SIE_SE_EPN      (1<<4)
+#define SIE_SE_B_1_FULL (1<<5)
+#define SIE_SE_B_2_FULL (1<<6)
+\r
+// Set Endpoint Status command
+#define SIE_SES_ST      (1<<0)
+#define SIE_SES_DA      (1<<5)
+#define SIE_SES_RF_MO   (1<<6)
+#define SIE_SES_CND_ST  (1<<7)
+\r
+\r
+USBHAL * USBHAL::instance;
+\r
+volatile int epComplete;
+uint32_t endpointStallState;
+\r
+static void SIECommand(uint32_t command) {
+    // The command phase of a SIE transaction
+    LPC_USB->USBDevIntClr = CCEMPTY;
+    LPC_USB->USBCmdCode = SIE_CMD_CODE(SIE_COMMAND, command);
+    while (!(LPC_USB->USBDevIntSt & CCEMPTY));
+}
+\r
+static void SIEWriteData(uint8_t data) {
+    // The data write phase of a SIE transaction
+    LPC_USB->USBDevIntClr = CCEMPTY;
+    LPC_USB->USBCmdCode = SIE_CMD_CODE(SIE_WRITE, data);
+    while (!(LPC_USB->USBDevIntSt & CCEMPTY));
+}
+\r
+static uint8_t SIEReadData(uint32_t command) {
+    // The data read phase of a SIE transaction
+    LPC_USB->USBDevIntClr = CDFULL;
+    LPC_USB->USBCmdCode = SIE_CMD_CODE(SIE_READ, command);
+    while (!(LPC_USB->USBDevIntSt & CDFULL));
+    return (uint8_t)LPC_USB->USBCmdData;
+}
+\r
+static void SIEsetDeviceStatus(uint8_t status) {
+    // Write SIE device status register
+    SIECommand(SIE_CMD_SET_DEVICE_STATUS);
+    SIEWriteData(status);
+}
+\r
+static uint8_t SIEgetDeviceStatus(void) {
+    // Read SIE device status register
+    SIECommand(SIE_CMD_GET_DEVICE_STATUS);
+    return SIEReadData(SIE_CMD_GET_DEVICE_STATUS);
+}
+\r
+void SIEsetAddress(uint8_t address) {
+    // Write SIE device address register
+    SIECommand(SIE_CMD_SET_ADDRESS);
+    SIEWriteData((address & 0x7f) | SIE_DSA_DEV_EN);
+}
+\r
+static uint8_t SIEselectEndpoint(uint8_t endpoint) {
+    // SIE select endpoint command
+    SIECommand(SIE_CMD_SELECT_ENDPOINT(endpoint));
+    return SIEReadData(SIE_CMD_SELECT_ENDPOINT(endpoint));
+}
+\r
+static uint8_t SIEclearBuffer(void) {
+    // SIE clear buffer command
+    SIECommand(SIE_CMD_CLEAR_BUFFER);
+    return SIEReadData(SIE_CMD_CLEAR_BUFFER);
+}
+\r
+static void SIEvalidateBuffer(void) {
+    // SIE validate buffer command
+    SIECommand(SIE_CMD_VALIDATE_BUFFER);
+}
+\r
+static void SIEsetEndpointStatus(uint8_t endpoint, uint8_t status) {
+    // SIE set endpoint status command
+    SIECommand(SIE_CMD_SET_ENDPOINT_STATUS(endpoint));
+    SIEWriteData(status);
+}
+\r
+static uint16_t SIEgetFrameNumber(void) __attribute__ ((unused));
+static uint16_t SIEgetFrameNumber(void) {
+    // Read current frame number
+    uint16_t lowByte;
+    uint16_t highByte;
+\r
+    SIECommand(SIE_CMD_READ_FRAME_NUMBER);
+    lowByte = SIEReadData(SIE_CMD_READ_FRAME_NUMBER);
+    highByte = SIEReadData(SIE_CMD_READ_FRAME_NUMBER);
+\r
+    return (highByte << 8) | lowByte;
+}
+\r
+static void SIEconfigureDevice(void) {
+    // SIE Configure device command
+    SIECommand(SIE_CMD_CONFIGURE_DEVICE);
+    SIEWriteData(SIE_CONF_DEVICE);
+}
+\r
+static void SIEunconfigureDevice(void) {
+    // SIE Configure device command
+    SIECommand(SIE_CMD_CONFIGURE_DEVICE);
+    SIEWriteData(0);
+}
+\r
+static void SIEconnect(void) {
+    // Connect USB device
+    uint8_t status;
+\r
+    status = SIEgetDeviceStatus();
+    SIEsetDeviceStatus(status | SIE_DS_CON);
+}
+\r
+\r
+static void SIEdisconnect(void) {
+    // Disconnect USB device
+    uint8_t status;
+\r
+    status = SIEgetDeviceStatus();
+    SIEsetDeviceStatus(status & ~SIE_DS_CON);
+}
+\r
+\r
+static uint8_t selectEndpointClearInterrupt(uint8_t endpoint) {
+    // Implemented using using EP_INT_CLR.
+    LPC_USB->USBEpIntClr = EP(endpoint);
+    while (!(LPC_USB->USBDevIntSt & CDFULL));
+    return (uint8_t)LPC_USB->USBCmdData;
+}
+\r
+\r
+\r
+\r
+\r
+static void enableEndpointEvent(uint8_t endpoint) {
+    // Enable an endpoint interrupt
+    LPC_USB->USBEpIntEn |= EP(endpoint);
+}
+\r
+static void disableEndpointEvent(uint8_t endpoint) __attribute__ ((unused));
+static void disableEndpointEvent(uint8_t endpoint) {
+    // Disable an endpoint interrupt
+    LPC_USB->USBEpIntEn &= ~EP(endpoint);
+}
+\r
+static volatile uint32_t __attribute__((used)) dummyRead;
 \r
 \r
-uint32_t USBHAL::endpointReadcore(uint8_t endpoint, uint8_t *buffer) {\r
-    // Read from an OUT endpoint\r
-    uint32_t size;\r
-    uint32_t i;\r
-    uint32_t data = 0;\r
-    uint8_t offset;\r
+uint32_t USBHAL::endpointReadcore(uint8_t endpoint, uint8_t *buffer) {
+    // Read from an OUT endpoint
+    uint32_t size;
+    uint32_t i;
+    uint32_t data = 0;
+    uint8_t offset;
 \r
-    LPC_USB->USBCtrl = LOG_ENDPOINT(endpoint) | RD_EN;\r
-    while (!(LPC_USB->USBRxPLen & PKT_RDY));\r
+    LPC_USB->USBCtrl = LOG_ENDPOINT(endpoint) | RD_EN;
+    while (!(LPC_USB->USBRxPLen & PKT_RDY));
 \r
-    size = LPC_USB->USBRxPLen & PKT_LNGTH_MASK;\r
+    size = LPC_USB->USBRxPLen & PKT_LNGTH_MASK;
 \r
-    offset = 0;\r
+    offset = 0;
 \r
-    if (size > 0) {\r
-        for (i=0; i<size; i++) {\r
-            if (offset==0) {\r
-                // Fetch up to four bytes of data as a word\r
-                data = LPC_USB->USBRxData;\r
-            }\r
+    if (size > 0) {
+        for (i=0; i<size; i++) {
+            if (offset==0) {
+                // Fetch up to four bytes of data as a word
+                data = LPC_USB->USBRxData;
+            }
 \r
-            // extract a byte\r
-            *buffer = (data>>offset) & 0xff;\r
-            buffer++;\r
+            // extract a byte
+            *buffer = (data>>offset) & 0xff;
+            buffer++;
 \r
-            // move on to the next byte\r
-            offset = (offset + 8) % 32;\r
-        }\r
-    } else {\r
-        dummyRead = LPC_USB->USBRxData;\r
-    }\r
+            // move on to the next byte
+            offset = (offset + 8) % 32;
+        }
+    } else {
+        dummyRead = LPC_USB->USBRxData;
+    }
 \r
-    LPC_USB->USBCtrl = 0;\r
+    LPC_USB->USBCtrl = 0;
 \r
-    if ((endpoint >> 1) % 3 || (endpoint >> 1) == 0) {\r
-        SIEselectEndpoint(endpoint);\r
-        SIEclearBuffer();\r
-    }\r
+    if ((endpoint >> 1) % 3 || (endpoint >> 1) == 0) {
+        SIEselectEndpoint(endpoint);
+        SIEclearBuffer();
+    }
     \r
-    return size;\r
-}\r
+    return size;
+}
 \r
-static void endpointWritecore(uint8_t endpoint, uint8_t *buffer, uint32_t size) {\r
-    // Write to an IN endpoint\r
-    uint32_t temp, data;\r
-    uint8_t offset;\r
+static void endpointWritecore(uint8_t endpoint, uint8_t *buffer, uint32_t size) {
+    // Write to an IN endpoint
+    uint32_t temp, data;
+    uint8_t offset;
 \r
-    LPC_USB->USBCtrl = LOG_ENDPOINT(endpoint) | WR_EN;\r
+    LPC_USB->USBCtrl = LOG_ENDPOINT(endpoint) | WR_EN;
 \r
-    LPC_USB->USBTxPLen = size;\r
-    offset = 0;\r
-    data = 0;\r
+    LPC_USB->USBTxPLen = size;
+    offset = 0;
+    data = 0;
 \r
-    if (size>0) {\r
-        do {\r
-            // Fetch next data byte into a word-sized temporary variable\r
-            temp = *buffer++;\r
+    if (size>0) {
+        do {
+            // Fetch next data byte into a word-sized temporary variable
+            temp = *buffer++;
 \r
-            // Add to current data word\r
-            temp = temp << offset;\r
-            data = data | temp;\r
+            // Add to current data word
+            temp = temp << offset;
+            data = data | temp;
 \r
-            // move on to the next byte\r
-            offset = (offset + 8) % 32;\r
-            size--;\r
+            // move on to the next byte
+            offset = (offset + 8) % 32;
+            size--;
 \r
-            if ((offset==0) || (size==0)) {\r
-                // Write the word to the endpoint\r
-                LPC_USB->USBTxData = data;\r
-                data = 0;\r
-            }\r
-        } while (size>0);\r
-    } else {\r
-        LPC_USB->USBTxData = 0;\r
-    }\r
+            if ((offset==0) || (size==0)) {
+                // Write the word to the endpoint
+                LPC_USB->USBTxData = data;
+                data = 0;
+            }
+        } while (size>0);
+    } else {
+        LPC_USB->USBTxData = 0;
+    }
 \r
-    // Clear WR_EN to cover zero length packet case\r
-    LPC_USB->USBCtrl=0;\r
+    // Clear WR_EN to cover zero length packet case
+    LPC_USB->USBCtrl=0;
 \r
-    SIEselectEndpoint(endpoint);\r
-    SIEvalidateBuffer();\r
-}\r
+    SIEselectEndpoint(endpoint);
+    SIEvalidateBuffer();
+}
 \r
 \r
 \r
@@ -325,311 +325,311 @@ static void endpointWritecore(uint8_t endpoint, uint8_t *buffer, uint32_t size)
 \r
 \r
 \r
-USBHAL::USBHAL(void) {\r
-    // Disable IRQ\r
-    NVIC_DisableIRQ(USB_IRQn);\r
+USBHAL::USBHAL(void) {
+    // Disable IRQ
+    NVIC_DisableIRQ(USB_IRQn);
 \r
-    // Enable power to USB device controller\r
-    LPC_SC->PCONP |= PCUSB;\r
+    // Enable power to USB device controller
+    LPC_SC->PCONP |= PCUSB;
 \r
-    // Enable USB clocks\r
-    LPC_USB->USBClkCtrl |= DEV_CLK_EN | AHB_CLK_EN;\r
-    while (LPC_USB->USBClkSt != (DEV_CLK_ON | AHB_CLK_ON));\r
+    // Enable USB clocks
+    LPC_USB->USBClkCtrl |= DEV_CLK_EN | AHB_CLK_EN;
+    while (LPC_USB->USBClkSt != (DEV_CLK_ON | AHB_CLK_ON));
 \r
-    // Configure pins P0.29 and P0.30 to be USB D+ and USB D-\r
-    LPC_PINCON->PINSEL1 &= 0xc3ffffff;\r
-    LPC_PINCON->PINSEL1 |= 0x14000000;\r
+    // Configure pins P0.29 and P0.30 to be USB D+ and USB D-
+    LPC_PINCON->PINSEL1 &= 0xc3ffffff;
+    LPC_PINCON->PINSEL1 |= 0x14000000;
 \r
-    // Disconnect USB device\r
-    SIEdisconnect();\r
+    // Disconnect USB device
+    SIEdisconnect();
 \r
-    // Configure pin P2.9 to be Connect\r
-    LPC_PINCON->PINSEL4 &= 0xfffcffff;\r
-    LPC_PINCON->PINSEL4 |= 0x00040000;\r
+    // Configure pin P2.9 to be Connect
+    LPC_PINCON->PINSEL4 &= 0xfffcffff;
+    LPC_PINCON->PINSEL4 |= 0x00040000;
 \r
-    // Connect must be low for at least 2.5uS\r
-    wait(0.3);\r
+    // Connect must be low for at least 2.5uS
+    wait(0.3);
 \r
-    // Set the maximum packet size for the control endpoints\r
-    realiseEndpoint(EP0IN, MAX_PACKET_SIZE_EP0, 0);\r
-    realiseEndpoint(EP0OUT, MAX_PACKET_SIZE_EP0, 0);\r
+    // Set the maximum packet size for the control endpoints
+    realiseEndpoint(EP0IN, MAX_PACKET_SIZE_EP0, 0);
+    realiseEndpoint(EP0OUT, MAX_PACKET_SIZE_EP0, 0);
 \r
-    // Attach IRQ\r
-    instance = this;\r
-    NVIC_SetVector(USB_IRQn, (uint32_t)&_usbisr);\r
-    NVIC_EnableIRQ(USB_IRQn);\r
+    // Attach IRQ
+    instance = this;
+    NVIC_SetVector(USB_IRQn, (uint32_t)&_usbisr);
+    NVIC_EnableIRQ(USB_IRQn);
 \r
-    // Enable interrupts for device events and EP0\r
-    LPC_USB->USBDevIntEn = EP_SLOW | DEV_STAT | FRAME;\r
-    enableEndpointEvent(EP0IN);\r
-    enableEndpointEvent(EP0OUT);\r
-}\r
+    // Enable interrupts for device events and EP0
+    LPC_USB->USBDevIntEn = EP_SLOW | DEV_STAT | FRAME;
+    enableEndpointEvent(EP0IN);
+    enableEndpointEvent(EP0OUT);
+}
 \r
-USBHAL::~USBHAL(void) {\r
-    // Ensure device disconnected\r
-    SIEdisconnect();\r
+USBHAL::~USBHAL(void) {
+    // Ensure device disconnected
+    SIEdisconnect();
 \r
-    // Disable USB interrupts\r
-    NVIC_DisableIRQ(USB_IRQn);\r
-}\r
+    // Disable USB interrupts
+    NVIC_DisableIRQ(USB_IRQn);
+}
 \r
-void USBHAL::connect(void) {\r
-    // Connect USB device\r
-    SIEconnect();\r
-}\r
+void USBHAL::connect(void) {
+    // Connect USB device
+    SIEconnect();
+}
 \r
-void USBHAL::disconnect(void) {\r
-    // Disconnect USB device\r
-    SIEdisconnect();\r
-}\r
+void USBHAL::disconnect(void) {
+    // Disconnect USB device
+    SIEdisconnect();
+}
 \r
-void USBHAL::configureDevice(void) {\r
-    SIEconfigureDevice();\r
-}\r
+void USBHAL::configureDevice(void) {
+    SIEconfigureDevice();
+}
 \r
-void USBHAL::unconfigureDevice(void) {\r
-    SIEunconfigureDevice();\r
-}\r
+void USBHAL::unconfigureDevice(void) {
+    SIEunconfigureDevice();
+}
 \r
-void USBHAL::setAddress(uint8_t address) {\r
-    SIEsetAddress(address);\r
-}\r
+void USBHAL::setAddress(uint8_t address) {
+    SIEsetAddress(address);
+}
 \r
-void USBHAL::EP0setup(uint8_t *buffer) {\r
-    endpointReadcore(EP0OUT, buffer);\r
-}\r
+void USBHAL::EP0setup(uint8_t *buffer) {
+    endpointReadcore(EP0OUT, buffer);
+}
 \r
-void USBHAL::EP0read(void) {\r
-    // Not required\r
-}\r
+void USBHAL::EP0read(void) {
+    // Not required
+}
 \r
-uint32_t USBHAL::EP0getReadResult(uint8_t *buffer) {\r
-    return endpointReadcore(EP0OUT, buffer);\r
-}\r
+uint32_t USBHAL::EP0getReadResult(uint8_t *buffer) {
+    return endpointReadcore(EP0OUT, buffer);
+}
 \r
-void USBHAL::EP0write(uint8_t *buffer, uint32_t size) {\r
-    endpointWritecore(EP0IN, buffer, size);\r
-}\r
+void USBHAL::EP0write(uint8_t *buffer, uint32_t size) {
+    endpointWritecore(EP0IN, buffer, size);
+}
 \r
-void USBHAL::EP0getWriteResult(void) {\r
-    // Not required\r
-}\r
+void USBHAL::EP0getWriteResult(void) {
+    // Not required
+}
 \r
-void USBHAL::EP0stall(void) {\r
-    // This will stall both control endpoints\r
-    stallEndpoint(EP0OUT);\r
-}\r
+void USBHAL::EP0stall(void) {
+    // This will stall both control endpoints
+    stallEndpoint(EP0OUT);
+}
 \r
-EP_STATUS USBHAL::endpointRead(uint8_t endpoint, uint32_t maximumSize) {\r
-    return EP_PENDING;\r
-}\r
+EP_STATUS USBHAL::endpointRead(uint8_t endpoint, uint32_t maximumSize) {
+    return EP_PENDING;
+}
 \r
-EP_STATUS USBHAL::endpointReadResult(uint8_t endpoint, uint8_t * buffer, uint32_t *bytesRead) {\r
-\r
-    //for isochronous endpoint, we don't wait an interrupt\r
-    if ((endpoint >> 1) % 3 || (endpoint >> 1) == 0) {\r
-        if (!(epComplete & EP(endpoint)))\r
-            return EP_PENDING;\r
-    }\r
+EP_STATUS USBHAL::endpointReadResult(uint8_t endpoint, uint8_t * buffer, uint32_t *bytesRead) {
+\r
+    //for isochronous endpoint, we don't wait an interrupt
+    if ((endpoint >> 1) % 3 || (endpoint >> 1) == 0) {
+        if (!(epComplete & EP(endpoint)))
+            return EP_PENDING;
+    }
     \r
-    *bytesRead = endpointReadcore(endpoint, buffer);\r
-    epComplete &= ~EP(endpoint);\r
-    return EP_COMPLETED;\r
-}\r
+    *bytesRead = endpointReadcore(endpoint, buffer);
+    epComplete &= ~EP(endpoint);
+    return EP_COMPLETED;
+}
 \r
-EP_STATUS USBHAL::endpointWrite(uint8_t endpoint, uint8_t *data, uint32_t size) {\r
-    if (getEndpointStallState(endpoint)) {\r
-        return EP_STALLED;\r
-    }\r
+EP_STATUS USBHAL::endpointWrite(uint8_t endpoint, uint8_t *data, uint32_t size) {
+    if (getEndpointStallState(endpoint)) {
+        return EP_STALLED;
+    }
 \r
-    epComplete &= ~EP(endpoint);\r
+    epComplete &= ~EP(endpoint);
 \r
-    endpointWritecore(endpoint, data, size);\r
-    return EP_PENDING;\r
-}\r
+    endpointWritecore(endpoint, data, size);
+    return EP_PENDING;
+}
 \r
-EP_STATUS USBHAL::endpointWriteResult(uint8_t endpoint) {\r
-    if (epComplete & EP(endpoint)) {\r
-        epComplete &= ~EP(endpoint);\r
-        return EP_COMPLETED;\r
-    }\r
+EP_STATUS USBHAL::endpointWriteResult(uint8_t endpoint) {
+    if (epComplete & EP(endpoint)) {
+        epComplete &= ~EP(endpoint);
+        return EP_COMPLETED;
+    }
 \r
-    return EP_PENDING;\r
-}\r
-\r
-bool USBHAL::realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, uint32_t flags) {\r
-    // Realise an endpoint\r
-    LPC_USB->USBDevIntClr = EP_RLZED;\r
-    LPC_USB->USBReEp |= EP(endpoint);\r
-    LPC_USB->USBEpInd = endpoint;\r
-    LPC_USB->USBMaxPSize = maxPacket;\r
-\r
-    while (!(LPC_USB->USBDevIntSt & EP_RLZED));\r
-    LPC_USB->USBDevIntClr = EP_RLZED;\r
-\r
-    // Clear stall state\r
-    endpointStallState &= ~EP(endpoint);\r
-\r
-    enableEndpointEvent(endpoint);\r
-    return true;\r
-}\r
-\r
-void USBHAL::stallEndpoint(uint8_t endpoint) {\r
-    // Stall an endpoint\r
-    if ( (endpoint==EP0IN) || (endpoint==EP0OUT) ) {\r
-        // Conditionally stall both control endpoints\r
-        SIEsetEndpointStatus(EP0OUT, SIE_SES_CND_ST);\r
-    } else {\r
-        SIEsetEndpointStatus(endpoint, SIE_SES_ST);\r
-\r
-        // Update stall state\r
-        endpointStallState |= EP(endpoint);\r
-    }\r
-}\r
-\r
-void USBHAL::unstallEndpoint(uint8_t endpoint) {\r
-    // Unstall an endpoint. The endpoint will also be reinitialised\r
-    SIEsetEndpointStatus(endpoint, 0);\r
-\r
-    // Update stall state\r
-    endpointStallState &= ~EP(endpoint);\r
-}\r
-\r
-bool USBHAL::getEndpointStallState(uint8_t endpoint) {\r
-    // Returns true if endpoint stalled\r
-    return endpointStallState & EP(endpoint);\r
-}\r
-\r
-void USBHAL::remoteWakeup(void) {\r
-    // Remote wakeup\r
-    uint8_t status;\r
-\r
-    // Enable USB clocks\r
-    LPC_USB->USBClkCtrl |= DEV_CLK_EN | AHB_CLK_EN;\r
-    while (LPC_USB->USBClkSt != (DEV_CLK_ON | AHB_CLK_ON));\r
-\r
-    status = SIEgetDeviceStatus();\r
-    SIEsetDeviceStatus(status & ~SIE_DS_SUS);\r
-}\r
-\r
-\r
-\r
-\r
-\r
-void USBHAL::_usbisr(void) {\r
-    instance->usbisr();\r
-}\r
-\r
-\r
-void USBHAL::usbisr(void) {\r
-    uint8_t devStat;\r
-\r
-    if (LPC_USB->USBDevIntSt & FRAME) {\r
-        // Start of frame event\r
-        SOF(SIEgetFrameNumber());\r
-        // Clear interrupt status flag\r
-        LPC_USB->USBDevIntClr = FRAME;\r
-    }\r
-\r
-    if (LPC_USB->USBDevIntSt & DEV_STAT) {\r
-        // Device Status interrupt\r
-        // Must clear the interrupt status flag before reading the device status from the SIE\r
-        LPC_USB->USBDevIntClr = DEV_STAT;\r
-\r
-        // Read device status from SIE\r
-        devStat = SIEgetDeviceStatus();\r
-\r
-        if (devStat & SIE_DS_RST) {\r
-            // Bus reset\r
-            busReset();\r
-        }\r
-    }\r
-\r
-    if (LPC_USB->USBDevIntSt & EP_SLOW) {\r
-        // (Slow) Endpoint Interrupt\r
-\r
-        // Process each endpoint interrupt\r
-        if (LPC_USB->USBEpIntSt & EP(EP0OUT)) {\r
-            if (selectEndpointClearInterrupt(EP0OUT) & SIE_SE_STP) {\r
-                // this is a setup packet\r
-                EP0setupCallback();\r
-            } else {\r
-                EP0out();\r
-            }\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-        }\r
-\r
-        if (LPC_USB->USBEpIntSt & EP(EP0IN)) {\r
-            selectEndpointClearInterrupt(EP0IN);\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-            EP0in();\r
-        }\r
-\r
-        // TODO: This should cover all endpoints, not just EP1,2,3:\r
-        if (LPC_USB->USBEpIntSt & EP(EP1IN)) {\r
-            selectEndpointClearInterrupt(EP1IN);\r
-            epComplete |= EP(EP1IN);\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-            if (EP1_IN_callback())\r
-                epComplete &= ~EP(EP1IN);\r
-        }\r
-\r
-        if (LPC_USB->USBEpIntSt & EP(EP1OUT)) {\r
-            selectEndpointClearInterrupt(EP1OUT);\r
-            epComplete |= EP(EP1OUT);\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-            if (EP1_OUT_callback())\r
-                epComplete &= ~EP(EP1OUT);\r
-        }\r
-\r
-        if (LPC_USB->USBEpIntSt & EP(EP2IN)) {\r
-            selectEndpointClearInterrupt(EP2IN);\r
-            epComplete |= EP(EP2IN);\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-            if (EP2_IN_callback())\r
-                epComplete &= ~EP(EP2IN);\r
-        }\r
-\r
-        if (LPC_USB->USBEpIntSt & EP(EP2OUT)) {\r
-            selectEndpointClearInterrupt(EP2OUT);\r
-            epComplete |= EP(EP2OUT);\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-            if (EP2_OUT_callback())\r
-                epComplete &= ~EP(EP2OUT);\r
-        }\r
-\r
-        if (LPC_USB->USBEpIntSt & EP(EP3IN)) {\r
-            selectEndpointClearInterrupt(EP3IN);\r
-            epComplete |= EP(EP3IN);\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-            if (EP3_IN_callback())\r
-                epComplete &= ~EP(EP3IN);\r
-        }\r
-\r
-        if (LPC_USB->USBEpIntSt & EP(EP3OUT)) {\r
-            selectEndpointClearInterrupt(EP3OUT);\r
-            epComplete |= EP(EP3OUT);\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-            if (EP3_OUT_callback())\r
-                epComplete &= ~EP(EP3OUT);\r
-        }\r
-\r
-        if (LPC_USB->USBEpIntSt & EP(EP5IN)) {\r
-            selectEndpointClearInterrupt(EP5IN);\r
-            epComplete |= EP(EP5IN);\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-            if (EP5_IN_callback())\r
-                epComplete &= ~EP(EP5IN);\r
-        }\r
-\r
-        if (LPC_USB->USBEpIntSt & EP(EP5OUT)) {\r
-            selectEndpointClearInterrupt(EP5OUT);\r
-            epComplete |= EP(EP5OUT);\r
-            LPC_USB->USBDevIntClr = EP_SLOW;\r
-            if (EP5_OUT_callback())\r
-                epComplete &= ~EP(EP5OUT);\r
-        }\r
-    }\r
-}\r
-\r
-#endif\r
+    return EP_PENDING;
+}
+\r
+bool USBHAL::realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, uint32_t flags) {
+    // Realise an endpoint
+    LPC_USB->USBDevIntClr = EP_RLZED;
+    LPC_USB->USBReEp |= EP(endpoint);
+    LPC_USB->USBEpInd = endpoint;
+    LPC_USB->USBMaxPSize = maxPacket;
+\r
+    while (!(LPC_USB->USBDevIntSt & EP_RLZED));
+    LPC_USB->USBDevIntClr = EP_RLZED;
+\r
+    // Clear stall state
+    endpointStallState &= ~EP(endpoint);
+\r
+    enableEndpointEvent(endpoint);
+    return true;
+}
+\r
+void USBHAL::stallEndpoint(uint8_t endpoint) {
+    // Stall an endpoint
+    if ( (endpoint==EP0IN) || (endpoint==EP0OUT) ) {
+        // Conditionally stall both control endpoints
+        SIEsetEndpointStatus(EP0OUT, SIE_SES_CND_ST);
+    } else {
+        SIEsetEndpointStatus(endpoint, SIE_SES_ST);
+\r
+        // Update stall state
+        endpointStallState |= EP(endpoint);
+    }
+}
+\r
+void USBHAL::unstallEndpoint(uint8_t endpoint) {
+    // Unstall an endpoint. The endpoint will also be reinitialised
+    SIEsetEndpointStatus(endpoint, 0);
+\r
+    // Update stall state
+    endpointStallState &= ~EP(endpoint);
+}
+\r
+bool USBHAL::getEndpointStallState(uint8_t endpoint) {
+    // Returns true if endpoint stalled
+    return endpointStallState & EP(endpoint);
+}
+\r
+void USBHAL::remoteWakeup(void) {
+    // Remote wakeup
+    uint8_t status;
+\r
+    // Enable USB clocks
+    LPC_USB->USBClkCtrl |= DEV_CLK_EN | AHB_CLK_EN;
+    while (LPC_USB->USBClkSt != (DEV_CLK_ON | AHB_CLK_ON));
+\r
+    status = SIEgetDeviceStatus();
+    SIEsetDeviceStatus(status & ~SIE_DS_SUS);
+}
+\r
+\r
+\r
+\r
+\r
+void USBHAL::_usbisr(void) {
+    instance->usbisr();
+}
+\r
+\r
+void USBHAL::usbisr(void) {
+    uint8_t devStat;
+\r
+    if (LPC_USB->USBDevIntSt & FRAME) {
+        // Start of frame event
+        SOF(SIEgetFrameNumber());
+        // Clear interrupt status flag
+        LPC_USB->USBDevIntClr = FRAME;
+    }
+\r
+    if (LPC_USB->USBDevIntSt & DEV_STAT) {
+        // Device Status interrupt
+        // Must clear the interrupt status flag before reading the device status from the SIE
+        LPC_USB->USBDevIntClr = DEV_STAT;
+\r
+        // Read device status from SIE
+        devStat = SIEgetDeviceStatus();
+\r
+        if (devStat & SIE_DS_RST) {
+            // Bus reset
+            busReset();
+        }
+    }
+\r
+    if (LPC_USB->USBDevIntSt & EP_SLOW) {
+        // (Slow) Endpoint Interrupt
+\r
+        // Process each endpoint interrupt
+        if (LPC_USB->USBEpIntSt & EP(EP0OUT)) {
+            if (selectEndpointClearInterrupt(EP0OUT) & SIE_SE_STP) {
+                // this is a setup packet
+                EP0setupCallback();
+            } else {
+                EP0out();
+            }
+            LPC_USB->USBDevIntClr = EP_SLOW;
+        }
+\r
+        if (LPC_USB->USBEpIntSt & EP(EP0IN)) {
+            selectEndpointClearInterrupt(EP0IN);
+            LPC_USB->USBDevIntClr = EP_SLOW;
+            EP0in();
+        }
+\r
+        // TODO: This should cover all endpoints, not just EP1,2,3:
+        if (LPC_USB->USBEpIntSt & EP(EP1IN)) {
+            selectEndpointClearInterrupt(EP1IN);
+            epComplete |= EP(EP1IN);
+            LPC_USB->USBDevIntClr = EP_SLOW;
+            if (EP1_IN_callback())
+                epComplete &= ~EP(EP1IN);
+        }
+\r
+        if (LPC_USB->USBEpIntSt & EP(EP1OUT)) {
+            selectEndpointClearInterrupt(EP1OUT);
+            epComplete |= EP(EP1OUT);
+            LPC_USB->USBDevIntClr = EP_SLOW;
+            if (EP1_OUT_callback())
+                epComplete &= ~EP(EP1OUT);
+        }
+\r
+        if (LPC_USB->USBEpIntSt & EP(EP2IN)) {
+            selectEndpointClearInterrupt(EP2IN);
+            epComplete |= EP(EP2IN);
+            LPC_USB->USBDevIntClr = EP_SLOW;
+            if (EP2_IN_callback())
+                epComplete &= ~EP(EP2IN);
+        }
+\r
+        if (LPC_USB->USBEpIntSt & EP(EP2OUT)) {
+            selectEndpointClearInterrupt(EP2OUT);
+            epComplete |= EP(EP2OUT);
+            LPC_USB->USBDevIntClr = EP_SLOW;
+            if (EP2_OUT_callback())
+                epComplete &= ~EP(EP2OUT);
+        }
+\r
+        if (LPC_USB->USBEpIntSt & EP(EP3IN)) {
+            selectEndpointClearInterrupt(EP3IN);
+            epComplete |= EP(EP3IN);
+            LPC_USB->USBDevIntClr = EP_SLOW;
+            if (EP3_IN_callback())
+                epComplete &= ~EP(EP3IN);
+        }
+\r
+        if (LPC_USB->USBEpIntSt & EP(EP3OUT)) {
+            selectEndpointClearInterrupt(EP3OUT);
+            epComplete |= EP(EP3OUT);
+            LPC_USB->USBDevIntClr = EP_SLOW;
+            if (EP3_OUT_callback())
+                epComplete &= ~EP(EP3OUT);
+        }
+\r
+        if (LPC_USB->USBEpIntSt & EP(EP5IN)) {
+            selectEndpointClearInterrupt(EP5IN);
+            epComplete |= EP(EP5IN);
+            LPC_USB->USBDevIntClr = EP_SLOW;
+            if (EP5_IN_callback())
+                epComplete &= ~EP(EP5IN);
+        }
+\r
+        if (LPC_USB->USBEpIntSt & EP(EP5OUT)) {
+            selectEndpointClearInterrupt(EP5OUT);
+            epComplete |= EP(EP5OUT);
+            LPC_USB->USBDevIntClr = EP_SLOW;
+            if (EP5_OUT_callback())
+                epComplete &= ~EP(EP5OUT);
+        }
+    }
+}
+\r
+#endif
index dcb2cec..a8f9607 100644 (file)
@@ -1,60 +1,60 @@
-/* USBDescriptor.h */\r
-/* Definitions and macros for constructing USB descriptors */\r
-/* Copyright (c) 2011 ARM Limited. All rights reserved. */\r
-\r
-/* Standard descriptor types */\r
-#define DEVICE_DESCRIPTOR        (1)\r
-#define CONFIGURATION_DESCRIPTOR (2)\r
-#define STRING_DESCRIPTOR        (3)\r
-#define INTERFACE_DESCRIPTOR     (4)\r
-#define ENDPOINT_DESCRIPTOR      (5)\r
-#define QUALIFIER_DESCRIPTOR     (6)\r
-\r
-/* Standard descriptor lengths */\r
-#define DEVICE_DESCRIPTOR_LENGTH        (0x12)\r
-#define CONFIGURATION_DESCRIPTOR_LENGTH (0x09)\r
-#define INTERFACE_DESCRIPTOR_LENGTH     (0x09)\r
-#define ENDPOINT_DESCRIPTOR_LENGTH      (0x07)\r
-\r
-\r
-/*string offset*/\r
-#define STRING_OFFSET_LANGID            (0)\r
-#define STRING_OFFSET_IMANUFACTURER     (1)\r
-#define STRING_OFFSET_IPRODUCT          (2)\r
-#define STRING_OFFSET_ISERIAL           (3)\r
-#define STRING_OFFSET_ICONFIGURATION    (4)\r
-#define STRING_OFFSET_IINTERFACE        (5)\r
-\r
-/* USB Specification Release Number */\r
-#define USB_VERSION_2_0 (0x0200)\r
-\r
-/* Least/Most significant byte of short integer */\r
-#define LSB(n)  ((uint8_t)((n)&0xff))\r
-#define MSB(n)  ((uint8_t)(((n)&0xff00)>>8))\r
-\r
-/* Convert physical endpoint number to descriptor endpoint number */\r
-#define PHY_TO_DESC(endpoint) (((endpoint)>>1) | (((endpoint) & 1) ? 0x80:0))\r
-\r
-/* bmAttributes in configuration descriptor */\r
-/* C_RESERVED must always be set */\r
-#define C_RESERVED      (1U<<7)\r
-#define C_SELF_POWERED  (1U<<6)\r
-#define C_REMOTE_WAKEUP (1U<<5)\r
-\r
-/* bMaxPower in configuration descriptor */\r
-#define C_POWER(mA)     ((mA)/2)\r
-\r
-/* bmAttributes in endpoint descriptor */\r
-#define E_CONTROL       (0x00)\r
-#define E_ISOCHRONOUS   (0x01)\r
-#define E_BULK          (0x02)\r
-#define E_INTERRUPT     (0x03)\r
-\r
-/* For isochronous endpoints only: */\r
-#define E_NO_SYNCHRONIZATION    (0x00)\r
-#define E_ASYNCHRONOUS          (0x04)\r
-#define E_ADAPTIVE              (0x08)\r
-#define E_SYNCHRONOUS           (0x0C)\r
-#define E_DATA                  (0x00)\r
-#define E_FEEDBACK              (0x10)\r
-#define E_IMPLICIT_FEEDBACK     (0x20)\r
+/* USBDescriptor.h */
+/* Definitions and macros for constructing USB descriptors */
+/* Copyright (c) 2011 ARM Limited. All rights reserved. */
+\r
+/* Standard descriptor types */
+#define DEVICE_DESCRIPTOR        (1)
+#define CONFIGURATION_DESCRIPTOR (2)
+#define STRING_DESCRIPTOR        (3)
+#define INTERFACE_DESCRIPTOR     (4)
+#define ENDPOINT_DESCRIPTOR      (5)
+#define QUALIFIER_DESCRIPTOR     (6)
+\r
+/* Standard descriptor lengths */
+#define DEVICE_DESCRIPTOR_LENGTH        (0x12)
+#define CONFIGURATION_DESCRIPTOR_LENGTH (0x09)
+#define INTERFACE_DESCRIPTOR_LENGTH     (0x09)
+#define ENDPOINT_DESCRIPTOR_LENGTH      (0x07)
+\r
+\r
+/*string offset*/
+#define STRING_OFFSET_LANGID            (0)
+#define STRING_OFFSET_IMANUFACTURER     (1)
+#define STRING_OFFSET_IPRODUCT          (2)
+#define STRING_OFFSET_ISERIAL           (3)
+#define STRING_OFFSET_ICONFIGURATION    (4)
+#define STRING_OFFSET_IINTERFACE        (5)
+\r
+/* USB Specification Release Number */
+#define USB_VERSION_2_0 (0x0200)
+\r
+/* Least/Most significant byte of short integer */
+#define LSB(n)  ((uint8_t)((n)&0xff))
+#define MSB(n)  ((uint8_t)(((n)&0xff00)>>8))
+\r
+/* Convert physical endpoint number to descriptor endpoint number */
+#define PHY_TO_DESC(endpoint) (((endpoint)>>1) | (((endpoint) & 1) ? 0x80:0))
+\r
+/* bmAttributes in configuration descriptor */
+/* C_RESERVED must always be set */
+#define C_RESERVED      (1U<<7)
+#define C_SELF_POWERED  (1U<<6)
+#define C_REMOTE_WAKEUP (1U<<5)
+\r
+/* bMaxPower in configuration descriptor */
+#define C_POWER(mA)     ((mA)/2)
+\r
+/* bmAttributes in endpoint descriptor */
+#define E_CONTROL       (0x00)
+#define E_ISOCHRONOUS   (0x01)
+#define E_BULK          (0x02)
+#define E_INTERRUPT     (0x03)
+\r
+/* For isochronous endpoints only: */
+#define E_NO_SYNCHRONIZATION    (0x00)
+#define E_ASYNCHRONOUS          (0x04)
+#define E_ADAPTIVE              (0x08)
+#define E_SYNCHRONOUS           (0x0C)
+#define E_DATA                  (0x00)
+#define E_FEEDBACK              (0x10)
+#define E_IMPLICIT_FEEDBACK     (0x20)
index 1663f77..649b958 100644 (file)
-/* USBDevice.c */\r
-/* Generic USB device */\r
-/* Copyright (c) 2011 ARM Limited. All rights reserved. */\r
-\r
-/* Reference: */\r
-/* Universal Serial Bus Specification Revision 2.0, Chapter 9 "USB Device Framework" */\r
-\r
-#include "stdint.h"\r
-\r
-#include "USBEndpoints.h"\r
-#include "USBDevice.h"\r
-#include "USBDescriptor.h"\r
-#include "USBHID_Types.h"\r
-\r
-\r
-/* Device status */\r
-#define DEVICE_STATUS_SELF_POWERED  (1U<<0)\r
-#define DEVICE_STATUS_REMOTE_WAKEUP (1U<<1)\r
-\r
-/* Endpoint status */\r
-#define ENDPOINT_STATUS_HALT        (1U<<0)\r
-\r
-/* Standard feature selectors */\r
-#define DEVICE_REMOTE_WAKEUP        (1)\r
-#define ENDPOINT_HALT               (0)\r
-\r
-/* Macro to convert wIndex endpoint number to physical endpoint number */\r
-#define WINDEX_TO_PHYSICAL(endpoint) (((endpoint & 0x0f) << 1) + \\r
-    ((endpoint & 0x80) ? 1 : 0))\r
-\r
-\r
-bool USBDevice::requestGetDescriptor(void)\r
-{\r
-    bool success = false;\r
-\r
-    switch (DESCRIPTOR_TYPE(transfer.setup.wValue))\r
-    {\r
-        case DEVICE_DESCRIPTOR:\r
-            if (deviceDesc() != NULL)\r
-            {\r
-                if ((deviceDesc()[0] == DEVICE_DESCRIPTOR_LENGTH) \\r
-                    && (deviceDesc()[1] == DEVICE_DESCRIPTOR))\r
-                {\r
-                    transfer.remaining = DEVICE_DESCRIPTOR_LENGTH;\r
-                    transfer.ptr = deviceDesc();\r
-                    transfer.direction = DEVICE_TO_HOST;\r
-                    success = true;\r
-                }\r
-            }\r
-            break;\r
-        case CONFIGURATION_DESCRIPTOR:\r
-            if (configurationDesc() != NULL)\r
-            {\r
-                if ((configurationDesc()[0] == CONFIGURATION_DESCRIPTOR_LENGTH) \\r
-                    && (configurationDesc()[1] == CONFIGURATION_DESCRIPTOR))\r
-                {\r
-                    /* Get wTotalLength */\r
-                    transfer.remaining = configurationDesc()[2] \\r
-                        | (configurationDesc()[3] << 8);\r
-\r
-                    transfer.ptr = configurationDesc();\r
-                    transfer.direction = DEVICE_TO_HOST;\r
-                    success = true;\r
-                }\r
-            }\r
-            break;\r
-        case STRING_DESCRIPTOR:\r
-            switch (DESCRIPTOR_INDEX(transfer.setup.wValue))\r
-            {\r
-                            case STRING_OFFSET_LANGID:\r
-                                transfer.remaining = stringLangidDesc()[0];\r
-                                transfer.ptr = stringLangidDesc();\r
-                                transfer.direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break;\r
-                            case STRING_OFFSET_IMANUFACTURER:\r
-                                transfer.remaining =  stringImanufacturerDesc()[0];\r
-                                transfer.ptr = stringImanufacturerDesc();\r
-                                transfer.direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break;       \r
-                            case STRING_OFFSET_IPRODUCT:\r
-                                transfer.remaining = stringIproductDesc()[0];\r
-                                transfer.ptr = stringIproductDesc();\r
-                                transfer.direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break;            \r
-                            case STRING_OFFSET_ISERIAL:\r
-                                transfer.remaining = stringIserialDesc()[0];\r
-                                transfer.ptr = stringIserialDesc();\r
-                                transfer.direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break;        \r
-                            case STRING_OFFSET_ICONFIGURATION:\r
-                                transfer.remaining = stringIConfigurationDesc()[0];\r
-                                transfer.ptr = stringIConfigurationDesc();\r
-                                transfer.direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break; \r
-                            case STRING_OFFSET_IINTERFACE:\r
-                                transfer.remaining = stringIinterfaceDesc()[0];\r
-                                transfer.ptr = stringIinterfaceDesc();\r
-                                transfer.direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                                break; \r
-            }\r
-            break;\r
-        case INTERFACE_DESCRIPTOR:\r
-        case ENDPOINT_DESCRIPTOR:\r
-            /* TODO: Support is optional, not implemented here */\r
-            break;\r
-        default:\r
-            break;\r
-    }\r
-\r
-    return success;\r
-}\r
-\r
-void USBDevice::decodeSetupPacket(uint8_t *data, SETUP_PACKET *packet)\r
-{\r
-    /* Fill in the elements of a SETUP_PACKET structure from raw data */\r
-    packet->bmRequestType.dataTransferDirection = (data[0] & 0x80) >> 7;\r
-    packet->bmRequestType.Type = (data[0] & 0x60) >> 5;\r
-    packet->bmRequestType.Recipient = data[0] & 0x1f;\r
-    packet->bRequest = data[1];\r
-    packet->wValue = (data[2] | (uint16_t)data[3] << 8);\r
-    packet->wIndex = (data[4] | (uint16_t)data[5] << 8);\r
-    packet->wLength = (data[6] | (uint16_t)data[7] << 8);\r
-}\r
-\r
-\r
-bool USBDevice::controlOut(void)\r
-{\r
-    /* Control transfer data OUT stage */\r
-    uint8_t buffer[MAX_PACKET_SIZE_EP0];\r
-    uint32_t packetSize;\r
-\r
-    /* Check we should be transferring data OUT */\r
-    if (transfer.direction != HOST_TO_DEVICE)\r
-    {\r
-        return false;\r
-    }\r
-\r
-    /* Read from endpoint */\r
-    packetSize = EP0getReadResult(buffer);\r
-\r
-    /* Check if transfer size is valid */\r
-    if (packetSize > transfer.remaining)\r
-    {\r
-        /* Too big */\r
-        return false;\r
-    }\r
-\r
-    /* Update transfer */\r
-    transfer.ptr += packetSize;\r
-    transfer.remaining -= packetSize;\r
-\r
-    /* Check if transfer has completed */\r
-    if (transfer.remaining == 0)\r
-    {\r
-        /* Transfer completed */\r
-        if (transfer.notify)\r
-        {\r
-            /* Notify class layer. */\r
-            USBCallback_requestCompleted(buffer, packetSize);\r
-            transfer.notify = false;\r
-        }\r
-        /* Status stage */\r
-        EP0write(NULL, 0);\r
-    }\r
-    else\r
-    {\r
-        EP0read();\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-bool USBDevice::controlIn(void)\r
-{\r
-    /* Control transfer data IN stage */\r
-    uint32_t packetSize;\r
-\r
-    /* Check if transfer has completed (status stage transactions */\r
-    /* also have transfer.remaining == 0) */\r
-    if (transfer.remaining == 0)\r
-    {\r
-        if (transfer.zlp)\r
-        {\r
-            /* Send zero length packet */\r
-            EP0write(NULL, 0);\r
-            transfer.zlp = false;\r
-        }\r
-\r
-        /* Transfer completed */\r
-        if (transfer.notify)\r
-        {\r
-            /* Notify class layer. */\r
-            USBCallback_requestCompleted(NULL, 0);\r
-            transfer.notify = false;\r
-        }\r
-\r
-        EP0read();\r
-\r
-        /* Completed */\r
-        return true;\r
-    }\r
-\r
-    /* Check we should be transferring data IN */\r
-    if (transfer.direction != DEVICE_TO_HOST)\r
-    {\r
-        return false;\r
-    }\r
-\r
-    packetSize = transfer.remaining;\r
-\r
-    if (packetSize > MAX_PACKET_SIZE_EP0)\r
-    {\r
-        packetSize = MAX_PACKET_SIZE_EP0;\r
-    }\r
-\r
-    /* Write to endpoint */\r
-    EP0write(transfer.ptr, packetSize);\r
-\r
-    /* Update transfer */\r
-    transfer.ptr += packetSize;\r
-    transfer.remaining -= packetSize;\r
-\r
-    return true;\r
-}\r
-\r
-bool USBDevice::requestSetAddress(void)\r
-{\r
-    /* Set the device address */\r
-    setAddress(transfer.setup.wValue);\r
-\r
-    if (transfer.setup.wValue == 0)\r
-    {\r
-        device.state = DEFAULT;\r
-    }\r
-    else\r
-    {\r
-        device.state = ADDRESS;\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-bool USBDevice::requestSetConfiguration(void)\r
-{\r
-\r
-    device.configuration = transfer.setup.wValue;\r
-    /* Set the device configuration */\r
-    if (device.configuration == 0)\r
-    {\r
-        /* Not configured */\r
-        unconfigureDevice();\r
-        device.state = ADDRESS;\r
-    }\r
-    else\r
-    {\r
-        if (USBCallback_setConfiguration(device.configuration))\r
-        {\r
-            /* Valid configuration */\r
-            configureDevice();\r
-            device.state = CONFIGURED;\r
-        }\r
-        else\r
-        {\r
-            return false;\r
-        }\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-bool USBDevice::requestGetConfiguration(void)\r
-{\r
-    /* Send the device configuration */\r
-    transfer.ptr = &device.configuration;\r
-    transfer.remaining = sizeof(device.configuration);\r
-    transfer.direction = DEVICE_TO_HOST;\r
-    return true;\r
-}\r
-\r
-bool USBDevice::requestGetInterface(void)\r
-{\r
-    /* Return the selected alternate setting for an interface */\r
-\r
-    if (device.state != CONFIGURED)\r
-    {\r
-        return false;\r
-    }\r
-\r
-    /* Send the alternate setting */\r
-    transfer.setup.wIndex = currentInterface;\r
-    transfer.ptr = &currentAlternate;\r
-    transfer.remaining = sizeof(currentAlternate);\r
-    transfer.direction = DEVICE_TO_HOST;\r
-    return true;\r
-}\r
-\r
-bool USBDevice::requestSetInterface(void)\r
-{\r
-    bool success = false;\r
-    if(USBCallback_setInterface(transfer.setup.wIndex, transfer.setup.wValue))\r
-    {\r
-        success = true;\r
-        currentInterface = transfer.setup.wIndex;\r
-        currentAlternate = transfer.setup.wValue;       \r
-    }\r
-    return success;\r
-}\r
-\r
-bool USBDevice::requestSetFeature()\r
-{\r
-    bool success = false;\r
-\r
-    if (device.state != CONFIGURED)\r
-    {\r
-        /* Endpoint or interface must be zero */\r
-        if (transfer.setup.wIndex != 0)\r
-        {\r
-            return false;\r
-        }\r
-    }\r
-\r
-    switch (transfer.setup.bmRequestType.Recipient)\r
-    {\r
-        case DEVICE_RECIPIENT:\r
-            /* TODO: Remote wakeup feature not supported */\r
-            break;\r
-        case ENDPOINT_RECIPIENT:\r
-            if (transfer.setup.wValue == ENDPOINT_HALT)\r
-            {\r
-                /* TODO: We should check that the endpoint number is valid */\r
-                stallEndpoint(\r
-                    WINDEX_TO_PHYSICAL(transfer.setup.wIndex));\r
-                success = true;\r
-            }\r
-            break;\r
-        default:\r
-            break;\r
-    }\r
-\r
-    return success;\r
-}\r
-\r
-bool USBDevice::requestClearFeature()\r
-{\r
-    bool success = false;\r
-\r
-    if (device.state != CONFIGURED)\r
-    {\r
-        /* Endpoint or interface must be zero */\r
-        if (transfer.setup.wIndex != 0)\r
-        {\r
-            return false;\r
-        }\r
-    }\r
-\r
-    switch (transfer.setup.bmRequestType.Recipient)\r
-    {\r
-        case DEVICE_RECIPIENT:\r
-            /* TODO: Remote wakeup feature not supported */\r
-            break;\r
-        case ENDPOINT_RECIPIENT:\r
-            /* TODO: We should check that the endpoint number is valid */\r
-            if (transfer.setup.wValue == ENDPOINT_HALT)\r
-            {\r
-                unstallEndpoint( WINDEX_TO_PHYSICAL(transfer.setup.wIndex));\r
-                success = true;\r
-            }\r
-            break;\r
-        default:\r
-            break;\r
-    }\r
-\r
-    return success;\r
-}\r
-\r
-bool USBDevice::requestGetStatus(void)\r
-{\r
-    static uint16_t status;\r
-    bool success = false;\r
-\r
-    if (device.state != CONFIGURED)\r
-    {\r
-        /* Endpoint or interface must be zero */\r
-        if (transfer.setup.wIndex != 0)\r
-        {\r
-            return false;\r
-        }\r
-    }\r
-\r
-    switch (transfer.setup.bmRequestType.Recipient)\r
-    {\r
-        case DEVICE_RECIPIENT:\r
-            /* TODO: Currently only supports self powered devices */\r
-            status = DEVICE_STATUS_SELF_POWERED;\r
-            success = true;\r
-            break;\r
-        case INTERFACE_RECIPIENT:\r
-            status = 0;\r
-            success = true;\r
-            break;\r
-        case ENDPOINT_RECIPIENT:\r
-            /* TODO: We should check that the endpoint number is valid */\r
-            if (getEndpointStallState(\r
-                WINDEX_TO_PHYSICAL(transfer.setup.wIndex)))\r
-            {\r
-                status = ENDPOINT_STATUS_HALT;\r
-            }\r
-            else\r
-            {\r
-                status = 0;\r
-            }\r
-            success = true;\r
-            break;\r
-        default:\r
-            break;\r
-    }\r
-\r
-    if (success)\r
-    {\r
-        /* Send the status */ \r
-        transfer.ptr = (uint8_t *)&status; /* Assumes little endian */\r
-        transfer.remaining = sizeof(status);\r
-        transfer.direction = DEVICE_TO_HOST;\r
-    }\r
+/* USBDevice.c */
+/* Generic USB device */
+/* Copyright (c) 2011 ARM Limited. All rights reserved. */
+\r
+/* Reference: */
+/* Universal Serial Bus Specification Revision 2.0, Chapter 9 "USB Device Framework" */
+\r
+#include "stdint.h"
+\r
+#include "USBEndpoints.h"
+#include "USBDevice.h"
+#include "USBDescriptor.h"
+#include "USBHID_Types.h"
+\r
+\r
+/* Device status */
+#define DEVICE_STATUS_SELF_POWERED  (1U<<0)
+#define DEVICE_STATUS_REMOTE_WAKEUP (1U<<1)
+\r
+/* Endpoint status */
+#define ENDPOINT_STATUS_HALT        (1U<<0)
+\r
+/* Standard feature selectors */
+#define DEVICE_REMOTE_WAKEUP        (1)
+#define ENDPOINT_HALT               (0)
+\r
+/* Macro to convert wIndex endpoint number to physical endpoint number */
+#define WINDEX_TO_PHYSICAL(endpoint) (((endpoint & 0x0f) << 1) + \
+    ((endpoint & 0x80) ? 1 : 0))
+\r
+\r
+bool USBDevice::requestGetDescriptor(void)
+{
+    bool success = false;
+\r
+    switch (DESCRIPTOR_TYPE(transfer.setup.wValue))
+    {
+        case DEVICE_DESCRIPTOR:
+            if (deviceDesc() != NULL)
+            {
+                if ((deviceDesc()[0] == DEVICE_DESCRIPTOR_LENGTH) \
+                    && (deviceDesc()[1] == DEVICE_DESCRIPTOR))
+                {
+                    transfer.remaining = DEVICE_DESCRIPTOR_LENGTH;
+                    transfer.ptr = deviceDesc();
+                    transfer.direction = DEVICE_TO_HOST;
+                    success = true;
+                }
+            }
+            break;
+        case CONFIGURATION_DESCRIPTOR:
+            if (configurationDesc() != NULL)
+            {
+                if ((configurationDesc()[0] == CONFIGURATION_DESCRIPTOR_LENGTH) \
+                    && (configurationDesc()[1] == CONFIGURATION_DESCRIPTOR))
+                {
+                    /* Get wTotalLength */
+                    transfer.remaining = configurationDesc()[2] \
+                        | (configurationDesc()[3] << 8);
+\r
+                    transfer.ptr = configurationDesc();
+                    transfer.direction = DEVICE_TO_HOST;
+                    success = true;
+                }
+            }
+            break;
+        case STRING_DESCRIPTOR:
+            switch (DESCRIPTOR_INDEX(transfer.setup.wValue))
+            {
+                            case STRING_OFFSET_LANGID:
+                                transfer.remaining = stringLangidDesc()[0];
+                                transfer.ptr = stringLangidDesc();
+                                transfer.direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+                            case STRING_OFFSET_IMANUFACTURER:
+                                transfer.remaining =  stringImanufacturerDesc()[0];
+                                transfer.ptr = stringImanufacturerDesc();
+                                transfer.direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+                            case STRING_OFFSET_IPRODUCT:
+                                transfer.remaining = stringIproductDesc()[0];
+                                transfer.ptr = stringIproductDesc();
+                                transfer.direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+                            case STRING_OFFSET_ISERIAL:
+                                transfer.remaining = stringIserialDesc()[0];
+                                transfer.ptr = stringIserialDesc();
+                                transfer.direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+                            case STRING_OFFSET_ICONFIGURATION:
+                                transfer.remaining = stringIConfigurationDesc()[0];
+                                transfer.ptr = stringIConfigurationDesc();
+                                transfer.direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+                            case STRING_OFFSET_IINTERFACE:
+                                transfer.remaining = stringIinterfaceDesc()[0];
+                                transfer.ptr = stringIinterfaceDesc();
+                                transfer.direction = DEVICE_TO_HOST;
+                                success = true;
+                                break;
+            }
+            break;
+        case INTERFACE_DESCRIPTOR:
+        case ENDPOINT_DESCRIPTOR:
+            /* TODO: Support is optional, not implemented here */
+            break;
+        default:
+            break;
+    }
+\r
+    return success;
+}
+\r
+void USBDevice::decodeSetupPacket(uint8_t *data, SETUP_PACKET *packet)
+{
+    /* Fill in the elements of a SETUP_PACKET structure from raw data */
+    packet->bmRequestType.dataTransferDirection = (data[0] & 0x80) >> 7;
+    packet->bmRequestType.Type = (data[0] & 0x60) >> 5;
+    packet->bmRequestType.Recipient = data[0] & 0x1f;
+    packet->bRequest = data[1];
+    packet->wValue = (data[2] | (uint16_t)data[3] << 8);
+    packet->wIndex = (data[4] | (uint16_t)data[5] << 8);
+    packet->wLength = (data[6] | (uint16_t)data[7] << 8);
+}
+\r
+\r
+bool USBDevice::controlOut(void)
+{
+    /* Control transfer data OUT stage */
+    uint8_t buffer[MAX_PACKET_SIZE_EP0];
+    uint32_t packetSize;
+\r
+    /* Check we should be transferring data OUT */
+    if (transfer.direction != HOST_TO_DEVICE)
+    {
+        return false;
+    }
+\r
+    /* Read from endpoint */
+    packetSize = EP0getReadResult(buffer);
+\r
+    /* Check if transfer size is valid */
+    if (packetSize > transfer.remaining)
+    {
+        /* Too big */
+        return false;
+    }
+\r
+    /* Update transfer */
+    transfer.ptr += packetSize;
+    transfer.remaining -= packetSize;
+\r
+    /* Check if transfer has completed */
+    if (transfer.remaining == 0)
+    {
+        /* Transfer completed */
+        if (transfer.notify)
+        {
+            /* Notify class layer. */
+            USBCallback_requestCompleted(buffer, packetSize);
+            transfer.notify = false;
+        }
+        /* Status stage */
+        EP0write(NULL, 0);
+    }
+    else
+    {
+        EP0read();
+    }
+\r
+    return true;
+}
+\r
+bool USBDevice::controlIn(void)
+{
+    /* Control transfer data IN stage */
+    uint32_t packetSize;
+\r
+    /* Check if transfer has completed (status stage transactions */
+    /* also have transfer.remaining == 0) */
+    if (transfer.remaining == 0)
+    {
+        if (transfer.zlp)
+        {
+            /* Send zero length packet */
+            EP0write(NULL, 0);
+            transfer.zlp = false;
+        }
+\r
+        /* Transfer completed */
+        if (transfer.notify)
+        {
+            /* Notify class layer. */
+            USBCallback_requestCompleted(NULL, 0);
+            transfer.notify = false;
+        }
+\r
+        EP0read();
+\r
+        /* Completed */
+        return true;
+    }
+\r
+    /* Check we should be transferring data IN */
+    if (transfer.direction != DEVICE_TO_HOST)
+    {
+        return false;
+    }
+\r
+    packetSize = transfer.remaining;
+\r
+    if (packetSize > MAX_PACKET_SIZE_EP0)
+    {
+        packetSize = MAX_PACKET_SIZE_EP0;
+    }
+\r
+    /* Write to endpoint */
+    EP0write(transfer.ptr, packetSize);
+\r
+    /* Update transfer */
+    transfer.ptr += packetSize;
+    transfer.remaining -= packetSize;
+\r
+    return true;
+}
+\r
+bool USBDevice::requestSetAddress(void)
+{
+    /* Set the device address */
+    setAddress(transfer.setup.wValue);
+\r
+    if (transfer.setup.wValue == 0)
+    {
+        device.state = DEFAULT;
+    }
+    else
+    {
+        device.state = ADDRESS;
+    }
+\r
+    return true;
+}
+\r
+bool USBDevice::requestSetConfiguration(void)
+{
+\r
+    device.configuration = transfer.setup.wValue;
+    /* Set the device configuration */
+    if (device.configuration == 0)
+    {
+        /* Not configured */
+        unconfigureDevice();
+        device.state = ADDRESS;
+    }
+    else
+    {
+        if (USBCallback_setConfiguration(device.configuration))
+        {
+            /* Valid configuration */
+            configureDevice();
+            device.state = CONFIGURED;
+        }
+        else
+        {
+            return false;
+        }
+    }
+\r
+    return true;
+}
+\r
+bool USBDevice::requestGetConfiguration(void)
+{
+    /* Send the device configuration */
+    transfer.ptr = &device.configuration;
+    transfer.remaining = sizeof(device.configuration);
+    transfer.direction = DEVICE_TO_HOST;
+    return true;
+}
+\r
+bool USBDevice::requestGetInterface(void)
+{
+    /* Return the selected alternate setting for an interface */
+\r
+    if (device.state != CONFIGURED)
+    {
+        return false;
+    }
+\r
+    /* Send the alternate setting */
+    transfer.setup.wIndex = currentInterface;
+    transfer.ptr = &currentAlternate;
+    transfer.remaining = sizeof(currentAlternate);
+    transfer.direction = DEVICE_TO_HOST;
+    return true;
+}
+\r
+bool USBDevice::requestSetInterface(void)
+{
+    bool success = false;
+    if(USBCallback_setInterface(transfer.setup.wIndex, transfer.setup.wValue))
+    {
+        success = true;
+        currentInterface = transfer.setup.wIndex;
+        currentAlternate = transfer.setup.wValue;
+    }
+    return success;
+}
+\r
+bool USBDevice::requestSetFeature()
+{
+    bool success = false;
+\r
+    if (device.state != CONFIGURED)
+    {
+        /* Endpoint or interface must be zero */
+        if (transfer.setup.wIndex != 0)
+        {
+            return false;
+        }
+    }
+\r
+    switch (transfer.setup.bmRequestType.Recipient)
+    {
+        case DEVICE_RECIPIENT:
+            /* TODO: Remote wakeup feature not supported */
+            break;
+        case ENDPOINT_RECIPIENT:
+            if (transfer.setup.wValue == ENDPOINT_HALT)
+            {
+                /* TODO: We should check that the endpoint number is valid */
+                stallEndpoint(
+                    WINDEX_TO_PHYSICAL(transfer.setup.wIndex));
+                success = true;
+            }
+            break;
+        default:
+            break;
+    }
+\r
+    return success;
+}
+\r
+bool USBDevice::requestClearFeature()
+{
+    bool success = false;
+\r
+    if (device.state != CONFIGURED)
+    {
+        /* Endpoint or interface must be zero */
+        if (transfer.setup.wIndex != 0)
+        {
+            return false;
+        }
+    }
+\r
+    switch (transfer.setup.bmRequestType.Recipient)
+    {
+        case DEVICE_RECIPIENT:
+            /* TODO: Remote wakeup feature not supported */
+            break;
+        case ENDPOINT_RECIPIENT:
+            /* TODO: We should check that the endpoint number is valid */
+            if (transfer.setup.wValue == ENDPOINT_HALT)
+            {
+                unstallEndpoint( WINDEX_TO_PHYSICAL(transfer.setup.wIndex));
+                success = true;
+            }
+            break;
+        default:
+            break;
+    }
+\r
+    return success;
+}
+\r
+bool USBDevice::requestGetStatus(void)
+{
+    static uint16_t status;
+    bool success = false;
+\r
+    if (device.state != CONFIGURED)
+    {
+        /* Endpoint or interface must be zero */
+        if (transfer.setup.wIndex != 0)
+        {
+            return false;
+        }
+    }
+\r
+    switch (transfer.setup.bmRequestType.Recipient)
+    {
+        case DEVICE_RECIPIENT:
+            /* TODO: Currently only supports self powered devices */
+            status = DEVICE_STATUS_SELF_POWERED;
+            success = true;
+            break;
+        case INTERFACE_RECIPIENT:
+            status = 0;
+            success = true;
+            break;
+        case ENDPOINT_RECIPIENT:
+            /* TODO: We should check that the endpoint number is valid */
+            if (getEndpointStallState(
+                WINDEX_TO_PHYSICAL(transfer.setup.wIndex)))
+            {
+                status = ENDPOINT_STATUS_HALT;
+            }
+            else
+            {
+                status = 0;
+            }
+            success = true;
+            break;
+        default:
+            break;
+    }
+\r
+    if (success)
+    {
+        /* Send the status */
+        transfer.ptr = (uint8_t *)&status; /* Assumes little endian */
+        transfer.remaining = sizeof(status);
+        transfer.direction = DEVICE_TO_HOST;
+    }
     \r
-    return success;\r
-}\r
-\r
-bool USBDevice::requestSetup(void)\r
-{\r
-    bool success = false;\r
-\r
-    /* Process standard requests */\r
-    if ((transfer.setup.bmRequestType.Type == STANDARD_TYPE))\r
-    {\r
-        switch (transfer.setup.bRequest)\r
-        {\r
-             case GET_STATUS:\r
-                 success = requestGetStatus();\r
-                 break;\r
-             case CLEAR_FEATURE:\r
-                 success = requestClearFeature();\r
-                 break;\r
-             case SET_FEATURE:\r
-                 success = requestSetFeature();\r
-                 break;\r
-             case SET_ADDRESS:\r
-                success = requestSetAddress();\r
-                 break;\r
-             case GET_DESCRIPTOR:\r
-                 success = requestGetDescriptor();\r
-                 break;\r
-             case SET_DESCRIPTOR:\r
-                 /* TODO: Support is optional, not implemented here */\r
-                 success = false;\r
-                 break;\r
-             case GET_CONFIGURATION:\r
-                 success = requestGetConfiguration();\r
-                 break;\r
-             case SET_CONFIGURATION:\r
-                 success = requestSetConfiguration();\r
-                 break;\r
-             case GET_INTERFACE:\r
-                 success = requestGetInterface();\r
-                 break;\r
-             case SET_INTERFACE:\r
-                 success = requestSetInterface();\r
-                 break;\r
-             default:\r
-                 break;\r
-        }\r
-    }\r
-\r
-    return success;\r
-}\r
-\r
-bool USBDevice::controlSetup(void)\r
-{\r
-    bool success = false;\r
-\r
-    /* Control transfer setup stage */\r
-    uint8_t buffer[MAX_PACKET_SIZE_EP0];\r
-\r
-    EP0setup(buffer);\r
-\r
-    /* Initialise control transfer state */\r
-    decodeSetupPacket(buffer, &transfer.setup);\r
-    transfer.ptr = NULL;\r
-    transfer.remaining = 0;\r
-    transfer.direction = 0;\r
-    transfer.zlp = false;\r
-    transfer.notify = false;\r
-\r
-    /* Class / vendor specific */\r
-    success = USBCallback_request();\r
-\r
-    if (!success)\r
-    {\r
-        /* Standard requests */\r
-        if (!requestSetup())\r
-        {\r
-            return false;\r
-        }\r
-    }\r
-\r
-    /* Check transfer size and direction */\r
-    if (transfer.setup.wLength>0)\r
-    {\r
-        if (transfer.setup.bmRequestType.dataTransferDirection \\r
-            == DEVICE_TO_HOST)\r
-        {\r
-            /* IN data stage is required */\r
-            if (transfer.direction != DEVICE_TO_HOST)\r
-            {\r
-                return false;\r
-            }\r
-\r
-            /* Transfer must be less than or equal to the size */\r
-            /* requested by the host */\r
-            if (transfer.remaining > transfer.setup.wLength)\r
-            {\r
-                transfer.remaining = transfer.setup.wLength;\r
-            }\r
-        }\r
-        else\r
-        {\r
+    return success;
+}
+\r
+bool USBDevice::requestSetup(void)
+{
+    bool success = false;
+\r
+    /* Process standard requests */
+    if ((transfer.setup.bmRequestType.Type == STANDARD_TYPE))
+    {
+        switch (transfer.setup.bRequest)
+        {
+             case GET_STATUS:
+                 success = requestGetStatus();
+                 break;
+             case CLEAR_FEATURE:
+                 success = requestClearFeature();
+                 break;
+             case SET_FEATURE:
+                 success = requestSetFeature();
+                 break;
+             case SET_ADDRESS:
+                success = requestSetAddress();
+                 break;
+             case GET_DESCRIPTOR:
+                 success = requestGetDescriptor();
+                 break;
+             case SET_DESCRIPTOR:
+                 /* TODO: Support is optional, not implemented here */
+                 success = false;
+                 break;
+             case GET_CONFIGURATION:
+                 success = requestGetConfiguration();
+                 break;
+             case SET_CONFIGURATION:
+                 success = requestSetConfiguration();
+                 break;
+             case GET_INTERFACE:
+                 success = requestGetInterface();
+                 break;
+             case SET_INTERFACE:
+                 success = requestSetInterface();
+                 break;
+             default:
+                 break;
+        }
+    }
+\r
+    return success;
+}
+\r
+bool USBDevice::controlSetup(void)
+{
+    bool success = false;
+\r
+    /* Control transfer setup stage */
+    uint8_t buffer[MAX_PACKET_SIZE_EP0];
+\r
+    EP0setup(buffer);
+\r
+    /* Initialise control transfer state */
+    decodeSetupPacket(buffer, &transfer.setup);
+    transfer.ptr = NULL;
+    transfer.remaining = 0;
+    transfer.direction = 0;
+    transfer.zlp = false;
+    transfer.notify = false;
+\r
+    /* Class / vendor specific */
+    success = USBCallback_request();
+\r
+    if (!success)
+    {
+        /* Standard requests */
+        if (!requestSetup())
+        {
+            return false;
+        }
+    }
+\r
+    /* Check transfer size and direction */
+    if (transfer.setup.wLength>0)
+    {
+        if (transfer.setup.bmRequestType.dataTransferDirection \
+            == DEVICE_TO_HOST)
+        {
+            /* IN data stage is required */
+            if (transfer.direction != DEVICE_TO_HOST)
+            {
+                return false;
+            }
+\r
+            /* Transfer must be less than or equal to the size */
+            /* requested by the host */
+            if (transfer.remaining > transfer.setup.wLength)
+            {
+                transfer.remaining = transfer.setup.wLength;
+            }
+        }
+        else
+        {
             \r
-            /* OUT data stage is required */\r
-            if (transfer.direction != HOST_TO_DEVICE)\r
-            {\r
-                return false;\r
-            }\r
-\r
-            /* Transfer must be equal to the size requested by the host */\r
-            if (transfer.remaining != transfer.setup.wLength)\r
-            {\r
-                return false;\r
-            }\r
-        }\r
-    }\r
-    else\r
-    {\r
-        /* No data stage; transfer size must be zero */\r
-        if (transfer.remaining != 0)\r
-        {\r
-            return false;\r
-        }\r
-    }\r
-\r
-    /* Data or status stage if applicable */\r
-    if (transfer.setup.wLength>0)\r
-    {\r
-        if (transfer.setup.bmRequestType.dataTransferDirection \\r
-            == DEVICE_TO_HOST)\r
-        {\r
-            /* Check if we'll need to send a zero length packet at */\r
-            /* the end of this transfer */\r
-            if (transfer.setup.wLength > transfer.remaining)\r
-            {\r
-                /* Device wishes to transfer less than host requested */\r
-                if ((transfer.remaining % MAX_PACKET_SIZE_EP0) == 0)\r
-                {\r
-                    /* Transfer is a multiple of EP0 max packet size */\r
-                    transfer.zlp = true;\r
-                }\r
-            }\r
-\r
-            /* IN stage */\r
-            controlIn();\r
-        }\r
-        else\r
-        {\r
-            /* OUT stage */\r
-            EP0read();\r
-        }\r
-    }\r
-    else\r
-    {\r
-        /* Status stage */\r
-        EP0write(NULL, 0);\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-void USBDevice::busReset(void)\r
-{\r
-    device.state = DEFAULT;\r
-    device.configuration = 0;\r
-    device.suspended = false;\r
-\r
-    /* Call class / vendor specific busReset function */\r
-    USBCallback_busReset();\r
-}\r
-\r
-void USBDevice::EP0setupCallback(void)\r
-{\r
-    /* Endpoint 0 setup event */\r
-    if (!controlSetup())\r
-    {\r
-        /* Protocol stall */\r
-        EP0stall();\r
-    }\r
-\r
-    /* Return true if an OUT data stage is expected */\r
-}\r
-\r
-void USBDevice::EP0out(void)\r
-{\r
-    /* Endpoint 0 OUT data event */\r
-    if (!controlOut())\r
-    {\r
-        /* Protocol stall; this will stall both endpoints */\r
-        EP0stall();\r
-    }\r
-}\r
-\r
-void USBDevice::EP0in(void)\r
-{\r
-    /* Endpoint 0 IN data event */\r
-    if (!controlIn())\r
-    {\r
-        /* Protocol stall; this will stall both endpoints */\r
-        EP0stall();\r
-    }\r
-}\r
-\r
-bool USBDevice::configured(void)\r
-{\r
-    /* Returns true if device is in the CONFIGURED state */\r
-    return (device.state == CONFIGURED);\r
-}\r
-\r
-void USBDevice::connect(void)\r
-{\r
-    /* Connect device */\r
-    USBHAL::connect();\r
-    /* Block if not configured */\r
-    while (!configured());\r
-}\r
-\r
-void USBDevice::disconnect(void)\r
-{\r
-    /* Disconnect device */\r
-    USBHAL::disconnect();\r
-}\r
-\r
-CONTROL_TRANSFER * USBDevice::getTransferPtr(void)\r
-{\r
-    return &transfer;\r
-}\r
-\r
-bool USBDevice::addEndpoint(uint8_t endpoint, uint32_t maxPacket)\r
-{\r
-    return realiseEndpoint(endpoint, maxPacket, 0);\r
-}\r
-\r
-bool USBDevice::addRateFeedbackEndpoint(uint8_t endpoint, uint32_t maxPacket)\r
-{\r
-    /* For interrupt endpoints only */\r
-    return realiseEndpoint(endpoint, maxPacket, RATE_FEEDBACK_MODE);\r
-}\r
-\r
-uint8_t * USBDevice::findDescriptor(uint8_t descriptorType)\r
-{\r
-    /* Find a descriptor within the list of descriptors */\r
-    /* following a configuration descriptor. */\r
-    uint16_t wTotalLength;\r
-    uint8_t *ptr;\r
-\r
-    if (configurationDesc() == NULL)\r
-    {\r
-        return NULL;\r
-    }\r
-\r
-    /* Check this is a configuration descriptor */\r
-    if ((configurationDesc()[0] != CONFIGURATION_DESCRIPTOR_LENGTH) \\r
-            || (configurationDesc()[1] != CONFIGURATION_DESCRIPTOR))\r
-    {\r
-        return NULL;\r
-    }\r
-\r
-    wTotalLength = configurationDesc()[2] | (configurationDesc()[3] << 8);\r
-\r
-    /* Check there are some more descriptors to follow */\r
-    if (wTotalLength <= (CONFIGURATION_DESCRIPTOR_LENGTH+2))\r
-    /* +2 is for bLength and bDescriptorType of next descriptor */\r
-    {\r
-        return false;\r
-    }\r
-\r
-    /* Start at first descriptor after the configuration descriptor */\r
-    ptr = &(configurationDesc()[CONFIGURATION_DESCRIPTOR_LENGTH]);\r
-\r
-    do {\r
-        if (ptr[1] /* bDescriptorType */ == descriptorType)\r
-        {\r
-            /* Found */\r
-            return ptr;\r
-        }\r
-\r
-        /* Skip to next descriptor */\r
-        ptr += ptr[0]; /* bLength */\r
-    } while (ptr < (configurationDesc() + wTotalLength));\r
-\r
-    /* Reached end of the descriptors - not found */\r
-    return NULL;\r
-}\r
-\r
-\r
-void USBDevice::connectStateChanged(unsigned int connected)\r
-{\r
-}\r
-\r
-void USBDevice::suspendStateChanged(unsigned int suspended)\r
-{\r
-}\r
-\r
-\r
-USBDevice::USBDevice(uint16_t vendor_id, uint16_t product_id, uint16_t product_release){\r
-    VENDOR_ID = vendor_id; \r
-    PRODUCT_ID = product_id; \r
-    PRODUCT_RELEASE = product_release;\r
-\r
-    /* Set initial device state */\r
-    device.state = POWERED;\r
-    device.configuration = 0;\r
-    device.suspended = false;\r
-};\r
-\r
-\r
-bool USBDevice::readStart(uint8_t endpoint, uint16_t maxSize)\r
-{\r
-    return endpointRead(endpoint, maxSize) == EP_PENDING;\r
-}\r
-\r
-\r
-bool USBDevice::write(uint8_t endpoint, uint8_t * buffer, uint16_t size, uint16_t maxSize)\r
-{\r
-    EP_STATUS result;\r
-\r
-    if (size > maxSize)\r
-    {\r
-        return false;\r
-    }\r
+            /* OUT data stage is required */
+            if (transfer.direction != HOST_TO_DEVICE)
+            {
+                return false;
+            }
+\r
+            /* Transfer must be equal to the size requested by the host */
+            if (transfer.remaining != transfer.setup.wLength)
+            {
+                return false;
+            }
+        }
+    }
+    else
+    {
+        /* No data stage; transfer size must be zero */
+        if (transfer.remaining != 0)
+        {
+            return false;
+        }
+    }
+\r
+    /* Data or status stage if applicable */
+    if (transfer.setup.wLength>0)
+    {
+        if (transfer.setup.bmRequestType.dataTransferDirection \
+            == DEVICE_TO_HOST)
+        {
+            /* Check if we'll need to send a zero length packet at */
+            /* the end of this transfer */
+            if (transfer.setup.wLength > transfer.remaining)
+            {
+                /* Device wishes to transfer less than host requested */
+                if ((transfer.remaining % MAX_PACKET_SIZE_EP0) == 0)
+                {
+                    /* Transfer is a multiple of EP0 max packet size */
+                    transfer.zlp = true;
+                }
+            }
+\r
+            /* IN stage */
+            controlIn();
+        }
+        else
+        {
+            /* OUT stage */
+            EP0read();
+        }
+    }
+    else
+    {
+        /* Status stage */
+        EP0write(NULL, 0);
+    }
+\r
+    return true;
+}
+\r
+void USBDevice::busReset(void)
+{
+    device.state = DEFAULT;
+    device.configuration = 0;
+    device.suspended = false;
+\r
+    /* Call class / vendor specific busReset function */
+    USBCallback_busReset();
+}
+\r
+void USBDevice::EP0setupCallback(void)
+{
+    /* Endpoint 0 setup event */
+    if (!controlSetup())
+    {
+        /* Protocol stall */
+        EP0stall();
+    }
+\r
+    /* Return true if an OUT data stage is expected */
+}
+\r
+void USBDevice::EP0out(void)
+{
+    /* Endpoint 0 OUT data event */
+    if (!controlOut())
+    {
+        /* Protocol stall; this will stall both endpoints */
+        EP0stall();
+    }
+}
+\r
+void USBDevice::EP0in(void)
+{
+    /* Endpoint 0 IN data event */
+    if (!controlIn())
+    {
+        /* Protocol stall; this will stall both endpoints */
+        EP0stall();
+    }
+}
+\r
+bool USBDevice::configured(void)
+{
+    /* Returns true if device is in the CONFIGURED state */
+    return (device.state == CONFIGURED);
+}
+\r
+void USBDevice::connect(void)
+{
+    /* Connect device */
+    USBHAL::connect();
+    /* Block if not configured */
+    while (!configured());
+}
+\r
+void USBDevice::disconnect(void)
+{
+    /* Disconnect device */
+    USBHAL::disconnect();
+}
+\r
+CONTROL_TRANSFER * USBDevice::getTransferPtr(void)
+{
+    return &transfer;
+}
+\r
+bool USBDevice::addEndpoint(uint8_t endpoint, uint32_t maxPacket)
+{
+    return realiseEndpoint(endpoint, maxPacket, 0);
+}
+\r
+bool USBDevice::addRateFeedbackEndpoint(uint8_t endpoint, uint32_t maxPacket)
+{
+    /* For interrupt endpoints only */
+    return realiseEndpoint(endpoint, maxPacket, RATE_FEEDBACK_MODE);
+}
+\r
+uint8_t * USBDevice::findDescriptor(uint8_t descriptorType)
+{
+    /* Find a descriptor within the list of descriptors */
+    /* following a configuration descriptor. */
+    uint16_t wTotalLength;
+    uint8_t *ptr;
+\r
+    if (configurationDesc() == NULL)
+    {
+        return NULL;
+    }
+\r
+    /* Check this is a configuration descriptor */
+    if ((configurationDesc()[0] != CONFIGURATION_DESCRIPTOR_LENGTH) \
+            || (configurationDesc()[1] != CONFIGURATION_DESCRIPTOR))
+    {
+        return NULL;
+    }
+\r
+    wTotalLength = configurationDesc()[2] | (configurationDesc()[3] << 8);
+\r
+    /* Check there are some more descriptors to follow */
+    if (wTotalLength <= (CONFIGURATION_DESCRIPTOR_LENGTH+2))
+    /* +2 is for bLength and bDescriptorType of next descriptor */
+    {
+        return false;
+    }
+\r
+    /* Start at first descriptor after the configuration descriptor */
+    ptr = &(configurationDesc()[CONFIGURATION_DESCRIPTOR_LENGTH]);
+\r
+    do {
+        if (ptr[1] /* bDescriptorType */ == descriptorType)
+        {
+            /* Found */
+            return ptr;
+        }
+\r
+        /* Skip to next descriptor */
+        ptr += ptr[0]; /* bLength */
+    } while (ptr < (configurationDesc() + wTotalLength));
+\r
+    /* Reached end of the descriptors - not found */
+    return NULL;
+}
+\r
+\r
+void USBDevice::connectStateChanged(unsigned int connected)
+{
+}
+\r
+void USBDevice::suspendStateChanged(unsigned int suspended)
+{
+}
+\r
+\r
+USBDevice::USBDevice(uint16_t vendor_id, uint16_t product_id, uint16_t product_release){
+    VENDOR_ID = vendor_id;
+    PRODUCT_ID = product_id;
+    PRODUCT_RELEASE = product_release;
+\r
+    /* Set initial device state */
+    device.state = POWERED;
+    device.configuration = 0;
+    device.suspended = false;
+};
+\r
+\r
+bool USBDevice::readStart(uint8_t endpoint, uint16_t maxSize)
+{
+    return endpointRead(endpoint, maxSize) == EP_PENDING;
+}
+\r
+\r
+bool USBDevice::write(uint8_t endpoint, uint8_t * buffer, uint16_t size, uint16_t maxSize)
+{
+    EP_STATUS result;
+\r
+    if (size > maxSize)
+    {
+        return false;
+    }
     \r
     \r
-    if(!configured()) {\r
-        return false;\r
-    }\r
+    if(!configured()) {
+        return false;
+    }
     \r
-    /* Send report */\r
-    result = endpointWrite(endpoint, buffer, size);\r
+    /* Send report */
+    result = endpointWrite(endpoint, buffer, size);
 \r
-    if (result != EP_PENDING)\r
-    {\r
-        return false;\r
-    }\r
+    if (result != EP_PENDING)
+    {
+        return false;
+    }
 \r
-    /* Wait for completion */\r
-    do {\r
-        result = endpointWriteResult(endpoint);\r
-    } while ((result == EP_PENDING) && configured());\r
+    /* Wait for completion */
+    do {
+        result = endpointWriteResult(endpoint);
+    } while ((result == EP_PENDING) && configured());
 \r
-    return (result == EP_COMPLETED);\r
-}\r
+    return (result == EP_COMPLETED);
+}
 \r
 \r
-bool USBDevice::writeNB(uint8_t endpoint, uint8_t * buffer, uint16_t size, uint16_t maxSize)\r
-{\r
-    EP_STATUS result;\r
+bool USBDevice::writeNB(uint8_t endpoint, uint8_t * buffer, uint16_t size, uint16_t maxSize)
+{
+    EP_STATUS result;
 \r
-    if (size > maxSize)\r
-    {\r
-        return false;\r
-    }\r
+    if (size > maxSize)
+    {
+        return false;
+    }
     \r
-    if(!configured()) {\r
-        return false;\r
-    }\r
+    if(!configured()) {
+        return false;
+    }
 \r
-    /* Send report */\r
-    result = endpointWrite(endpoint, buffer, size);\r
+    /* Send report */
+    result = endpointWrite(endpoint, buffer, size);
 \r
-    if (result != EP_PENDING)\r
-    {\r
-        return false;\r
-    }\r
+    if (result != EP_PENDING)
+    {
+        return false;
+    }
 \r
-    result = endpointWriteResult(endpoint);\r
+    result = endpointWriteResult(endpoint);
 \r
-    return (result == EP_COMPLETED);\r
-}\r
+    return (result == EP_COMPLETED);
+}
 \r
 \r
 \r
-bool USBDevice::readEP(uint8_t endpoint, uint8_t * buffer, uint16_t * size, uint16_t maxSize)\r
-{\r
-    EP_STATUS result;\r
+bool USBDevice::readEP(uint8_t endpoint, uint8_t * buffer, uint16_t * size, uint16_t maxSize)
+{
+    EP_STATUS result;
     \r
-    if(!configured()) {\r
-        return false;\r
-    }\r
+    if(!configured()) {
+        return false;
+    }
 \r
-    /* Wait for completion */\r
-    do {\r
-        result = endpointReadResult(endpoint, buffer, (uint32_t *)size);\r
-    } while ((result == EP_PENDING) && configured());\r
+    /* Wait for completion */
+    do {
+        result = endpointReadResult(endpoint, buffer, (uint32_t *)size);
+    } while ((result == EP_PENDING) && configured());
 \r
-    return (result == EP_COMPLETED);\r
-}\r
+    return (result == EP_COMPLETED);
+}
 \r
 \r
-bool USBDevice::readEP_NB(uint8_t endpoint, uint8_t * buffer, uint16_t * size, uint16_t maxSize)\r
-{\r
-    EP_STATUS result;\r
+bool USBDevice::readEP_NB(uint8_t endpoint, uint8_t * buffer, uint16_t * size, uint16_t maxSize)
+{
+    EP_STATUS result;
     \r
-    if(!configured()) {\r
-        return false;\r
-    }\r
+    if(!configured()) {
+        return false;
+    }
 \r
-    result = endpointReadResult(endpoint, buffer, (uint32_t *)size);\r
+    result = endpointReadResult(endpoint, buffer, (uint32_t *)size);
     \r
-    return (result == EP_COMPLETED);\r
-}\r
-\r
-\r
-\r
-uint8_t * USBDevice::deviceDesc() {\r
-    static uint8_t deviceDescriptor[] = {\r
-        DEVICE_DESCRIPTOR_LENGTH,       /* bLength */\r
-        DEVICE_DESCRIPTOR,              /* bDescriptorType */\r
-        LSB(USB_VERSION_2_0),           /* bcdUSB (LSB) */\r
-        MSB(USB_VERSION_2_0),           /* bcdUSB (MSB) */\r
-        0x00,                           /* bDeviceClass */\r
-        0x00,                           /* bDeviceSubClass */\r
-        0x00,                           /* bDeviceprotocol */\r
-        MAX_PACKET_SIZE_EP0,            /* bMaxPacketSize0 */\r
-        LSB(VENDOR_ID),                 /* idVendor (LSB) */\r
-        MSB(VENDOR_ID),                 /* idVendor (MSB) */\r
-        LSB(PRODUCT_ID),                /* idProduct (LSB) */\r
-        MSB(PRODUCT_ID),                /* idProduct (MSB) */\r
-        LSB(PRODUCT_RELEASE),           /* bcdDevice (LSB) */\r
-        MSB(PRODUCT_RELEASE),           /* bcdDevice (MSB) */\r
-        STRING_OFFSET_IMANUFACTURER,    /* iManufacturer */\r
-        STRING_OFFSET_IPRODUCT,         /* iProduct */\r
-        STRING_OFFSET_ISERIAL,          /* iSerialNumber */\r
-        0x01                            /* bNumConfigurations */\r
-    };\r
-    return deviceDescriptor;\r
-}\r
-\r
-uint8_t * USBDevice::stringLangidDesc() {\r
-    static uint8_t stringLangidDescriptor[] = {\r
-        0x04,               /*bLength*/\r
-        STRING_DESCRIPTOR,  /*bDescriptorType 0x03*/\r
-        0x09,0x00,          /*bString Lang ID - 0x009 - English*/\r
-    };\r
-    return stringLangidDescriptor;\r
-}\r
-\r
-uint8_t * USBDevice::stringImanufacturerDesc() {\r
-    static uint8_t stringImanufacturerDescriptor[] = {\r
-        0x12,                                            /*bLength*/\r
-        STRING_DESCRIPTOR,                               /*bDescriptorType 0x03*/\r
-        'm',0,'b',0,'e',0,'d',0,'.',0,'o',0,'r',0,'g',0, /*bString iManufacturer - mbed.org*/\r
-    };\r
-    return stringImanufacturerDescriptor;\r
-}\r
-\r
-uint8_t * USBDevice::stringIserialDesc() {\r
-    static uint8_t stringIserialDescriptor[] = {\r
-        0x16,                                                           /*bLength*/\r
-        STRING_DESCRIPTOR,                                              /*bDescriptorType 0x03*/\r
-        '0',0,'1',0,'2',0,'3',0,'4',0,'5',0,'6',0,'7',0,'8',0,'9',0,    /*bString iSerial - 0123456789*/\r
-    };\r
-    return stringIserialDescriptor;\r
-}\r
-\r
-uint8_t * USBDevice::stringIConfigurationDesc() {\r
-    static uint8_t stringIconfigurationDescriptor[] = {\r
-        0x06,               /*bLength*/\r
-        STRING_DESCRIPTOR,  /*bDescriptorType 0x03*/\r
-        '0',0,'1',0,        /*bString iConfiguration - 01*/\r
-    };\r
-    return stringIconfigurationDescriptor;\r
-}\r
-\r
-uint8_t * USBDevice::stringIinterfaceDesc() {\r
-    static uint8_t stringIinterfaceDescriptor[] = {\r
-        0x08,               /*bLength*/\r
-        STRING_DESCRIPTOR,  /*bDescriptorType 0x03*/\r
-        'U',0,'S',0,'B',0,  /*bString iInterface - USB*/\r
-    };\r
-    return stringIinterfaceDescriptor;\r
-}\r
-\r
-uint8_t * USBDevice::stringIproductDesc() {\r
-    static uint8_t stringIproductDescriptor[] = {\r
-        0x16,                                                       /*bLength*/\r
-        STRING_DESCRIPTOR,                                          /*bDescriptorType 0x03*/\r
-        'U',0,'S',0,'B',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0 /*bString iProduct - USB DEVICE*/\r
-    };\r
-    return stringIproductDescriptor;\r
-}\r
+    return (result == EP_COMPLETED);
+}
+\r
+\r
+\r
+uint8_t * USBDevice::deviceDesc() {
+    static uint8_t deviceDescriptor[] = {
+        DEVICE_DESCRIPTOR_LENGTH,       /* bLength */
+        DEVICE_DESCRIPTOR,              /* bDescriptorType */
+        LSB(USB_VERSION_2_0),           /* bcdUSB (LSB) */
+        MSB(USB_VERSION_2_0),           /* bcdUSB (MSB) */
+        0x00,                           /* bDeviceClass */
+        0x00,                           /* bDeviceSubClass */
+        0x00,                           /* bDeviceprotocol */
+        MAX_PACKET_SIZE_EP0,            /* bMaxPacketSize0 */
+        LSB(VENDOR_ID),                 /* idVendor (LSB) */
+        MSB(VENDOR_ID),                 /* idVendor (MSB) */
+        LSB(PRODUCT_ID),                /* idProduct (LSB) */
+        MSB(PRODUCT_ID),                /* idProduct (MSB) */
+        LSB(PRODUCT_RELEASE),           /* bcdDevice (LSB) */
+        MSB(PRODUCT_RELEASE),           /* bcdDevice (MSB) */
+        STRING_OFFSET_IMANUFACTURER,    /* iManufacturer */
+        STRING_OFFSET_IPRODUCT,         /* iProduct */
+        STRING_OFFSET_ISERIAL,          /* iSerialNumber */
+        0x01                            /* bNumConfigurations */
+    };
+    return deviceDescriptor;
+}
+\r
+uint8_t * USBDevice::stringLangidDesc() {
+    static uint8_t stringLangidDescriptor[] = {
+        0x04,               /*bLength*/
+        STRING_DESCRIPTOR,  /*bDescriptorType 0x03*/
+        0x09,0x00,          /*bString Lang ID - 0x009 - English*/
+    };
+    return stringLangidDescriptor;
+}
+\r
+uint8_t * USBDevice::stringImanufacturerDesc() {
+    static uint8_t stringImanufacturerDescriptor[] = {
+        0x12,                                            /*bLength*/
+        STRING_DESCRIPTOR,                               /*bDescriptorType 0x03*/
+        'm',0,'b',0,'e',0,'d',0,'.',0,'o',0,'r',0,'g',0, /*bString iManufacturer - mbed.org*/
+    };
+    return stringImanufacturerDescriptor;
+}
+\r
+uint8_t * USBDevice::stringIserialDesc() {
+    static uint8_t stringIserialDescriptor[] = {
+        0x16,                                                           /*bLength*/
+        STRING_DESCRIPTOR,                                              /*bDescriptorType 0x03*/
+        '0',0,'1',0,'2',0,'3',0,'4',0,'5',0,'6',0,'7',0,'8',0,'9',0,    /*bString iSerial - 0123456789*/
+    };
+    return stringIserialDescriptor;
+}
+\r
+uint8_t * USBDevice::stringIConfigurationDesc() {
+    static uint8_t stringIconfigurationDescriptor[] = {
+        0x06,               /*bLength*/
+        STRING_DESCRIPTOR,  /*bDescriptorType 0x03*/
+        '0',0,'1',0,        /*bString iConfiguration - 01*/
+    };
+    return stringIconfigurationDescriptor;
+}
+\r
+uint8_t * USBDevice::stringIinterfaceDesc() {
+    static uint8_t stringIinterfaceDescriptor[] = {
+        0x08,               /*bLength*/
+        STRING_DESCRIPTOR,  /*bDescriptorType 0x03*/
+        'U',0,'S',0,'B',0,  /*bString iInterface - USB*/
+    };
+    return stringIinterfaceDescriptor;
+}
+\r
+uint8_t * USBDevice::stringIproductDesc() {
+    static uint8_t stringIproductDescriptor[] = {
+        0x16,                                                       /*bLength*/
+        STRING_DESCRIPTOR,                                          /*bDescriptorType 0x03*/
+        'U',0,'S',0,'B',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0 /*bString iProduct - USB DEVICE*/
+    };
+    return stringIproductDescriptor;
+}
index fca7b48..b60bc3b 100644 (file)
-/* USBDevice.h */\r
-/* Generic USB device */\r
-/* Copyright (c) 2011 ARM Limited. All rights reserved. */\r
+/* USBDevice.h */
+/* Generic USB device */
+/* Copyright (c) 2011 ARM Limited. All rights reserved. */
 \r
-#ifndef USBDEVICE_H\r
-#define USBDEVICE_H\r
+#ifndef USBDEVICE_H
+#define USBDEVICE_H
 \r
-#include "mbed.h"\r
-#include "USBDevice_Types.h"\r
-#include "USBBusInterface.h"\r
+#include "mbed.h"
+#include "USBDevice_Types.h"
+#include "USBBusInterface.h"
 \r
 \r
 \r
-class USBDevice: public USBHAL\r
-{\r
-public:\r
-    USBDevice(uint16_t vendor_id, uint16_t product_id, uint16_t product_release);\r
+class USBDevice: public USBHAL
+{
+public:
+    USBDevice(uint16_t vendor_id, uint16_t product_id, uint16_t product_release);
     \r
-    /*\r
-    * Check if the device is configured\r
-    *\r
-    * @returns true if configured, false otherwise\r
-    */\r
-    bool configured(void);\r
+    /*
+    * Check if the device is configured
+    *
+    * @returns true if configured, false otherwise
+    */
+    bool configured(void);
     \r
-    /*\r
-    * Connect a device\r
-    */\r
-    void connect(void);\r
+    /*
+    * Connect a device
+    */
+    void connect(void);
     \r
-    /*\r
-    * Disconnect a device\r
-    */\r
-    void disconnect(void);\r
+    /*
+    * Disconnect a device
+    */
+    void disconnect(void);
     \r
-    /*\r
-    * Add an endpoint\r
-    *\r
-    * @param endpoint endpoint which will be added\r
-    * @param maxPacket Maximum size of a packet which can be sent for this endpoint\r
-    * @returns true if successful, false otherwise\r
-    */\r
-    bool addEndpoint(uint8_t endpoint, uint32_t maxPacket);\r
+    /*
+    * Add an endpoint
+    *
+    * @param endpoint endpoint which will be added
+    * @param maxPacket Maximum size of a packet which can be sent for this endpoint
+    * @returns true if successful, false otherwise
+    */
+    bool addEndpoint(uint8_t endpoint, uint32_t maxPacket);
 \r
-    /*\r
-    * Start a reading on a certain endpoint.\r
-    * You can access the result of the reading by USBDevice_read\r
-    *\r
-    * @param endpoint endpoint which will be read\r
-    * @param maxSize the maximum length that can be read\r
-    * @return true if successful\r
-    */\r
-    bool readStart(uint8_t endpoint, uint16_t maxSize);\r
+    /*
+    * Start a reading on a certain endpoint.
+    * You can access the result of the reading by USBDevice_read
+    *
+    * @param endpoint endpoint which will be read
+    * @param maxSize the maximum length that can be read
+    * @return true if successful
+    */
+    bool readStart(uint8_t endpoint, uint16_t maxSize);
     \r
-    /*\r
-    * Read a certain endpoint. Before calling this function, USBUSBDevice_readStart\r
-    * must be called.\r
-    *\r
-    * Warning: blocking\r
-    *\r
-    * @param endpoint endpoint which will be read\r
-    * @param buffer buffer will be filled with the data received\r
-    * @param size the number of bytes read will be stored in *size\r
-    * @param maxSize the maximum length that can be read\r
-    * @returns true if successful\r
-    */\r
-    bool readEP(uint8_t endpoint, uint8_t * buffer, uint16_t * size, uint16_t maxSize);\r
+    /*
+    * Read a certain endpoint. Before calling this function, USBUSBDevice_readStart
+    * must be called.
+    *
+    * Warning: blocking
+    *
+    * @param endpoint endpoint which will be read
+    * @param buffer buffer will be filled with the data received
+    * @param size the number of bytes read will be stored in *size
+    * @param maxSize the maximum length that can be read
+    * @returns true if successful
+    */
+    bool readEP(uint8_t endpoint, uint8_t * buffer, uint16_t * size, uint16_t maxSize);
     \r
-    /*\r
-    * Read a certain endpoint.\r
-    *\r
-    * Warning: non blocking\r
-    *\r
-    * @param endpoint endpoint which will be read\r
-    * @param buffer buffer will be filled with the data received (if data are available) \r
-    * @param size the number of bytes read will be stored in *size\r
-    * @param maxSize the maximum length that can be read\r
-    * @returns true if successful\r
-    */\r
-    bool readEP_NB(uint8_t endpoint, uint8_t * buffer, uint16_t * size, uint16_t maxSize);\r
+    /*
+    * Read a certain endpoint.
+    *
+    * Warning: non blocking
+    *
+    * @param endpoint endpoint which will be read
+    * @param buffer buffer will be filled with the data received (if data are available)
+    * @param size the number of bytes read will be stored in *size
+    * @param maxSize the maximum length that can be read
+    * @returns true if successful
+    */
+    bool readEP_NB(uint8_t endpoint, uint8_t * buffer, uint16_t * size, uint16_t maxSize);
     \r
-    /*\r
-    * Write a certain endpoint.\r
-    *\r
-    * Warning: blocking\r
-    *\r
-    * @param endpoint endpoint to write\r
-    * @param buffer data contained in buffer will be write\r
-    * @param size the number of bytes to write\r
-    * @param maxSize the maximum length that can be written on this endpoint\r
-    */\r
-    bool write(uint8_t endpoint, uint8_t * buffer, uint16_t size, uint16_t maxSize);\r
+    /*
+    * Write a certain endpoint.
+    *
+    * Warning: blocking
+    *
+    * @param endpoint endpoint to write
+    * @param buffer data contained in buffer will be write
+    * @param size the number of bytes to write
+    * @param maxSize the maximum length that can be written on this endpoint
+    */
+    bool write(uint8_t endpoint, uint8_t * buffer, uint16_t size, uint16_t maxSize);
     \r
     \r
-    /*\r
-    * Write a certain endpoint.\r
-    *\r
-    * Warning: non blocking\r
-    *\r
-    * @param endpoint endpoint to write\r
-    * @param buffer data contained in buffer will be write\r
-    * @param size the number of bytes to write\r
-    * @param maxSize the maximum length that can be written on this endpoint\r
-    */\r
-    bool writeNB(uint8_t endpoint, uint8_t * buffer, uint16_t size, uint16_t maxSize);\r
+    /*
+    * Write a certain endpoint.
+    *
+    * Warning: non blocking
+    *
+    * @param endpoint endpoint to write
+    * @param buffer data contained in buffer will be write
+    * @param size the number of bytes to write
+    * @param maxSize the maximum length that can be written on this endpoint
+    */
+    bool writeNB(uint8_t endpoint, uint8_t * buffer, uint16_t size, uint16_t maxSize);
 \r
     \r
-    /*\r
-    * Called by USBDevice layer on bus reset. Warning: Called in ISR context\r
-    *\r
-    * May be used to reset state\r
-    */\r
-    virtual void USBCallback_busReset(void) {};\r
+    /*
+    * Called by USBDevice layer on bus reset. Warning: Called in ISR context
+    *
+    * May be used to reset state
+    */
+    virtual void USBCallback_busReset(void) {};
     \r
-    /*\r
-    * Called by USBDevice on Endpoint0 request. Warning: Called in ISR context\r
-    * This is used to handle extensions to standard requests\r
-    * and class specific requests\r
-    *\r
-    * @returns true if class handles this request\r
-    */\r
-    virtual bool USBCallback_request() { return false; };   \r
+    /*
+    * Called by USBDevice on Endpoint0 request. Warning: Called in ISR context
+    * This is used to handle extensions to standard requests
+    * and class specific requests
+    *
+    * @returns true if class handles this request
+    */
+    virtual bool USBCallback_request() { return false; };
     \r
-    /*\r
-    * Called by USBDevice on Endpoint0 request completion\r
-    * if the 'notify' flag has been set to true. Warning: Called in ISR context\r
-    *\r
-    * In this case it is used to indicate that a HID report has\r
-    * been received from the host on endpoint 0\r
-    *\r
-    * @param buf buffer received on endpoint 0\r
-    * @param length length of this buffer\r
-    */\r
-    virtual void USBCallback_requestCompleted(uint8_t * buf, uint16_t length) {};\r
+    /*
+    * Called by USBDevice on Endpoint0 request completion
+    * if the 'notify' flag has been set to true. Warning: Called in ISR context
+    *
+    * In this case it is used to indicate that a HID report has
+    * been received from the host on endpoint 0
+    *
+    * @param buf buffer received on endpoint 0
+    * @param length length of this buffer
+    */
+    virtual void USBCallback_requestCompleted(uint8_t * buf, uint16_t length) {};
     \r
-    /*\r
-    * Called by USBDevice layer. Set configuration of the device.\r
-    * For instance, you can add all endpoints that you need on this function.\r
-    *\r
-    * @param configuration Number of the configuration\r
-    */\r
-    virtual bool USBCallback_setConfiguration(uint8_t configuration) { return false; };\r
+    /*
+    * Called by USBDevice layer. Set configuration of the device.
+    * For instance, you can add all endpoints that you need on this function.
+    *
+    * @param configuration Number of the configuration
+    */
+    virtual bool USBCallback_setConfiguration(uint8_t configuration) { return false; };
     \r
-    /*\r
-     * Called by USBDevice layer. Set interface/alternate of the device.\r
-     *\r
-     * @param interface Number of the interface to be configured\r
-     * @param alternate Number of the alternate to be configured\r
-     * @returns true if class handles this request\r
-     */\r
-    virtual bool USBCallback_setInterface(uint16_t interface, uint8_t alternate) { return false; };\r
+    /*
+     * Called by USBDevice layer. Set interface/alternate of the device.
+     *
+     * @param interface Number of the interface to be configured
+     * @param alternate Number of the alternate to be configured
+     * @returns true if class handles this request
+     */
+    virtual bool USBCallback_setInterface(uint16_t interface, uint8_t alternate) { return false; };
 \r
-    /*\r
-    * Get device descriptor. Warning: this method has to store the length of the report descriptor in reportLength.\r
-    *\r
-    * @returns pointer to the device descriptor\r
-    */\r
-    virtual uint8_t * deviceDesc();\r
+    /*
+    * Get device descriptor. Warning: this method has to store the length of the report descriptor in reportLength.
+    *
+    * @returns pointer to the device descriptor
+    */
+    virtual uint8_t * deviceDesc();
     \r
-    /*\r
-    * Get configuration descriptor\r
-    *\r
-    * @returns pointer to the configuration descriptor\r
-    */\r
-    virtual uint8_t * configurationDesc(){return NULL;};\r
+    /*
+    * Get configuration descriptor
+    *
+    * @returns pointer to the configuration descriptor
+    */
+    virtual uint8_t * configurationDesc(){return NULL;};
     \r
-    /*\r
-    * Get string lang id descriptor\r
-    *\r
-    * @return pointer to the string lang id descriptor\r
-    */\r
-    virtual uint8_t * stringLangidDesc();\r
+    /*
+    * Get string lang id descriptor
+    *
+    * @return pointer to the string lang id descriptor
+    */
+    virtual uint8_t * stringLangidDesc();
     \r
-    /*\r
-    * Get string manufacturer descriptor\r
-    *\r
-    * @returns pointer to the string manufacturer descriptor\r
-    */\r
-    virtual uint8_t * stringImanufacturerDesc();\r
+    /*
+    * Get string manufacturer descriptor
+    *
+    * @returns pointer to the string manufacturer descriptor
+    */
+    virtual uint8_t * stringImanufacturerDesc();
     \r
-    /*\r
-    * Get string product descriptor\r
-    *\r
-    * @returns pointer to the string product descriptor\r
-    */\r
-    virtual uint8_t * stringIproductDesc();\r
+    /*
+    * Get string product descriptor
+    *
+    * @returns pointer to the string product descriptor
+    */
+    virtual uint8_t * stringIproductDesc();
     \r
-    /*\r
-    * Get string serial descriptor\r
-    *\r
-    * @returns pointer to the string serial descriptor\r
-    */\r
-    virtual uint8_t * stringIserialDesc();\r
+    /*
+    * Get string serial descriptor
+    *
+    * @returns pointer to the string serial descriptor
+    */
+    virtual uint8_t * stringIserialDesc();
     \r
-    /*\r
-    * Get string configuration descriptor\r
-    *\r
-    * @returns pointer to the string configuration descriptor\r
-    */\r
-    virtual uint8_t * stringIConfigurationDesc();\r
+    /*
+    * Get string configuration descriptor
+    *
+    * @returns pointer to the string configuration descriptor
+    */
+    virtual uint8_t * stringIConfigurationDesc();
     \r
-    /*\r
-    * Get string interface descriptor\r
-    *\r
-    * @returns pointer to the string interface descriptor\r
-    */\r
-    virtual uint8_t * stringIinterfaceDesc();\r
+    /*
+    * Get string interface descriptor
+    *
+    * @returns pointer to the string interface descriptor
+    */
+    virtual uint8_t * stringIinterfaceDesc();
     \r
-    /*\r
-    * Get the length of the report descriptor\r
-    *\r
-    * @returns length of the report descriptor\r
-    */\r
-    virtual uint16_t reportDescLength() { return 0; };\r
+    /*
+    * Get the length of the report descriptor
+    *
+    * @returns length of the report descriptor
+    */
+    virtual uint16_t reportDescLength() { return 0; };
     \r
 \r
 \r
-protected:\r
-    virtual void busReset(void);\r
-    virtual void EP0setupCallback(void);\r
-    virtual void EP0out(void);\r
-    virtual void EP0in(void);\r
-    virtual void connectStateChanged(unsigned int connected);\r
-    virtual void suspendStateChanged(unsigned int suspended);\r
-    uint8_t * findDescriptor(uint8_t descriptorType);\r
-    CONTROL_TRANSFER * getTransferPtr(void);\r
+protected:
+    virtual void busReset(void);
+    virtual void EP0setupCallback(void);
+    virtual void EP0out(void);
+    virtual void EP0in(void);
+    virtual void connectStateChanged(unsigned int connected);
+    virtual void suspendStateChanged(unsigned int suspended);
+    uint8_t * findDescriptor(uint8_t descriptorType);
+    CONTROL_TRANSFER * getTransferPtr(void);
     \r
-    uint16_t VENDOR_ID;\r
-    uint16_t PRODUCT_ID;\r
-    uint16_t PRODUCT_RELEASE;\r
+    uint16_t VENDOR_ID;
+    uint16_t PRODUCT_ID;
+    uint16_t PRODUCT_RELEASE;
 \r
-private:\r
-    bool addRateFeedbackEndpoint(uint8_t endpoint, uint32_t maxPacket);\r
-    bool requestGetDescriptor(void);\r
-    bool controlOut(void);\r
-    bool controlIn(void);\r
-    bool requestSetAddress(void);\r
-    bool requestSetConfiguration(void);\r
-    bool requestSetFeature(void);\r
-    bool requestClearFeature(void);\r
-    bool requestGetStatus(void);\r
-    bool requestSetup(void);\r
-    bool controlSetup(void);\r
-    void decodeSetupPacket(uint8_t *data, SETUP_PACKET *packet);\r
-    bool requestGetConfiguration(void);\r
-    bool requestGetInterface(void);\r
-    bool requestSetInterface(void);\r
+private:
+    bool addRateFeedbackEndpoint(uint8_t endpoint, uint32_t maxPacket);
+    bool requestGetDescriptor(void);
+    bool controlOut(void);
+    bool controlIn(void);
+    bool requestSetAddress(void);
+    bool requestSetConfiguration(void);
+    bool requestSetFeature(void);
+    bool requestClearFeature(void);
+    bool requestGetStatus(void);
+    bool requestSetup(void);
+    bool controlSetup(void);
+    void decodeSetupPacket(uint8_t *data, SETUP_PACKET *packet);
+    bool requestGetConfiguration(void);
+    bool requestGetInterface(void);
+    bool requestSetInterface(void);
 \r
-    CONTROL_TRANSFER transfer;\r
-    USB_DEVICE device;\r
+    CONTROL_TRANSFER transfer;
+    USB_DEVICE device;
     \r
-    uint16_t currentInterface;\r
-    uint8_t currentAlternate;\r
-};\r
+    uint16_t currentInterface;
+    uint8_t currentAlternate;
+};
 \r
 \r
-#endif\r
+#endif
index d636712..c0b1724 100644 (file)
@@ -1,69 +1,69 @@
-/* USBDevice_Types.h */\r
-/* USB Device type definitions, conversions and constants */\r
-/* Copyright (c) 2011 ARM Limited. All rights reserved. */\r
+/* USBDevice_Types.h */
+/* USB Device type definitions, conversions and constants */
+/* Copyright (c) 2011 ARM Limited. All rights reserved. */
 \r
-#ifndef USBDEVICE_TYPES_H\r
-#define USBDEVICE_TYPES_H\r
+#ifndef USBDEVICE_TYPES_H
+#define USBDEVICE_TYPES_H
 \r
-/* Standard requests */\r
-#define GET_STATUS        (0)\r
-#define CLEAR_FEATURE     (1)\r
-#define SET_FEATURE       (3)\r
-#define SET_ADDRESS       (5)\r
-#define GET_DESCRIPTOR    (6)\r
-#define SET_DESCRIPTOR    (7)\r
-#define GET_CONFIGURATION (8)\r
-#define SET_CONFIGURATION (9)\r
-#define GET_INTERFACE     (10)\r
-#define SET_INTERFACE     (11)\r
+/* Standard requests */
+#define GET_STATUS        (0)
+#define CLEAR_FEATURE     (1)
+#define SET_FEATURE       (3)
+#define SET_ADDRESS       (5)
+#define GET_DESCRIPTOR    (6)
+#define SET_DESCRIPTOR    (7)
+#define GET_CONFIGURATION (8)
+#define SET_CONFIGURATION (9)
+#define GET_INTERFACE     (10)
+#define SET_INTERFACE     (11)
 \r
-/* bmRequestType.dataTransferDirection */\r
-#define HOST_TO_DEVICE (0)\r
-#define DEVICE_TO_HOST (1)\r
+/* bmRequestType.dataTransferDirection */
+#define HOST_TO_DEVICE (0)
+#define DEVICE_TO_HOST (1)
 \r
-/* bmRequestType.Type*/\r
-#define STANDARD_TYPE  (0)\r
-#define CLASS_TYPE     (1)\r
-#define VENDOR_TYPE    (2)\r
-#define RESERVED_TYPE  (3)\r
+/* bmRequestType.Type*/
+#define STANDARD_TYPE  (0)
+#define CLASS_TYPE     (1)
+#define VENDOR_TYPE    (2)
+#define RESERVED_TYPE  (3)
 \r
-/* bmRequestType.Recipient */\r
-#define DEVICE_RECIPIENT    (0)\r
-#define INTERFACE_RECIPIENT (1)\r
-#define ENDPOINT_RECIPIENT  (2)\r
-#define OTHER_RECIPIENT     (3)\r
+/* bmRequestType.Recipient */
+#define DEVICE_RECIPIENT    (0)
+#define INTERFACE_RECIPIENT (1)
+#define ENDPOINT_RECIPIENT  (2)
+#define OTHER_RECIPIENT     (3)
 \r
-/* Descriptors */\r
-#define DESCRIPTOR_TYPE(wValue)  (wValue >> 8)\r
-#define DESCRIPTOR_INDEX(wValue) (wValue & 0xf)\r
+/* Descriptors */
+#define DESCRIPTOR_TYPE(wValue)  (wValue >> 8)
+#define DESCRIPTOR_INDEX(wValue) (wValue & 0xf)
 \r
-typedef struct {\r
-    struct {\r
-        uint8_t dataTransferDirection;\r
-        uint8_t Type;\r
-        uint8_t Recipient;\r
-    } bmRequestType;\r
-    uint8_t  bRequest;\r
-    uint16_t wValue;\r
-    uint16_t wIndex;\r
-    uint16_t wLength;\r
-} SETUP_PACKET;\r
+typedef struct {
+    struct {
+        uint8_t dataTransferDirection;
+        uint8_t Type;
+        uint8_t Recipient;
+    } bmRequestType;
+    uint8_t  bRequest;
+    uint16_t wValue;
+    uint16_t wIndex;
+    uint16_t wLength;
+} SETUP_PACKET;
 \r
-typedef struct {\r
-    SETUP_PACKET setup;\r
-    uint8_t *ptr;\r
-    uint32_t remaining;\r
-    uint8_t direction;\r
-    bool zlp;\r
-    bool notify;\r
-} CONTROL_TRANSFER;\r
+typedef struct {
+    SETUP_PACKET setup;
+    uint8_t *ptr;
+    uint32_t remaining;
+    uint8_t direction;
+    bool zlp;
+    bool notify;
+} CONTROL_TRANSFER;
 \r
-typedef enum {ATTACHED, POWERED, DEFAULT, ADDRESS, CONFIGURED} DEVICE_STATE;\r
+typedef enum {ATTACHED, POWERED, DEFAULT, ADDRESS, CONFIGURED} DEVICE_STATE;
 \r
-typedef struct {\r
-    volatile DEVICE_STATE state;\r
-    uint8_t configuration;\r
-    bool suspended;\r
-} USB_DEVICE;\r
+typedef struct {
+    volatile DEVICE_STATE state;
+    uint8_t configuration;
+    bool suspended;
+} USB_DEVICE;
 \r
-#endif\r
+#endif
index 6a51336..ffcd9c5 100644 (file)
@@ -1,34 +1,34 @@
-/* USBEndpoints.h */\r
-/* USB endpoint configuration */\r
-/* Copyright (c) 2011 ARM Limited. All rights reserved. */\r
+/* USBEndpoints.h */
+/* USB endpoint configuration */
+/* Copyright (c) 2011 ARM Limited. All rights reserved. */
 \r
-#ifndef USBENDPOINTS_H\r
-#define USBENDPOINTS_H\r
+#ifndef USBENDPOINTS_H
+#define USBENDPOINTS_H
 \r
-/* SETUP packet size */\r
-#define SETUP_PACKET_SIZE (8)\r
+/* SETUP packet size */
+#define SETUP_PACKET_SIZE (8)
 \r
-/* Options flags for configuring endpoints */\r
-#define DEFAULT_OPTIONS     (0)\r
-#define SINGLE_BUFFERED     (1U << 0)\r
-#define ISOCHRONOUS         (1U << 1)\r
-#define RATE_FEEDBACK_MODE  (1U << 2) /* Interrupt endpoints only */\r
+/* Options flags for configuring endpoints */
+#define DEFAULT_OPTIONS     (0)
+#define SINGLE_BUFFERED     (1U << 0)
+#define ISOCHRONOUS         (1U << 1)
+#define RATE_FEEDBACK_MODE  (1U << 2) /* Interrupt endpoints only */
 \r
-/* Endpoint transfer status, for endpoints > 0 */\r
-typedef enum {\r
-    EP_COMPLETED,   /* Transfer completed */\r
-    EP_PENDING,     /* Transfer in progress */\r
-    EP_INVALID,     /* Invalid parameter */\r
-    EP_STALLED,     /* Endpoint stalled */\r
-} EP_STATUS;\r
+/* Endpoint transfer status, for endpoints > 0 */
+typedef enum {
+    EP_COMPLETED,   /* Transfer completed */
+    EP_PENDING,     /* Transfer in progress */
+    EP_INVALID,     /* Invalid parameter */
+    EP_STALLED,     /* Endpoint stalled */
+} EP_STATUS;
 \r
-/* Include configuration for specific target */\r
-#if defined(TARGET_LPC1768) || defined(TARGET_LPC2368)\r
-#include "USBEndpoints_LPC17_LPC23.h"\r
-#elif defined(TARGET_LPC11U24)\r
-#include "USBEndpoints_LPC11U.h"\r
-#else\r
-#error "Unknown target type"\r
-#endif\r
+/* Include configuration for specific target */
+#if defined(TARGET_LPC1768) || defined(TARGET_LPC2368)
+#include "USBEndpoints_LPC17_LPC23.h"
+#elif defined(TARGET_LPC11U24)
+#include "USBEndpoints_LPC11U.h"
+#else
+#error "Unknown target type"
+#endif
 \r
-#endif\r
+#endif
index 6b546e0..9bba5be 100644 (file)
@@ -1,51 +1,51 @@
-/* USBEndpoints_LPC11U.h */\r
-/* Endpoint configuration for LPC11U */\r
-/* Copyright (c) 2011 ARM Limited. All rights reserved. */\r
-\r
-#define NUMBER_OF_LOGICAL_ENDPOINTS (5)\r
-#define NUMBER_OF_PHYSICAL_ENDPOINTS (NUMBER_OF_LOGICAL_ENDPOINTS * 2)\r
-\r
-/* Define physical endpoint numbers */\r
-\r
-/*      Endpoint    No.     Type(s)       MaxPacket   DoubleBuffer  */\r
-/*      ----------------    ------------  ----------  ---           */\r
-#define EP0OUT      (0)  /* Control       64          No            */\r
-#define EP0IN       (1)  /* Control       64          No            */\r
-#define EP1OUT      (2)  /* Int/Bulk/Iso  64/64/1023  Yes           */\r
-#define EP1IN       (3)  /* Int/Bulk/Iso  64/64/1023  Yes           */\r
-#define EP2OUT      (4)  /* Int/Bulk/Iso  64/64/1023  Yes           */\r
-#define EP2IN       (5)  /* Int/Bulk/Iso  64/64/1023  Yes           */\r
-#define EP3OUT      (6)  /* Int/Bulk/Iso  64/64/1023  Yes           */\r
-#define EP3IN       (7)  /* Int/Bulk/Iso  64/64/1023  Yes           */\r
-#define EP4OUT      (8)  /* Int/Bulk/Iso  64/64/1023  Yes           */\r
-#define EP4IN       (9)  /* Int/Bulk/Iso  64/64/1023  Yes           */\r
-\r
-/* Maximum Packet sizes */\r
-\r
-#define MAX_PACKET_SIZE_EP0 (64)\r
-#define MAX_PACKET_SIZE_EP1 (64) /* Int/Bulk */\r
-#define MAX_PACKET_SIZE_EP2 (64) /* Int/Bulk */\r
-#define MAX_PACKET_SIZE_EP3 (64) /* Int/Bulk */\r
-#define MAX_PACKET_SIZE_EP4 (64) /* Int/Bulk */\r
-\r
-#define MAX_PACKET_SIZE_EP1_ISO (1023) /* Isochronous */\r
-#define MAX_PACKET_SIZE_EP2_ISO (1023) /* Isochronous */\r
-#define MAX_PACKET_SIZE_EP3_ISO (1023) /* Isochronous */\r
-#define MAX_PACKET_SIZE_EP4_ISO (1023) /* Isochronous */\r
-\r
-/* Generic endpoints - intended to be portable accross devices */\r
-/* and be suitable for simple USB devices. */\r
-\r
-/* Bulk endpoint */\r
-#define EPBULK_OUT  (EP2OUT)\r
-#define EPBULK_IN   (EP2IN)\r
-/* Interrupt endpoint */\r
-#define EPINT_OUT   (EP1OUT)\r
-#define EPINT_IN    (EP1IN)\r
-/* Isochronous endpoint */\r
-#define EPISO_OUT   (EP3OUT)\r
-#define EPISO_IN    (EP3IN)\r
-\r
-#define MAX_PACKET_SIZE_EPBULK  (MAX_PACKET_SIZE_EP2)\r
-#define MAX_PACKET_SIZE_EPINT   (MAX_PACKET_SIZE_EP1)\r
-#define MAX_PACKET_SIZE_EPISO   (MAX_PACKET_SIZE_EP3_ISO)\r
+/* USBEndpoints_LPC11U.h */
+/* Endpoint configuration for LPC11U */
+/* Copyright (c) 2011 ARM Limited. All rights reserved. */
+\r
+#define NUMBER_OF_LOGICAL_ENDPOINTS (5)
+#define NUMBER_OF_PHYSICAL_ENDPOINTS (NUMBER_OF_LOGICAL_ENDPOINTS * 2)
+\r
+/* Define physical endpoint numbers */
+\r
+/*      Endpoint    No.     Type(s)       MaxPacket   DoubleBuffer  */
+/*      ----------------    ------------  ----------  ---           */
+#define EP0OUT      (0)  /* Control       64          No            */
+#define EP0IN       (1)  /* Control       64          No            */
+#define EP1OUT      (2)  /* Int/Bulk/Iso  64/64/1023  Yes           */
+#define EP1IN       (3)  /* Int/Bulk/Iso  64/64/1023  Yes           */
+#define EP2OUT      (4)  /* Int/Bulk/Iso  64/64/1023  Yes           */
+#define EP2IN       (5)  /* Int/Bulk/Iso  64/64/1023  Yes           */
+#define EP3OUT      (6)  /* Int/Bulk/Iso  64/64/1023  Yes           */
+#define EP3IN       (7)  /* Int/Bulk/Iso  64/64/1023  Yes           */
+#define EP4OUT      (8)  /* Int/Bulk/Iso  64/64/1023  Yes           */
+#define EP4IN       (9)  /* Int/Bulk/Iso  64/64/1023  Yes           */
+\r
+/* Maximum Packet sizes */
+\r
+#define MAX_PACKET_SIZE_EP0 (64)
+#define MAX_PACKET_SIZE_EP1 (64) /* Int/Bulk */
+#define MAX_PACKET_SIZE_EP2 (64) /* Int/Bulk */
+#define MAX_PACKET_SIZE_EP3 (64) /* Int/Bulk */
+#define MAX_PACKET_SIZE_EP4 (64) /* Int/Bulk */
+\r
+#define MAX_PACKET_SIZE_EP1_ISO (1023) /* Isochronous */
+#define MAX_PACKET_SIZE_EP2_ISO (1023) /* Isochronous */
+#define MAX_PACKET_SIZE_EP3_ISO (1023) /* Isochronous */
+#define MAX_PACKET_SIZE_EP4_ISO (1023) /* Isochronous */
+\r
+/* Generic endpoints - intended to be portable accross devices */
+/* and be suitable for simple USB devices. */
+\r
+/* Bulk endpoint */
+#define EPBULK_OUT  (EP2OUT)
+#define EPBULK_IN   (EP2IN)
+/* Interrupt endpoint */
+#define EPINT_OUT   (EP1OUT)
+#define EPINT_IN    (EP1IN)
+/* Isochronous endpoint */
+#define EPISO_OUT   (EP3OUT)
+#define EPISO_IN    (EP3IN)
+\r
+#define MAX_PACKET_SIZE_EPBULK  (MAX_PACKET_SIZE_EP2)
+#define MAX_PACKET_SIZE_EPINT   (MAX_PACKET_SIZE_EP1)
+#define MAX_PACKET_SIZE_EPISO   (MAX_PACKET_SIZE_EP3_ISO)
index 1f760c1..fa88d9c 100644 (file)
@@ -1,84 +1,84 @@
-/* USBEndpoints_LPC17_LPC23.h */\r
-/* Endpoint configuration for LPC1768 and LPC2368 */\r
-/* Copyright (c) 2011 ARM Limited. All rights reserved. */\r
+/* USBEndpoints_LPC17_LPC23.h */
+/* Endpoint configuration for LPC1768 and LPC2368 */
+/* Copyright (c) 2011 ARM Limited. All rights reserved. */
 \r
-#define NUMBER_OF_LOGICAL_ENDPOINTS (16)\r
-#define NUMBER_OF_PHYSICAL_ENDPOINTS (NUMBER_OF_LOGICAL_ENDPOINTS * 2)\r
+#define NUMBER_OF_LOGICAL_ENDPOINTS (16)
+#define NUMBER_OF_PHYSICAL_ENDPOINTS (NUMBER_OF_LOGICAL_ENDPOINTS * 2)
 \r
-/* Define physical endpoint numbers */\r
+/* Define physical endpoint numbers */
 \r
-/*      Endpoint    No.     Type(s)       MaxPacket   DoubleBuffer  */\r
-/*      ----------------    ------------  ----------  ---           */\r
-#define EP0OUT      (0)  /* Control       64          No            */\r
-#define EP0IN       (1)  /* Control       64          No            */\r
-#define EP1OUT      (2)  /* Interrupt     64          No            */\r
-#define EP1IN       (3)  /* Interrupt     64          No            */\r
-#define EP2OUT      (4)  /* Bulk          64          Yes           */\r
-#define EP2IN       (5)  /* Bulk          64          Yes           */\r
-#define EP3OUT      (6)  /* Isochronous   1023        Yes           */\r
-#define EP3IN       (7)  /* Isochronous   1023        Yes           */\r
-#define EP4OUT      (8)  /* Interrupt     64          No            */\r
-#define EP4IN       (9)  /* Interrupt     64          No            */\r
-#define EP5OUT      (10) /* Bulk          64          Yes           */\r
-#define EP5IN       (11) /* Bulk          64          Yes           */\r
-#define EP6OUT      (12) /* Isochronous   1023        Yes           */\r
-#define EP6IN       (13) /* Isochronous   1023        Yes           */\r
-#define EP7OUT      (14) /* Interrupt     64          No            */\r
-#define EP7IN       (15) /* Interrupt     64          No            */\r
-#define EP8OUT      (16) /* Bulk          64          Yes           */\r
-#define EP8IN       (17) /* Bulk          64          Yes           */\r
-#define EP9OUT      (18) /* Isochronous   1023        Yes           */\r
-#define EP9IN       (19) /* Isochronous   1023        Yes           */\r
-#define EP10OUT     (20) /* Interrupt     64          No            */\r
-#define EP10IN      (21) /* Interrupt     64          No            */\r
-#define EP11OUT     (22) /* Bulk          64          Yes           */\r
-#define EP11IN      (23) /* Bulk          64          Yes           */\r
-#define EP12OUT     (24) /* Isochronous   1023        Yes           */\r
-#define EP12IN      (25) /* Isochronous   1023        Yes           */\r
-#define EP13OUT     (26) /* Interrupt     64          No            */\r
-#define EP13IN      (27) /* Interrupt     64          No            */\r
-#define EP14OUT     (28) /* Bulk          64          Yes           */\r
-#define EP14IN      (29) /* Bulk          64          Yes           */\r
-#define EP15OUT     (30) /* Bulk          64          Yes           */\r
-#define EP15IN      (31) /* Bulk          64          Yes           */\r
+/*      Endpoint    No.     Type(s)       MaxPacket   DoubleBuffer  */
+/*      ----------------    ------------  ----------  ---           */
+#define EP0OUT      (0)  /* Control       64          No            */
+#define EP0IN       (1)  /* Control       64          No            */
+#define EP1OUT      (2)  /* Interrupt     64          No            */
+#define EP1IN       (3)  /* Interrupt     64          No            */
+#define EP2OUT      (4)  /* Bulk          64          Yes           */
+#define EP2IN       (5)  /* Bulk          64          Yes           */
+#define EP3OUT      (6)  /* Isochronous   1023        Yes           */
+#define EP3IN       (7)  /* Isochronous   1023        Yes           */
+#define EP4OUT      (8)  /* Interrupt     64          No            */
+#define EP4IN       (9)  /* Interrupt     64          No            */
+#define EP5OUT      (10) /* Bulk          64          Yes           */
+#define EP5IN       (11) /* Bulk          64          Yes           */
+#define EP6OUT      (12) /* Isochronous   1023        Yes           */
+#define EP6IN       (13) /* Isochronous   1023        Yes           */
+#define EP7OUT      (14) /* Interrupt     64          No            */
+#define EP7IN       (15) /* Interrupt     64          No            */
+#define EP8OUT      (16) /* Bulk          64          Yes           */
+#define EP8IN       (17) /* Bulk          64          Yes           */
+#define EP9OUT      (18) /* Isochronous   1023        Yes           */
+#define EP9IN       (19) /* Isochronous   1023        Yes           */
+#define EP10OUT     (20) /* Interrupt     64          No            */
+#define EP10IN      (21) /* Interrupt     64          No            */
+#define EP11OUT     (22) /* Bulk          64          Yes           */
+#define EP11IN      (23) /* Bulk          64          Yes           */
+#define EP12OUT     (24) /* Isochronous   1023        Yes           */
+#define EP12IN      (25) /* Isochronous   1023        Yes           */
+#define EP13OUT     (26) /* Interrupt     64          No            */
+#define EP13IN      (27) /* Interrupt     64          No            */
+#define EP14OUT     (28) /* Bulk          64          Yes           */
+#define EP14IN      (29) /* Bulk          64          Yes           */
+#define EP15OUT     (30) /* Bulk          64          Yes           */
+#define EP15IN      (31) /* Bulk          64          Yes           */
 \r
-/* Maximum Packet sizes */\r
+/* Maximum Packet sizes */
 \r
-#define MAX_PACKET_SIZE_EP0  (64)\r
-#define MAX_PACKET_SIZE_EP1  (64)\r
-#define MAX_PACKET_SIZE_EP2  (64)\r
-#define MAX_PACKET_SIZE_EP3  (1023)\r
-#define MAX_PACKET_SIZE_EP4  (64)\r
-#define MAX_PACKET_SIZE_EP5  (64)\r
-#define MAX_PACKET_SIZE_EP6  (1023)\r
-#define MAX_PACKET_SIZE_EP7  (64)\r
-#define MAX_PACKET_SIZE_EP8  (64)\r
-#define MAX_PACKET_SIZE_EP9  (1023)\r
-#define MAX_PACKET_SIZE_EP10 (64)\r
-#define MAX_PACKET_SIZE_EP11 (64)\r
-#define MAX_PACKET_SIZE_EP12 (1023)\r
-#define MAX_PACKET_SIZE_EP13 (64)\r
-#define MAX_PACKET_SIZE_EP14 (64)\r
-#define MAX_PACKET_SIZE_EP15 (64)\r
+#define MAX_PACKET_SIZE_EP0  (64)
+#define MAX_PACKET_SIZE_EP1  (64)
+#define MAX_PACKET_SIZE_EP2  (64)
+#define MAX_PACKET_SIZE_EP3  (1023)
+#define MAX_PACKET_SIZE_EP4  (64)
+#define MAX_PACKET_SIZE_EP5  (64)
+#define MAX_PACKET_SIZE_EP6  (1023)
+#define MAX_PACKET_SIZE_EP7  (64)
+#define MAX_PACKET_SIZE_EP8  (64)
+#define MAX_PACKET_SIZE_EP9  (1023)
+#define MAX_PACKET_SIZE_EP10 (64)
+#define MAX_PACKET_SIZE_EP11 (64)
+#define MAX_PACKET_SIZE_EP12 (1023)
+#define MAX_PACKET_SIZE_EP13 (64)
+#define MAX_PACKET_SIZE_EP14 (64)
+#define MAX_PACKET_SIZE_EP15 (64)
 \r
-/* Generic endpoints - intended to be portable accross devices */\r
-/* and be suitable for simple USB devices. */\r
+/* Generic endpoints - intended to be portable accross devices */
+/* and be suitable for simple USB devices. */
 \r
-/* Bulk endpoints */\r
-#define EPBULK_OUT  (EP2OUT)\r
-#define EPBULK_IN   (EP2IN)\r
-/* Interrupt endpoints */\r
-#define EPINT_OUT   (EP1OUT)\r
-#define EPINT_IN    (EP1IN)\r
-/* Isochronous endpoints */\r
-#define EPISO_OUT   (EP3OUT)\r
-#define EPISO_IN    (EP3IN)\r
+/* Bulk endpoints */
+#define EPBULK_OUT  (EP2OUT)
+#define EPBULK_IN   (EP2IN)
+/* Interrupt endpoints */
+#define EPINT_OUT   (EP1OUT)
+#define EPINT_IN    (EP1IN)
+/* Isochronous endpoints */
+#define EPISO_OUT   (EP3OUT)
+#define EPISO_IN    (EP3IN)
 \r
-#define MAX_PACKET_SIZE_EPBULK  (MAX_PACKET_SIZE_EP2)\r
-#define MAX_PACKET_SIZE_EPINT   (MAX_PACKET_SIZE_EP1)\r
-#define MAX_PACKET_SIZE_EPISO   (MAX_PACKET_SIZE_EP3)\r
+#define MAX_PACKET_SIZE_EPBULK  (MAX_PACKET_SIZE_EP2)
+#define MAX_PACKET_SIZE_EPINT   (MAX_PACKET_SIZE_EP1)
+#define MAX_PACKET_SIZE_EPISO   (MAX_PACKET_SIZE_EP3)
 \r
-/* Bulk endpoints */\r
-#define MSDBULK_OUT  (EP5OUT)\r
-#define MSDBULK_IN   (EP5IN)\r
-#define MAX_PACKET_SIZE_MSDBULK  (MAX_PACKET_SIZE_EP5)\r
+/* Bulk endpoints */
+#define MSDBULK_OUT  (EP5OUT)
+#define MSDBULK_IN   (EP5IN)
+#define MAX_PACKET_SIZE_MSDBULK  (MAX_PACKET_SIZE_EP5)
index e7f6552..ae6776e 100644 (file)
-// USBHID.c\r
-// Human Interface Device (HID) class\r
-// Copyright (c) 2011 ARM Limited. All rights reserved.\r
-\r
-#include "stdint.h"\r
-#include "USBBusInterface.h"\r
-#include "USBHID.h"\r
-\r
-\r
-USBHID::USBHID(uint8_t output_report_length, uint8_t input_report_length, uint16_t vendor_id, uint16_t product_id, uint16_t product_release, bool connect): USBDevice(vendor_id, product_id, product_release)\r
-{\r
-    output_length = output_report_length;\r
-    input_length = input_report_length;\r
-    if(connect) {\r
-        USBDevice::connect();\r
-    }\r
-}\r
-\r
-\r
-bool USBHID::send(HID_REPORT *report)\r
-{\r
-    return write(EPINT_IN, report->data, report->length, MAX_HID_REPORT_SIZE);\r
-}\r
-\r
-bool USBHID::sendNB(HID_REPORT *report)\r
-{\r
-    return writeNB(EPINT_IN, report->data, report->length, MAX_HID_REPORT_SIZE);\r
-}\r
-\r
-\r
-bool USBHID::read(HID_REPORT *report)\r
-{\r
-    uint16_t bytesRead = 0;\r
-    bool result;\r
-    result = USBDevice::readEP(EPINT_OUT, report->data, &bytesRead, MAX_HID_REPORT_SIZE);\r
-    if(!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE))\r
-        return false;\r
-    report->length = bytesRead;\r
-    return result;\r
-}\r
-\r
-\r
-bool USBHID::readNB(HID_REPORT *report)\r
-{\r
-    uint16_t bytesRead = 0;\r
-    bool result;\r
-    result = USBDevice::readEP_NB(EPINT_OUT, report->data, &bytesRead, MAX_HID_REPORT_SIZE);\r
-    report->length = bytesRead;\r
-    if(!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE))\r
-        return false;\r
-    return result;\r
-}\r
-\r
-\r
-uint16_t USBHID::reportDescLength() {\r
-    reportDesc();\r
-    return reportLength;\r
-}\r
-\r
-\r
-\r
-//\r
-//  Route callbacks from lower layers to class(es)\r
-//\r
-\r
-\r
-// Called in ISR context\r
-// Called by USBDevice on Endpoint0 request\r
-// This is used to handle extensions to standard requests\r
-// and class specific requests\r
-// Return true if class handles this request\r
-bool USBHID::USBCallback_request() {\r
-    bool success = false;\r
-    CONTROL_TRANSFER * transfer = getTransferPtr();\r
-    uint8_t *hidDescriptor;\r
-\r
-    // Process additional standard requests\r
-\r
-    if ((transfer->setup.bmRequestType.Type == STANDARD_TYPE))\r
-    {\r
-        switch (transfer->setup.bRequest)\r
-        {\r
-            case GET_DESCRIPTOR:\r
-                switch (DESCRIPTOR_TYPE(transfer->setup.wValue))\r
-                {\r
-                    case REPORT_DESCRIPTOR:\r
-                        if ((reportDesc() != NULL) \\r
-                            && (reportDescLength() != 0))\r
-                        {\r
-                            transfer->remaining = reportDescLength();\r
-                            transfer->ptr = reportDesc();\r
-                            transfer->direction = DEVICE_TO_HOST;\r
-                            success = true;\r
-                        }\r
-                        break;\r
-                    case HID_DESCRIPTOR:\r
-                            // Find the HID descriptor, after the configuration descriptor\r
-                            hidDescriptor = findDescriptor(HID_DESCRIPTOR);\r
-                            if (hidDescriptor != NULL)\r
-                            {\r
-                                transfer->remaining = HID_DESCRIPTOR_LENGTH;\r
-                                transfer->ptr = hidDescriptor;\r
-                                transfer->direction = DEVICE_TO_HOST;\r
-                                success = true;\r
-                            }\r
-                            break;\r
+// USBHID.c
+// Human Interface Device (HID) class
+// Copyright (c) 2011 ARM Limited. All rights reserved.
+\r
+#include "stdint.h"
+#include "USBBusInterface.h"
+#include "USBHID.h"
+\r
+\r
+USBHID::USBHID(uint8_t output_report_length, uint8_t input_report_length, uint16_t vendor_id, uint16_t product_id, uint16_t product_release, bool connect): USBDevice(vendor_id, product_id, product_release)
+{
+    output_length = output_report_length;
+    input_length = input_report_length;
+    if(connect) {
+        USBDevice::connect();
+    }
+}
+\r
+\r
+bool USBHID::send(HID_REPORT *report)
+{
+    return write(EPINT_IN, report->data, report->length, MAX_HID_REPORT_SIZE);
+}
+\r
+bool USBHID::sendNB(HID_REPORT *report)
+{
+    return writeNB(EPINT_IN, report->data, report->length, MAX_HID_REPORT_SIZE);
+}
+\r
+\r
+bool USBHID::read(HID_REPORT *report)
+{
+    uint16_t bytesRead = 0;
+    bool result;
+    result = USBDevice::readEP(EPINT_OUT, report->data, &bytesRead, MAX_HID_REPORT_SIZE);
+    if(!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE))
+        return false;
+    report->length = bytesRead;
+    return result;
+}
+\r
+\r
+bool USBHID::readNB(HID_REPORT *report)
+{
+    uint16_t bytesRead = 0;
+    bool result;
+    result = USBDevice::readEP_NB(EPINT_OUT, report->data, &bytesRead, MAX_HID_REPORT_SIZE);
+    report->length = bytesRead;
+    if(!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE))
+        return false;
+    return result;
+}
+\r
+\r
+uint16_t USBHID::reportDescLength() {
+    reportDesc();
+    return reportLength;
+}
+\r
+\r
+\r
+//
+//  Route callbacks from lower layers to class(es)
+//
+\r
+\r
+// Called in ISR context
+// Called by USBDevice on Endpoint0 request
+// This is used to handle extensions to standard requests
+// and class specific requests
+// Return true if class handles this request
+bool USBHID::USBCallback_request() {
+    bool success = false;
+    CONTROL_TRANSFER * transfer = getTransferPtr();
+    uint8_t *hidDescriptor;
+\r
+    // Process additional standard requests
+\r
+    if ((transfer->setup.bmRequestType.Type == STANDARD_TYPE))
+    {
+        switch (transfer->setup.bRequest)
+        {
+            case GET_DESCRIPTOR:
+                switch (DESCRIPTOR_TYPE(transfer->setup.wValue))
+                {
+                    case REPORT_DESCRIPTOR:
+                        if ((reportDesc() != NULL) \
+                            && (reportDescLength() != 0))
+                        {
+                            transfer->remaining = reportDescLength();
+                            transfer->ptr = reportDesc();
+                            transfer->direction = DEVICE_TO_HOST;
+                            success = true;
+                        }
+                        break;
+                    case HID_DESCRIPTOR:
+                            // Find the HID descriptor, after the configuration descriptor
+                            hidDescriptor = findDescriptor(HID_DESCRIPTOR);
+                            if (hidDescriptor != NULL)
+                            {
+                                transfer->remaining = HID_DESCRIPTOR_LENGTH;
+                                transfer->ptr = hidDescriptor;
+                                transfer->direction = DEVICE_TO_HOST;
+                                success = true;
+                            }
+                            break;
                      \r
-                    default:\r
-                        break;\r
-                }\r
-                break;\r
-            default:\r
-                break;\r
-        }\r
-    }\r
-\r
-    // Process class-specific requests\r
-\r
-    if (transfer->setup.bmRequestType.Type == CLASS_TYPE)\r
-    {\r
-        switch (transfer->setup.bRequest)\r
-        {\r
-             case SET_REPORT:\r
-                // First byte will be used for report ID\r
-                outputReport.data[0] = transfer->setup.wValue & 0xff;\r
-                outputReport.length = transfer->setup.wLength + 1;\r
-\r
-                transfer->remaining = sizeof(outputReport.data) - 1;\r
-                transfer->ptr = &outputReport.data[1];\r
-                transfer->direction = HOST_TO_DEVICE;\r
-                transfer->notify = true;\r
-                success = true;\r
-            default:\r
-                break;\r
-        }\r
-    }\r
-\r
-    return success;\r
-}\r
-\r
-\r
-#define DEFAULT_CONFIGURATION (1)\r
-\r
-\r
-// Called in ISR context\r
-// Set configuration. Return false if the\r
-// configuration is not supported\r
-bool USBHID::USBCallback_setConfiguration(uint8_t configuration) {\r
-    if (configuration != DEFAULT_CONFIGURATION) {\r
-        return false;\r
-    }\r
-\r
-    // Configure endpoints > 0\r
-    addEndpoint(EPINT_IN, MAX_PACKET_SIZE_EPINT);\r
-    addEndpoint(EPINT_OUT, MAX_PACKET_SIZE_EPINT);\r
-\r
-    // We activate the endpoint to be able to recceive data\r
-    readStart(EPINT_OUT, MAX_PACKET_SIZE_EPINT);\r
-    return true;\r
-}\r
-\r
-\r
-uint8_t * USBHID::stringIinterfaceDesc() {\r
-    static uint8_t stringIinterfaceDescriptor[] = {\r
-        0x08,               //bLength\r
-        STRING_DESCRIPTOR,  //bDescriptorType 0x03\r
-        'H',0,'I',0,'D',0,  //bString iInterface - HID\r
-    };\r
-    return stringIinterfaceDescriptor;\r
-}\r
-\r
-uint8_t * USBHID::stringIproductDesc() {\r
-    static uint8_t stringIproductDescriptor[] = {\r
-        0x16,                                                       //bLength\r
-        STRING_DESCRIPTOR,                                          //bDescriptorType 0x03\r
-        'H',0,'I',0,'D',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0 //bString iProduct - HID device\r
-    };\r
-    return stringIproductDescriptor;\r
-}\r
-\r
-\r
-\r
-uint8_t * USBHID::reportDesc() {\r
-    static uint8_t reportDescriptor[] = {\r
-        0x06, LSB(0xFFAB), MSB(0xFFAB),\r
-        0x0A, LSB(0x0200), MSB(0x0200),\r
-        0xA1, 0x01,         // Collection 0x01\r
-        0x75, 0x08,         // report size = 8 bits\r
-        0x15, 0x00,         // logical minimum = 0\r
-        0x26, 0xFF, 0x00,   // logical maximum = 255\r
-        0x95, input_length,           // report count\r
-        0x09, 0x01,         // usage\r
-        0x81, 0x02,         // Input (array)\r
-        0x95, output_length,           // report count\r
-        0x09, 0x02,         // usage\r
-        0x91, 0x02,         // Output (array)\r
-        0xC0                // end collection\r
-\r
-    };\r
-    reportLength = sizeof(reportDescriptor);\r
-    return reportDescriptor;\r
-}\r
-\r
-#define DEFAULT_CONFIGURATION (1)\r
-#define TOTAL_DESCRIPTOR_LENGTH ((1 * CONFIGURATION_DESCRIPTOR_LENGTH) \\r
-                               + (1 * INTERFACE_DESCRIPTOR_LENGTH) \\r
-                               + (1 * HID_DESCRIPTOR_LENGTH) \\r
-                               + (2 * ENDPOINT_DESCRIPTOR_LENGTH))\r
-\r
-uint8_t * USBHID::configurationDesc() {\r
-    static uint8_t configurationDescriptor[] = {\r
-        CONFIGURATION_DESCRIPTOR_LENGTH,// bLength\r
-        CONFIGURATION_DESCRIPTOR,       // bDescriptorType\r
-        LSB(TOTAL_DESCRIPTOR_LENGTH),   // wTotalLength (LSB)\r
-        MSB(TOTAL_DESCRIPTOR_LENGTH),   // wTotalLength (MSB)\r
-        0x01,                           // bNumInterfaces\r
-        DEFAULT_CONFIGURATION,          // bConfigurationValue\r
-        0x00,                           // iConfiguration\r
-        C_RESERVED | C_SELF_POWERED,    // bmAttributes\r
-        C_POWER(0),                     // bMaxPower\r
-\r
-        INTERFACE_DESCRIPTOR_LENGTH,    // bLength\r
-        INTERFACE_DESCRIPTOR,           // bDescriptorType\r
-        0x00,                           // bInterfaceNumber\r
-        0x00,                           // bAlternateSetting\r
-        0x02,                           // bNumEndpoints\r
-        HID_CLASS,                      // bInterfaceClass\r
-        HID_SUBCLASS_NONE,              // bInterfaceSubClass\r
-        HID_PROTOCOL_NONE,              // bInterfaceProtocol\r
-        0x00,                           // iInterface\r
-\r
-        HID_DESCRIPTOR_LENGTH,          // bLength\r
-        HID_DESCRIPTOR,                 // bDescriptorType\r
-        LSB(HID_VERSION_1_11),          // bcdHID (LSB)\r
-        MSB(HID_VERSION_1_11),          // bcdHID (MSB)\r
-        0x00,                           // bCountryCode\r
-        0x01,                           // bNumDescriptors\r
-        REPORT_DESCRIPTOR,              // bDescriptorType\r
-        LSB(this->reportDescLength()),  // wDescriptorLength (LSB)\r
-        MSB(this->reportDescLength()),  // wDescriptorLength (MSB)\r
-\r
-        ENDPOINT_DESCRIPTOR_LENGTH,     // bLength\r
-        ENDPOINT_DESCRIPTOR,            // bDescriptorType\r
-        PHY_TO_DESC(EPINT_IN),          // bEndpointAddress\r
-        E_INTERRUPT,                    // bmAttributes\r
-        LSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (MSB)\r
-        1,                             // bInterval (milliseconds)\r
-\r
-        ENDPOINT_DESCRIPTOR_LENGTH,     // bLength\r
-        ENDPOINT_DESCRIPTOR,            // bDescriptorType\r
-        PHY_TO_DESC(EPINT_OUT),          // bEndpointAddress\r
-        E_INTERRUPT,                    // bmAttributes\r
-        LSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (MSB)\r
-        1,                             // bInterval (milliseconds)\r
-    };\r
-    return configurationDescriptor;\r
-}\r
+                    default:
+                        break;
+                }
+                break;
+            default:
+                break;
+        }
+    }
+\r
+    // Process class-specific requests
+\r
+    if (transfer->setup.bmRequestType.Type == CLASS_TYPE)
+    {
+        switch (transfer->setup.bRequest)
+        {
+             case SET_REPORT:
+                // First byte will be used for report ID
+                outputReport.data[0] = transfer->setup.wValue & 0xff;
+                outputReport.length = transfer->setup.wLength + 1;
+\r
+                transfer->remaining = sizeof(outputReport.data) - 1;
+                transfer->ptr = &outputReport.data[1];
+                transfer->direction = HOST_TO_DEVICE;
+                transfer->notify = true;
+                success = true;
+            default:
+                break;
+        }
+    }
+\r
+    return success;
+}
+\r
+\r
+#define DEFAULT_CONFIGURATION (1)
+\r
+\r
+// Called in ISR context
+// Set configuration. Return false if the
+// configuration is not supported
+bool USBHID::USBCallback_setConfiguration(uint8_t configuration) {
+    if (configuration != DEFAULT_CONFIGURATION) {
+        return false;
+    }
+\r
+    // Configure endpoints > 0
+    addEndpoint(EPINT_IN, MAX_PACKET_SIZE_EPINT);
+    addEndpoint(EPINT_OUT, MAX_PACKET_SIZE_EPINT);
+\r
+    // We activate the endpoint to be able to recceive data
+    readStart(EPINT_OUT, MAX_PACKET_SIZE_EPINT);
+    return true;
+}
+\r
+\r
+uint8_t * USBHID::stringIinterfaceDesc() {
+    static uint8_t stringIinterfaceDescriptor[] = {
+        0x08,               //bLength
+        STRING_DESCRIPTOR,  //bDescriptorType 0x03
+        'H',0,'I',0,'D',0,  //bString iInterface - HID
+    };
+    return stringIinterfaceDescriptor;
+}
+\r
+uint8_t * USBHID::stringIproductDesc() {
+    static uint8_t stringIproductDescriptor[] = {
+        0x16,                                                       //bLength
+        STRING_DESCRIPTOR,                                          //bDescriptorType 0x03
+        'H',0,'I',0,'D',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0 //bString iProduct - HID device
+    };
+    return stringIproductDescriptor;
+}
+\r
+\r
+\r
+uint8_t * USBHID::reportDesc() {
+    static uint8_t reportDescriptor[] = {
+        0x06, LSB(0xFFAB), MSB(0xFFAB),
+        0x0A, LSB(0x0200), MSB(0x0200),
+        0xA1, 0x01,         // Collection 0x01
+        0x75, 0x08,         // report size = 8 bits
+        0x15, 0x00,         // logical minimum = 0
+        0x26, 0xFF, 0x00,   // logical maximum = 255
+        0x95, input_length,           // report count
+        0x09, 0x01,         // usage
+        0x81, 0x02,         // Input (array)
+        0x95, output_length,           // report count
+        0x09, 0x02,         // usage
+        0x91, 0x02,         // Output (array)
+        0xC0                // end collection
+\r
+    };
+    reportLength = sizeof(reportDescriptor);
+    return reportDescriptor;
+}
+\r
+#define DEFAULT_CONFIGURATION (1)
+#define TOTAL_DESCRIPTOR_LENGTH ((1 * CONFIGURATION_DESCRIPTOR_LENGTH) \
+                               + (1 * INTERFACE_DESCRIPTOR_LENGTH) \
+                               + (1 * HID_DESCRIPTOR_LENGTH) \
+                               + (2 * ENDPOINT_DESCRIPTOR_LENGTH))
+\r
+uint8_t * USBHID::configurationDesc() {
+    static uint8_t configurationDescriptor[] = {
+        CONFIGURATION_DESCRIPTOR_LENGTH,// bLength
+        CONFIGURATION_DESCRIPTOR,       // bDescriptorType
+        LSB(TOTAL_DESCRIPTOR_LENGTH),   // wTotalLength (LSB)
+        MSB(TOTAL_DESCRIPTOR_LENGTH),   // wTotalLength (MSB)
+        0x01,                           // bNumInterfaces
+        DEFAULT_CONFIGURATION,          // bConfigurationValue
+        0x00,                           // iConfiguration
+        C_RESERVED | C_SELF_POWERED,    // bmAttributes
+        C_POWER(0),                     // bMaxPower
+\r
+        INTERFACE_DESCRIPTOR_LENGTH,    // bLength
+        INTERFACE_DESCRIPTOR,           // bDescriptorType
+        0x00,                           // bInterfaceNumber
+        0x00,                           // bAlternateSetting
+        0x02,                           // bNumEndpoints
+        HID_CLASS,                      // bInterfaceClass
+        HID_SUBCLASS_NONE,              // bInterfaceSubClass
+        HID_PROTOCOL_NONE,              // bInterfaceProtocol
+        0x00,                           // iInterface
+\r
+        HID_DESCRIPTOR_LENGTH,          // bLength
+        HID_DESCRIPTOR,                 // bDescriptorType
+        LSB(HID_VERSION_1_11),          // bcdHID (LSB)
+        MSB(HID_VERSION_1_11),          // bcdHID (MSB)
+        0x00,                           // bCountryCode
+        0x01,                           // bNumDescriptors
+        REPORT_DESCRIPTOR,              // bDescriptorType
+        LSB(this->reportDescLength()),  // wDescriptorLength (LSB)
+        MSB(this->reportDescLength()),  // wDescriptorLength (MSB)
+\r
+        ENDPOINT_DESCRIPTOR_LENGTH,     // bLength
+        ENDPOINT_DESCRIPTOR,            // bDescriptorType
+        PHY_TO_DESC(EPINT_IN),          // bEndpointAddress
+        E_INTERRUPT,                    // bmAttributes
+        LSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (MSB)
+        1,                             // bInterval (milliseconds)
+\r
+        ENDPOINT_DESCRIPTOR_LENGTH,     // bLength
+        ENDPOINT_DESCRIPTOR,            // bDescriptorType
+        PHY_TO_DESC(EPINT_OUT),          // bEndpointAddress
+        E_INTERRUPT,                    // bmAttributes
+        LSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (MSB)
+        1,                             // bInterval (milliseconds)
+    };
+    return configurationDescriptor;
+}
index bc0701e..5b2a29a 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#ifndef USB_HID_H\r
-#define USB_HID_H\r
-\r
-/* These headers are included for child class. */\r
-#include "USBEndpoints.h"\r
-#include "USBDescriptor.h"\r
-#include "USBDevice_Types.h"\r
-\r
-#include "USBHID_Types.h"\r
-#include "USBDevice.h"\r
-\r
-\r
-/**\r
- * USBHID example\r
- * @code\r
- * #include "mbed.h"\r
- * #include "USBHID.h"\r
- *\r
- * USBHID hid;\r
- * HID_REPORT recv;\r
- * BusOut leds(LED1,LED2,LED3,LED4);\r
- *\r
- * int main(void) {\r
- *    while (1) {\r
- *        hid.read(&recv);\r
- *        leds = recv.data[0];\r
- *    }\r
- * }\r
- * @endcode\r
- */\r
-\r
-class USBHID: public USBDevice {\r
-public:\r
-\r
-    /**\r
-    * Constructor\r
-    *\r
-    * @param output_report_length Maximum length of a sent report (up to 64 bytes) (default: 64 bytes)\r
-    * @param input_report_length Maximum length of a received report (up to 64 bytes) (default: 64 bytes)\r
-    * @param vendor_id Your vendor_id\r
-    * @param product_id Your product_id\r
-    * @param product_release Your preoduct_release\r
-    * @param connect Connect the device\r
-    */\r
-    USBHID(uint8_t output_report_length = 64, uint8_t input_report_length = 64, uint16_t vendor_id = 0x1234, uint16_t product_id = 0x0006, uint16_t product_release = 0x0001, bool connect = true);\r
-\r
-\r
-    /**\r
-    * Send a Report. warning: blocking\r
-    *\r
-    * @param report Report which will be sent (a report is defined by all data and the length)\r
-    * @returns true if successful\r
-    */\r
-    bool send(HID_REPORT *report);\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#ifndef USB_HID_H
+#define USB_HID_H
+\r
+/* These headers are included for child class. */
+#include "USBEndpoints.h"
+#include "USBDescriptor.h"
+#include "USBDevice_Types.h"
+\r
+#include "USBHID_Types.h"
+#include "USBDevice.h"
+\r
+\r
+/**
+ * USBHID example
+ * @code
+ * #include "mbed.h"
+ * #include "USBHID.h"
+ *
+ * USBHID hid;
+ * HID_REPORT recv;
+ * BusOut leds(LED1,LED2,LED3,LED4);
+ *
+ * int main(void) {
+ *    while (1) {
+ *        hid.read(&recv);
+ *        leds = recv.data[0];
+ *    }
+ * }
+ * @endcode
+ */
+\r
+class USBHID: public USBDevice {
+public:
+\r
+    /**
+    * Constructor
+    *
+    * @param output_report_length Maximum length of a sent report (up to 64 bytes) (default: 64 bytes)
+    * @param input_report_length Maximum length of a received report (up to 64 bytes) (default: 64 bytes)
+    * @param vendor_id Your vendor_id
+    * @param product_id Your product_id
+    * @param product_release Your preoduct_release
+    * @param connect Connect the device
+    */
+    USBHID(uint8_t output_report_length = 64, uint8_t input_report_length = 64, uint16_t vendor_id = 0x1234, uint16_t product_id = 0x0006, uint16_t product_release = 0x0001, bool connect = true);
+\r
+\r
+    /**
+    * Send a Report. warning: blocking
+    *
+    * @param report Report which will be sent (a report is defined by all data and the length)
+    * @returns true if successful
+    */
+    bool send(HID_REPORT *report);
     \r
     \r
-    /**\r
-    * Send a Report. warning: non blocking\r
-    *\r
-    * @param report Report which will be sent (a report is defined by all data and the length)\r
-    * @returns true if successful\r
-    */\r
-    bool sendNB(HID_REPORT *report);\r
+    /**
+    * Send a Report. warning: non blocking
+    *
+    * @param report Report which will be sent (a report is defined by all data and the length)
+    * @returns true if successful
+    */
+    bool sendNB(HID_REPORT *report);
     \r
-    /**\r
-    * Read a report: blocking\r
-    *\r
-    * @param report pointer to the report to fill\r
-    * @returns true if successful\r
-    */\r
-    bool read(HID_REPORT * report);\r
+    /**
+    * Read a report: blocking
+    *
+    * @param report pointer to the report to fill
+    * @returns true if successful
+    */
+    bool read(HID_REPORT * report);
     \r
-    /**\r
-    * Read a report: non blocking\r
-    *\r
-    * @param report pointer to the report to fill\r
-    * @returns true if successful\r
-    */\r
-    bool readNB(HID_REPORT * report);\r
-\r
-protected:\r
-    uint16_t reportLength;\r
+    /**
+    * Read a report: non blocking
+    *
+    * @param report pointer to the report to fill
+    * @returns true if successful
+    */
+    bool readNB(HID_REPORT * report);
+\r
+protected:
+    uint16_t reportLength;
     \r
-    /*\r
-    * Get the Report descriptor\r
-    *\r
-    * @returns pointer to the report descriptor\r
-    */\r
-    virtual uint8_t * reportDesc();\r
-\r
-    /*\r
-    * Get the length of the report descriptor\r
-    *\r
-    * @returns the length of the report descriptor\r
-    */\r
-    virtual uint16_t reportDescLength();\r
-\r
-    /*\r
-    * Get string product descriptor\r
-    *\r
-    * @returns pointer to the string product descriptor\r
-    */\r
-    virtual uint8_t * stringIproductDesc();\r
+    /*
+    * Get the Report descriptor
+    *
+    * @returns pointer to the report descriptor
+    */
+    virtual uint8_t * reportDesc();
+\r
+    /*
+    * Get the length of the report descriptor
+    *
+    * @returns the length of the report descriptor
+    */
+    virtual uint16_t reportDescLength();
+\r
+    /*
+    * Get string product descriptor
+    *
+    * @returns pointer to the string product descriptor
+    */
+    virtual uint8_t * stringIproductDesc();
     \r
-    /*\r
-    * Get string interface descriptor\r
-    *\r
-    * @returns pointer to the string interface descriptor\r
-    */\r
-    virtual uint8_t * stringIinterfaceDesc();\r
+    /*
+    * Get string interface descriptor
+    *
+    * @returns pointer to the string interface descriptor
+    */
+    virtual uint8_t * stringIinterfaceDesc();
     \r
-    /*\r
-    * Get configuration descriptor\r
-    *\r
-    * @returns pointer to the configuration descriptor\r
-    */\r
-    virtual uint8_t * configurationDesc();\r
-\r
-\r
-    /*\r
-    * HID Report received by SET_REPORT request. Warning: Called in ISR context\r
-    * First byte of data will be the report ID\r
-    *\r
-    * @param report Data and length received\r
-    */\r
-    virtual void HID_callbackSetReport(HID_REPORT *report){};\r
-\r
-\r
-    /*\r
-    * Called by USBDevice on Endpoint0 request. Warning: Called in ISR context\r
-    * This is used to handle extensions to standard requests\r
-    * and class specific requests\r
-    *\r
-    * @returns true if class handles this request\r
-    */\r
-    virtual bool USBCallback_request();\r
-\r
-\r
-    /*\r
-    * Called by USBDevice layer. Set configuration of the device.\r
-    * For instance, you can add all endpoints that you need on this function.\r
-    *\r
-    * @param configuration Number of the configuration\r
-    * @returns true if class handles this request\r
-    */\r
-    virtual bool USBCallback_setConfiguration(uint8_t configuration);\r
-\r
-private:\r
-    HID_REPORT outputReport;\r
-    uint8_t output_length;\r
-    uint8_t input_length;\r
-};\r
-\r
-#endif\r
+    /*
+    * Get configuration descriptor
+    *
+    * @returns pointer to the configuration descriptor
+    */
+    virtual uint8_t * configurationDesc();
+\r
+\r
+    /*
+    * HID Report received by SET_REPORT request. Warning: Called in ISR context
+    * First byte of data will be the report ID
+    *
+    * @param report Data and length received
+    */
+    virtual void HID_callbackSetReport(HID_REPORT *report){};
+\r
+\r
+    /*
+    * Called by USBDevice on Endpoint0 request. Warning: Called in ISR context
+    * This is used to handle extensions to standard requests
+    * and class specific requests
+    *
+    * @returns true if class handles this request
+    */
+    virtual bool USBCallback_request();
+\r
+\r
+    /*
+    * Called by USBDevice layer. Set configuration of the device.
+    * For instance, you can add all endpoints that you need on this function.
+    *
+    * @param configuration Number of the configuration
+    * @returns true if class handles this request
+    */
+    virtual bool USBCallback_setConfiguration(uint8_t configuration);
+\r
+private:
+    HID_REPORT outputReport;
+    uint8_t output_length;
+    uint8_t input_length;
+};
+\r
+#endif
index 0459f13..214d653 100644 (file)
@@ -1,91 +1,91 @@
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
 \r
-#ifndef USBCLASS_HID_TYPES\r
-#define USBCLASS_HID_TYPES\r
+#ifndef USBCLASS_HID_TYPES
+#define USBCLASS_HID_TYPES
 \r
-#include <stdint.h>\r
+#include <stdint.h>
 \r
-/* */\r
-#define HID_VERSION_1_11    (0x0111)\r
+/* */
+#define HID_VERSION_1_11    (0x0111)
 \r
-/* HID Class */\r
-#define HID_CLASS           (3)\r
-#define HID_SUBCLASS_NONE   (0)\r
-#define HID_PROTOCOL_NONE   (0)\r
+/* HID Class */
+#define HID_CLASS           (3)
+#define HID_SUBCLASS_NONE   (0)
+#define HID_PROTOCOL_NONE   (0)
 \r
-/* Descriptors */\r
-#define HID_DESCRIPTOR          (33)\r
-#define HID_DESCRIPTOR_LENGTH   (0x09)\r
-#define REPORT_DESCRIPTOR       (34)\r
+/* Descriptors */
+#define HID_DESCRIPTOR          (33)
+#define HID_DESCRIPTOR_LENGTH   (0x09)
+#define REPORT_DESCRIPTOR       (34)
 \r
-/* Class requests */\r
-#define GET_REPORT (0x1)\r
-#define GET_IDLE   (0x2)\r
-#define SET_REPORT (0x9)\r
-#define SET_IDLE   (0xa)\r
+/* Class requests */
+#define GET_REPORT (0x1)
+#define GET_IDLE   (0x2)
+#define SET_REPORT (0x9)
+#define SET_IDLE   (0xa)
 \r
-/* HID Class Report Descriptor */\r
-/* Short items: size is 0, 1, 2 or 3 specifying 0, 1, 2 or 4 (four) bytes */\r
-/* of data as per HID Class standard */\r
+/* HID Class Report Descriptor */
+/* Short items: size is 0, 1, 2 or 3 specifying 0, 1, 2 or 4 (four) bytes */
+/* of data as per HID Class standard */
 \r
-/* Main items */\r
-#define INPUT(size)             (0x80 | size)\r
-#define OUTPUT(size)            (0x90 | size)\r
-#define FEATURE(size)           (0xb0 | size)\r
-#define COLLECTION(size)        (0xa0 | size)\r
-#define END_COLLECTION(size)    (0xc0 | size)\r
+/* Main items */
+#define INPUT(size)             (0x80 | size)
+#define OUTPUT(size)            (0x90 | size)
+#define FEATURE(size)           (0xb0 | size)
+#define COLLECTION(size)        (0xa0 | size)
+#define END_COLLECTION(size)    (0xc0 | size)
 \r
-/* Global items */\r
-#define USAGE_PAGE(size)        (0x04 | size)\r
-#define LOGICAL_MINIMUM(size)   (0x14 | size)\r
-#define LOGICAL_MAXIMUM(size)   (0x24 | size)\r
-#define PHYSICAL_MINIMUM(size)  (0x34 | size)\r
-#define PHYSICAL_MAXIMUM(size)  (0x44 | size)\r
-#define UNIT_EXPONENT(size)     (0x54 | size)\r
-#define UNIT(size)              (0x64 | size)\r
-#define REPORT_SIZE(size)       (0x74 | size)\r
-#define REPORT_ID(size)         (0x84 | size)\r
-#define REPORT_COUNT(size)      (0x94 | size)\r
-#define PUSH(size)              (0xa4 | size)\r
-#define POP(size)               (0xb4 | size)\r
+/* Global items */
+#define USAGE_PAGE(size)        (0x04 | size)
+#define LOGICAL_MINIMUM(size)   (0x14 | size)
+#define LOGICAL_MAXIMUM(size)   (0x24 | size)
+#define PHYSICAL_MINIMUM(size)  (0x34 | size)
+#define PHYSICAL_MAXIMUM(size)  (0x44 | size)
+#define UNIT_EXPONENT(size)     (0x54 | size)
+#define UNIT(size)              (0x64 | size)
+#define REPORT_SIZE(size)       (0x74 | size)
+#define REPORT_ID(size)         (0x84 | size)
+#define REPORT_COUNT(size)      (0x94 | size)
+#define PUSH(size)              (0xa4 | size)
+#define POP(size)               (0xb4 | size)
 \r
-/* Local items */\r
-#define USAGE(size)                 (0x08 | size)\r
-#define USAGE_MINIMUM(size)         (0x18 | size)\r
-#define USAGE_MAXIMUM(size)         (0x28 | size)\r
-#define DESIGNATOR_INDEX(size)      (0x38 | size)\r
-#define DESIGNATOR_MINIMUM(size)    (0x48 | size)\r
-#define DESIGNATOR_MAXIMUM(size)    (0x58 | size)\r
-#define STRING_INDEX(size)          (0x78 | size)\r
-#define STRING_MINIMUM(size)        (0x88 | size)\r
-#define STRING_MAXIMUM(size)        (0x98 | size)\r
-#define DELIMITER(size)             (0xa8 | size)\r
+/* Local items */
+#define USAGE(size)                 (0x08 | size)
+#define USAGE_MINIMUM(size)         (0x18 | size)
+#define USAGE_MAXIMUM(size)         (0x28 | size)
+#define DESIGNATOR_INDEX(size)      (0x38 | size)
+#define DESIGNATOR_MINIMUM(size)    (0x48 | size)
+#define DESIGNATOR_MAXIMUM(size)    (0x58 | size)
+#define STRING_INDEX(size)          (0x78 | size)
+#define STRING_MINIMUM(size)        (0x88 | size)
+#define STRING_MAXIMUM(size)        (0x98 | size)
+#define DELIMITER(size)             (0xa8 | size)
 \r
-/* HID Report */\r
-/* Where report IDs are used the first byte of 'data' will be the */\r
-/* report ID and 'length' will include this report ID byte. */\r
+/* HID Report */
+/* Where report IDs are used the first byte of 'data' will be the */
+/* report ID and 'length' will include this report ID byte. */
 \r
-#define MAX_HID_REPORT_SIZE (64)\r
+#define MAX_HID_REPORT_SIZE (64)
 \r
-typedef struct {\r
-    uint32_t length;\r
-    uint8_t data[MAX_HID_REPORT_SIZE];\r
-} HID_REPORT;\r
+typedef struct {
+    uint32_t length;
+    uint8_t data[MAX_HID_REPORT_SIZE];
+} HID_REPORT;
 \r
-#endif\r
+#endif
index e349069..abfa951 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#include "stdint.h"\r
-\r
-#include "USBKeyboard.h"\r
-\r
-#define REPORT_ID_KEYBOARD 1\r
-#define REPORT_ID_VOLUME   3\r
-\r
-\r
-typedef struct {\r
-    unsigned char usage;\r
-    unsigned char modifier;\r
-} KEYMAP;\r
-\r
-#ifdef US_KEYBOARD\r
-/* US keyboard (as HID standard) */\r
-#define KEYMAP_SIZE (148)\r
-const KEYMAP keymap[KEYMAP_SIZE] = {\r
-    {0, 0},             /* NUL */\r
-    {0, 0},             /* SOH */\r
-    {0, 0},             /* STX */\r
-    {0, 0},             /* ETX */\r
-    {0, 0},             /* EOT */\r
-    {0, 0},             /* ENQ */\r
-    {0, 0},             /* ACK */\r
-    {0, 0},             /* BEL */\r
-    {0x2a, 0},          /* BS  */  /* Keyboard Delete (Backspace) */\r
-    {0x2b, 0},          /* TAB */  /* Keyboard Tab */\r
-    {0x28, 0},          /* LF  */  /* Keyboard Return (Enter) */\r
-    {0, 0},             /* VT  */\r
-    {0, 0},             /* FF  */\r
-    {0, 0},             /* CR  */\r
-    {0, 0},             /* SO  */\r
-    {0, 0},             /* SI  */\r
-    {0, 0},             /* DEL */\r
-    {0, 0},             /* DC1 */\r
-    {0, 0},             /* DC2 */\r
-    {0, 0},             /* DC3 */\r
-    {0, 0},             /* DC4 */\r
-    {0, 0},             /* NAK */\r
-    {0, 0},             /* SYN */\r
-    {0, 0},             /* ETB */\r
-    {0, 0},             /* CAN */\r
-    {0, 0},             /* EM  */\r
-    {0, 0},             /* SUB */\r
-    {0, 0},             /* ESC */\r
-    {0, 0},             /* FS  */\r
-    {0, 0},             /* GS  */\r
-    {0, 0},             /* RS  */\r
-    {0, 0},             /* US  */\r
-    {0x2c, 0},          /*   */\r
-    {0x1e, KEY_SHIFT},      /* ! */\r
-    {0x34, KEY_SHIFT},      /* " */\r
-    {0x20, KEY_SHIFT},      /* # */\r
-    {0x21, KEY_SHIFT},      /* $ */\r
-    {0x22, KEY_SHIFT},      /* % */\r
-    {0x24, KEY_SHIFT},      /* & */\r
-    {0x34, 0},          /* ' */\r
-    {0x26, KEY_SHIFT},      /* ( */\r
-    {0x27, KEY_SHIFT},      /* ) */\r
-    {0x25, KEY_SHIFT},      /* * */\r
-    {0x2e, KEY_SHIFT},      /* + */\r
-    {0x36, 0},          /* , */\r
-    {0x2d, 0},          /* - */\r
-    {0x37, 0},          /* . */\r
-    {0x38, 0},          /* / */\r
-    {0x27, 0},          /* 0 */\r
-    {0x1e, 0},          /* 1 */\r
-    {0x1f, 0},          /* 2 */\r
-    {0x20, 0},          /* 3 */\r
-    {0x21, 0},          /* 4 */\r
-    {0x22, 0},          /* 5 */\r
-    {0x23, 0},          /* 6 */\r
-    {0x24, 0},          /* 7 */\r
-    {0x25, 0},          /* 8 */\r
-    {0x26, 0},          /* 9 */\r
-    {0x33, KEY_SHIFT},      /* : */\r
-    {0x33, 0},          /* ; */\r
-    {0x36, KEY_SHIFT},      /* < */\r
-    {0x2e, 0},          /* = */\r
-    {0x37, KEY_SHIFT},      /* > */\r
-    {0x38, KEY_SHIFT},      /* ? */\r
-    {0x1f, KEY_SHIFT},      /* @ */\r
-    {0x04, KEY_SHIFT},      /* A */\r
-    {0x05, KEY_SHIFT},      /* B */\r
-    {0x06, KEY_SHIFT},      /* C */\r
-    {0x07, KEY_SHIFT},      /* D */\r
-    {0x08, KEY_SHIFT},      /* E */\r
-    {0x09, KEY_SHIFT},      /* F */\r
-    {0x0a, KEY_SHIFT},      /* G */\r
-    {0x0b, KEY_SHIFT},      /* H */\r
-    {0x0c, KEY_SHIFT},      /* I */\r
-    {0x0d, KEY_SHIFT},      /* J */\r
-    {0x0e, KEY_SHIFT},      /* K */\r
-    {0x0f, KEY_SHIFT},      /* L */\r
-    {0x10, KEY_SHIFT},      /* M */\r
-    {0x11, KEY_SHIFT},      /* N */\r
-    {0x12, KEY_SHIFT},      /* O */\r
-    {0x13, KEY_SHIFT},      /* P */\r
-    {0x14, KEY_SHIFT},      /* Q */\r
-    {0x15, KEY_SHIFT},      /* R */\r
-    {0x16, KEY_SHIFT},      /* S */\r
-    {0x17, KEY_SHIFT},      /* T */\r
-    {0x18, KEY_SHIFT},      /* U */\r
-    {0x19, KEY_SHIFT},      /* V */\r
-    {0x1a, KEY_SHIFT},      /* W */\r
-    {0x1b, KEY_SHIFT},      /* X */\r
-    {0x1c, KEY_SHIFT},      /* Y */\r
-    {0x1d, KEY_SHIFT},      /* Z */\r
-    {0x2f, 0},          /* [ */\r
-    {0x31, 0},          /* \ */\r
-    {0x30, 0},          /* ] */\r
-    {0x23, KEY_SHIFT},      /* ^ */\r
-    {0x2d, KEY_SHIFT},      /* _ */\r
-    {0x35, 0},          /* ` */\r
-    {0x04, 0},          /* a */\r
-    {0x05, 0},          /* b */\r
-    {0x06, 0},          /* c */\r
-    {0x07, 0},          /* d */\r
-    {0x08, 0},          /* e */\r
-    {0x09, 0},          /* f */\r
-    {0x0a, 0},          /* g */\r
-    {0x0b, 0},          /* h */\r
-    {0x0c, 0},          /* i */\r
-    {0x0d, 0},          /* j */\r
-    {0x0e, 0},          /* k */\r
-    {0x0f, 0},          /* l */\r
-    {0x10, 0},          /* m */\r
-    {0x11, 0},          /* n */\r
-    {0x12, 0},          /* o */\r
-    {0x13, 0},          /* p */\r
-    {0x14, 0},          /* q */\r
-    {0x15, 0},          /* r */\r
-    {0x16, 0},          /* s */\r
-    {0x17, 0},          /* t */\r
-    {0x18, 0},          /* u */\r
-    {0x19, 0},          /* v */\r
-    {0x1a, 0},          /* w */\r
-    {0x1b, 0},          /* x */\r
-    {0x1c, 0},          /* y */\r
-    {0x1d, 0},          /* z */\r
-    {0x2f, KEY_SHIFT},      /* { */\r
-    {0x31, KEY_SHIFT},      /* | */\r
-    {0x30, KEY_SHIFT},      /* } */\r
-    {0x35, KEY_SHIFT},      /* ~ */\r
-    {0,0},              /* DEL */\r
-\r
-    {0x3a, 0},          /* F1 */\r
-    {0x3b, 0},          /* F2 */\r
-    {0x3c, 0},          /* F3 */\r
-    {0x3d, 0},          /* F4 */\r
-    {0x3e, 0},          /* F5 */\r
-    {0x3f, 0},          /* F6 */\r
-    {0x40, 0},          /* F7 */\r
-    {0x41, 0},          /* F8 */\r
-    {0x42, 0},          /* F9 */\r
-    {0x43, 0},          /* F10 */\r
-    {0x44, 0},          /* F11 */\r
-    {0x45, 0},          /* F12 */\r
-\r
-    {0x46, 0},          /* PRINT_SCREEN */\r
-    {0x47, 0},          /* SCROLL_LOCK */\r
-    {0x39, 0},          /* CAPS_LOCK */\r
-    {0x53, 0},          /* NUM_LOCK */\r
-    {0x49, 0},          /* INSERT */\r
-    {0x4a, 0},          /* HOME */\r
-    {0x4b, 0},          /* PAGE_UP */\r
-    {0x4e, 0},          /* PAGE_DOWN */\r
-};\r
-\r
-#else\r
-/* UK keyboard */\r
-#define KEYMAP_SIZE (148)\r
-const KEYMAP keymap[KEYMAP_SIZE] = {\r
-    {0, 0},             /* NUL */\r
-    {0, 0},             /* SOH */\r
-    {0, 0},             /* STX */\r
-    {0, 0},             /* ETX */\r
-    {0, 0},             /* EOT */\r
-    {0, 0},             /* ENQ */\r
-    {0, 0},             /* ACK */\r
-    {0, 0},             /* BEL */\r
-    {0x2a, 0},          /* BS  */  /* Keyboard Delete (Backspace) */\r
-    {0x2b, 0},          /* TAB */  /* Keyboard Tab */\r
-    {0x28, 0},          /* LF  */  /* Keyboard Return (Enter) */\r
-    {0, 0},             /* VT  */\r
-    {0, 0},             /* FF  */\r
-    {0, 0},             /* CR  */\r
-    {0, 0},             /* SO  */\r
-    {0, 0},             /* SI  */\r
-    {0, 0},             /* DEL */\r
-    {0, 0},             /* DC1 */\r
-    {0, 0},             /* DC2 */\r
-    {0, 0},             /* DC3 */\r
-    {0, 0},             /* DC4 */\r
-    {0, 0},             /* NAK */\r
-    {0, 0},             /* SYN */\r
-    {0, 0},             /* ETB */\r
-    {0, 0},             /* CAN */\r
-    {0, 0},             /* EM  */\r
-    {0, 0},             /* SUB */\r
-    {0, 0},             /* ESC */\r
-    {0, 0},             /* FS  */\r
-    {0, 0},             /* GS  */\r
-    {0, 0},             /* RS  */\r
-    {0, 0},             /* US  */\r
-    {0x2c, 0},          /*   */\r
-    {0x1e, KEY_SHIFT},      /* ! */\r
-    {0x1f, KEY_SHIFT},      /* " */\r
-    {0x32, 0},          /* # */\r
-    {0x21, KEY_SHIFT},      /* $ */\r
-    {0x22, KEY_SHIFT},      /* % */\r
-    {0x24, KEY_SHIFT},      /* & */\r
-    {0x34, 0},          /* ' */\r
-    {0x26, KEY_SHIFT},      /* ( */\r
-    {0x27, KEY_SHIFT},      /* ) */\r
-    {0x25, KEY_SHIFT},      /* * */\r
-    {0x2e, KEY_SHIFT},      /* + */\r
-    {0x36, 0},          /* , */\r
-    {0x2d, 0},          /* - */\r
-    {0x37, 0},          /* . */\r
-    {0x38, 0},          /* / */\r
-    {0x27, 0},          /* 0 */\r
-    {0x1e, 0},          /* 1 */\r
-    {0x1f, 0},          /* 2 */\r
-    {0x20, 0},          /* 3 */\r
-    {0x21, 0},          /* 4 */\r
-    {0x22, 0},          /* 5 */\r
-    {0x23, 0},          /* 6 */\r
-    {0x24, 0},          /* 7 */\r
-    {0x25, 0},          /* 8 */\r
-    {0x26, 0},          /* 9 */\r
-    {0x33, KEY_SHIFT},      /* : */\r
-    {0x33, 0},          /* ; */\r
-    {0x36, KEY_SHIFT},      /* < */\r
-    {0x2e, 0},          /* = */\r
-    {0x37, KEY_SHIFT},      /* > */\r
-    {0x38, KEY_SHIFT},      /* ? */\r
-    {0x34, KEY_SHIFT},      /* @ */\r
-    {0x04, KEY_SHIFT},      /* A */\r
-    {0x05, KEY_SHIFT},      /* B */\r
-    {0x06, KEY_SHIFT},      /* C */\r
-    {0x07, KEY_SHIFT},      /* D */\r
-    {0x08, KEY_SHIFT},      /* E */\r
-    {0x09, KEY_SHIFT},      /* F */\r
-    {0x0a, KEY_SHIFT},      /* G */\r
-    {0x0b, KEY_SHIFT},      /* H */\r
-    {0x0c, KEY_SHIFT},      /* I */\r
-    {0x0d, KEY_SHIFT},      /* J */\r
-    {0x0e, KEY_SHIFT},      /* K */\r
-    {0x0f, KEY_SHIFT},      /* L */\r
-    {0x10, KEY_SHIFT},      /* M */\r
-    {0x11, KEY_SHIFT},      /* N */\r
-    {0x12, KEY_SHIFT},      /* O */\r
-    {0x13, KEY_SHIFT},      /* P */\r
-    {0x14, KEY_SHIFT},      /* Q */\r
-    {0x15, KEY_SHIFT},      /* R */\r
-    {0x16, KEY_SHIFT},      /* S */\r
-    {0x17, KEY_SHIFT},      /* T */\r
-    {0x18, KEY_SHIFT},      /* U */\r
-    {0x19, KEY_SHIFT},      /* V */\r
-    {0x1a, KEY_SHIFT},      /* W */\r
-    {0x1b, KEY_SHIFT},      /* X */\r
-    {0x1c, KEY_SHIFT},      /* Y */\r
-    {0x1d, KEY_SHIFT},      /* Z */\r
-    {0x2f, 0},          /* [ */\r
-    {0x64, 0},          /* \ */\r
-    {0x30, 0},          /* ] */\r
-    {0x23, KEY_SHIFT},      /* ^ */\r
-    {0x2d, KEY_SHIFT},      /* _ */\r
-    {0x35, 0},          /* ` */\r
-    {0x04, 0},          /* a */\r
-    {0x05, 0},          /* b */\r
-    {0x06, 0},          /* c */\r
-    {0x07, 0},          /* d */\r
-    {0x08, 0},          /* e */\r
-    {0x09, 0},          /* f */\r
-    {0x0a, 0},          /* g */\r
-    {0x0b, 0},          /* h */\r
-    {0x0c, 0},          /* i */\r
-    {0x0d, 0},          /* j */\r
-    {0x0e, 0},          /* k */\r
-    {0x0f, 0},          /* l */\r
-    {0x10, 0},          /* m */\r
-    {0x11, 0},          /* n */\r
-    {0x12, 0},          /* o */\r
-    {0x13, 0},          /* p */\r
-    {0x14, 0},          /* q */\r
-    {0x15, 0},          /* r */\r
-    {0x16, 0},          /* s */\r
-    {0x17, 0},          /* t */\r
-    {0x18, 0},          /* u */\r
-    {0x19, 0},          /* v */\r
-    {0x1a, 0},          /* w */\r
-    {0x1b, 0},          /* x */\r
-    {0x1c, 0},          /* y */\r
-    {0x1d, 0},          /* z */\r
-    {0x2f, KEY_SHIFT},      /* { */\r
-    {0x64, KEY_SHIFT},      /* | */\r
-    {0x30, KEY_SHIFT},      /* } */\r
-    {0x32, KEY_SHIFT},      /* ~ */\r
-    {0,0},             /* DEL */\r
-\r
-    {0x3a, 0},          /* F1 */\r
-    {0x3b, 0},          /* F2 */\r
-    {0x3c, 0},          /* F3 */\r
-    {0x3d, 0},          /* F4 */\r
-    {0x3e, 0},          /* F5 */\r
-    {0x3f, 0},          /* F6 */\r
-    {0x40, 0},          /* F7 */\r
-    {0x41, 0},          /* F8 */\r
-    {0x42, 0},          /* F9 */\r
-    {0x43, 0},          /* F10 */\r
-    {0x44, 0},          /* F11 */\r
-    {0x45, 0},          /* F12 */\r
-\r
-    {0x46, 0},          /* PRINT_SCREEN */\r
-    {0x47, 0},          /* SCROLL_LOCK */\r
-    {0x39, 0},          /* CAPS_LOCK */\r
-    {0x53, 0},          /* NUM_LOCK */\r
-    {0x49, 0},          /* INSERT */\r
-    {0x4a, 0},          /* HOME */\r
-    {0x4b, 0},          /* PAGE_UP */\r
-    {0x4e, 0},          /* PAGE_DOWN */\r
-};\r
-#endif\r
-\r
-uint8_t * USBKeyboard::reportDesc() {\r
-    static uint8_t reportDescriptor[] = {\r
-        USAGE_PAGE(1), 0x01,                    // Generic Desktop\r
-        USAGE(1), 0x06,                         // Keyboard\r
-        COLLECTION(1), 0x01,                    // Application\r
-        REPORT_ID(1),       REPORT_ID_KEYBOARD,\r
-\r
-        USAGE_PAGE(1), 0x07,                    // Key Codes\r
-        USAGE_MINIMUM(1), 0xE0,\r
-        USAGE_MAXIMUM(1), 0xE7,\r
-        LOGICAL_MINIMUM(1), 0x00,\r
-        LOGICAL_MAXIMUM(1), 0x01,\r
-        REPORT_SIZE(1), 0x01,\r
-        REPORT_COUNT(1), 0x08,\r
-        INPUT(1), 0x02,                         // Data, Variable, Absolute\r
-        REPORT_COUNT(1), 0x01,\r
-        REPORT_SIZE(1), 0x08,\r
-        INPUT(1), 0x01,                         // Constant\r
-\r
-\r
-        REPORT_COUNT(1), 0x05,\r
-        REPORT_SIZE(1), 0x01,\r
-        USAGE_PAGE(1), 0x08,                    // LEDs\r
-        USAGE_MINIMUM(1), 0x01,\r
-        USAGE_MAXIMUM(1), 0x05,\r
-        OUTPUT(1), 0x02,                        // Data, Variable, Absolute\r
-        REPORT_COUNT(1), 0x01,\r
-        REPORT_SIZE(1), 0x03,\r
-        OUTPUT(1), 0x01,                        // Constant\r
-\r
-\r
-        REPORT_COUNT(1), 0x06,\r
-        REPORT_SIZE(1), 0x08,\r
-        LOGICAL_MINIMUM(1), 0x00,\r
-        LOGICAL_MAXIMUM(1), 0x65,\r
-        USAGE_PAGE(1), 0x07,                    // Key Codes\r
-        USAGE_MINIMUM(1), 0x00,\r
-        USAGE_MAXIMUM(1), 0x65,\r
-        INPUT(1), 0x00,                         // Data, Array\r
-        END_COLLECTION(0),\r
-\r
-        // Media Control\r
-        USAGE_PAGE(1), 0x0C,\r
-        USAGE(1), 0x01,\r
-        COLLECTION(1), 0x01,\r
-        REPORT_ID(1), REPORT_ID_VOLUME,\r
-        USAGE_PAGE(1), 0x0C,\r
-        LOGICAL_MINIMUM(1), 0x00,\r
-        LOGICAL_MAXIMUM(1), 0x01,\r
-        REPORT_SIZE(1), 0x01,\r
-        REPORT_COUNT(1), 0x07,\r
-        USAGE(1), 0xB5,             // Next Track\r
-        USAGE(1), 0xB6,             // Previous Track\r
-        USAGE(1), 0xB7,             // Stop\r
-        USAGE(1), 0xCD,             // Play / Pause\r
-        USAGE(1), 0xE2,             // Mute\r
-        USAGE(1), 0xE9,             // Volume Up\r
-        USAGE(1), 0xEA,             // Volume Down\r
-        INPUT(1), 0x02,             // Input (Data, Variable, Absolute)\r
-        REPORT_COUNT(1), 0x01,\r
-        INPUT(1), 0x01,\r
-        END_COLLECTION(0),\r
-    };\r
-    reportLength = sizeof(reportDescriptor);\r
-    return reportDescriptor;\r
-}\r
-\r
-\r
-bool USBKeyboard::EP1_OUT_callback() {\r
-    uint16_t bytesRead = 0;\r
-    uint8_t led[65];\r
-    USBDevice::readEP(EPINT_OUT, led, &bytesRead, MAX_HID_REPORT_SIZE);\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#include "stdint.h"
+\r
+#include "USBKeyboard.h"
+\r
+#define REPORT_ID_KEYBOARD 1
+#define REPORT_ID_VOLUME   3
+\r
+\r
+typedef struct {
+    unsigned char usage;
+    unsigned char modifier;
+} KEYMAP;
+\r
+#ifdef US_KEYBOARD
+/* US keyboard (as HID standard) */
+#define KEYMAP_SIZE (148)
+const KEYMAP keymap[KEYMAP_SIZE] = {
+    {0, 0},             /* NUL */
+    {0, 0},             /* SOH */
+    {0, 0},             /* STX */
+    {0, 0},             /* ETX */
+    {0, 0},             /* EOT */
+    {0, 0},             /* ENQ */
+    {0, 0},             /* ACK */
+    {0, 0},             /* BEL */
+    {0x2a, 0},          /* BS  */  /* Keyboard Delete (Backspace) */
+    {0x2b, 0},          /* TAB */  /* Keyboard Tab */
+    {0x28, 0},          /* LF  */  /* Keyboard Return (Enter) */
+    {0, 0},             /* VT  */
+    {0, 0},             /* FF  */
+    {0, 0},             /* CR  */
+    {0, 0},             /* SO  */
+    {0, 0},             /* SI  */
+    {0, 0},             /* DEL */
+    {0, 0},             /* DC1 */
+    {0, 0},             /* DC2 */
+    {0, 0},             /* DC3 */
+    {0, 0},             /* DC4 */
+    {0, 0},             /* NAK */
+    {0, 0},             /* SYN */
+    {0, 0},             /* ETB */
+    {0, 0},             /* CAN */
+    {0, 0},             /* EM  */
+    {0, 0},             /* SUB */
+    {0, 0},             /* ESC */
+    {0, 0},             /* FS  */
+    {0, 0},             /* GS  */
+    {0, 0},             /* RS  */
+    {0, 0},             /* US  */
+    {0x2c, 0},          /*   */
+    {0x1e, KEY_SHIFT},      /* ! */
+    {0x34, KEY_SHIFT},      /* " */
+    {0x20, KEY_SHIFT},      /* # */
+    {0x21, KEY_SHIFT},      /* $ */
+    {0x22, KEY_SHIFT},      /* % */
+    {0x24, KEY_SHIFT},      /* & */
+    {0x34, 0},          /* ' */
+    {0x26, KEY_SHIFT},      /* ( */
+    {0x27, KEY_SHIFT},      /* ) */
+    {0x25, KEY_SHIFT},      /* * */
+    {0x2e, KEY_SHIFT},      /* + */
+    {0x36, 0},          /* , */
+    {0x2d, 0},          /* - */
+    {0x37, 0},          /* . */
+    {0x38, 0},          /* / */
+    {0x27, 0},          /* 0 */
+    {0x1e, 0},          /* 1 */
+    {0x1f, 0},          /* 2 */
+    {0x20, 0},          /* 3 */
+    {0x21, 0},          /* 4 */
+    {0x22, 0},          /* 5 */
+    {0x23, 0},          /* 6 */
+    {0x24, 0},          /* 7 */
+    {0x25, 0},          /* 8 */
+    {0x26, 0},          /* 9 */
+    {0x33, KEY_SHIFT},      /* : */
+    {0x33, 0},          /* ; */
+    {0x36, KEY_SHIFT},      /* < */
+    {0x2e, 0},          /* = */
+    {0x37, KEY_SHIFT},      /* > */
+    {0x38, KEY_SHIFT},      /* ? */
+    {0x1f, KEY_SHIFT},      /* @ */
+    {0x04, KEY_SHIFT},      /* A */
+    {0x05, KEY_SHIFT},      /* B */
+    {0x06, KEY_SHIFT},      /* C */
+    {0x07, KEY_SHIFT},      /* D */
+    {0x08, KEY_SHIFT},      /* E */
+    {0x09, KEY_SHIFT},      /* F */
+    {0x0a, KEY_SHIFT},      /* G */
+    {0x0b, KEY_SHIFT},      /* H */
+    {0x0c, KEY_SHIFT},      /* I */
+    {0x0d, KEY_SHIFT},      /* J */
+    {0x0e, KEY_SHIFT},      /* K */
+    {0x0f, KEY_SHIFT},      /* L */
+    {0x10, KEY_SHIFT},      /* M */
+    {0x11, KEY_SHIFT},      /* N */
+    {0x12, KEY_SHIFT},      /* O */
+    {0x13, KEY_SHIFT},      /* P */
+    {0x14, KEY_SHIFT},      /* Q */
+    {0x15, KEY_SHIFT},      /* R */
+    {0x16, KEY_SHIFT},      /* S */
+    {0x17, KEY_SHIFT},      /* T */
+    {0x18, KEY_SHIFT},      /* U */
+    {0x19, KEY_SHIFT},      /* V */
+    {0x1a, KEY_SHIFT},      /* W */
+    {0x1b, KEY_SHIFT},      /* X */
+    {0x1c, KEY_SHIFT},      /* Y */
+    {0x1d, KEY_SHIFT},      /* Z */
+    {0x2f, 0},          /* [ */
+    {0x31, 0},          /* \ */
+    {0x30, 0},          /* ] */
+    {0x23, KEY_SHIFT},      /* ^ */
+    {0x2d, KEY_SHIFT},      /* _ */
+    {0x35, 0},          /* ` */
+    {0x04, 0},          /* a */
+    {0x05, 0},          /* b */
+    {0x06, 0},          /* c */
+    {0x07, 0},          /* d */
+    {0x08, 0},          /* e */
+    {0x09, 0},          /* f */
+    {0x0a, 0},          /* g */
+    {0x0b, 0},          /* h */
+    {0x0c, 0},          /* i */
+    {0x0d, 0},          /* j */
+    {0x0e, 0},          /* k */
+    {0x0f, 0},          /* l */
+    {0x10, 0},          /* m */
+    {0x11, 0},          /* n */
+    {0x12, 0},          /* o */
+    {0x13, 0},          /* p */
+    {0x14, 0},          /* q */
+    {0x15, 0},          /* r */
+    {0x16, 0},          /* s */
+    {0x17, 0},          /* t */
+    {0x18, 0},          /* u */
+    {0x19, 0},          /* v */
+    {0x1a, 0},          /* w */
+    {0x1b, 0},          /* x */
+    {0x1c, 0},          /* y */
+    {0x1d, 0},          /* z */
+    {0x2f, KEY_SHIFT},      /* { */
+    {0x31, KEY_SHIFT},      /* | */
+    {0x30, KEY_SHIFT},      /* } */
+    {0x35, KEY_SHIFT},      /* ~ */
+    {0,0},              /* DEL */
+\r
+    {0x3a, 0},          /* F1 */
+    {0x3b, 0},          /* F2 */
+    {0x3c, 0},          /* F3 */
+    {0x3d, 0},          /* F4 */
+    {0x3e, 0},          /* F5 */
+    {0x3f, 0},          /* F6 */
+    {0x40, 0},          /* F7 */
+    {0x41, 0},          /* F8 */
+    {0x42, 0},          /* F9 */
+    {0x43, 0},          /* F10 */
+    {0x44, 0},          /* F11 */
+    {0x45, 0},          /* F12 */
+\r
+    {0x46, 0},          /* PRINT_SCREEN */
+    {0x47, 0},          /* SCROLL_LOCK */
+    {0x39, 0},          /* CAPS_LOCK */
+    {0x53, 0},          /* NUM_LOCK */
+    {0x49, 0},          /* INSERT */
+    {0x4a, 0},          /* HOME */
+    {0x4b, 0},          /* PAGE_UP */
+    {0x4e, 0},          /* PAGE_DOWN */
+};
+\r
+#else
+/* UK keyboard */
+#define KEYMAP_SIZE (148)
+const KEYMAP keymap[KEYMAP_SIZE] = {
+    {0, 0},             /* NUL */
+    {0, 0},             /* SOH */
+    {0, 0},             /* STX */
+    {0, 0},             /* ETX */
+    {0, 0},             /* EOT */
+    {0, 0},             /* ENQ */
+    {0, 0},             /* ACK */
+    {0, 0},             /* BEL */
+    {0x2a, 0},          /* BS  */  /* Keyboard Delete (Backspace) */
+    {0x2b, 0},          /* TAB */  /* Keyboard Tab */
+    {0x28, 0},          /* LF  */  /* Keyboard Return (Enter) */
+    {0, 0},             /* VT  */
+    {0, 0},             /* FF  */
+    {0, 0},             /* CR  */
+    {0, 0},             /* SO  */
+    {0, 0},             /* SI  */
+    {0, 0},             /* DEL */
+    {0, 0},             /* DC1 */
+    {0, 0},             /* DC2 */
+    {0, 0},             /* DC3 */
+    {0, 0},             /* DC4 */
+    {0, 0},             /* NAK */
+    {0, 0},             /* SYN */
+    {0, 0},             /* ETB */
+    {0, 0},             /* CAN */
+    {0, 0},             /* EM  */
+    {0, 0},             /* SUB */
+    {0, 0},             /* ESC */
+    {0, 0},             /* FS  */
+    {0, 0},             /* GS  */
+    {0, 0},             /* RS  */
+    {0, 0},             /* US  */
+    {0x2c, 0},          /*   */
+    {0x1e, KEY_SHIFT},      /* ! */
+    {0x1f, KEY_SHIFT},      /* " */
+    {0x32, 0},          /* # */
+    {0x21, KEY_SHIFT},      /* $ */
+    {0x22, KEY_SHIFT},      /* % */
+    {0x24, KEY_SHIFT},      /* & */
+    {0x34, 0},          /* ' */
+    {0x26, KEY_SHIFT},      /* ( */
+    {0x27, KEY_SHIFT},      /* ) */
+    {0x25, KEY_SHIFT},      /* * */
+    {0x2e, KEY_SHIFT},      /* + */
+    {0x36, 0},          /* , */
+    {0x2d, 0},          /* - */
+    {0x37, 0},          /* . */
+    {0x38, 0},          /* / */
+    {0x27, 0},          /* 0 */
+    {0x1e, 0},          /* 1 */
+    {0x1f, 0},          /* 2 */
+    {0x20, 0},          /* 3 */
+    {0x21, 0},          /* 4 */
+    {0x22, 0},          /* 5 */
+    {0x23, 0},          /* 6 */
+    {0x24, 0},          /* 7 */
+    {0x25, 0},          /* 8 */
+    {0x26, 0},          /* 9 */
+    {0x33, KEY_SHIFT},      /* : */
+    {0x33, 0},          /* ; */
+    {0x36, KEY_SHIFT},      /* < */
+    {0x2e, 0},          /* = */
+    {0x37, KEY_SHIFT},      /* > */
+    {0x38, KEY_SHIFT},      /* ? */
+    {0x34, KEY_SHIFT},      /* @ */
+    {0x04, KEY_SHIFT},      /* A */
+    {0x05, KEY_SHIFT},      /* B */
+    {0x06, KEY_SHIFT},      /* C */
+    {0x07, KEY_SHIFT},      /* D */
+    {0x08, KEY_SHIFT},      /* E */
+    {0x09, KEY_SHIFT},      /* F */
+    {0x0a, KEY_SHIFT},      /* G */
+    {0x0b, KEY_SHIFT},      /* H */
+    {0x0c, KEY_SHIFT},      /* I */
+    {0x0d, KEY_SHIFT},      /* J */
+    {0x0e, KEY_SHIFT},      /* K */
+    {0x0f, KEY_SHIFT},      /* L */
+    {0x10, KEY_SHIFT},      /* M */
+    {0x11, KEY_SHIFT},      /* N */
+    {0x12, KEY_SHIFT},      /* O */
+    {0x13, KEY_SHIFT},      /* P */
+    {0x14, KEY_SHIFT},      /* Q */
+    {0x15, KEY_SHIFT},      /* R */
+    {0x16, KEY_SHIFT},      /* S */
+    {0x17, KEY_SHIFT},      /* T */
+    {0x18, KEY_SHIFT},      /* U */
+    {0x19, KEY_SHIFT},      /* V */
+    {0x1a, KEY_SHIFT},      /* W */
+    {0x1b, KEY_SHIFT},      /* X */
+    {0x1c, KEY_SHIFT},      /* Y */
+    {0x1d, KEY_SHIFT},      /* Z */
+    {0x2f, 0},          /* [ */
+    {0x64, 0},          /* \ */
+    {0x30, 0},          /* ] */
+    {0x23, KEY_SHIFT},      /* ^ */
+    {0x2d, KEY_SHIFT},      /* _ */
+    {0x35, 0},          /* ` */
+    {0x04, 0},          /* a */
+    {0x05, 0},          /* b */
+    {0x06, 0},          /* c */
+    {0x07, 0},          /* d */
+    {0x08, 0},          /* e */
+    {0x09, 0},          /* f */
+    {0x0a, 0},          /* g */
+    {0x0b, 0},          /* h */
+    {0x0c, 0},          /* i */
+    {0x0d, 0},          /* j */
+    {0x0e, 0},          /* k */
+    {0x0f, 0},          /* l */
+    {0x10, 0},          /* m */
+    {0x11, 0},          /* n */
+    {0x12, 0},          /* o */
+    {0x13, 0},          /* p */
+    {0x14, 0},          /* q */
+    {0x15, 0},          /* r */
+    {0x16, 0},          /* s */
+    {0x17, 0},          /* t */
+    {0x18, 0},          /* u */
+    {0x19, 0},          /* v */
+    {0x1a, 0},          /* w */
+    {0x1b, 0},          /* x */
+    {0x1c, 0},          /* y */
+    {0x1d, 0},          /* z */
+    {0x2f, KEY_SHIFT},      /* { */
+    {0x64, KEY_SHIFT},      /* | */
+    {0x30, KEY_SHIFT},      /* } */
+    {0x32, KEY_SHIFT},      /* ~ */
+    {0,0},             /* DEL */
+\r
+    {0x3a, 0},          /* F1 */
+    {0x3b, 0},          /* F2 */
+    {0x3c, 0},          /* F3 */
+    {0x3d, 0},          /* F4 */
+    {0x3e, 0},          /* F5 */
+    {0x3f, 0},          /* F6 */
+    {0x40, 0},          /* F7 */
+    {0x41, 0},          /* F8 */
+    {0x42, 0},          /* F9 */
+    {0x43, 0},          /* F10 */
+    {0x44, 0},          /* F11 */
+    {0x45, 0},          /* F12 */
+\r
+    {0x46, 0},          /* PRINT_SCREEN */
+    {0x47, 0},          /* SCROLL_LOCK */
+    {0x39, 0},          /* CAPS_LOCK */
+    {0x53, 0},          /* NUM_LOCK */
+    {0x49, 0},          /* INSERT */
+    {0x4a, 0},          /* HOME */
+    {0x4b, 0},          /* PAGE_UP */
+    {0x4e, 0},          /* PAGE_DOWN */
+};
+#endif
+\r
+uint8_t * USBKeyboard::reportDesc() {
+    static uint8_t reportDescriptor[] = {
+        USAGE_PAGE(1), 0x01,                    // Generic Desktop
+        USAGE(1), 0x06,                         // Keyboard
+        COLLECTION(1), 0x01,                    // Application
+        REPORT_ID(1),       REPORT_ID_KEYBOARD,
+\r
+        USAGE_PAGE(1), 0x07,                    // Key Codes
+        USAGE_MINIMUM(1), 0xE0,
+        USAGE_MAXIMUM(1), 0xE7,
+        LOGICAL_MINIMUM(1), 0x00,
+        LOGICAL_MAXIMUM(1), 0x01,
+        REPORT_SIZE(1), 0x01,
+        REPORT_COUNT(1), 0x08,
+        INPUT(1), 0x02,                         // Data, Variable, Absolute
+        REPORT_COUNT(1), 0x01,
+        REPORT_SIZE(1), 0x08,
+        INPUT(1), 0x01,                         // Constant
+\r
+\r
+        REPORT_COUNT(1), 0x05,
+        REPORT_SIZE(1), 0x01,
+        USAGE_PAGE(1), 0x08,                    // LEDs
+        USAGE_MINIMUM(1), 0x01,
+        USAGE_MAXIMUM(1), 0x05,
+        OUTPUT(1), 0x02,                        // Data, Variable, Absolute
+        REPORT_COUNT(1), 0x01,
+        REPORT_SIZE(1), 0x03,
+        OUTPUT(1), 0x01,                        // Constant
+\r
+\r
+        REPORT_COUNT(1), 0x06,
+        REPORT_SIZE(1), 0x08,
+        LOGICAL_MINIMUM(1), 0x00,
+        LOGICAL_MAXIMUM(1), 0x65,
+        USAGE_PAGE(1), 0x07,                    // Key Codes
+        USAGE_MINIMUM(1), 0x00,
+        USAGE_MAXIMUM(1), 0x65,
+        INPUT(1), 0x00,                         // Data, Array
+        END_COLLECTION(0),
+\r
+        // Media Control
+        USAGE_PAGE(1), 0x0C,
+        USAGE(1), 0x01,
+        COLLECTION(1), 0x01,
+        REPORT_ID(1), REPORT_ID_VOLUME,
+        USAGE_PAGE(1), 0x0C,
+        LOGICAL_MINIMUM(1), 0x00,
+        LOGICAL_MAXIMUM(1), 0x01,
+        REPORT_SIZE(1), 0x01,
+        REPORT_COUNT(1), 0x07,
+        USAGE(1), 0xB5,             // Next Track
+        USAGE(1), 0xB6,             // Previous Track
+        USAGE(1), 0xB7,             // Stop
+        USAGE(1), 0xCD,             // Play / Pause
+        USAGE(1), 0xE2,             // Mute
+        USAGE(1), 0xE9,             // Volume Up
+        USAGE(1), 0xEA,             // Volume Down
+        INPUT(1), 0x02,             // Input (Data, Variable, Absolute)
+        REPORT_COUNT(1), 0x01,
+        INPUT(1), 0x01,
+        END_COLLECTION(0),
+    };
+    reportLength = sizeof(reportDescriptor);
+    return reportDescriptor;
+}
+\r
+\r
+bool USBKeyboard::EP1_OUT_callback() {
+    uint16_t bytesRead = 0;
+    uint8_t led[65];
+    USBDevice::readEP(EPINT_OUT, led, &bytesRead, MAX_HID_REPORT_SIZE);
     \r
-    // we take led[1] because led[0] is the report ID\r
-    lock_status = led[1] & 0x07;\r
+    // we take led[1] because led[0] is the report ID
+    lock_status = led[1] & 0x07;
     \r
-    // We activate the endpoint to be able to recceive data\r
-    if (!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE))\r
-        return false;\r
-    return true;\r
-}\r
+    // We activate the endpoint to be able to recceive data
+    if (!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE))
+        return false;
+    return true;
+}
 \r
-uint8_t USBKeyboard::lockStatus() {\r
-    return lock_status;\r
-}\r
+uint8_t USBKeyboard::lockStatus() {
+    return lock_status;
+}
 \r
-int USBKeyboard::_putc(int c) {\r
-    return keyCode(c, keymap[c].modifier);\r
-}\r
+int USBKeyboard::_putc(int c) {
+    return keyCode(c, keymap[c].modifier);
+}
 \r
-bool USBKeyboard::keyCode(uint8_t key, uint8_t modifier) {\r
-    // Send a simulated keyboard keypress. Returns true if successful.\r
-    HID_REPORT report;\r
+bool USBKeyboard::keyCode(uint8_t key, uint8_t modifier) {
+    // Send a simulated keyboard keypress. Returns true if successful.
+    HID_REPORT report;
 \r
-    report.data[0] = REPORT_ID_KEYBOARD;\r
-    report.data[1] = modifier;\r
-    report.data[2] = 0;\r
-    report.data[3] = keymap[key].usage;\r
-    report.data[4] = 0;\r
-    report.data[5] = 0;\r
-    report.data[6] = 0;\r
-    report.data[7] = 0;\r
-    report.data[8] = 0;\r
+    report.data[0] = REPORT_ID_KEYBOARD;
+    report.data[1] = modifier;
+    report.data[2] = 0;
+    report.data[3] = keymap[key].usage;
+    report.data[4] = 0;
+    report.data[5] = 0;
+    report.data[6] = 0;
+    report.data[7] = 0;
+    report.data[8] = 0;
 \r
-    report.length = 9;\r
+    report.length = 9;
 \r
-    if (!send(&report)) {\r
-        return false;\r
-    }\r
+    if (!send(&report)) {
+        return false;
+    }
 \r
-    report.data[1] = 0;\r
-    report.data[3] = 0;\r
+    report.data[1] = 0;
+    report.data[3] = 0;
 \r
-    if (!send(&report)) {\r
-        return false;\r
-    }\r
+    if (!send(&report)) {
+        return false;
+    }
 \r
-    return true;\r
+    return true;
 \r
-}\r
+}
 \r
 \r
-bool USBKeyboard::mediaControl(MEDIA_KEY key) {\r
-    HID_REPORT report;\r
+bool USBKeyboard::mediaControl(MEDIA_KEY key) {
+    HID_REPORT report;
 \r
-    report.data[0] = REPORT_ID_VOLUME;\r
-    report.data[1] = (1 << key) & 0x7f;\r
+    report.data[0] = REPORT_ID_VOLUME;
+    report.data[1] = (1 << key) & 0x7f;
 \r
-    report.length = 2;\r
+    report.length = 2;
 \r
-    if (!send(&report)) {\r
-        return false;\r
-    }\r
+    if (!send(&report)) {
+        return false;
+    }
 \r
-    report.data[0] = REPORT_ID_VOLUME;\r
-    report.data[1] = 0;\r
+    report.data[0] = REPORT_ID_VOLUME;
+    report.data[1] = 0;
 \r
-    report.length = 2;\r
+    report.length = 2;
 \r
-    return send(&report);\r
-}\r
+    return send(&report);
+}
index 0a369e2..2418ff4 100644 (file)
@@ -66,7 +66,7 @@ enum FUNCTION_KEY
     KEY_PAGE_DOWN,      /* Page Down key */
 };
 
-/** 
+/**
  * USBKeyboard example
  * @code
  *
@@ -74,7 +74,7 @@ enum FUNCTION_KEY
  * #include "USBKeyboard.h"
  *
  * USBKeyboard key;
- * 
+ *
  * int main(void)
  * {
  *   while (1)
@@ -100,14 +100,14 @@ class USBKeyboard: public USBHID, public Stream
         * @param product_release Your preoduct_release (default: 0x0001)
         *
         */
-        USBKeyboard(uint16_t vendor_id = 0x1235, uint16_t product_id = 0x0050, uint16_t product_release = 0x0001): 
+        USBKeyboard(uint16_t vendor_id = 0x1235, uint16_t product_id = 0x0050, uint16_t product_release = 0x0001):
             USBHID(0, 0, vendor_id, product_id, product_release, false){
                 lock_status = 0;
                 connect();
             };
         
         /**
-        * To send a character defined by a modifier(CTRL, SHIFT, ALT) and the key 
+        * To send a character defined by a modifier(CTRL, SHIFT, ALT) and the key
         *
         * @code
         * //To send CTRL + s (save)
index e3473e1..0601a8a 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#include "stdint.h"\r
-#include "USBMouse.h"\r
-\r
-bool USBMouse::update(int16_t x, int16_t y, uint8_t button, int8_t z) {\r
-    switch (mouse_type) {\r
-        case REL_MOUSE:\r
-            while (x > 127) {\r
-                if (!mouseSend(127, 0, button, z)) return false;\r
-                x = x - 127;\r
-            }\r
-            while (x < -128) {\r
-                if (!mouseSend(-128, 0, button, z)) return false;\r
-                x = x + 128;\r
-            }\r
-            while (y > 127) {\r
-                if (!mouseSend(0, 127, button, z)) return false;\r
-                y = y - 127;\r
-            }\r
-            while (y < -128) {\r
-                if (!mouseSend(0, -128, button, z)) return false;\r
-                y = y + 128;\r
-            }\r
-            return mouseSend(x, y, button, z);\r
-        case ABS_MOUSE:\r
-            HID_REPORT report;\r
-\r
-            report.data[0] = x & 0xff;\r
-            report.data[1] = (x >> 8) & 0xff;\r
-            report.data[2] = y & 0xff;\r
-            report.data[3] = (y >> 8) & 0xff;\r
-            report.data[4] = -z;\r
-            report.data[5] = button & 0x07;\r
-\r
-            report.length = 6;\r
-\r
-            return send(&report);\r
-        default:\r
-            return false;\r
-    }\r
-}\r
-\r
-bool USBMouse::mouseSend(int8_t x, int8_t y, uint8_t buttons, int8_t z) {\r
-    HID_REPORT report;\r
-    report.data[0] = buttons & 0x07;\r
-    report.data[1] = x;\r
-    report.data[2] = y;\r
-    report.data[3] = -z; // >0 to scroll down, <0 to scroll up\r
-\r
-    report.length = 4;\r
-\r
-    return send(&report);\r
-}\r
-\r
-bool USBMouse::move(int16_t x, int16_t y) {\r
-    return update(x, y, button, 0);\r
-}\r
-\r
-bool USBMouse::scroll(int8_t z) {\r
-    return update(0, 0, button, z);\r
-}\r
-\r
-\r
-bool USBMouse::doubleClick() {\r
-    if (!click(MOUSE_LEFT))\r
-        return false;\r
-    wait(0.1);\r
-    return click(MOUSE_LEFT);\r
-}\r
-\r
-bool USBMouse::click(uint8_t button) {\r
-    if (!update(0, 0, button, 0))\r
-        return false;\r
-    wait(0.01);\r
-    return update(0, 0, 0, 0);\r
-}\r
-\r
-bool USBMouse::press(uint8_t button_) {\r
-    button = button_ & 0x07;\r
-    return update(0, 0, button, 0);\r
-}\r
-\r
-bool USBMouse::release(uint8_t button_) {\r
-    button = (button & (~button_)) & 0x07;\r
-    return update(0, 0, button, 0);\r
-}\r
-\r
-\r
-uint8_t * USBMouse::reportDesc() {\r
-\r
-    if (mouse_type == REL_MOUSE) {\r
-        static uint8_t reportDescriptor[] = {\r
-            USAGE_PAGE(1),      0x01,       // Genric Desktop\r
-            USAGE(1),           0x02,       // Mouse\r
-            COLLECTION(1),      0x01,       // Application\r
-            USAGE(1),           0x01,       // Pointer\r
-            COLLECTION(1),      0x00,       // Physical\r
-\r
-            REPORT_COUNT(1),    0x03,\r
-            REPORT_SIZE(1),     0x01,\r
-            USAGE_PAGE(1),      0x09,       // Buttons\r
-            USAGE_MINIMUM(1),       0x1,\r
-            USAGE_MAXIMUM(1),       0x3,\r
-            LOGICAL_MINIMUM(1),     0x00,\r
-            LOGICAL_MAXIMUM(1),     0x01,\r
-            INPUT(1),           0x02,\r
-            REPORT_COUNT(1),    0x01,\r
-            REPORT_SIZE(1),     0x05,\r
-            INPUT(1),           0x01,\r
-\r
-            REPORT_COUNT(1),    0x03,\r
-            REPORT_SIZE(1),     0x08,\r
-            USAGE_PAGE(1),      0x01,\r
-            USAGE(1),           0x30,       // X\r
-            USAGE(1),           0x31,       // Y\r
-            USAGE(1),           0x38,       // scroll\r
-            LOGICAL_MINIMUM(1),     0x81,\r
-            LOGICAL_MAXIMUM(1),     0x7f,\r
-            INPUT(1),           0x06,       // Relative data\r
-\r
-            END_COLLECTION(0),\r
-            END_COLLECTION(0),\r
-        };\r
-        reportLength = sizeof(reportDescriptor);\r
-        return reportDescriptor;\r
-    } else if (mouse_type == ABS_MOUSE) {\r
-        static uint8_t reportDescriptor[] = {\r
-\r
-            USAGE_PAGE(1), 0x01,           // Generic Desktop\r
-            USAGE(1), 0x02,                // Mouse\r
-            COLLECTION(1), 0x01,           // Application\r
-            USAGE(1), 0x01,                // Pointer\r
-            COLLECTION(1), 0x00,           // Physical\r
-\r
-            USAGE_PAGE(1), 0x01,            // Generic Desktop\r
-            USAGE(1), 0x30,                 // X\r
-            USAGE(1), 0x31,                 // Y\r
-            LOGICAL_MINIMUM(1), 0x00,       // 0\r
-            LOGICAL_MAXIMUM(2), 0xff, 0x7f, // 32767\r
-            REPORT_SIZE(1), 0x10,\r
-            REPORT_COUNT(1), 0x02,\r
-            INPUT(1), 0x02,                 // Data, Variable, Absolute\r
-\r
-            USAGE_PAGE(1), 0x01,            // Generic Desktop\r
-            USAGE(1), 0x38,                 // scroll\r
-            LOGICAL_MINIMUM(1), 0x81,       // -127\r
-            LOGICAL_MAXIMUM(1), 0x7f,       // 127\r
-            REPORT_SIZE(1), 0x08,\r
-            REPORT_COUNT(1), 0x01,\r
-            INPUT(1), 0x06,                 // Data, Variable, Relative\r
-\r
-            USAGE_PAGE(1), 0x09,            // Buttons\r
-            USAGE_MINIMUM(1), 0x01,\r
-            USAGE_MAXIMUM(1), 0x03,\r
-            LOGICAL_MINIMUM(1), 0x00,       // 0\r
-            LOGICAL_MAXIMUM(1), 0x01,       // 1\r
-            REPORT_COUNT(1), 0x03,\r
-            REPORT_SIZE(1), 0x01,\r
-            INPUT(1), 0x02,                 // Data, Variable, Absolute\r
-            REPORT_COUNT(1), 0x01,\r
-            REPORT_SIZE(1), 0x05,\r
-            INPUT(1), 0x01,                 // Constant\r
-\r
-            END_COLLECTION(0),\r
-            END_COLLECTION(0)\r
-        };\r
-        reportLength = sizeof(reportDescriptor);\r
-        return reportDescriptor;\r
-    }\r
-    return NULL;\r
-}\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#include "stdint.h"
+#include "USBMouse.h"
+\r
+bool USBMouse::update(int16_t x, int16_t y, uint8_t button, int8_t z) {
+    switch (mouse_type) {
+        case REL_MOUSE:
+            while (x > 127) {
+                if (!mouseSend(127, 0, button, z)) return false;
+                x = x - 127;
+            }
+            while (x < -128) {
+                if (!mouseSend(-128, 0, button, z)) return false;
+                x = x + 128;
+            }
+            while (y > 127) {
+                if (!mouseSend(0, 127, button, z)) return false;
+                y = y - 127;
+            }
+            while (y < -128) {
+                if (!mouseSend(0, -128, button, z)) return false;
+                y = y + 128;
+            }
+            return mouseSend(x, y, button, z);
+        case ABS_MOUSE:
+            HID_REPORT report;
+\r
+            report.data[0] = x & 0xff;
+            report.data[1] = (x >> 8) & 0xff;
+            report.data[2] = y & 0xff;
+            report.data[3] = (y >> 8) & 0xff;
+            report.data[4] = -z;
+            report.data[5] = button & 0x07;
+\r
+            report.length = 6;
+\r
+            return send(&report);
+        default:
+            return false;
+    }
+}
+\r
+bool USBMouse::mouseSend(int8_t x, int8_t y, uint8_t buttons, int8_t z) {
+    HID_REPORT report;
+    report.data[0] = buttons & 0x07;
+    report.data[1] = x;
+    report.data[2] = y;
+    report.data[3] = -z; // >0 to scroll down, <0 to scroll up
+\r
+    report.length = 4;
+\r
+    return send(&report);
+}
+\r
+bool USBMouse::move(int16_t x, int16_t y) {
+    return update(x, y, button, 0);
+}
+\r
+bool USBMouse::scroll(int8_t z) {
+    return update(0, 0, button, z);
+}
+\r
+\r
+bool USBMouse::doubleClick() {
+    if (!click(MOUSE_LEFT))
+        return false;
+    wait(0.1);
+    return click(MOUSE_LEFT);
+}
+\r
+bool USBMouse::click(uint8_t button) {
+    if (!update(0, 0, button, 0))
+        return false;
+    wait(0.01);
+    return update(0, 0, 0, 0);
+}
+\r
+bool USBMouse::press(uint8_t button_) {
+    button = button_ & 0x07;
+    return update(0, 0, button, 0);
+}
+\r
+bool USBMouse::release(uint8_t button_) {
+    button = (button & (~button_)) & 0x07;
+    return update(0, 0, button, 0);
+}
+\r
+\r
+uint8_t * USBMouse::reportDesc() {
+\r
+    if (mouse_type == REL_MOUSE) {
+        static uint8_t reportDescriptor[] = {
+            USAGE_PAGE(1),      0x01,       // Genric Desktop
+            USAGE(1),           0x02,       // Mouse
+            COLLECTION(1),      0x01,       // Application
+            USAGE(1),           0x01,       // Pointer
+            COLLECTION(1),      0x00,       // Physical
+\r
+            REPORT_COUNT(1),    0x03,
+            REPORT_SIZE(1),     0x01,
+            USAGE_PAGE(1),      0x09,       // Buttons
+            USAGE_MINIMUM(1),       0x1,
+            USAGE_MAXIMUM(1),       0x3,
+            LOGICAL_MINIMUM(1),     0x00,
+            LOGICAL_MAXIMUM(1),     0x01,
+            INPUT(1),           0x02,
+            REPORT_COUNT(1),    0x01,
+            REPORT_SIZE(1),     0x05,
+            INPUT(1),           0x01,
+\r
+            REPORT_COUNT(1),    0x03,
+            REPORT_SIZE(1),     0x08,
+            USAGE_PAGE(1),      0x01,
+            USAGE(1),           0x30,       // X
+            USAGE(1),           0x31,       // Y
+            USAGE(1),           0x38,       // scroll
+            LOGICAL_MINIMUM(1),     0x81,
+            LOGICAL_MAXIMUM(1),     0x7f,
+            INPUT(1),           0x06,       // Relative data
+\r
+            END_COLLECTION(0),
+            END_COLLECTION(0),
+        };
+        reportLength = sizeof(reportDescriptor);
+        return reportDescriptor;
+    } else if (mouse_type == ABS_MOUSE) {
+        static uint8_t reportDescriptor[] = {
+\r
+            USAGE_PAGE(1), 0x01,           // Generic Desktop
+            USAGE(1), 0x02,                // Mouse
+            COLLECTION(1), 0x01,           // Application
+            USAGE(1), 0x01,                // Pointer
+            COLLECTION(1), 0x00,           // Physical
+\r
+            USAGE_PAGE(1), 0x01,            // Generic Desktop
+            USAGE(1), 0x30,                 // X
+            USAGE(1), 0x31,                 // Y
+            LOGICAL_MINIMUM(1), 0x00,       // 0
+            LOGICAL_MAXIMUM(2), 0xff, 0x7f, // 32767
+            REPORT_SIZE(1), 0x10,
+            REPORT_COUNT(1), 0x02,
+            INPUT(1), 0x02,                 // Data, Variable, Absolute
+\r
+            USAGE_PAGE(1), 0x01,            // Generic Desktop
+            USAGE(1), 0x38,                 // scroll
+            LOGICAL_MINIMUM(1), 0x81,       // -127
+            LOGICAL_MAXIMUM(1), 0x7f,       // 127
+            REPORT_SIZE(1), 0x08,
+            REPORT_COUNT(1), 0x01,
+            INPUT(1), 0x06,                 // Data, Variable, Relative
+\r
+            USAGE_PAGE(1), 0x09,            // Buttons
+            USAGE_MINIMUM(1), 0x01,
+            USAGE_MAXIMUM(1), 0x03,
+            LOGICAL_MINIMUM(1), 0x00,       // 0
+            LOGICAL_MAXIMUM(1), 0x01,       // 1
+            REPORT_COUNT(1), 0x03,
+            REPORT_SIZE(1), 0x01,
+            INPUT(1), 0x02,                 // Data, Variable, Absolute
+            REPORT_COUNT(1), 0x01,
+            REPORT_SIZE(1), 0x05,
+            INPUT(1), 0x01,                 // Constant
+\r
+            END_COLLECTION(0),
+            END_COLLECTION(0)
+        };
+        reportLength = sizeof(reportDescriptor);
+        return reportDescriptor;
+    }
+    return NULL;
+}
 \r
 \r
index 23eb925..01dcd06 100644 (file)
-/* USBMouse.h */\r
-/* USB device example: relative mouse */\r
-/* Copyright (c) 2011 ARM Limited. All rights reserved. */\r
+/* USBMouse.h */
+/* USB device example: relative mouse */
+/* Copyright (c) 2011 ARM Limited. All rights reserved. */
 \r
-#ifndef USBMOUSE_H\r
-#define USBMOUSE_H\r
+#ifndef USBMOUSE_H
+#define USBMOUSE_H
 \r
-#include "USBHID.h"\r
+#include "USBHID.h"
 \r
-#define REPORT_ID_MOUSE   2\r
+#define REPORT_ID_MOUSE   2
 \r
-/* Common usage */\r
+/* Common usage */
 \r
-enum MOUSE_BUTTON\r
-{\r
-    MOUSE_LEFT = 1,\r
-    MOUSE_RIGHT = 2,\r
-    MOUSE_MIDDLE = 4,\r
-};\r
+enum MOUSE_BUTTON
+{
+    MOUSE_LEFT = 1,
+    MOUSE_RIGHT = 2,
+    MOUSE_MIDDLE = 4,
+};
 \r
-/* X and Y limits */\r
-/* These values do not directly map to screen pixels */\r
-/* Zero may be interpreted as meaning 'no movement' */\r
-#define X_MIN_ABS    (1)        /*!< Minimum value on x-axis */  \r
-#define Y_MIN_ABS    (1)        /*!< Minimum value on y-axis */\r
-#define X_MAX_ABS    (0x7fff)   /*!< Maximum value on x-axis */\r
-#define Y_MAX_ABS    (0x7fff)   /*!< Maximum value on y-axis */\r
+/* X and Y limits */
+/* These values do not directly map to screen pixels */
+/* Zero may be interpreted as meaning 'no movement' */
+#define X_MIN_ABS    (1)        /*!< Minimum value on x-axis */
+#define Y_MIN_ABS    (1)        /*!< Minimum value on y-axis */
+#define X_MAX_ABS    (0x7fff)   /*!< Maximum value on x-axis */
+#define Y_MAX_ABS    (0x7fff)   /*!< Maximum value on y-axis */
 \r
-#define X_MIN_REL    (-127)     /*!< The maximum value that we can move to the left on the x-axis */\r
-#define Y_MIN_REL    (-127)     /*!< The maximum value that we can move up on the y-axis */\r
-#define X_MAX_REL    (127)      /*!< The maximum value that we can move to the right on the x-axis */\r
-#define Y_MAX_REL    (127)      /*!< The maximum value that we can move down on the y-axis */\r
+#define X_MIN_REL    (-127)     /*!< The maximum value that we can move to the left on the x-axis */
+#define Y_MIN_REL    (-127)     /*!< The maximum value that we can move up on the y-axis */
+#define X_MAX_REL    (127)      /*!< The maximum value that we can move to the right on the x-axis */
+#define Y_MAX_REL    (127)      /*!< The maximum value that we can move down on the y-axis */
 \r
-enum MOUSE_TYPE\r
-{\r
-    ABS_MOUSE,\r
-    REL_MOUSE,\r
-};\r
+enum MOUSE_TYPE
+{
+    ABS_MOUSE,
+    REL_MOUSE,
+};
 \r
-/**\r
- *\r
- * USBMouse example\r
- * @code\r
- * #include "mbed.h"\r
- * #include "USBMouse.h"\r
- *\r
- * USBMouse mouse;\r
- *\r
- * int main(void)\r
- * {\r
- *   while (1)\r
- *   {\r
- *      mouse.move(20, 0);\r
- *      wait(0.5);\r
- *   }\r
- * }\r
- *\r
- * @endcode\r
- *\r
- *\r
- * @code\r
- * #include "mbed.h"\r
- * #include "USBMouse.h"\r
- * #include <math.h>\r
- *\r
- * USBMouse mouse(ABS_MOUSE);\r
- *\r
- * int main(void)\r
- * {\r
- *   uint16_t x_center = (X_MAX_ABS - X_MIN_ABS)/2;\r
- *   uint16_t y_center = (Y_MAX_ABS - Y_MIN_ABS)/2;\r
- *   uint16_t x_screen = 0;\r
- *   uint16_t y_screen = 0;\r
- *   \r
- *   uint32_t x_origin = x_center;\r
- *   uint32_t y_origin = y_center;\r
- *   uint32_t radius = 5000;\r
- *   uint32_t angle = 0;\r
- *\r
- *   while (1)\r
- *   {\r
- *       x_screen = x_origin + cos((double)angle*3.14/180.0)*radius;\r
- *       y_screen = y_origin + sin((double)angle*3.14/180.0)*radius;\r
- *       \r
- *       mouse.move(x_screen, y_screen);\r
- *       angle += 3;\r
- *       wait(0.01);\r
- *   }\r
- * }\r
- *\r
- * @endcode\r
- */\r
-class USBMouse: public USBHID\r
-{\r
-    public:\r
+/**
+ *
+ * USBMouse example
+ * @code
+ * #include "mbed.h"
+ * #include "USBMouse.h"
+ *
+ * USBMouse mouse;
+ *
+ * int main(void)
+ * {
+ *   while (1)
+ *   {
+ *      mouse.move(20, 0);
+ *      wait(0.5);
+ *   }
+ * }
+ *
+ * @endcode
+ *
+ *
+ * @code
+ * #include "mbed.h"
+ * #include "USBMouse.h"
+ * #include <math.h>
+ *
+ * USBMouse mouse(ABS_MOUSE);
+ *
+ * int main(void)
+ * {
+ *   uint16_t x_center = (X_MAX_ABS - X_MIN_ABS)/2;
+ *   uint16_t y_center = (Y_MAX_ABS - Y_MIN_ABS)/2;
+ *   uint16_t x_screen = 0;
+ *   uint16_t y_screen = 0;
+ *
+ *   uint32_t x_origin = x_center;
+ *   uint32_t y_origin = y_center;
+ *   uint32_t radius = 5000;
+ *   uint32_t angle = 0;
+ *
+ *   while (1)
+ *   {
+ *       x_screen = x_origin + cos((double)angle*3.14/180.0)*radius;
+ *       y_screen = y_origin + sin((double)angle*3.14/180.0)*radius;
+ *
+ *       mouse.move(x_screen, y_screen);
+ *       angle += 3;
+ *       wait(0.01);
+ *   }
+ * }
+ *
+ * @endcode
+ */
+class USBMouse: public USBHID
+{
+    public:
         \r
-        /**\r
-        *   Constructor\r
-        *\r
-        * @param mouse_type Mouse type: ABS_MOUSE (absolute mouse) or REL_MOUSE (relative mouse) (default: REL_MOUSE)\r
-        * @param vendor_id Your vendor_id (default: 0x1234)\r
-        * @param product_id Your product_id (default: 0x0001)\r
-        * @param product_release Your preoduct_release (default: 0x0001)\r
-        *\r
-        */\r
-        USBMouse(MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x1234, uint16_t product_id = 0x0001, uint16_t product_release = 0x0001): \r
-            USBHID(0, 0, vendor_id, product_id, product_release, false)\r
-            { \r
-                button = 0;\r
-                this->mouse_type = mouse_type;\r
-                connect();\r
-            };\r
+        /**
+        *   Constructor
+        *
+        * @param mouse_type Mouse type: ABS_MOUSE (absolute mouse) or REL_MOUSE (relative mouse) (default: REL_MOUSE)
+        * @param vendor_id Your vendor_id (default: 0x1234)
+        * @param product_id Your product_id (default: 0x0001)
+        * @param product_release Your preoduct_release (default: 0x0001)
+        *
+        */
+        USBMouse(MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x1234, uint16_t product_id = 0x0001, uint16_t product_release = 0x0001):
+            USBHID(0, 0, vendor_id, product_id, product_release, false)
+            {
+                button = 0;
+                this->mouse_type = mouse_type;
+                connect();
+            };
         \r
-        /**\r
-        * Write a state of the mouse\r
-        *\r
-        * @param x x-axis position\r
-        * @param y y-axis position\r
-        * @param buttons buttons state (first bit represents MOUSE_LEFT, second bit MOUSE_RIGHT and third bit MOUSE_MIDDLE)\r
-        * @param z wheel state (>0 to scroll down, <0 to scroll up)\r
-        * @returns true if there is no error, false otherwise\r
-        */\r
-        bool update(int16_t x, int16_t y, uint8_t buttons, int8_t z);\r
+        /**
+        * Write a state of the mouse
+        *
+        * @param x x-axis position
+        * @param y y-axis position
+        * @param buttons buttons state (first bit represents MOUSE_LEFT, second bit MOUSE_RIGHT and third bit MOUSE_MIDDLE)
+        * @param z wheel state (>0 to scroll down, <0 to scroll up)
+        * @returns true if there is no error, false otherwise
+        */
+        bool update(int16_t x, int16_t y, uint8_t buttons, int8_t z);
         \r
         \r
-        /**\r
-        * Move the cursor to (x, y)\r
-        *\r
-        * @param x-axis position\r
-        * @param y-axis position\r
-        * @returns true if there is no error, false otherwise\r
-        */\r
-        bool move(int16_t x, int16_t y);\r
+        /**
+        * Move the cursor to (x, y)
+        *
+        * @param x-axis position
+        * @param y-axis position
+        * @returns true if there is no error, false otherwise
+        */
+        bool move(int16_t x, int16_t y);
         \r
-        /**\r
-        * Press one or several buttons\r
-        *\r
-        * @param button button state (ex: press(MOUSE_LEFT))\r
-        * @returns true if there is no error, false otherwise\r
-        */\r
-        bool press(uint8_t button);\r
+        /**
+        * Press one or several buttons
+        *
+        * @param button button state (ex: press(MOUSE_LEFT))
+        * @returns true if there is no error, false otherwise
+        */
+        bool press(uint8_t button);
         \r
-        /**\r
-        * Release one or several buttons\r
-        *\r
-        * @param button button state (ex: release(MOUSE_LEFT))\r
-        * @returns true if there is no error, false otherwise\r
-        */\r
-        bool release(uint8_t button);\r
+        /**
+        * Release one or several buttons
+        *
+        * @param button button state (ex: release(MOUSE_LEFT))
+        * @returns true if there is no error, false otherwise
+        */
+        bool release(uint8_t button);
         \r
-        /**\r
-        * Double click (MOUSE_LEFT)\r
-        *\r
-        * @returns true if there is no error, false otherwise\r
-        */\r
-        bool doubleClick();\r
+        /**
+        * Double click (MOUSE_LEFT)
+        *
+        * @returns true if there is no error, false otherwise
+        */
+        bool doubleClick();
         \r
-        /**\r
-        * Click\r
-        *\r
-        * @param button state of the buttons ( ex: clic(MOUSE_LEFT))\r
-        * @returns true if there is no error, false otherwise\r
-        */\r
-        bool click(uint8_t button); \r
+        /**
+        * Click
+        *
+        * @param button state of the buttons ( ex: clic(MOUSE_LEFT))
+        * @returns true if there is no error, false otherwise
+        */
+        bool click(uint8_t button);
         \r
-        /**\r
-        * Scrolling\r
-        *\r
-        * @param z value of the wheel (>0 to go down, <0 to go up)\r
-        * @returns true if there is no error, false otherwise\r
-        */\r
-        bool scroll(int8_t z);\r
+        /**
+        * Scrolling
+        *
+        * @param z value of the wheel (>0 to go down, <0 to go up)
+        * @returns true if there is no error, false otherwise
+        */
+        bool scroll(int8_t z);
         \r
-        /*\r
-        * To define the report descriptor. Warning: this method has to store the length of the report descriptor in reportLength.\r
-        *\r
-        * @returns pointer to the report descriptor\r
-        */\r
-        virtual uint8_t * reportDesc();\r
+        /*
+        * To define the report descriptor. Warning: this method has to store the length of the report descriptor in reportLength.
+        *
+        * @returns pointer to the report descriptor
+        */
+        virtual uint8_t * reportDesc();
         \r
-    private:\r
-        MOUSE_TYPE mouse_type;\r
-        uint8_t button;\r
-        bool mouseSend(int8_t x, int8_t y, uint8_t buttons, int8_t z);\r
-};\r
+    private:
+        MOUSE_TYPE mouse_type;
+        uint8_t button;
+        bool mouseSend(int8_t x, int8_t y, uint8_t buttons, int8_t z);
+};
 \r
-#endif\r
+#endif
index 387f9c1..ec3cd90 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#include "stdint.h"\r
-#include "USBMouseKeyboard.h"\r
-\r
-typedef struct {\r
-    unsigned char usage;\r
-    unsigned char modifier;\r
-} KEYMAP;\r
-\r
-#ifdef US_KEYBOARD\r
-/* US keyboard (as HID standard) */\r
-#define KEYMAP_SIZE (148)\r
-const KEYMAP keymap[KEYMAP_SIZE] = {\r
-    {0, 0},             /* NUL */\r
-    {0, 0},             /* SOH */\r
-    {0, 0},             /* STX */\r
-    {0, 0},             /* ETX */\r
-    {0, 0},             /* EOT */\r
-    {0, 0},             /* ENQ */\r
-    {0, 0},             /* ACK */\r
-    {0, 0},             /* BEL */\r
-    {0x2a, 0},          /* BS  */  /* Keyboard Delete (Backspace) */\r
-    {0x2b, 0},          /* TAB */  /* Keyboard Tab */\r
-    {0x28, 0},          /* LF  */  /* Keyboard Return (Enter) */\r
-    {0, 0},             /* VT  */\r
-    {0, 0},             /* FF  */\r
-    {0, 0},             /* CR  */\r
-    {0, 0},             /* SO  */\r
-    {0, 0},             /* SI  */\r
-    {0, 0},             /* DEL */\r
-    {0, 0},             /* DC1 */\r
-    {0, 0},             /* DC2 */\r
-    {0, 0},             /* DC3 */\r
-    {0, 0},             /* DC4 */\r
-    {0, 0},             /* NAK */\r
-    {0, 0},             /* SYN */\r
-    {0, 0},             /* ETB */\r
-    {0, 0},             /* CAN */\r
-    {0, 0},             /* EM  */\r
-    {0, 0},             /* SUB */\r
-    {0, 0},             /* ESC */\r
-    {0, 0},             /* FS  */\r
-    {0, 0},             /* GS  */\r
-    {0, 0},             /* RS  */\r
-    {0, 0},             /* US  */\r
-    {0x2c, 0},          /*   */\r
-    {0x1e, KEY_SHIFT},      /* ! */\r
-    {0x34, KEY_SHIFT},      /* " */\r
-    {0x20, KEY_SHIFT},      /* # */\r
-    {0x21, KEY_SHIFT},      /* $ */\r
-    {0x22, KEY_SHIFT},      /* % */\r
-    {0x24, KEY_SHIFT},      /* & */\r
-    {0x34, 0},          /* ' */\r
-    {0x26, KEY_SHIFT},      /* ( */\r
-    {0x27, KEY_SHIFT},      /* ) */\r
-    {0x25, KEY_SHIFT},      /* * */\r
-    {0x2e, KEY_SHIFT},      /* + */\r
-    {0x36, 0},          /* , */\r
-    {0x2d, 0},          /* - */\r
-    {0x37, 0},          /* . */\r
-    {0x38, 0},          /* / */\r
-    {0x27, 0},          /* 0 */\r
-    {0x1e, 0},          /* 1 */\r
-    {0x1f, 0},          /* 2 */\r
-    {0x20, 0},          /* 3 */\r
-    {0x21, 0},          /* 4 */\r
-    {0x22, 0},          /* 5 */\r
-    {0x23, 0},          /* 6 */\r
-    {0x24, 0},          /* 7 */\r
-    {0x25, 0},          /* 8 */\r
-    {0x26, 0},          /* 9 */\r
-    {0x33, KEY_SHIFT},      /* : */\r
-    {0x33, 0},          /* ; */\r
-    {0x36, KEY_SHIFT},      /* < */\r
-    {0x2e, 0},          /* = */\r
-    {0x37, KEY_SHIFT},      /* > */\r
-    {0x38, KEY_SHIFT},      /* ? */\r
-    {0x1f, KEY_SHIFT},      /* @ */\r
-    {0x04, KEY_SHIFT},      /* A */\r
-    {0x05, KEY_SHIFT},      /* B */\r
-    {0x06, KEY_SHIFT},      /* C */\r
-    {0x07, KEY_SHIFT},      /* D */\r
-    {0x08, KEY_SHIFT},      /* E */\r
-    {0x09, KEY_SHIFT},      /* F */\r
-    {0x0a, KEY_SHIFT},      /* G */\r
-    {0x0b, KEY_SHIFT},      /* H */\r
-    {0x0c, KEY_SHIFT},      /* I */\r
-    {0x0d, KEY_SHIFT},      /* J */\r
-    {0x0e, KEY_SHIFT},      /* K */\r
-    {0x0f, KEY_SHIFT},      /* L */\r
-    {0x10, KEY_SHIFT},      /* M */\r
-    {0x11, KEY_SHIFT},      /* N */\r
-    {0x12, KEY_SHIFT},      /* O */\r
-    {0x13, KEY_SHIFT},      /* P */\r
-    {0x14, KEY_SHIFT},      /* Q */\r
-    {0x15, KEY_SHIFT},      /* R */\r
-    {0x16, KEY_SHIFT},      /* S */\r
-    {0x17, KEY_SHIFT},      /* T */\r
-    {0x18, KEY_SHIFT},      /* U */\r
-    {0x19, KEY_SHIFT},      /* V */\r
-    {0x1a, KEY_SHIFT},      /* W */\r
-    {0x1b, KEY_SHIFT},      /* X */\r
-    {0x1c, KEY_SHIFT},      /* Y */\r
-    {0x1d, KEY_SHIFT},      /* Z */\r
-    {0x2f, 0},          /* [ */\r
-    {0x31, 0},          /* \ */\r
-    {0x30, 0},          /* ] */\r
-    {0x23, KEY_SHIFT},      /* ^ */\r
-    {0x2d, KEY_SHIFT},      /* _ */\r
-    {0x35, 0},          /* ` */\r
-    {0x04, 0},          /* a */\r
-    {0x05, 0},          /* b */\r
-    {0x06, 0},          /* c */\r
-    {0x07, 0},          /* d */\r
-    {0x08, 0},          /* e */\r
-    {0x09, 0},          /* f */\r
-    {0x0a, 0},          /* g */\r
-    {0x0b, 0},          /* h */\r
-    {0x0c, 0},          /* i */\r
-    {0x0d, 0},          /* j */\r
-    {0x0e, 0},          /* k */\r
-    {0x0f, 0},          /* l */\r
-    {0x10, 0},          /* m */\r
-    {0x11, 0},          /* n */\r
-    {0x12, 0},          /* o */\r
-    {0x13, 0},          /* p */\r
-    {0x14, 0},          /* q */\r
-    {0x15, 0},          /* r */\r
-    {0x16, 0},          /* s */\r
-    {0x17, 0},          /* t */\r
-    {0x18, 0},          /* u */\r
-    {0x19, 0},          /* v */\r
-    {0x1a, 0},          /* w */\r
-    {0x1b, 0},          /* x */\r
-    {0x1c, 0},          /* y */\r
-    {0x1d, 0},          /* z */\r
-    {0x2f, KEY_SHIFT},      /* { */\r
-    {0x31, KEY_SHIFT},      /* | */\r
-    {0x30, KEY_SHIFT},      /* } */\r
-    {0x35, KEY_SHIFT},      /* ~ */\r
-    {0,0},              /* DEL */\r
-\r
-    {0x3a, 0},          /* F1 */\r
-    {0x3b, 0},          /* F2 */\r
-    {0x3c, 0},          /* F3 */\r
-    {0x3d, 0},          /* F4 */\r
-    {0x3e, 0},          /* F5 */\r
-    {0x3f, 0},          /* F6 */\r
-    {0x40, 0},          /* F7 */\r
-    {0x41, 0},          /* F8 */\r
-    {0x42, 0},          /* F9 */\r
-    {0x43, 0},          /* F10 */\r
-    {0x44, 0},          /* F11 */\r
-    {0x45, 0},          /* F12 */\r
-\r
-    {0x46, 0},          /* PRINT_SCREEN */\r
-    {0x47, 0},          /* SCROLL_LOCK */\r
-    {0x39, 0},          /* CAPS_LOCK */\r
-    {0x53, 0},          /* NUM_LOCK */\r
-    {0x49, 0},          /* INSERT */\r
-    {0x4a, 0},          /* HOME */\r
-    {0x4b, 0},          /* PAGE_UP */\r
-    {0x4e, 0},          /* PAGE_DOWN */\r
-};\r
-\r
-#else\r
-/* UK keyboard */\r
-#define KEYMAP_SIZE (148)\r
-const KEYMAP keymap[KEYMAP_SIZE] = {\r
-    {0, 0},             /* NUL */\r
-    {0, 0},             /* SOH */\r
-    {0, 0},             /* STX */\r
-    {0, 0},             /* ETX */\r
-    {0, 0},             /* EOT */\r
-    {0, 0},             /* ENQ */\r
-    {0, 0},             /* ACK */\r
-    {0, 0},             /* BEL */\r
-    {0x2a, 0},          /* BS  */  /* Keyboard Delete (Backspace) */\r
-    {0x2b, 0},          /* TAB */  /* Keyboard Tab */\r
-    {0x28, 0},          /* LF  */  /* Keyboard Return (Enter) */\r
-    {0, 0},             /* VT  */\r
-    {0, 0},             /* FF  */\r
-    {0, 0},             /* CR  */\r
-    {0, 0},             /* SO  */\r
-    {0, 0},             /* SI  */\r
-    {0, 0},             /* DEL */\r
-    {0, 0},             /* DC1 */\r
-    {0, 0},             /* DC2 */\r
-    {0, 0},             /* DC3 */\r
-    {0, 0},             /* DC4 */\r
-    {0, 0},             /* NAK */\r
-    {0, 0},             /* SYN */\r
-    {0, 0},             /* ETB */\r
-    {0, 0},             /* CAN */\r
-    {0, 0},             /* EM  */\r
-    {0, 0},             /* SUB */\r
-    {0, 0},             /* ESC */\r
-    {0, 0},             /* FS  */\r
-    {0, 0},             /* GS  */\r
-    {0, 0},             /* RS  */\r
-    {0, 0},             /* US  */\r
-    {0x2c, 0},          /*   */\r
-    {0x1e, KEY_SHIFT},      /* ! */\r
-    {0x1f, KEY_SHIFT},      /* " */\r
-    {0x32, 0},          /* # */\r
-    {0x21, KEY_SHIFT},      /* $ */\r
-    {0x22, KEY_SHIFT},      /* % */\r
-    {0x24, KEY_SHIFT},      /* & */\r
-    {0x34, 0},          /* ' */\r
-    {0x26, KEY_SHIFT},      /* ( */\r
-    {0x27, KEY_SHIFT},      /* ) */\r
-    {0x25, KEY_SHIFT},      /* * */\r
-    {0x2e, KEY_SHIFT},      /* + */\r
-    {0x36, 0},          /* , */\r
-    {0x2d, 0},          /* - */\r
-    {0x37, 0},          /* . */\r
-    {0x38, 0},          /* / */\r
-    {0x27, 0},          /* 0 */\r
-    {0x1e, 0},          /* 1 */\r
-    {0x1f, 0},          /* 2 */\r
-    {0x20, 0},          /* 3 */\r
-    {0x21, 0},          /* 4 */\r
-    {0x22, 0},          /* 5 */\r
-    {0x23, 0},          /* 6 */\r
-    {0x24, 0},          /* 7 */\r
-    {0x25, 0},          /* 8 */\r
-    {0x26, 0},          /* 9 */\r
-    {0x33, KEY_SHIFT},      /* : */\r
-    {0x33, 0},          /* ; */\r
-    {0x36, KEY_SHIFT},      /* < */\r
-    {0x2e, 0},          /* = */\r
-    {0x37, KEY_SHIFT},      /* > */\r
-    {0x38, KEY_SHIFT},      /* ? */\r
-    {0x34, KEY_SHIFT},      /* @ */\r
-    {0x04, KEY_SHIFT},      /* A */\r
-    {0x05, KEY_SHIFT},      /* B */\r
-    {0x06, KEY_SHIFT},      /* C */\r
-    {0x07, KEY_SHIFT},      /* D */\r
-    {0x08, KEY_SHIFT},      /* E */\r
-    {0x09, KEY_SHIFT},      /* F */\r
-    {0x0a, KEY_SHIFT},      /* G */\r
-    {0x0b, KEY_SHIFT},      /* H */\r
-    {0x0c, KEY_SHIFT},      /* I */\r
-    {0x0d, KEY_SHIFT},      /* J */\r
-    {0x0e, KEY_SHIFT},      /* K */\r
-    {0x0f, KEY_SHIFT},      /* L */\r
-    {0x10, KEY_SHIFT},      /* M */\r
-    {0x11, KEY_SHIFT},      /* N */\r
-    {0x12, KEY_SHIFT},      /* O */\r
-    {0x13, KEY_SHIFT},      /* P */\r
-    {0x14, KEY_SHIFT},      /* Q */\r
-    {0x15, KEY_SHIFT},      /* R */\r
-    {0x16, KEY_SHIFT},      /* S */\r
-    {0x17, KEY_SHIFT},      /* T */\r
-    {0x18, KEY_SHIFT},      /* U */\r
-    {0x19, KEY_SHIFT},      /* V */\r
-    {0x1a, KEY_SHIFT},      /* W */\r
-    {0x1b, KEY_SHIFT},      /* X */\r
-    {0x1c, KEY_SHIFT},      /* Y */\r
-    {0x1d, KEY_SHIFT},      /* Z */\r
-    {0x2f, 0},          /* [ */\r
-    {0x64, 0},          /* \ */\r
-    {0x30, 0},          /* ] */\r
-    {0x23, KEY_SHIFT},      /* ^ */\r
-    {0x2d, KEY_SHIFT},      /* _ */\r
-    {0x35, 0},          /* ` */\r
-    {0x04, 0},          /* a */\r
-    {0x05, 0},          /* b */\r
-    {0x06, 0},          /* c */\r
-    {0x07, 0},          /* d */\r
-    {0x08, 0},          /* e */\r
-    {0x09, 0},          /* f */\r
-    {0x0a, 0},          /* g */\r
-    {0x0b, 0},          /* h */\r
-    {0x0c, 0},          /* i */\r
-    {0x0d, 0},          /* j */\r
-    {0x0e, 0},          /* k */\r
-    {0x0f, 0},          /* l */\r
-    {0x10, 0},          /* m */\r
-    {0x11, 0},          /* n */\r
-    {0x12, 0},          /* o */\r
-    {0x13, 0},          /* p */\r
-    {0x14, 0},          /* q */\r
-    {0x15, 0},          /* r */\r
-    {0x16, 0},          /* s */\r
-    {0x17, 0},          /* t */\r
-    {0x18, 0},          /* u */\r
-    {0x19, 0},          /* v */\r
-    {0x1a, 0},          /* w */\r
-    {0x1b, 0},          /* x */\r
-    {0x1c, 0},          /* y */\r
-    {0x1d, 0},          /* z */\r
-    {0x2f, KEY_SHIFT},      /* { */\r
-    {0x64, KEY_SHIFT},      /* | */\r
-    {0x30, KEY_SHIFT},      /* } */\r
-    {0x32, KEY_SHIFT},      /* ~ */\r
-    {0,0},             /* DEL */\r
-\r
-    {0x3a, 0},          /* F1 */\r
-    {0x3b, 0},          /* F2 */\r
-    {0x3c, 0},          /* F3 */\r
-    {0x3d, 0},          /* F4 */\r
-    {0x3e, 0},          /* F5 */\r
-    {0x3f, 0},          /* F6 */\r
-    {0x40, 0},          /* F7 */\r
-    {0x41, 0},          /* F8 */\r
-    {0x42, 0},          /* F9 */\r
-    {0x43, 0},          /* F10 */\r
-    {0x44, 0},          /* F11 */\r
-    {0x45, 0},          /* F12 */\r
-\r
-    {0x46, 0},          /* PRINT_SCREEN */\r
-    {0x47, 0},          /* SCROLL_LOCK */\r
-    {0x39, 0},          /* CAPS_LOCK */\r
-    {0x53, 0},          /* NUM_LOCK */\r
-    {0x49, 0},          /* INSERT */\r
-    {0x4a, 0},          /* HOME */\r
-    {0x4b, 0},          /* PAGE_UP */\r
-    {0x4e, 0},          /* PAGE_DOWN */\r
-};\r
-#endif\r
-\r
-\r
-uint8_t * USBMouseKeyboard::reportDesc() {\r
-    if (mouse_type == REL_MOUSE) {\r
-        static uint8_t reportDescriptor[] = {\r
-                // Keyboard\r
-                USAGE_PAGE(1),      0x01,\r
-                USAGE(1),           0x06,\r
-                COLLECTION(1),      0x01,\r
-                REPORT_ID(1),       REPORT_ID_KEYBOARD,\r
-                USAGE_PAGE(1),      0x07,\r
-                USAGE_MINIMUM(1),       0xE0,\r
-                USAGE_MAXIMUM(1),       0xE7,\r
-                LOGICAL_MINIMUM(1),     0x00,\r
-                LOGICAL_MAXIMUM(1),     0x01,\r
-                REPORT_SIZE(1),     0x01,\r
-                REPORT_COUNT(1),    0x08,\r
-                INPUT(1),           0x02,\r
-                REPORT_COUNT(1),    0x01,\r
-                REPORT_SIZE(1),     0x08,\r
-                INPUT(1),           0x01,\r
-                REPORT_COUNT(1),    0x05,\r
-                REPORT_SIZE(1),     0x01,\r
-                USAGE_PAGE(1),      0x08,\r
-                USAGE_MINIMUM(1),       0x01,\r
-                USAGE_MAXIMUM(1),       0x05,\r
-                OUTPUT(1),          0x02,\r
-                REPORT_COUNT(1),    0x01,\r
-                REPORT_SIZE(1),     0x03,\r
-                OUTPUT(1),          0x01,\r
-                REPORT_COUNT(1),    0x06,\r
-                REPORT_SIZE(1),     0x08,\r
-                LOGICAL_MINIMUM(1),     0x00,\r
-                LOGICAL_MAXIMUM(2),     0xff, 0x00,\r
-                USAGE_PAGE(1),      0x07,\r
-                USAGE_MINIMUM(1),       0x00,\r
-                USAGE_MAXIMUM(2),       0xff, 0x00,\r
-                INPUT(1),           0x00,\r
-                END_COLLECTION(0),\r
-\r
-                // Mouse\r
-                USAGE_PAGE(1),      0x01,           // Generic Desktop\r
-                USAGE(1),           0x02,           // Mouse\r
-                COLLECTION(1),      0x01,           // Application\r
-                USAGE(1),           0x01,           // Pointer\r
-                COLLECTION(1),      0x00,           // Physical\r
-                REPORT_ID(1),       REPORT_ID_MOUSE,\r
-                REPORT_COUNT(1),    0x03,\r
-                REPORT_SIZE(1),     0x01,\r
-                USAGE_PAGE(1),      0x09,           // Buttons\r
-                USAGE_MINIMUM(1),       0x1,\r
-                USAGE_MAXIMUM(1),       0x3,\r
-                LOGICAL_MINIMUM(1),     0x00,\r
-                LOGICAL_MAXIMUM(1),     0x01,\r
-                INPUT(1),           0x02,\r
-                REPORT_COUNT(1),    0x01,\r
-                REPORT_SIZE(1),     0x05,\r
-                INPUT(1),           0x01,\r
-                REPORT_COUNT(1),    0x03,\r
-                REPORT_SIZE(1),     0x08,\r
-                USAGE_PAGE(1),      0x01,\r
-                USAGE(1),           0x30,           // X\r
-                USAGE(1),           0x31,           // Y\r
-                USAGE(1),           0x38,           // scroll\r
-                LOGICAL_MINIMUM(1),     0x81,\r
-                LOGICAL_MAXIMUM(1),     0x7f,\r
-                INPUT(1),           0x06,\r
-                END_COLLECTION(0),\r
-                END_COLLECTION(0),\r
-\r
-\r
-                // Media Control\r
-                USAGE_PAGE(1), 0x0C,\r
-                USAGE(1), 0x01,\r
-                COLLECTION(1), 0x01,\r
-                REPORT_ID(1), REPORT_ID_VOLUME,\r
-                USAGE_PAGE(1), 0x0C,\r
-                LOGICAL_MINIMUM(1), 0x00,\r
-                LOGICAL_MAXIMUM(1), 0x01,\r
-                REPORT_SIZE(1), 0x01,\r
-                REPORT_COUNT(1), 0x07,\r
-                USAGE(1), 0xB5,             // Next Track\r
-                USAGE(1), 0xB6,             // Previous Track\r
-                USAGE(1), 0xB7,             // Stop\r
-                USAGE(1), 0xCD,             // Play / Pause\r
-                USAGE(1), 0xE2,             // Mute\r
-                USAGE(1), 0xE9,             // Volume Up\r
-                USAGE(1), 0xEA,             // Volume Down\r
-                INPUT(1), 0x02,             // Input (Data, Variable, Absolute)\r
-                REPORT_COUNT(1), 0x01,\r
-                INPUT(1), 0x01,\r
-                END_COLLECTION(0),\r
-        };\r
-        reportLength = sizeof(reportDescriptor);\r
-        return reportDescriptor;\r
-    } else if (mouse_type == ABS_MOUSE) {\r
-        static uint8_t reportDescriptor[] = {\r
-\r
-                // Keyboard\r
-                USAGE_PAGE(1),      0x01,\r
-                USAGE(1),           0x06,\r
-                COLLECTION(1),      0x01,\r
-                REPORT_ID(1),       REPORT_ID_KEYBOARD,\r
-                USAGE_PAGE(1),      0x07,\r
-                USAGE_MINIMUM(1),       0xE0,\r
-                USAGE_MAXIMUM(1),       0xE7,\r
-                LOGICAL_MINIMUM(1),     0x00,\r
-                LOGICAL_MAXIMUM(1),     0x01,\r
-                REPORT_SIZE(1),     0x01,\r
-                REPORT_COUNT(1),    0x08,\r
-                INPUT(1),           0x02,\r
-                REPORT_COUNT(1),    0x01,\r
-                REPORT_SIZE(1),     0x08,\r
-                INPUT(1),           0x01,\r
-                REPORT_COUNT(1),    0x05,\r
-                REPORT_SIZE(1),     0x01,\r
-                USAGE_PAGE(1),      0x08,\r
-                USAGE_MINIMUM(1),       0x01,\r
-                USAGE_MAXIMUM(1),       0x05,\r
-                OUTPUT(1),          0x02,\r
-                REPORT_COUNT(1),    0x01,\r
-                REPORT_SIZE(1),     0x03,\r
-                OUTPUT(1),          0x01,\r
-                REPORT_COUNT(1),    0x06,\r
-                REPORT_SIZE(1),     0x08,\r
-                LOGICAL_MINIMUM(1),     0x00,\r
-                LOGICAL_MAXIMUM(2),     0xff, 0x00,\r
-                USAGE_PAGE(1),      0x07,\r
-                USAGE_MINIMUM(1),       0x00,\r
-                USAGE_MAXIMUM(2),       0xff, 0x00,\r
-                INPUT(1),           0x00,\r
-                END_COLLECTION(0),\r
-\r
-                // Mouse\r
-                USAGE_PAGE(1), 0x01,               // Generic Desktop\r
-                USAGE(1), 0x02,                    // Mouse\r
-                COLLECTION(1), 0x01,               // Application\r
-                USAGE(1), 0x01,                    // Pointer\r
-                COLLECTION(1), 0x00,               // Physical\r
-                REPORT_ID(1),       REPORT_ID_MOUSE,\r
-\r
-                USAGE_PAGE(1), 0x01,                // Generic Desktop\r
-                USAGE(1), 0x30,                     // X\r
-                USAGE(1), 0x31,                     // Y\r
-                LOGICAL_MINIMUM(1), 0x00,           // 0\r
-                LOGICAL_MAXIMUM(2), 0xff, 0x7f,     // 32767\r
-                REPORT_SIZE(1), 0x10,\r
-                REPORT_COUNT(1), 0x02,\r
-                INPUT(1), 0x02,                     // Data, Variable, Absolute\r
-\r
-                USAGE_PAGE(1), 0x01,                // Generic Desktop\r
-                USAGE(1), 0x38,                     // scroll\r
-                LOGICAL_MINIMUM(1), 0x81,           // -127\r
-                LOGICAL_MAXIMUM(1), 0x7f,           // 127\r
-                REPORT_SIZE(1), 0x08,\r
-                REPORT_COUNT(1), 0x01,\r
-                INPUT(1), 0x06,                     // Data, Variable, Relative\r
-\r
-                USAGE_PAGE(1), 0x09,                // Buttons\r
-                USAGE_MINIMUM(1), 0x01,\r
-                USAGE_MAXIMUM(1), 0x03,\r
-                LOGICAL_MINIMUM(1), 0x00,           // 0\r
-                LOGICAL_MAXIMUM(1), 0x01,           // 1\r
-                REPORT_COUNT(1), 0x03,\r
-                REPORT_SIZE(1), 0x01,\r
-                INPUT(1), 0x02,                     // Data, Variable, Absolute\r
-                REPORT_COUNT(1), 0x01,\r
-                REPORT_SIZE(1), 0x05,\r
-                INPUT(1), 0x01,                     // Constant\r
-\r
-                END_COLLECTION(0),\r
-                END_COLLECTION(0),\r
-\r
-                // Media Control\r
-                USAGE_PAGE(1), 0x0C,\r
-                USAGE(1), 0x01,\r
-                COLLECTION(1), 0x01,\r
-                REPORT_ID(1), REPORT_ID_VOLUME,\r
-                USAGE_PAGE(1), 0x0C,\r
-                LOGICAL_MINIMUM(1), 0x00,\r
-                LOGICAL_MAXIMUM(1), 0x01,\r
-                REPORT_SIZE(1), 0x01,\r
-                REPORT_COUNT(1), 0x07,\r
-                USAGE(1), 0xB5,             // Next Track\r
-                USAGE(1), 0xB6,             // Previous Track\r
-                USAGE(1), 0xB7,             // Stop\r
-                USAGE(1), 0xCD,             // Play / Pause\r
-                USAGE(1), 0xE2,             // Mute\r
-                USAGE(1), 0xE9,             // Volume Up\r
-                USAGE(1), 0xEA,             // Volume Down\r
-                INPUT(1), 0x02,             // Input (Data, Variable, Absolute)\r
-                REPORT_COUNT(1), 0x01,\r
-                INPUT(1), 0x01,\r
-                END_COLLECTION(0),\r
-        };\r
-        reportLength = sizeof(reportDescriptor);\r
-        return reportDescriptor;\r
-    }\r
-\r
-    return NULL;\r
-}\r
-\r
-bool USBMouseKeyboard::EP1_OUT_callback() {\r
-    uint16_t bytesRead = 0;\r
-    uint8_t led[65];\r
-    USBDevice::readEP(EPINT_OUT, led, &bytesRead, MAX_HID_REPORT_SIZE);\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#include "stdint.h"
+#include "USBMouseKeyboard.h"
+\r
+typedef struct {
+    unsigned char usage;
+    unsigned char modifier;
+} KEYMAP;
+\r
+#ifdef US_KEYBOARD
+/* US keyboard (as HID standard) */
+#define KEYMAP_SIZE (148)
+const KEYMAP keymap[KEYMAP_SIZE] = {
+    {0, 0},             /* NUL */
+    {0, 0},             /* SOH */
+    {0, 0},             /* STX */
+    {0, 0},             /* ETX */
+    {0, 0},             /* EOT */
+    {0, 0},             /* ENQ */
+    {0, 0},             /* ACK */
+    {0, 0},             /* BEL */
+    {0x2a, 0},          /* BS  */  /* Keyboard Delete (Backspace) */
+    {0x2b, 0},          /* TAB */  /* Keyboard Tab */
+    {0x28, 0},          /* LF  */  /* Keyboard Return (Enter) */
+    {0, 0},             /* VT  */
+    {0, 0},             /* FF  */
+    {0, 0},             /* CR  */
+    {0, 0},             /* SO  */
+    {0, 0},             /* SI  */
+    {0, 0},             /* DEL */
+    {0, 0},             /* DC1 */
+    {0, 0},             /* DC2 */
+    {0, 0},             /* DC3 */
+    {0, 0},             /* DC4 */
+    {0, 0},             /* NAK */
+    {0, 0},             /* SYN */
+    {0, 0},             /* ETB */
+    {0, 0},             /* CAN */
+    {0, 0},             /* EM  */
+    {0, 0},             /* SUB */
+    {0, 0},             /* ESC */
+    {0, 0},             /* FS  */
+    {0, 0},             /* GS  */
+    {0, 0},             /* RS  */
+    {0, 0},             /* US  */
+    {0x2c, 0},          /*   */
+    {0x1e, KEY_SHIFT},      /* ! */
+    {0x34, KEY_SHIFT},      /* " */
+    {0x20, KEY_SHIFT},      /* # */
+    {0x21, KEY_SHIFT},      /* $ */
+    {0x22, KEY_SHIFT},      /* % */
+    {0x24, KEY_SHIFT},      /* & */
+    {0x34, 0},          /* ' */
+    {0x26, KEY_SHIFT},      /* ( */
+    {0x27, KEY_SHIFT},      /* ) */
+    {0x25, KEY_SHIFT},      /* * */
+    {0x2e, KEY_SHIFT},      /* + */
+    {0x36, 0},          /* , */
+    {0x2d, 0},          /* - */
+    {0x37, 0},          /* . */
+    {0x38, 0},          /* / */
+    {0x27, 0},          /* 0 */
+    {0x1e, 0},          /* 1 */
+    {0x1f, 0},          /* 2 */
+    {0x20, 0},          /* 3 */
+    {0x21, 0},          /* 4 */
+    {0x22, 0},          /* 5 */
+    {0x23, 0},          /* 6 */
+    {0x24, 0},          /* 7 */
+    {0x25, 0},          /* 8 */
+    {0x26, 0},          /* 9 */
+    {0x33, KEY_SHIFT},      /* : */
+    {0x33, 0},          /* ; */
+    {0x36, KEY_SHIFT},      /* < */
+    {0x2e, 0},          /* = */
+    {0x37, KEY_SHIFT},      /* > */
+    {0x38, KEY_SHIFT},      /* ? */
+    {0x1f, KEY_SHIFT},      /* @ */
+    {0x04, KEY_SHIFT},      /* A */
+    {0x05, KEY_SHIFT},      /* B */
+    {0x06, KEY_SHIFT},      /* C */
+    {0x07, KEY_SHIFT},      /* D */
+    {0x08, KEY_SHIFT},      /* E */
+    {0x09, KEY_SHIFT},      /* F */
+    {0x0a, KEY_SHIFT},      /* G */
+    {0x0b, KEY_SHIFT},      /* H */
+    {0x0c, KEY_SHIFT},      /* I */
+    {0x0d, KEY_SHIFT},      /* J */
+    {0x0e, KEY_SHIFT},      /* K */
+    {0x0f, KEY_SHIFT},      /* L */
+    {0x10, KEY_SHIFT},      /* M */
+    {0x11, KEY_SHIFT},      /* N */
+    {0x12, KEY_SHIFT},      /* O */
+    {0x13, KEY_SHIFT},      /* P */
+    {0x14, KEY_SHIFT},      /* Q */
+    {0x15, KEY_SHIFT},      /* R */
+    {0x16, KEY_SHIFT},      /* S */
+    {0x17, KEY_SHIFT},      /* T */
+    {0x18, KEY_SHIFT},      /* U */
+    {0x19, KEY_SHIFT},      /* V */
+    {0x1a, KEY_SHIFT},      /* W */
+    {0x1b, KEY_SHIFT},      /* X */
+    {0x1c, KEY_SHIFT},      /* Y */
+    {0x1d, KEY_SHIFT},      /* Z */
+    {0x2f, 0},          /* [ */
+    {0x31, 0},          /* \ */
+    {0x30, 0},          /* ] */
+    {0x23, KEY_SHIFT},      /* ^ */
+    {0x2d, KEY_SHIFT},      /* _ */
+    {0x35, 0},          /* ` */
+    {0x04, 0},          /* a */
+    {0x05, 0},          /* b */
+    {0x06, 0},          /* c */
+    {0x07, 0},          /* d */
+    {0x08, 0},          /* e */
+    {0x09, 0},          /* f */
+    {0x0a, 0},          /* g */
+    {0x0b, 0},          /* h */
+    {0x0c, 0},          /* i */
+    {0x0d, 0},          /* j */
+    {0x0e, 0},          /* k */
+    {0x0f, 0},          /* l */
+    {0x10, 0},          /* m */
+    {0x11, 0},          /* n */
+    {0x12, 0},          /* o */
+    {0x13, 0},          /* p */
+    {0x14, 0},          /* q */
+    {0x15, 0},          /* r */
+    {0x16, 0},          /* s */
+    {0x17, 0},          /* t */
+    {0x18, 0},          /* u */
+    {0x19, 0},          /* v */
+    {0x1a, 0},          /* w */
+    {0x1b, 0},          /* x */
+    {0x1c, 0},          /* y */
+    {0x1d, 0},          /* z */
+    {0x2f, KEY_SHIFT},      /* { */
+    {0x31, KEY_SHIFT},      /* | */
+    {0x30, KEY_SHIFT},      /* } */
+    {0x35, KEY_SHIFT},      /* ~ */
+    {0,0},              /* DEL */
+\r
+    {0x3a, 0},          /* F1 */
+    {0x3b, 0},          /* F2 */
+    {0x3c, 0},          /* F3 */
+    {0x3d, 0},          /* F4 */
+    {0x3e, 0},          /* F5 */
+    {0x3f, 0},          /* F6 */
+    {0x40, 0},          /* F7 */
+    {0x41, 0},          /* F8 */
+    {0x42, 0},          /* F9 */
+    {0x43, 0},          /* F10 */
+    {0x44, 0},          /* F11 */
+    {0x45, 0},          /* F12 */
+\r
+    {0x46, 0},          /* PRINT_SCREEN */
+    {0x47, 0},          /* SCROLL_LOCK */
+    {0x39, 0},          /* CAPS_LOCK */
+    {0x53, 0},          /* NUM_LOCK */
+    {0x49, 0},          /* INSERT */
+    {0x4a, 0},          /* HOME */
+    {0x4b, 0},          /* PAGE_UP */
+    {0x4e, 0},          /* PAGE_DOWN */
+};
+\r
+#else
+/* UK keyboard */
+#define KEYMAP_SIZE (148)
+const KEYMAP keymap[KEYMAP_SIZE] = {
+    {0, 0},             /* NUL */
+    {0, 0},             /* SOH */
+    {0, 0},             /* STX */
+    {0, 0},             /* ETX */
+    {0, 0},             /* EOT */
+    {0, 0},             /* ENQ */
+    {0, 0},             /* ACK */
+    {0, 0},             /* BEL */
+    {0x2a, 0},          /* BS  */  /* Keyboard Delete (Backspace) */
+    {0x2b, 0},          /* TAB */  /* Keyboard Tab */
+    {0x28, 0},          /* LF  */  /* Keyboard Return (Enter) */
+    {0, 0},             /* VT  */
+    {0, 0},             /* FF  */
+    {0, 0},             /* CR  */
+    {0, 0},             /* SO  */
+    {0, 0},             /* SI  */
+    {0, 0},             /* DEL */
+    {0, 0},             /* DC1 */
+    {0, 0},             /* DC2 */
+    {0, 0},             /* DC3 */
+    {0, 0},             /* DC4 */
+    {0, 0},             /* NAK */
+    {0, 0},             /* SYN */
+    {0, 0},             /* ETB */
+    {0, 0},             /* CAN */
+    {0, 0},             /* EM  */
+    {0, 0},             /* SUB */
+    {0, 0},             /* ESC */
+    {0, 0},             /* FS  */
+    {0, 0},             /* GS  */
+    {0, 0},             /* RS  */
+    {0, 0},             /* US  */
+    {0x2c, 0},          /*   */
+    {0x1e, KEY_SHIFT},      /* ! */
+    {0x1f, KEY_SHIFT},      /* " */
+    {0x32, 0},          /* # */
+    {0x21, KEY_SHIFT},      /* $ */
+    {0x22, KEY_SHIFT},      /* % */
+    {0x24, KEY_SHIFT},      /* & */
+    {0x34, 0},          /* ' */
+    {0x26, KEY_SHIFT},      /* ( */
+    {0x27, KEY_SHIFT},      /* ) */
+    {0x25, KEY_SHIFT},      /* * */
+    {0x2e, KEY_SHIFT},      /* + */
+    {0x36, 0},          /* , */
+    {0x2d, 0},          /* - */
+    {0x37, 0},          /* . */
+    {0x38, 0},          /* / */
+    {0x27, 0},          /* 0 */
+    {0x1e, 0},          /* 1 */
+    {0x1f, 0},          /* 2 */
+    {0x20, 0},          /* 3 */
+    {0x21, 0},          /* 4 */
+    {0x22, 0},          /* 5 */
+    {0x23, 0},          /* 6 */
+    {0x24, 0},          /* 7 */
+    {0x25, 0},          /* 8 */
+    {0x26, 0},          /* 9 */
+    {0x33, KEY_SHIFT},      /* : */
+    {0x33, 0},          /* ; */
+    {0x36, KEY_SHIFT},      /* < */
+    {0x2e, 0},          /* = */
+    {0x37, KEY_SHIFT},      /* > */
+    {0x38, KEY_SHIFT},      /* ? */
+    {0x34, KEY_SHIFT},      /* @ */
+    {0x04, KEY_SHIFT},      /* A */
+    {0x05, KEY_SHIFT},      /* B */
+    {0x06, KEY_SHIFT},      /* C */
+    {0x07, KEY_SHIFT},      /* D */
+    {0x08, KEY_SHIFT},      /* E */
+    {0x09, KEY_SHIFT},      /* F */
+    {0x0a, KEY_SHIFT},      /* G */
+    {0x0b, KEY_SHIFT},      /* H */
+    {0x0c, KEY_SHIFT},      /* I */
+    {0x0d, KEY_SHIFT},      /* J */
+    {0x0e, KEY_SHIFT},      /* K */
+    {0x0f, KEY_SHIFT},      /* L */
+    {0x10, KEY_SHIFT},      /* M */
+    {0x11, KEY_SHIFT},      /* N */
+    {0x12, KEY_SHIFT},      /* O */
+    {0x13, KEY_SHIFT},      /* P */
+    {0x14, KEY_SHIFT},      /* Q */
+    {0x15, KEY_SHIFT},      /* R */
+    {0x16, KEY_SHIFT},      /* S */
+    {0x17, KEY_SHIFT},      /* T */
+    {0x18, KEY_SHIFT},      /* U */
+    {0x19, KEY_SHIFT},      /* V */
+    {0x1a, KEY_SHIFT},      /* W */
+    {0x1b, KEY_SHIFT},      /* X */
+    {0x1c, KEY_SHIFT},      /* Y */
+    {0x1d, KEY_SHIFT},      /* Z */
+    {0x2f, 0},          /* [ */
+    {0x64, 0},          /* \ */
+    {0x30, 0},          /* ] */
+    {0x23, KEY_SHIFT},      /* ^ */
+    {0x2d, KEY_SHIFT},      /* _ */
+    {0x35, 0},          /* ` */
+    {0x04, 0},          /* a */
+    {0x05, 0},          /* b */
+    {0x06, 0},          /* c */
+    {0x07, 0},          /* d */
+    {0x08, 0},          /* e */
+    {0x09, 0},          /* f */
+    {0x0a, 0},          /* g */
+    {0x0b, 0},          /* h */
+    {0x0c, 0},          /* i */
+    {0x0d, 0},          /* j */
+    {0x0e, 0},          /* k */
+    {0x0f, 0},          /* l */
+    {0x10, 0},          /* m */
+    {0x11, 0},          /* n */
+    {0x12, 0},          /* o */
+    {0x13, 0},          /* p */
+    {0x14, 0},          /* q */
+    {0x15, 0},          /* r */
+    {0x16, 0},          /* s */
+    {0x17, 0},          /* t */
+    {0x18, 0},          /* u */
+    {0x19, 0},          /* v */
+    {0x1a, 0},          /* w */
+    {0x1b, 0},          /* x */
+    {0x1c, 0},          /* y */
+    {0x1d, 0},          /* z */
+    {0x2f, KEY_SHIFT},      /* { */
+    {0x64, KEY_SHIFT},      /* | */
+    {0x30, KEY_SHIFT},      /* } */
+    {0x32, KEY_SHIFT},      /* ~ */
+    {0,0},             /* DEL */
+\r
+    {0x3a, 0},          /* F1 */
+    {0x3b, 0},          /* F2 */
+    {0x3c, 0},          /* F3 */
+    {0x3d, 0},          /* F4 */
+    {0x3e, 0},          /* F5 */
+    {0x3f, 0},          /* F6 */
+    {0x40, 0},          /* F7 */
+    {0x41, 0},          /* F8 */
+    {0x42, 0},          /* F9 */
+    {0x43, 0},          /* F10 */
+    {0x44, 0},          /* F11 */
+    {0x45, 0},          /* F12 */
+\r
+    {0x46, 0},          /* PRINT_SCREEN */
+    {0x47, 0},          /* SCROLL_LOCK */
+    {0x39, 0},          /* CAPS_LOCK */
+    {0x53, 0},          /* NUM_LOCK */
+    {0x49, 0},          /* INSERT */
+    {0x4a, 0},          /* HOME */
+    {0x4b, 0},          /* PAGE_UP */
+    {0x4e, 0},          /* PAGE_DOWN */
+};
+#endif
+\r
+\r
+uint8_t * USBMouseKeyboard::reportDesc() {
+    if (mouse_type == REL_MOUSE) {
+        static uint8_t reportDescriptor[] = {
+                // Keyboard
+                USAGE_PAGE(1),      0x01,
+                USAGE(1),           0x06,
+                COLLECTION(1),      0x01,
+                REPORT_ID(1),       REPORT_ID_KEYBOARD,
+                USAGE_PAGE(1),      0x07,
+                USAGE_MINIMUM(1),       0xE0,
+                USAGE_MAXIMUM(1),       0xE7,
+                LOGICAL_MINIMUM(1),     0x00,
+                LOGICAL_MAXIMUM(1),     0x01,
+                REPORT_SIZE(1),     0x01,
+                REPORT_COUNT(1),    0x08,
+                INPUT(1),           0x02,
+                REPORT_COUNT(1),    0x01,
+                REPORT_SIZE(1),     0x08,
+                INPUT(1),           0x01,
+                REPORT_COUNT(1),    0x05,
+                REPORT_SIZE(1),     0x01,
+                USAGE_PAGE(1),      0x08,
+                USAGE_MINIMUM(1),       0x01,
+                USAGE_MAXIMUM(1),       0x05,
+                OUTPUT(1),          0x02,
+                REPORT_COUNT(1),    0x01,
+                REPORT_SIZE(1),     0x03,
+                OUTPUT(1),          0x01,
+                REPORT_COUNT(1),    0x06,
+                REPORT_SIZE(1),     0x08,
+                LOGICAL_MINIMUM(1),     0x00,
+                LOGICAL_MAXIMUM(2),     0xff, 0x00,
+                USAGE_PAGE(1),      0x07,
+                USAGE_MINIMUM(1),       0x00,
+                USAGE_MAXIMUM(2),       0xff, 0x00,
+                INPUT(1),           0x00,
+                END_COLLECTION(0),
+\r
+                // Mouse
+                USAGE_PAGE(1),      0x01,           // Generic Desktop
+                USAGE(1),           0x02,           // Mouse
+                COLLECTION(1),      0x01,           // Application
+                USAGE(1),           0x01,           // Pointer
+                COLLECTION(1),      0x00,           // Physical
+                REPORT_ID(1),       REPORT_ID_MOUSE,
+                REPORT_COUNT(1),    0x03,
+                REPORT_SIZE(1),     0x01,
+                USAGE_PAGE(1),      0x09,           // Buttons
+                USAGE_MINIMUM(1),       0x1,
+                USAGE_MAXIMUM(1),       0x3,
+                LOGICAL_MINIMUM(1),     0x00,
+                LOGICAL_MAXIMUM(1),     0x01,
+                INPUT(1),           0x02,
+                REPORT_COUNT(1),    0x01,
+                REPORT_SIZE(1),     0x05,
+                INPUT(1),           0x01,
+                REPORT_COUNT(1),    0x03,
+                REPORT_SIZE(1),     0x08,
+                USAGE_PAGE(1),      0x01,
+                USAGE(1),           0x30,           // X
+                USAGE(1),           0x31,           // Y
+                USAGE(1),           0x38,           // scroll
+                LOGICAL_MINIMUM(1),     0x81,
+                LOGICAL_MAXIMUM(1),     0x7f,
+                INPUT(1),           0x06,
+                END_COLLECTION(0),
+                END_COLLECTION(0),
+\r
+\r
+                // Media Control
+                USAGE_PAGE(1), 0x0C,
+                USAGE(1), 0x01,
+                COLLECTION(1), 0x01,
+                REPORT_ID(1), REPORT_ID_VOLUME,
+                USAGE_PAGE(1), 0x0C,
+                LOGICAL_MINIMUM(1), 0x00,
+                LOGICAL_MAXIMUM(1), 0x01,
+                REPORT_SIZE(1), 0x01,
+                REPORT_COUNT(1), 0x07,
+                USAGE(1), 0xB5,             // Next Track
+                USAGE(1), 0xB6,             // Previous Track
+                USAGE(1), 0xB7,             // Stop
+                USAGE(1), 0xCD,             // Play / Pause
+                USAGE(1), 0xE2,             // Mute
+                USAGE(1), 0xE9,             // Volume Up
+                USAGE(1), 0xEA,             // Volume Down
+                INPUT(1), 0x02,             // Input (Data, Variable, Absolute)
+                REPORT_COUNT(1), 0x01,
+                INPUT(1), 0x01,
+                END_COLLECTION(0),
+        };
+        reportLength = sizeof(reportDescriptor);
+        return reportDescriptor;
+    } else if (mouse_type == ABS_MOUSE) {
+        static uint8_t reportDescriptor[] = {
+\r
+                // Keyboard
+                USAGE_PAGE(1),      0x01,
+                USAGE(1),           0x06,
+                COLLECTION(1),      0x01,
+                REPORT_ID(1),       REPORT_ID_KEYBOARD,
+                USAGE_PAGE(1),      0x07,
+                USAGE_MINIMUM(1),       0xE0,
+                USAGE_MAXIMUM(1),       0xE7,
+                LOGICAL_MINIMUM(1),     0x00,
+                LOGICAL_MAXIMUM(1),     0x01,
+                REPORT_SIZE(1),     0x01,
+                REPORT_COUNT(1),    0x08,
+                INPUT(1),           0x02,
+                REPORT_COUNT(1),    0x01,
+                REPORT_SIZE(1),     0x08,
+                INPUT(1),           0x01,
+                REPORT_COUNT(1),    0x05,
+                REPORT_SIZE(1),     0x01,
+                USAGE_PAGE(1),      0x08,
+                USAGE_MINIMUM(1),       0x01,
+                USAGE_MAXIMUM(1),       0x05,
+                OUTPUT(1),          0x02,
+                REPORT_COUNT(1),    0x01,
+                REPORT_SIZE(1),     0x03,
+                OUTPUT(1),          0x01,
+                REPORT_COUNT(1),    0x06,
+                REPORT_SIZE(1),     0x08,
+                LOGICAL_MINIMUM(1),     0x00,
+                LOGICAL_MAXIMUM(2),     0xff, 0x00,
+                USAGE_PAGE(1),      0x07,
+                USAGE_MINIMUM(1),       0x00,
+                USAGE_MAXIMUM(2),       0xff, 0x00,
+                INPUT(1),           0x00,
+                END_COLLECTION(0),
+\r
+                // Mouse
+                USAGE_PAGE(1), 0x01,               // Generic Desktop
+                USAGE(1), 0x02,                    // Mouse
+                COLLECTION(1), 0x01,               // Application
+                USAGE(1), 0x01,                    // Pointer
+                COLLECTION(1), 0x00,               // Physical
+                REPORT_ID(1),       REPORT_ID_MOUSE,
+\r
+                USAGE_PAGE(1), 0x01,                // Generic Desktop
+                USAGE(1), 0x30,                     // X
+                USAGE(1), 0x31,                     // Y
+                LOGICAL_MINIMUM(1), 0x00,           // 0
+                LOGICAL_MAXIMUM(2), 0xff, 0x7f,     // 32767
+                REPORT_SIZE(1), 0x10,
+                REPORT_COUNT(1), 0x02,
+                INPUT(1), 0x02,                     // Data, Variable, Absolute
+\r
+                USAGE_PAGE(1), 0x01,                // Generic Desktop
+                USAGE(1), 0x38,                     // scroll
+                LOGICAL_MINIMUM(1), 0x81,           // -127
+                LOGICAL_MAXIMUM(1), 0x7f,           // 127
+                REPORT_SIZE(1), 0x08,
+                REPORT_COUNT(1), 0x01,
+                INPUT(1), 0x06,                     // Data, Variable, Relative
+\r
+                USAGE_PAGE(1), 0x09,                // Buttons
+                USAGE_MINIMUM(1), 0x01,
+                USAGE_MAXIMUM(1), 0x03,
+                LOGICAL_MINIMUM(1), 0x00,           // 0
+                LOGICAL_MAXIMUM(1), 0x01,           // 1
+                REPORT_COUNT(1), 0x03,
+                REPORT_SIZE(1), 0x01,
+                INPUT(1), 0x02,                     // Data, Variable, Absolute
+                REPORT_COUNT(1), 0x01,
+                REPORT_SIZE(1), 0x05,
+                INPUT(1), 0x01,                     // Constant
+\r
+                END_COLLECTION(0),
+                END_COLLECTION(0),
+\r
+                // Media Control
+                USAGE_PAGE(1), 0x0C,
+                USAGE(1), 0x01,
+                COLLECTION(1), 0x01,
+                REPORT_ID(1), REPORT_ID_VOLUME,
+                USAGE_PAGE(1), 0x0C,
+                LOGICAL_MINIMUM(1), 0x00,
+                LOGICAL_MAXIMUM(1), 0x01,
+                REPORT_SIZE(1), 0x01,
+                REPORT_COUNT(1), 0x07,
+                USAGE(1), 0xB5,             // Next Track
+                USAGE(1), 0xB6,             // Previous Track
+                USAGE(1), 0xB7,             // Stop
+                USAGE(1), 0xCD,             // Play / Pause
+                USAGE(1), 0xE2,             // Mute
+                USAGE(1), 0xE9,             // Volume Up
+                USAGE(1), 0xEA,             // Volume Down
+                INPUT(1), 0x02,             // Input (Data, Variable, Absolute)
+                REPORT_COUNT(1), 0x01,
+                INPUT(1), 0x01,
+                END_COLLECTION(0),
+        };
+        reportLength = sizeof(reportDescriptor);
+        return reportDescriptor;
+    }
+\r
+    return NULL;
+}
+\r
+bool USBMouseKeyboard::EP1_OUT_callback() {
+    uint16_t bytesRead = 0;
+    uint8_t led[65];
+    USBDevice::readEP(EPINT_OUT, led, &bytesRead, MAX_HID_REPORT_SIZE);
     \r
-    // we take led[1] because led[0] is the report ID\r
-    lock_status = led[1] & 0x07;\r
+    // we take led[1] because led[0] is the report ID
+    lock_status = led[1] & 0x07;
     \r
-    // We activate the endpoint to be able to recceive data\r
-    if (!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE))\r
-        return false;\r
-    return true;\r
-}\r
-\r
-uint8_t USBMouseKeyboard::lockStatus() {\r
-    return lock_status;\r
-}\r
-\r
-bool USBMouseKeyboard::update(int16_t x, int16_t y, uint8_t button, int8_t z) {\r
-    switch (mouse_type) {\r
-    case REL_MOUSE:\r
-        while (x > 127) {\r
-            if (!mouseSend(127, 0, button, z)) return false;\r
-            x = x - 127;\r
-        }\r
-        while (x < -128) {\r
-            if (!mouseSend(-128, 0, button, z)) return false;\r
-            x = x + 128;\r
-        }\r
-        while (y > 127) {\r
-            if (!mouseSend(0, 127, button, z)) return false;\r
-            y = y - 127;\r
-        }\r
-        while (y < -128) {\r
-            if (!mouseSend(0, -128, button, z)) return false;\r
-            y = y + 128;\r
-        }\r
-        return mouseSend(x, y, button, z);\r
-    case ABS_MOUSE:\r
-        HID_REPORT report;\r
-\r
-        report.data[0] = REPORT_ID_MOUSE;\r
-        report.data[1] = x & 0xff;\r
-        report.data[2] = (x >> 8) & 0xff;\r
-        report.data[3] = y & 0xff;\r
-        report.data[4] = (y >> 8) & 0xff;\r
-        report.data[5] = -z;\r
-        report.data[6] = button & 0x07;\r
-\r
-        report.length = 7;\r
-\r
-        return send(&report);\r
-    default:\r
-        return false;\r
-    }\r
-}\r
-\r
-bool USBMouseKeyboard::mouseSend(int8_t x, int8_t y, uint8_t buttons, int8_t z) {\r
-    HID_REPORT report;\r
-    report.data[0] = REPORT_ID_MOUSE;\r
-    report.data[1] = buttons & 0x07;\r
-    report.data[2] = x;\r
-    report.data[3] = y;\r
-    report.data[4] = -z; // >0 to scroll down, <0 to scroll up\r
-\r
-    report.length = 5;\r
-\r
-    return send(&report);\r
-}\r
-\r
-bool USBMouseKeyboard::move(int16_t x, int16_t y) {\r
-    return update(x, y, button, 0);\r
-}\r
-\r
-bool USBMouseKeyboard::scroll(int8_t z) {\r
-    return update(0, 0, button, z);\r
-}\r
-\r
-bool USBMouseKeyboard::doubleClick() {\r
-    if (!click(MOUSE_LEFT))\r
-        return false;\r
-    wait(0.1);\r
-    return click(MOUSE_LEFT);\r
-}\r
-\r
-bool USBMouseKeyboard::click(uint8_t button) {\r
-    if (!update(0, 0, button, 0))\r
-        return false;\r
-    wait(0.01);\r
-    return update(0, 0, 0, 0);\r
-}\r
-\r
-bool USBMouseKeyboard::press(uint8_t button_) {\r
-    button = button_ & 0x07;\r
-    return update(0, 0, button, 0);\r
-}\r
-\r
-bool USBMouseKeyboard::release(uint8_t button_) {\r
-    button = (button & (~button_)) & 0x07;\r
-    return update(0, 0, button, 0);\r
-}\r
-\r
-int USBMouseKeyboard::_putc(int c) {\r
-    return keyCode(c, keymap[c].modifier);\r
-}\r
-\r
-bool USBMouseKeyboard::keyCode(uint8_t key, uint8_t modifier) {\r
-    // Send a simulated keyboard keypress. Returns true if successful.\r
-\r
-    HID_REPORT report;\r
-\r
-    report.data[0] = REPORT_ID_KEYBOARD;\r
-    report.data[1] = modifier;\r
-    report.data[2] = 0;\r
-    report.data[3] = keymap[key].usage;\r
-    report.data[4] = 0;\r
-    report.data[5] = 0;\r
-    report.data[6] = 0;\r
-    report.data[7] = 0;\r
-    report.data[8] = 0;\r
-\r
-    report.length = 9;\r
-\r
-    if (!send(&report)) {\r
-        return false;\r
-    }\r
-\r
-    report.data[1] = 0;\r
-    report.data[3] = 0;\r
-\r
-    if (!send(&report)) {\r
-        return false;\r
-    }\r
-\r
-    return true;\r
-\r
-}\r
+    // We activate the endpoint to be able to recceive data
+    if (!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE))
+        return false;
+    return true;
+}
+\r
+uint8_t USBMouseKeyboard::lockStatus() {
+    return lock_status;
+}
+\r
+bool USBMouseKeyboard::update(int16_t x, int16_t y, uint8_t button, int8_t z) {
+    switch (mouse_type) {
+    case REL_MOUSE:
+        while (x > 127) {
+            if (!mouseSend(127, 0, button, z)) return false;
+            x = x - 127;
+        }
+        while (x < -128) {
+            if (!mouseSend(-128, 0, button, z)) return false;
+            x = x + 128;
+        }
+        while (y > 127) {
+            if (!mouseSend(0, 127, button, z)) return false;
+            y = y - 127;
+        }
+        while (y < -128) {
+            if (!mouseSend(0, -128, button, z)) return false;
+            y = y + 128;
+        }
+        return mouseSend(x, y, button, z);
+    case ABS_MOUSE:
+        HID_REPORT report;
+\r
+        report.data[0] = REPORT_ID_MOUSE;
+        report.data[1] = x & 0xff;
+        report.data[2] = (x >> 8) & 0xff;
+        report.data[3] = y & 0xff;
+        report.data[4] = (y >> 8) & 0xff;
+        report.data[5] = -z;
+        report.data[6] = button & 0x07;
+\r
+        report.length = 7;
+\r
+        return send(&report);
+    default:
+        return false;
+    }
+}
+\r
+bool USBMouseKeyboard::mouseSend(int8_t x, int8_t y, uint8_t buttons, int8_t z) {
+    HID_REPORT report;
+    report.data[0] = REPORT_ID_MOUSE;
+    report.data[1] = buttons & 0x07;
+    report.data[2] = x;
+    report.data[3] = y;
+    report.data[4] = -z; // >0 to scroll down, <0 to scroll up
+\r
+    report.length = 5;
+\r
+    return send(&report);
+}
+\r
+bool USBMouseKeyboard::move(int16_t x, int16_t y) {
+    return update(x, y, button, 0);
+}
+\r
+bool USBMouseKeyboard::scroll(int8_t z) {
+    return update(0, 0, button, z);
+}
+\r
+bool USBMouseKeyboard::doubleClick() {
+    if (!click(MOUSE_LEFT))
+        return false;
+    wait(0.1);
+    return click(MOUSE_LEFT);
+}
+\r
+bool USBMouseKeyboard::click(uint8_t button) {
+    if (!update(0, 0, button, 0))
+        return false;
+    wait(0.01);
+    return update(0, 0, 0, 0);
+}
+\r
+bool USBMouseKeyboard::press(uint8_t button_) {
+    button = button_ & 0x07;
+    return update(0, 0, button, 0);
+}
+\r
+bool USBMouseKeyboard::release(uint8_t button_) {
+    button = (button & (~button_)) & 0x07;
+    return update(0, 0, button, 0);
+}
+\r
+int USBMouseKeyboard::_putc(int c) {
+    return keyCode(c, keymap[c].modifier);
+}
+\r
+bool USBMouseKeyboard::keyCode(uint8_t key, uint8_t modifier) {
+    // Send a simulated keyboard keypress. Returns true if successful.
+\r
+    HID_REPORT report;
+\r
+    report.data[0] = REPORT_ID_KEYBOARD;
+    report.data[1] = modifier;
+    report.data[2] = 0;
+    report.data[3] = keymap[key].usage;
+    report.data[4] = 0;
+    report.data[5] = 0;
+    report.data[6] = 0;
+    report.data[7] = 0;
+    report.data[8] = 0;
+\r
+    report.length = 9;
+\r
+    if (!send(&report)) {
+        return false;
+    }
+\r
+    report.data[1] = 0;
+    report.data[3] = 0;
+\r
+    if (!send(&report)) {
+        return false;
+    }
+\r
+    return true;
+\r
+}
 \r
 \r
-bool USBMouseKeyboard::mediaControl(MEDIA_KEY key) {\r
-    HID_REPORT report;\r
+bool USBMouseKeyboard::mediaControl(MEDIA_KEY key) {
+    HID_REPORT report;
 \r
-    report.data[0] = REPORT_ID_VOLUME;\r
-    report.data[1] = (1 << key) & 0x7f;\r
+    report.data[0] = REPORT_ID_VOLUME;
+    report.data[1] = (1 << key) & 0x7f;
 \r
-    report.length = 2;\r
+    report.length = 2;
 \r
-    send(&report);\r
+    send(&report);
     \r
-    report.data[0] = REPORT_ID_VOLUME;\r
-    report.data[1] = 0;\r
+    report.data[0] = REPORT_ID_VOLUME;
+    report.data[1] = 0;
 \r
-    report.length = 2;\r
+    report.length = 2;
 \r
-    return send(&report);\r
-}\r
+    return send(&report);
+}
index ae729d9..591c16a 100644 (file)
@@ -28,7 +28,7 @@
 #include "Stream.h"
 #include "USBHID.h"
 
-/** 
+/**
  * USBMouseKeyboard example
  * @code
  *
@@ -81,7 +81,7 @@ class USBMouseKeyboard: public USBHID, public Stream
         * @param product_release Your preoduct_release (default: 0x0001)
         *
         */
-        USBMouseKeyboard(MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x0021, uint16_t product_id = 0x0011, uint16_t product_release = 0x0001): 
+        USBMouseKeyboard(MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x0021, uint16_t product_id = 0x0011, uint16_t product_release = 0x0001):
             USBHID(0, 0, vendor_id, product_id, product_release, false)
             {
                 lock_status = 0;
@@ -140,7 +140,7 @@ class USBMouseKeyboard: public USBHID, public Stream
         * @param button state of the buttons ( ex: clic(MOUSE_LEFT))
         * @returns true if there is no error, false otherwise
         */
-        bool click(uint8_t button); 
+        bool click(uint8_t button);
         
         /**
         * Scrolling
@@ -151,7 +151,7 @@ class USBMouseKeyboard: public USBHID, public Stream
         bool scroll(int8_t z);
 
         /**
-        * To send a character defined by a modifier(CTRL, SHIFT, ALT) and the key 
+        * To send a character defined by a modifier(CTRL, SHIFT, ALT) and the key
         *
         * @code
         * //To send CTRL + s (save)
index 4172e2e..12749d7 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
 \r
-#ifndef MIDIMESSAGE_H\r
-#define MIDIMESSAGE_H\r
+#ifndef MIDIMESSAGE_H
+#define MIDIMESSAGE_H
 \r
-#include "mbed.h"\r
+#include "mbed.h"
 \r
-// MIDI Message Format\r
-// \r
-// [ msg(4) | channel(4) ] [ 0 | n(7) ] [ 0 | m(7) ]\r
-//\r
-// MIDI Data Messages (Channel Specific)\r
-//\r
-// Message               msg n          m\r
-// ---------------------------------------------\r
-// Note Off              0x8 Key        Velocity\r
-// Note On               0x9 Key        Velocity\r
-// Polyphonic Aftertouch 0xA Key        Pressure\r
-// Control Change        0xB Controller Value\r
-// Program Change        0xC Program    -\r
-// Channel Aftertouch    0xD Pressure   -\r
-// Pitch Wheel           0xE LSB        MSB\r
+// MIDI Message Format
+//
+// [ msg(4) | channel(4) ] [ 0 | n(7) ] [ 0 | m(7) ]
+//
+// MIDI Data Messages (Channel Specific)
+//
+// Message               msg n          m
+// ---------------------------------------------
+// Note Off              0x8 Key        Velocity
+// Note On               0x9 Key        Velocity
+// Polyphonic Aftertouch 0xA Key        Pressure
+// Control Change        0xB Controller Value
+// Program Change        0xC Program    -
+// Channel Aftertouch    0xD Pressure   -
+// Pitch Wheel           0xE LSB        MSB
 \r
-#define CABLE_NUM (0<<4)\r
+#define CABLE_NUM (0<<4)
 \r
-/** A MIDI message container */\r
-class MIDIMessage {\r
-public:\r
-    MIDIMessage() {}\r
-    \r
-    MIDIMessage(uint8_t *buf) {\r
-        *((uint32_t *)data) = *((uint32_t *)buf);\r
-    }\r
-    \r
-    // create messages\r
-    \r
-    /** Create a NoteOff message \r
-     * @param key Key ID\r
-     * @param velocity Key velocity (0-127, default = 127)\r
-     * @param channel Key channel (0-15, default 0)\r
-     * @returns A MIDIMessage\r
-     */\r
-    static MIDIMessage NoteOff(int key, int velocity = 127, int channel = 0) {\r
-        MIDIMessage msg;\r
-        msg.data[0] = CABLE_NUM | 0x08;\r
-        msg.data[1] = 0x80 | (channel & 0x0F);\r
-        msg.data[2] = key & 0x7F;\r
-        msg.data[3] = velocity & 0x7F; \r
-        return msg;\r
-    }\r
-    \r
-    /** Create a NoteOn message \r
-     * @param key Key ID\r
-     * @param velocity Key velocity (0-127, default = 127)\r
-     * @param channel Key channel (0-15, default 0)\r
-     * @returns A MIDIMessage\r
-     */\r
-    static MIDIMessage NoteOn(int key, int velocity = 127, int channel = 0) {\r
-        MIDIMessage msg;\r
-        msg.data[0] = CABLE_NUM | 0x09;\r
-        msg.data[1] = 0x90 | (channel & 0x0F);\r
-        msg.data[2] = key & 0x7F;\r
-        msg.data[3] = velocity & 0x7F;                 \r
-        return msg;\r
-    }\r
-    \r
-    /** Create a PolyPhonic Aftertouch message \r
-     * @param key Key ID\r
-     * @param pressure Aftertouch pressure (0-127)\r
-     * @param channel Key channel (0-15, default 0)\r
-     * @returns A MIDIMessage\r
-     */    \r
-    static MIDIMessage PolyphonicAftertouch(int key, int pressure, int channel = 0) {\r
-        MIDIMessage msg;\r
-        msg.data[0] = CABLE_NUM | 0x0A;\r
-        msg.data[1] = 0xA0 | (channel & 0x0F);\r
-        msg.data[2] = key & 0x7F;\r
-        msg.data[3] = pressure & 0x7F;         \r
-        return msg;\r
-    }\r
-    \r
-    /** Create a Control Change message \r
-     * @param control Controller ID\r
-     * @param value Controller value (0-127)\r
-     * @param channel Controller channel (0-15, default 0)\r
-     * @returns A MIDIMessage\r
-     */\r
-    static MIDIMessage ControlChange(int control, int value, int channel = 0) {\r
-        MIDIMessage msg;\r
-        msg.data[0] = CABLE_NUM | 0x0B;\r
-        msg.data[1] = 0xB0 | (channel & 0x0F);\r
-        msg.data[2] = control & 0x7F;\r
-        msg.data[3] = value & 0x7F;         \r
-        return msg;\r
-    }\r
-    \r
-    /** Create a Program Change message \r
-     * @param program Program ID\r
-     * @param channel Channel (0-15, default 0)\r
-     * @returns A MIDIMessage\r
-     */    \r
-    static MIDIMessage ProgramChange(int program, int channel = 0) {\r
-        MIDIMessage msg;\r
-        msg.data[0] = CABLE_NUM | 0x0C;\r
-        msg.data[1] = 0xC0 | (channel & 0x0F);\r
-        msg.data[2] = program & 0x7F;\r
-        msg.data[3] = 0x00;         \r
-        return msg;\r
-    }\r
-    \r
-    /** Create a Channel Aftertouch message \r
-     * @param pressure Pressure \r
-     * @param channel Key channel (0-15, default 0)\r
-     * @returns A MIDIMessage\r
-     */    \r
-    static MIDIMessage ChannelAftertouch(int pressure, int channel = 0) {\r
-        MIDIMessage msg;\r
-        msg.data[0] = CABLE_NUM | 0x0D;\r
-        msg.data[1] = 0xD0 | (channel & 0x0F);\r
-        msg.data[2] = pressure & 0x7F;\r
-        msg.data[3] = 0x00;         \r
-        return msg;\r
-    }\r
-    \r
-    /** Create a Pitch Wheel message \r
-     * @param pitch Pitch (-8192 - 8191, default = 0)\r
-     * @param channel Channel (0-15, default 0)\r
-     * @returns A MIDIMessage\r
-     */    \r
-    static MIDIMessage PitchWheel(int pitch = 0, int channel = 0) {\r
-        MIDIMessage msg;\r
-        int p = pitch + 8192;    // 0 - 16383, 8192 is center\r
-        msg.data[0] = CABLE_NUM | 0x0E;\r
-        msg.data[1] = 0xE0 | (channel & 0x0F);\r
-        msg.data[2] = p & 0x7F;\r
-        msg.data[3] = (p >> 7) & 0x7F;                 \r
-        return msg;\r
-    }\r
-    \r
-    /** Create an All Notes Off message \r
-     * @param channel Channel (0-15, default 0)\r
-     * @returns A MIDIMessage\r
-     */    \r
-    static MIDIMessage AllNotesOff(int channel = 0) {\r
-        return ControlChange(123, 0, channel);\r
-    }\r
-    \r
-    // decode messages\r
-    \r
-    /** MIDI Message Types */\r
-    enum MIDIMessageType {\r
-        ErrorType,\r
-        NoteOffType,\r
-        NoteOnType,\r
-        PolyphonicAftertouchType,\r
-        ControlChangeType,\r
-        ProgramChangeType,\r
-        ChannelAftertouchType,\r
-        PitchWheelType,\r
-        AllNotesOffType\r
-    };\r
-    \r
-    /** Read the message type\r
-     * @returns MIDIMessageType\r
-     */    \r
-    MIDIMessageType type() {\r
-        switch((data[1] >> 4) & 0xF) {\r
-            case 0x8: return NoteOffType;\r
-            case 0x9: return NoteOnType;\r
-            case 0xA: return PolyphonicAftertouchType;\r
-            case 0xB: \r
-                if(controller() < 120) { // standard controllers\r
-                    return ControlChangeType;\r
-                } else if(controller() == 123) {\r
-                    return AllNotesOffType;\r
-                } else {\r
-                    return ErrorType; // unsupported atm\r
-                }\r
-            case 0xC: return ProgramChangeType;\r
-            case 0xD: return ChannelAftertouchType;\r
-            case 0xE: return PitchWheelType;\r
-            default: return ErrorType;\r
-        }\r
-    }\r
+/** A MIDI message container */
+class MIDIMessage {
+public:
+    MIDIMessage() {}
+    \r
+    MIDIMessage(uint8_t *buf) {
+        *((uint32_t *)data) = *((uint32_t *)buf);
+    }
+    \r
+    // create messages
+    \r
+    /** Create a NoteOff message
+     * @param key Key ID
+     * @param velocity Key velocity (0-127, default = 127)
+     * @param channel Key channel (0-15, default 0)
+     * @returns A MIDIMessage
+     */
+    static MIDIMessage NoteOff(int key, int velocity = 127, int channel = 0) {
+        MIDIMessage msg;
+        msg.data[0] = CABLE_NUM | 0x08;
+        msg.data[1] = 0x80 | (channel & 0x0F);
+        msg.data[2] = key & 0x7F;
+        msg.data[3] = velocity & 0x7F;
+        return msg;
+    }
+    \r
+    /** Create a NoteOn message
+     * @param key Key ID
+     * @param velocity Key velocity (0-127, default = 127)
+     * @param channel Key channel (0-15, default 0)
+     * @returns A MIDIMessage
+     */
+    static MIDIMessage NoteOn(int key, int velocity = 127, int channel = 0) {
+        MIDIMessage msg;
+        msg.data[0] = CABLE_NUM | 0x09;
+        msg.data[1] = 0x90 | (channel & 0x0F);
+        msg.data[2] = key & 0x7F;
+        msg.data[3] = velocity & 0x7F;
+        return msg;
+    }
+    \r
+    /** Create a PolyPhonic Aftertouch message
+     * @param key Key ID
+     * @param pressure Aftertouch pressure (0-127)
+     * @param channel Key channel (0-15, default 0)
+     * @returns A MIDIMessage
+     */
+    static MIDIMessage PolyphonicAftertouch(int key, int pressure, int channel = 0) {
+        MIDIMessage msg;
+        msg.data[0] = CABLE_NUM | 0x0A;
+        msg.data[1] = 0xA0 | (channel & 0x0F);
+        msg.data[2] = key & 0x7F;
+        msg.data[3] = pressure & 0x7F;
+        return msg;
+    }
+    \r
+    /** Create a Control Change message
+     * @param control Controller ID
+     * @param value Controller value (0-127)
+     * @param channel Controller channel (0-15, default 0)
+     * @returns A MIDIMessage
+     */
+    static MIDIMessage ControlChange(int control, int value, int channel = 0) {
+        MIDIMessage msg;
+        msg.data[0] = CABLE_NUM | 0x0B;
+        msg.data[1] = 0xB0 | (channel & 0x0F);
+        msg.data[2] = control & 0x7F;
+        msg.data[3] = value & 0x7F;
+        return msg;
+    }
+    \r
+    /** Create a Program Change message
+     * @param program Program ID
+     * @param channel Channel (0-15, default 0)
+     * @returns A MIDIMessage
+     */
+    static MIDIMessage ProgramChange(int program, int channel = 0) {
+        MIDIMessage msg;
+        msg.data[0] = CABLE_NUM | 0x0C;
+        msg.data[1] = 0xC0 | (channel & 0x0F);
+        msg.data[2] = program & 0x7F;
+        msg.data[3] = 0x00;
+        return msg;
+    }
+    \r
+    /** Create a Channel Aftertouch message
+     * @param pressure Pressure
+     * @param channel Key channel (0-15, default 0)
+     * @returns A MIDIMessage
+     */
+    static MIDIMessage ChannelAftertouch(int pressure, int channel = 0) {
+        MIDIMessage msg;
+        msg.data[0] = CABLE_NUM | 0x0D;
+        msg.data[1] = 0xD0 | (channel & 0x0F);
+        msg.data[2] = pressure & 0x7F;
+        msg.data[3] = 0x00;
+        return msg;
+    }
+    \r
+    /** Create a Pitch Wheel message
+     * @param pitch Pitch (-8192 - 8191, default = 0)
+     * @param channel Channel (0-15, default 0)
+     * @returns A MIDIMessage
+     */
+    static MIDIMessage PitchWheel(int pitch = 0, int channel = 0) {
+        MIDIMessage msg;
+        int p = pitch + 8192;    // 0 - 16383, 8192 is center
+        msg.data[0] = CABLE_NUM | 0x0E;
+        msg.data[1] = 0xE0 | (channel & 0x0F);
+        msg.data[2] = p & 0x7F;
+        msg.data[3] = (p >> 7) & 0x7F;
+        return msg;
+    }
+    \r
+    /** Create an All Notes Off message
+     * @param channel Channel (0-15, default 0)
+     * @returns A MIDIMessage
+     */
+    static MIDIMessage AllNotesOff(int channel = 0) {
+        return ControlChange(123, 0, channel);
+    }
+    \r
+    // decode messages
+    \r
+    /** MIDI Message Types */
+    enum MIDIMessageType {
+        ErrorType,
+        NoteOffType,
+        NoteOnType,
+        PolyphonicAftertouchType,
+        ControlChangeType,
+        ProgramChangeType,
+        ChannelAftertouchType,
+        PitchWheelType,
+        AllNotesOffType
+    };
+    \r
+    /** Read the message type
+     * @returns MIDIMessageType
+     */
+    MIDIMessageType type() {
+        switch((data[1] >> 4) & 0xF) {
+            case 0x8: return NoteOffType;
+            case 0x9: return NoteOnType;
+            case 0xA: return PolyphonicAftertouchType;
+            case 0xB:
+                if(controller() < 120) { // standard controllers
+                    return ControlChangeType;
+                } else if(controller() == 123) {
+                    return AllNotesOffType;
+                } else {
+                    return ErrorType; // unsupported atm
+                }
+            case 0xC: return ProgramChangeType;
+            case 0xD: return ChannelAftertouchType;
+            case 0xE: return PitchWheelType;
+            default: return ErrorType;
+        }
+    }
 \r
-    /** Read the channel number */    \r
-    int channel() {\r
-        return (data[1] & 0x0F);\r
-    }\r
-    \r
-    /** Read the key ID */    \r
-    int key() {\r
-        return (data[2] & 0x7F);        \r
-    }\r
+    /** Read the channel number */
+    int channel() {
+        return (data[1] & 0x0F);
+    }
+    \r
+    /** Read the key ID */
+    int key() {
+        return (data[2] & 0x7F);
+    }
         \r
-    /** Read the velocity */    \r
-    int velocity() {\r
-        return (data[3] & 0x7F);        \r
-    }\r
+    /** Read the velocity */
+    int velocity() {
+        return (data[3] & 0x7F);
+    }
 \r
-    /** Read the controller value */    \r
-    int value() {\r
-        return (data[3] & 0x7F);        \r
-    }\r
-    \r
-    /** Read the aftertouch pressure */        \r
-    int pressure() {\r
-        if(type() == PolyphonicAftertouchType) {\r
-            return (data[3] & 0x7F);        \r
-        } else {\r
-            return (data[2] & 0x7F);        \r
-        }\r
-    }\r
+    /** Read the controller value */
+    int value() {
+        return (data[3] & 0x7F);
+    }
+    \r
+    /** Read the aftertouch pressure */
+    int pressure() {
+        if(type() == PolyphonicAftertouchType) {
+            return (data[3] & 0x7F);
+        } else {
+            return (data[2] & 0x7F);
+        }
+    }
 \r
-    /** Read the controller number */    \r
-    int controller() {\r
-        return (data[2] & 0x7F);        \r
-    }\r
+    /** Read the controller number */
+    int controller() {
+        return (data[2] & 0x7F);
+    }
 \r
-    /** Read the program number */    \r
-    int program() {\r
-        return (data[2] & 0x7F);        \r
-    }\r
-    \r
-    /** Read the pitch value */        \r
-    int pitch() {\r
-        int p = ((data[3] & 0x7F) << 7) | (data[2] & 0x7F);\r
-        return p - 8192; // 0 - 16383, 8192 is center\r
-    }\r
-    \r
-    uint8_t data[4];\r
-};    \r
+    /** Read the program number */
+    int program() {
+        return (data[2] & 0x7F);
+    }
+    \r
+    /** Read the pitch value */
+    int pitch() {
+        int p = ((data[3] & 0x7F) << 7) | (data[2] & 0x7F);
+        return p - 8192; // 0 - 16383, 8192 is center
+    }
+    \r
+    uint8_t data[4];
+};
 \r
-#endif\r
+#endif
index 09159e1..0fe13ca 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#include "stdint.h"\r
-#include "USBMIDI.h"\r
-#include "USBBusInterface.h"\r
-\r
-\r
-USBMIDI::USBMIDI(uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release) {\r
-    midi_evt = NULL;\r
-    USBDevice::connect();\r
-}\r
-\r
-void USBMIDI::write(MIDIMessage m) {\r
-    USBDevice::write(EPBULK_IN, m.data, 4, MAX_PACKET_SIZE_EPBULK);\r
-}\r
-\r
-\r
-void USBMIDI::attach(void (*fptr)(MIDIMessage)) {\r
-    midi_evt = fptr;\r
-}\r
-\r
-\r
-bool USBMIDI::EP2_OUT_callback() {\r
-    uint8_t buf[64];\r
-    uint16_t len;\r
-    readEP(EPBULK_OUT, buf, &len, 64);\r
-\r
-    if (midi_evt != NULL) {\r
-        for (int i=0; i<len; i+=4) {\r
-            midi_evt(MIDIMessage(buf+i));\r
-        }\r
-    }\r
-\r
-    // We reactivate the endpoint to receive next characters\r
-    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-    return true;\r
-}\r
-\r
-\r
-\r
-// Called in ISR context\r
-// Set configuration. Return false if the\r
-// configuration is not supported.\r
-bool USBMIDI::USBCallback_setConfiguration(uint8_t configuration) {\r
-    if (configuration != DEFAULT_CONFIGURATION) {\r
-        return false;\r
-    }\r
-\r
-    // Configure endpoints > 0\r
-    addEndpoint(EPBULK_IN, MAX_PACKET_SIZE_EPBULK);\r
-    addEndpoint(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-\r
-    // We activate the endpoint to be able to receive data\r
-    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-    return true;\r
-}\r
-\r
-\r
-uint8_t * USBMIDI::stringIinterfaceDesc() {\r
-    static uint8_t stringIinterfaceDescriptor[] = {\r
-        0x0c,                           //bLength\r
-        STRING_DESCRIPTOR,              //bDescriptorType 0x03\r
-        'A',0,'u',0,'d',0,'i',0,'o',0   //bString iInterface - Audio\r
-    };\r
-    return stringIinterfaceDescriptor;\r
-}\r
-\r
-uint8_t * USBMIDI::stringIproductDesc() {\r
-    static uint8_t stringIproductDescriptor[] = {\r
-        0x16,                                                       //bLength\r
-        STRING_DESCRIPTOR,                                          //bDescriptorType 0x03\r
-        'M',0,'b',0,'e',0,'d',0,' ',0,'A',0,'u',0,'d',0,'i',0,'o',0 //bString iProduct - Mbed Audio\r
-    };\r
-    return stringIproductDescriptor;\r
-}\r
-\r
-\r
-uint8_t * USBMIDI::configurationDesc() {\r
-    static uint8_t configDescriptor[] = {\r
-        // configuration descriptor\r
-        0x09, 0x02, 0x65, 0x00, 0x02, 0x01, 0x00, 0xc0, 0x50,\r
-\r
-        // The Audio Interface Collection\r
-        0x09, 0x04, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, // Standard AC Interface Descriptor\r
-        0x09, 0x24, 0x01, 0x00, 0x01, 0x09, 0x00, 0x01, 0x01, // Class-specific AC Interface Descriptor\r
-        0x09, 0x04, 0x01, 0x00, 0x02, 0x01, 0x03, 0x00, 0x00, // MIDIStreaming Interface Descriptors\r
-        0x07, 0x24, 0x01, 0x00, 0x01, 0x41, 0x00,             // Class-Specific MS Interface Header Descriptor\r
-\r
-        // MIDI IN JACKS\r
-        0x06, 0x24, 0x02, 0x01, 0x01, 0x00,\r
-        0x06, 0x24, 0x02, 0x02, 0x02, 0x00,\r
-\r
-        // MIDI OUT JACKS\r
-        0x09, 0x24, 0x03, 0x01, 0x03, 0x01, 0x02, 0x01, 0x00,\r
-        0x09, 0x24, 0x03, 0x02, 0x06, 0x01, 0x01, 0x01, 0x00,\r
-\r
-        // OUT endpoint descriptor\r
-        0x09, 0x05, 0x02, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00,\r
-        0x05, 0x25, 0x01, 0x01, 0x01,\r
-\r
-        // IN endpoint descriptor\r
-        0x09, 0x05, 0x82, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00,\r
-        0x05, 0x25, 0x01, 0x01, 0x03,\r
-    };\r
-    return configDescriptor;\r
-}\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#include "stdint.h"
+#include "USBMIDI.h"
+#include "USBBusInterface.h"
+\r
+\r
+USBMIDI::USBMIDI(uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release) {
+    midi_evt = NULL;
+    USBDevice::connect();
+}
+\r
+void USBMIDI::write(MIDIMessage m) {
+    USBDevice::write(EPBULK_IN, m.data, 4, MAX_PACKET_SIZE_EPBULK);
+}
+\r
+\r
+void USBMIDI::attach(void (*fptr)(MIDIMessage)) {
+    midi_evt = fptr;
+}
+\r
+\r
+bool USBMIDI::EP2_OUT_callback() {
+    uint8_t buf[64];
+    uint16_t len;
+    readEP(EPBULK_OUT, buf, &len, 64);
+\r
+    if (midi_evt != NULL) {
+        for (int i=0; i<len; i+=4) {
+            midi_evt(MIDIMessage(buf+i));
+        }
+    }
+\r
+    // We reactivate the endpoint to receive next characters
+    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+    return true;
+}
+\r
+\r
+\r
+// Called in ISR context
+// Set configuration. Return false if the
+// configuration is not supported.
+bool USBMIDI::USBCallback_setConfiguration(uint8_t configuration) {
+    if (configuration != DEFAULT_CONFIGURATION) {
+        return false;
+    }
+\r
+    // Configure endpoints > 0
+    addEndpoint(EPBULK_IN, MAX_PACKET_SIZE_EPBULK);
+    addEndpoint(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+\r
+    // We activate the endpoint to be able to receive data
+    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+    return true;
+}
+\r
+\r
+uint8_t * USBMIDI::stringIinterfaceDesc() {
+    static uint8_t stringIinterfaceDescriptor[] = {
+        0x0c,                           //bLength
+        STRING_DESCRIPTOR,              //bDescriptorType 0x03
+        'A',0,'u',0,'d',0,'i',0,'o',0   //bString iInterface - Audio
+    };
+    return stringIinterfaceDescriptor;
+}
+\r
+uint8_t * USBMIDI::stringIproductDesc() {
+    static uint8_t stringIproductDescriptor[] = {
+        0x16,                                                       //bLength
+        STRING_DESCRIPTOR,                                          //bDescriptorType 0x03
+        'M',0,'b',0,'e',0,'d',0,' ',0,'A',0,'u',0,'d',0,'i',0,'o',0 //bString iProduct - Mbed Audio
+    };
+    return stringIproductDescriptor;
+}
+\r
+\r
+uint8_t * USBMIDI::configurationDesc() {
+    static uint8_t configDescriptor[] = {
+        // configuration descriptor
+        0x09, 0x02, 0x65, 0x00, 0x02, 0x01, 0x00, 0xc0, 0x50,
+\r
+        // The Audio Interface Collection
+        0x09, 0x04, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, // Standard AC Interface Descriptor
+        0x09, 0x24, 0x01, 0x00, 0x01, 0x09, 0x00, 0x01, 0x01, // Class-specific AC Interface Descriptor
+        0x09, 0x04, 0x01, 0x00, 0x02, 0x01, 0x03, 0x00, 0x00, // MIDIStreaming Interface Descriptors
+        0x07, 0x24, 0x01, 0x00, 0x01, 0x41, 0x00,             // Class-Specific MS Interface Header Descriptor
+\r
+        // MIDI IN JACKS
+        0x06, 0x24, 0x02, 0x01, 0x01, 0x00,
+        0x06, 0x24, 0x02, 0x02, 0x02, 0x00,
+\r
+        // MIDI OUT JACKS
+        0x09, 0x24, 0x03, 0x01, 0x03, 0x01, 0x02, 0x01, 0x00,
+        0x09, 0x24, 0x03, 0x02, 0x06, 0x01, 0x01, 0x01, 0x00,
+\r
+        // OUT endpoint descriptor
+        0x09, 0x05, 0x02, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00,
+        0x05, 0x25, 0x01, 0x01, 0x01,
+\r
+        // IN endpoint descriptor
+        0x09, 0x05, 0x82, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00,
+        0x05, 0x25, 0x01, 0x01, 0x03,
+    };
+    return configDescriptor;
+}
index 2d86c9b..47df7b2 100644 (file)
@@ -29,7 +29,7 @@
 
 #define DEFAULT_CONFIGURATION (1)
 
-/** 
+/**
 * USBMIDI example
 *
 * @code
@@ -38,8 +38,8 @@
 *
 * USBMIDI midi;
 *
-* int main() {            
-*    while (1) {    
+* int main() {
+*    while (1) {
 *        for(int i=48; i<83; i++) {     // send some messages!
 *            midi.write(MIDIMessage::NoteOn(i));
 *            wait(0.25);
@@ -66,7 +66,7 @@ public:
      * Send a MIDIMessage
      *
      * @param m The MIDIMessage to send
-     */    
+     */
     void write(MIDIMessage m);
 
     /**
index 6a58769..59cf62b 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#include "stdint.h"\r
-#include "USBMSD.h"\r
-\r
-#define DISK_OK         0x00\r
-#define NO_INIT         0x01\r
-#define NO_DISK         0x02\r
-#define WRITE_PROTECT   0x04\r
-\r
-#define CBW_Signature   0x43425355\r
-#define CSW_Signature   0x53425355\r
-\r
-// SCSI Commands\r
-#define TEST_UNIT_READY            0x00\r
-#define REQUEST_SENSE              0x03\r
-#define FORMAT_UNIT                0x04\r
-#define INQUIRY                    0x12\r
-#define MODE_SELECT6               0x15\r
-#define MODE_SENSE6                0x1A\r
-#define START_STOP_UNIT            0x1B\r
-#define MEDIA_REMOVAL              0x1E\r
-#define READ_FORMAT_CAPACITIES     0x23\r
-#define READ_CAPACITY              0x25\r
-#define READ10                     0x28\r
-#define WRITE10                    0x2A\r
-#define VERIFY10                   0x2F\r
-#define READ12                     0xA8\r
-#define WRITE12                    0xAA\r
-#define MODE_SELECT10              0x55\r
-#define MODE_SENSE10               0x5A\r
-\r
-// MSC class specific requests\r
-#define MSC_REQUEST_RESET          0xFF\r
-#define MSC_REQUEST_GET_MAX_LUN    0xFE\r
-\r
-#define DEFAULT_CONFIGURATION (1)\r
-\r
-// max packet size\r
-#define MAX_PACKET  MAX_PACKET_SIZE_EPBULK\r
-\r
-// CSW Status\r
-enum Status {\r
-    CSW_PASSED,\r
-    CSW_FAILED,\r
-    CSW_ERROR,\r
-};\r
-\r
-\r
-USBMSD::USBMSD(uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release) {\r
-}\r
-\r
-\r
-\r
-// Called in ISR context to process a class specific request\r
-bool USBMSD::USBCallback_request(void) {\r
-\r
-    bool success = false;\r
-    CONTROL_TRANSFER * transfer = getTransferPtr();\r
-    static uint8_t maxLUN[1] = {0};\r
-\r
-    if (transfer->setup.bmRequestType.Type == CLASS_TYPE) {\r
-        switch (transfer->setup.bRequest) {\r
-            case MSC_REQUEST_RESET:\r
-                reset();\r
-                success = true;\r
-                break;\r
-            case MSC_REQUEST_GET_MAX_LUN:\r
-                transfer->remaining = 1;\r
-                transfer->ptr = maxLUN;\r
-                transfer->direction = DEVICE_TO_HOST;\r
-                success = true;\r
-                break;\r
-            default:\r
-                break;\r
-        }\r
-    }\r
-\r
-    return success;\r
-}\r
-\r
-\r
-bool USBMSD::connect() {\r
-\r
-    //disk initialization\r
-    if (disk_status() & NO_INIT) {\r
-        if (disk_initialize()) {\r
-            return false;\r
-        }\r
-    }\r
-\r
-    // get number of blocks\r
-    BlockCount = disk_sectors();\r
-\r
-    // get memory size\r
-    MemorySize = disk_size();\r
-\r
-    if (BlockCount >= 0) {\r
-        BlockSize = MemorySize / BlockCount;\r
-        if (BlockSize != 0) {\r
-            page = (uint8_t *)malloc(BlockSize * sizeof(uint8_t));\r
-            if (page == NULL)\r
-                return false;\r
-        }\r
-    } else {\r
-        return false;\r
-    }\r
-\r
-    //connect the device\r
-    USBDevice::connect();\r
-    return true;\r
-}\r
-\r
-\r
-void USBMSD::reset() {\r
-    stage = READ_CBW;\r
-}\r
-\r
-\r
-// Called in ISR context called when a data is received\r
-bool USBMSD::EP2_OUT_callback() {\r
-    uint16_t size = 0;\r
-    uint8_t buf[MAX_PACKET_SIZE_EPBULK];\r
-    readEP(EPBULK_OUT, buf, &size, MAX_PACKET_SIZE_EPBULK);\r
-    switch (stage) {\r
-            // the device has to decode the CBW received\r
-        case READ_CBW:\r
-            CBWDecode(buf, size);\r
-            break;\r
-\r
-            // the device has to receive data from the host\r
-        case PROCESS_CBW:\r
-            switch (cbw.CB[0]) {\r
-                case WRITE10:\r
-                case WRITE12:\r
-                    memoryWrite(buf, size);\r
-                    break;\r
-                case VERIFY10:\r
-                    memoryVerify(buf, size);\r
-                    break;\r
-            }\r
-            break;\r
-\r
-            // an error has occured: stall endpoint and send CSW\r
-        default:\r
-            stallEndpoint(EPBULK_OUT);\r
-            csw.Status = CSW_ERROR;\r
-            sendCSW();\r
-            break;\r
-    }\r
-\r
-    //reactivate readings on the OUT bulk endpoint\r
-    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-    return true;\r
-}\r
-\r
-// Called in ISR context when a data has been transferred\r
-bool USBMSD::EP2_IN_callback() {\r
-    switch (stage) {\r
-\r
-            // the device has to send data to the host\r
-        case PROCESS_CBW:\r
-            switch (cbw.CB[0]) {\r
-                case READ10:\r
-                case READ12:\r
-                    memoryRead();\r
-                    break;\r
-            }\r
-            break;\r
-\r
-            //the device has to send a CSW\r
-        case SEND_CSW:\r
-            sendCSW();\r
-            break;\r
-\r
-            // an error has occured\r
-        case ERROR:\r
-            stallEndpoint(EPBULK_IN);\r
-            sendCSW();\r
-            break;\r
-\r
-            // the host has received the CSW -> we wait a CBW\r
-        case WAIT_CSW:\r
-            stage = READ_CBW;\r
-            break;\r
-    }\r
-    return true;\r
-}\r
-\r
-\r
-void USBMSD::memoryWrite (uint8_t * buf, uint16_t size) {\r
-\r
-    if ((addr + size) > MemorySize) {\r
-        size = MemorySize - addr;\r
-        stage = ERROR;\r
-        stallEndpoint(EPBULK_OUT);\r
-    }\r
-\r
-    // we fill an array in RAM of 1 block before writing it in memory\r
-    for (int i = 0; i < size; i++)\r
-        page[addr%BlockSize + i] = buf[i];\r
-\r
-    // if the array is filled, write it in memory\r
-    if (!((addr + size)%BlockSize)) {\r
-        if (!(disk_status() & WRITE_PROTECT)) {\r
-            disk_write((const char *)page, addr/BlockSize);\r
-        }\r
-    }\r
-\r
-    addr += size;\r
-    length -= size;\r
-    csw.DataResidue -= size;\r
-\r
-    if ((!length) || (stage != PROCESS_CBW)) {\r
-        csw.Status = (stage == ERROR) ? CSW_FAILED : CSW_PASSED;\r
-        sendCSW();\r
-    }\r
-}\r
-\r
-void USBMSD::memoryVerify (uint8_t * buf, uint16_t size) {\r
-    uint32_t n;\r
-\r
-    if ((addr + size) > MemorySize) {\r
-        size = MemorySize - addr;\r
-        stage = ERROR;\r
-        stallEndpoint(EPBULK_OUT);\r
-    }\r
-\r
-    // beginning of a new block -> load a whole block in RAM\r
-    if (!(addr%BlockSize))\r
-        disk_read((char *)page, addr/BlockSize);\r
-\r
-    // info are in RAM -> no need to re-read memory\r
-    for (n = 0; n < size; n++) {\r
-        if (page[addr%BlockSize + n] != buf[n]) {\r
-            memOK = false;\r
-            break;\r
-        }\r
-    }\r
-\r
-    addr += size;\r
-    length -= size;\r
-    csw.DataResidue -= size;\r
-\r
-    if ( !length || (stage != PROCESS_CBW)) {\r
-        csw.Status = (memOK && (stage == PROCESS_CBW)) ? CSW_PASSED : CSW_FAILED;\r
-        sendCSW();\r
-    }\r
-}\r
-\r
-\r
-bool USBMSD::inquiryRequest (void) {\r
-    uint8_t inquiry[] = { 0x00, 0x80, 0x00, 0x01,\r
-                          36 - 4, 0x80, 0x00, 0x00,\r
-                          'M', 'B', 'E', 'D', '.', 'O', 'R', 'G',\r
-                          'M', 'B', 'E', 'D', ' ', 'U', 'S', 'B', ' ', 'D', 'I', 'S', 'K', ' ', ' ', ' ',\r
-                          '1', '.', '0', ' ',\r
-                        };\r
-    if (!write(inquiry, sizeof(inquiry))) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-\r
-bool USBMSD::readFormatCapacity() {\r
-    uint8_t capacity[] = { 0x00, 0x00, 0x00, 0x08,\r
-                            ((uint8_t) ((BlockCount >> 24) & 0xff)),\r
-                            ((uint8_t) ((BlockCount >> 16) & 0xff)),\r
-                            ((uint8_t) ((BlockCount >> 8) & 0xff)),\r
-                            ((uint8_t) ((BlockCount >> 0) & 0xff)),\r
-\r
-                            0x02,\r
-                            ((uint8_t) ((BlockSize >> 16) & 0xff)),\r
-                            ((uint8_t) ((BlockSize >> 8) & 0xff)),\r
-                            ((uint8_t) ((BlockSize >> 0) & 0xff)),\r
-                         };\r
-    if (!write(capacity, sizeof(capacity))) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-\r
-bool USBMSD::readCapacity (void) {\r
-    uint8_t capacity[] = {\r
-        ((uint8_t) (((BlockCount - 1) >> 24) & 0xff)),\r
-        ((uint8_t) (((BlockCount - 1) >> 16) & 0xff)),\r
-        ((uint8_t) (((BlockCount - 1) >> 8) & 0xff)),\r
-        ((uint8_t) (((BlockCount - 1) >> 0) & 0xff)),\r
-\r
-        ((uint8_t) ((BlockSize >> 24) & 0xff)),\r
-        ((uint8_t) ((BlockSize >> 16) & 0xff)),\r
-        ((uint8_t) ((BlockSize >> 8) & 0xff)),\r
-        ((uint8_t) ((BlockSize >> 0) & 0xff)),\r
-    };\r
-    if (!write(capacity, sizeof(capacity))) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-bool USBMSD::write (uint8_t * buf, uint16_t size) {\r
-\r
-    if (size >= cbw.DataLength) {\r
-        size = cbw.DataLength;\r
-    }\r
-    stage = SEND_CSW;\r
-\r
-    if (!writeNB(EPBULK_IN, buf, size, MAX_PACKET_SIZE_EPBULK)) {\r
-        return false;\r
-    }\r
-\r
-    csw.DataResidue -= size;\r
-    csw.Status = CSW_PASSED;\r
-    return true;\r
-}\r
-\r
-\r
-bool USBMSD::modeSense6 (void) {\r
-    uint8_t sense6[] = { 0x03, 0x00, 0x00, 0x00 };\r
-    if (!write(sense6, sizeof(sense6))) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
-\r
-void USBMSD::sendCSW() {\r
-    csw.Signature = CSW_Signature;\r
-    writeNB(EPBULK_IN, (uint8_t *)&csw, sizeof(CSW), MAX_PACKET_SIZE_EPBULK);\r
-    stage = WAIT_CSW;\r
-}\r
-\r
-bool USBMSD::requestSense (void) {\r
-    uint8_t request_sense[] = {\r
-        0x70,\r
-        0x00,\r
-        0x05,   // Sense Key: illegal request\r
-        0x00,\r
-        0x00,\r
-        0x00,\r
-        0x00,\r
-        0x0A,\r
-        0x00,\r
-        0x00,\r
-        0x00,\r
-        0x00,\r
-        0x30,\r
-        0x01,\r
-        0x00,\r
-        0x00,\r
-        0x00,\r
-        0x00,\r
-    };\r
-\r
-    if (!write(request_sense, sizeof(request_sense))) {\r
-        return false;\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-void USBMSD::fail() {\r
-    csw.Status = CSW_FAILED;\r
-    sendCSW();\r
-}\r
-\r
-\r
-void USBMSD::CBWDecode(uint8_t * buf, uint16_t size) {\r
-    if (size == sizeof(cbw)) {\r
-        memcpy((uint8_t *)&cbw, buf, size);\r
-        if (cbw.Signature == CBW_Signature) {\r
-            csw.Tag = cbw.Tag;\r
-            csw.DataResidue = cbw.DataLength;\r
-            if ((cbw.CBLength <  1) || (cbw.CBLength > 16) ) {\r
-                fail();\r
-            } else {\r
-                switch (cbw.CB[0]) {\r
-                    case TEST_UNIT_READY:\r
-                        testUnitReady();\r
-                        break;\r
-                    case REQUEST_SENSE:\r
-                        requestSense();\r
-                        break;\r
-                    case INQUIRY:\r
-                        inquiryRequest();\r
-                        break;\r
-                    case MODE_SENSE6:\r
-                        modeSense6();\r
-                        break;\r
-                    case READ_FORMAT_CAPACITIES:\r
-                        readFormatCapacity();\r
-                        break;\r
-                    case READ_CAPACITY:\r
-                        readCapacity();\r
-                        break;\r
-                    case READ10:\r
-                    case READ12:\r
-                        if (infoTransfer()) {\r
-                            if ((cbw.Flags & 0x80)) {\r
-                                stage = PROCESS_CBW;\r
-                                memoryRead();\r
-                            } else {\r
-                                stallEndpoint(EPBULK_OUT);\r
-                                csw.Status = CSW_ERROR;\r
-                                sendCSW();\r
-                            }\r
-                        }\r
-                        break;\r
-                    case WRITE10:\r
-                    case WRITE12:\r
-                        if (infoTransfer()) {\r
-                            if (!(cbw.Flags & 0x80)) {\r
-                                stage = PROCESS_CBW;\r
-                            } else {\r
-                                stallEndpoint(EPBULK_IN);\r
-                                csw.Status = CSW_ERROR;\r
-                                sendCSW();\r
-                            }\r
-                        }\r
-                        break;\r
-                    case VERIFY10:\r
-                        if (!(cbw.CB[1] & 0x02)) {\r
-                            csw.Status = CSW_PASSED;\r
-                            sendCSW();\r
-                            break;\r
-                        }\r
-                        if (infoTransfer()) {\r
-                            if (!(cbw.Flags & 0x80)) {\r
-                                stage = PROCESS_CBW;\r
-                                memOK = true;\r
-                            } else {\r
-                                stallEndpoint(EPBULK_IN);\r
-                                csw.Status = CSW_ERROR;\r
-                                sendCSW();\r
-                            }\r
-                        }\r
-                        break;\r
-                    default:\r
-                        fail();\r
-                        break;\r
-                }\r
-            }\r
-        }\r
-    }\r
-}\r
-\r
-void USBMSD::testUnitReady (void) {\r
-\r
-    if (cbw.DataLength != 0) {\r
-        if ((cbw.Flags & 0x80) != 0) {\r
-            stallEndpoint(EPBULK_IN);\r
-        } else {\r
-            stallEndpoint(EPBULK_OUT);\r
-        }\r
-    }\r
-\r
-    csw.Status = CSW_PASSED;\r
-    sendCSW();\r
-}\r
-\r
-\r
-void USBMSD::memoryRead (void) {\r
-    uint32_t n;\r
-\r
-    n = (length > MAX_PACKET) ? MAX_PACKET : length;\r
-\r
-    if ((addr + n) > MemorySize) {\r
-        n = MemorySize - addr;\r
-        stage = ERROR;\r
-    }\r
-\r
-    // we read an entire block\r
-    if (!(addr%BlockSize))\r
-        disk_read((char *)page, addr/BlockSize);\r
-\r
-    // write data which are in RAM\r
-    writeNB(EPBULK_IN, &page[addr%BlockSize], n, MAX_PACKET_SIZE_EPBULK);\r
-\r
-    addr += n;\r
-    length -= n;\r
-\r
-    csw.DataResidue -= n;\r
-\r
-    if ( !length || (stage != PROCESS_CBW)) {\r
-        csw.Status = (stage == PROCESS_CBW) ? CSW_PASSED : CSW_FAILED;\r
-        stage = (stage == PROCESS_CBW) ? SEND_CSW : stage;\r
-    }\r
-}\r
-\r
-\r
-bool USBMSD::infoTransfer (void) {\r
-    uint32_t n;\r
-\r
-    // Logical Block Address of First Block\r
-    n = (cbw.CB[2] << 24) | (cbw.CB[3] << 16) | (cbw.CB[4] <<  8) | (cbw.CB[5] <<  0);\r
-\r
-    addr = n * BlockSize;\r
-\r
-    // Number of Blocks to transfer\r
-    switch (cbw.CB[0]) {\r
-        case READ10:\r
-        case WRITE10:\r
-        case VERIFY10:\r
-            n = (cbw.CB[7] <<  8) | (cbw.CB[8] <<  0);\r
-            break;\r
-\r
-        case READ12:\r
-        case WRITE12:\r
-            n = (cbw.CB[6] << 24) | (cbw.CB[7] << 16) | (cbw.CB[8] <<  8) | (cbw.CB[9] <<  0);\r
-            break;\r
-    }\r
-\r
-    length = n * BlockSize;\r
-\r
-    if (!cbw.DataLength) {              // host requests no data\r
-        csw.Status = CSW_FAILED;\r
-        sendCSW();\r
-        return false;\r
-    }\r
-\r
-    if (cbw.DataLength != length) {\r
-        if ((cbw.Flags & 0x80) != 0) {\r
-            stallEndpoint(EPBULK_IN);\r
-        } else {\r
-            stallEndpoint(EPBULK_OUT);\r
-        }\r
-\r
-        csw.Status = CSW_FAILED;\r
-        sendCSW();\r
-        return false;\r
-    }\r
-\r
-    return true;\r
-}\r
-\r
-\r
-\r
-\r
-\r
-// Called in ISR context\r
-// Set configuration. Return false if the\r
-// configuration is not supported.\r
-bool USBMSD::USBCallback_setConfiguration(uint8_t configuration) {\r
-    if (configuration != DEFAULT_CONFIGURATION) {\r
-        return false;\r
-    }\r
-\r
-    // Configure endpoints > 0\r
-    addEndpoint(EPBULK_IN, MAX_PACKET_SIZE_EPBULK);\r
-    addEndpoint(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-\r
-    //activate readings\r
-    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-    return true;\r
-}\r
-\r
-\r
-uint8_t * USBMSD::stringIinterfaceDesc() {\r
-    static uint8_t stringIinterfaceDescriptor[] = {\r
-        0x08,                           //bLength\r
-        STRING_DESCRIPTOR,              //bDescriptorType 0x03\r
-        'M',0,'S',0,'D',0               //bString iInterface - MSD\r
-    };\r
-    return stringIinterfaceDescriptor;\r
-}\r
-\r
-uint8_t * USBMSD::stringIproductDesc() {\r
-    static uint8_t stringIproductDescriptor[] = {\r
-        0x12,                                           //bLength\r
-        STRING_DESCRIPTOR,                              //bDescriptorType 0x03\r
-        'M',0,'b',0,'e',0,'d',0,' ',0,'M',0,'S',0,'D',0 //bString iProduct - Mbed Audio\r
-    };\r
-    return stringIproductDescriptor;\r
-}\r
-\r
-\r
-uint8_t * USBMSD::configurationDesc() {\r
-    static uint8_t configDescriptor[] = {\r
-\r
-        // Configuration 1\r
-        9,      // bLength\r
-        2,      // bDescriptorType\r
-        LSB(9 + 9 + 7 + 7), // wTotalLength\r
-        MSB(9 + 9 + 7 + 7),\r
-        0x01,   // bNumInterfaces\r
-        0x01,   // bConfigurationValue: 0x01 is used to select this configuration\r
-        0x00,   // iConfiguration: no string to describe this configuration\r
-        0xC0,   // bmAttributes\r
-        100,    // bMaxPower, device power consumption is 100 mA\r
-\r
-        // Interface 0, Alternate Setting 0, MSC Class\r
-        9,      // bLength\r
-        4,      // bDescriptorType\r
-        0x00,   // bInterfaceNumber\r
-        0x00,   // bAlternateSetting\r
-        0x02,   // bNumEndpoints\r
-        0x08,   // bInterfaceClass\r
-        0x06,   // bInterfaceSubClass\r
-        0x50,   // bInterfaceProtocol\r
-        0x04,   // iInterface\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        7,                          // bLength\r
-        5,                          // bDescriptorType\r
-        PHY_TO_DESC(EPBULK_IN),     // bEndpointAddress\r
-        0x02,                       // bmAttributes (0x02=bulk)\r
-        LSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (MSB)\r
-        0,                          // bInterval\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        7,                          // bLength\r
-        5,                          // bDescriptorType\r
-        PHY_TO_DESC(EPBULK_OUT),    // bEndpointAddress\r
-        0x02,                       // bmAttributes (0x02=bulk)\r
-        LSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (MSB)\r
-        0                           // bInterval\r
-    };\r
-    return configDescriptor;\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#include "stdint.h"
+#include "USBMSD.h"
+\r
+#define DISK_OK         0x00
+#define NO_INIT         0x01
+#define NO_DISK         0x02
+#define WRITE_PROTECT   0x04
+\r
+#define CBW_Signature   0x43425355
+#define CSW_Signature   0x53425355
+\r
+// SCSI Commands
+#define TEST_UNIT_READY            0x00
+#define REQUEST_SENSE              0x03
+#define FORMAT_UNIT                0x04
+#define INQUIRY                    0x12
+#define MODE_SELECT6               0x15
+#define MODE_SENSE6                0x1A
+#define START_STOP_UNIT            0x1B
+#define MEDIA_REMOVAL              0x1E
+#define READ_FORMAT_CAPACITIES     0x23
+#define READ_CAPACITY              0x25
+#define READ10                     0x28
+#define WRITE10                    0x2A
+#define VERIFY10                   0x2F
+#define READ12                     0xA8
+#define WRITE12                    0xAA
+#define MODE_SELECT10              0x55
+#define MODE_SENSE10               0x5A
+\r
+// MSC class specific requests
+#define MSC_REQUEST_RESET          0xFF
+#define MSC_REQUEST_GET_MAX_LUN    0xFE
+\r
+#define DEFAULT_CONFIGURATION (1)
+\r
+// max packet size
+#define MAX_PACKET  MAX_PACKET_SIZE_EPBULK
+\r
+// CSW Status
+enum Status {
+    CSW_PASSED,
+    CSW_FAILED,
+    CSW_ERROR,
+};
+\r
+\r
+USBMSD::USBMSD(uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release) {
+}
+\r
+\r
+\r
+// Called in ISR context to process a class specific request
+bool USBMSD::USBCallback_request(void) {
+\r
+    bool success = false;
+    CONTROL_TRANSFER * transfer = getTransferPtr();
+    static uint8_t maxLUN[1] = {0};
+\r
+    if (transfer->setup.bmRequestType.Type == CLASS_TYPE) {
+        switch (transfer->setup.bRequest) {
+            case MSC_REQUEST_RESET:
+                reset();
+                success = true;
+                break;
+            case MSC_REQUEST_GET_MAX_LUN:
+                transfer->remaining = 1;
+                transfer->ptr = maxLUN;
+                transfer->direction = DEVICE_TO_HOST;
+                success = true;
+                break;
+            default:
+                break;
+        }
+    }
+\r
+    return success;
+}
+\r
+\r
+bool USBMSD::connect() {
+\r
+    //disk initialization
+    if (disk_status() & NO_INIT) {
+        if (disk_initialize()) {
+            return false;
+        }
+    }
+\r
+    // get number of blocks
+    BlockCount = disk_sectors();
+\r
+    // get memory size
+    MemorySize = disk_size();
+\r
+    if (BlockCount >= 0) {
+        BlockSize = MemorySize / BlockCount;
+        if (BlockSize != 0) {
+            page = (uint8_t *)malloc(BlockSize * sizeof(uint8_t));
+            if (page == NULL)
+                return false;
+        }
+    } else {
+        return false;
+    }
+\r
+    //connect the device
+    USBDevice::connect();
+    return true;
+}
+\r
+\r
+void USBMSD::reset() {
+    stage = READ_CBW;
+}
+\r
+\r
+// Called in ISR context called when a data is received
+bool USBMSD::EP2_OUT_callback() {
+    uint16_t size = 0;
+    uint8_t buf[MAX_PACKET_SIZE_EPBULK];
+    readEP(EPBULK_OUT, buf, &size, MAX_PACKET_SIZE_EPBULK);
+    switch (stage) {
+            // the device has to decode the CBW received
+        case READ_CBW:
+            CBWDecode(buf, size);
+            break;
+\r
+            // the device has to receive data from the host
+        case PROCESS_CBW:
+            switch (cbw.CB[0]) {
+                case WRITE10:
+                case WRITE12:
+                    memoryWrite(buf, size);
+                    break;
+                case VERIFY10:
+                    memoryVerify(buf, size);
+                    break;
+            }
+            break;
+\r
+            // an error has occured: stall endpoint and send CSW
+        default:
+            stallEndpoint(EPBULK_OUT);
+            csw.Status = CSW_ERROR;
+            sendCSW();
+            break;
+    }
+\r
+    //reactivate readings on the OUT bulk endpoint
+    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+    return true;
+}
+\r
+// Called in ISR context when a data has been transferred
+bool USBMSD::EP2_IN_callback() {
+    switch (stage) {
+\r
+            // the device has to send data to the host
+        case PROCESS_CBW:
+            switch (cbw.CB[0]) {
+                case READ10:
+                case READ12:
+                    memoryRead();
+                    break;
+            }
+            break;
+\r
+            //the device has to send a CSW
+        case SEND_CSW:
+            sendCSW();
+            break;
+\r
+            // an error has occured
+        case ERROR:
+            stallEndpoint(EPBULK_IN);
+            sendCSW();
+            break;
+\r
+            // the host has received the CSW -> we wait a CBW
+        case WAIT_CSW:
+            stage = READ_CBW;
+            break;
+    }
+    return true;
+}
+\r
+\r
+void USBMSD::memoryWrite (uint8_t * buf, uint16_t size) {
+\r
+    if ((addr + size) > MemorySize) {
+        size = MemorySize - addr;
+        stage = ERROR;
+        stallEndpoint(EPBULK_OUT);
+    }
+\r
+    // we fill an array in RAM of 1 block before writing it in memory
+    for (int i = 0; i < size; i++)
+        page[addr%BlockSize + i] = buf[i];
+\r
+    // if the array is filled, write it in memory
+    if (!((addr + size)%BlockSize)) {
+        if (!(disk_status() & WRITE_PROTECT)) {
+            disk_write((const char *)page, addr/BlockSize);
+        }
+    }
+\r
+    addr += size;
+    length -= size;
+    csw.DataResidue -= size;
+\r
+    if ((!length) || (stage != PROCESS_CBW)) {
+        csw.Status = (stage == ERROR) ? CSW_FAILED : CSW_PASSED;
+        sendCSW();
+    }
+}
+\r
+void USBMSD::memoryVerify (uint8_t * buf, uint16_t size) {
+    uint32_t n;
+\r
+    if ((addr + size) > MemorySize) {
+        size = MemorySize - addr;
+        stage = ERROR;
+        stallEndpoint(EPBULK_OUT);
+    }
+\r
+    // beginning of a new block -> load a whole block in RAM
+    if (!(addr%BlockSize))
+        disk_read((char *)page, addr/BlockSize);
+\r
+    // info are in RAM -> no need to re-read memory
+    for (n = 0; n < size; n++) {
+        if (page[addr%BlockSize + n] != buf[n]) {
+            memOK = false;
+            break;
+        }
+    }
+\r
+    addr += size;
+    length -= size;
+    csw.DataResidue -= size;
+\r
+    if ( !length || (stage != PROCESS_CBW)) {
+        csw.Status = (memOK && (stage == PROCESS_CBW)) ? CSW_PASSED : CSW_FAILED;
+        sendCSW();
+    }
+}
+\r
+\r
+bool USBMSD::inquiryRequest (void) {
+    uint8_t inquiry[] = { 0x00, 0x80, 0x00, 0x01,
+                          36 - 4, 0x80, 0x00, 0x00,
+                          'M', 'B', 'E', 'D', '.', 'O', 'R', 'G',
+                          'M', 'B', 'E', 'D', ' ', 'U', 'S', 'B', ' ', 'D', 'I', 'S', 'K', ' ', ' ', ' ',
+                          '1', '.', '0', ' ',
+                        };
+    if (!write(inquiry, sizeof(inquiry))) {
+        return false;
+    }
+    return true;
+}
+\r
+\r
+bool USBMSD::readFormatCapacity() {
+    uint8_t capacity[] = { 0x00, 0x00, 0x00, 0x08,
+                            ((uint8_t) ((BlockCount >> 24) & 0xff)),
+                            ((uint8_t) ((BlockCount >> 16) & 0xff)),
+                            ((uint8_t) ((BlockCount >> 8) & 0xff)),
+                            ((uint8_t) ((BlockCount >> 0) & 0xff)),
+\r
+                            0x02,
+                            ((uint8_t) ((BlockSize >> 16) & 0xff)),
+                            ((uint8_t) ((BlockSize >> 8) & 0xff)),
+                            ((uint8_t) ((BlockSize >> 0) & 0xff)),
+                         };
+    if (!write(capacity, sizeof(capacity))) {
+        return false;
+    }
+    return true;
+}
+\r
+\r
+bool USBMSD::readCapacity (void) {
+    uint8_t capacity[] = {
+        ((uint8_t) (((BlockCount - 1) >> 24) & 0xff)),
+        ((uint8_t) (((BlockCount - 1) >> 16) & 0xff)),
+        ((uint8_t) (((BlockCount - 1) >> 8) & 0xff)),
+        ((uint8_t) (((BlockCount - 1) >> 0) & 0xff)),
+\r
+        ((uint8_t) ((BlockSize >> 24) & 0xff)),
+        ((uint8_t) ((BlockSize >> 16) & 0xff)),
+        ((uint8_t) ((BlockSize >> 8) & 0xff)),
+        ((uint8_t) ((BlockSize >> 0) & 0xff)),
+    };
+    if (!write(capacity, sizeof(capacity))) {
+        return false;
+    }
+    return true;
+}
+\r
+bool USBMSD::write (uint8_t * buf, uint16_t size) {
+\r
+    if (size >= cbw.DataLength) {
+        size = cbw.DataLength;
+    }
+    stage = SEND_CSW;
+\r
+    if (!writeNB(EPBULK_IN, buf, size, MAX_PACKET_SIZE_EPBULK)) {
+        return false;
+    }
+\r
+    csw.DataResidue -= size;
+    csw.Status = CSW_PASSED;
+    return true;
+}
+\r
+\r
+bool USBMSD::modeSense6 (void) {
+    uint8_t sense6[] = { 0x03, 0x00, 0x00, 0x00 };
+    if (!write(sense6, sizeof(sense6))) {
+        return false;
+    }
+    return true;
+}
+\r
+void USBMSD::sendCSW() {
+    csw.Signature = CSW_Signature;
+    writeNB(EPBULK_IN, (uint8_t *)&csw, sizeof(CSW), MAX_PACKET_SIZE_EPBULK);
+    stage = WAIT_CSW;
+}
+\r
+bool USBMSD::requestSense (void) {
+    uint8_t request_sense[] = {
+        0x70,
+        0x00,
+        0x05,   // Sense Key: illegal request
+        0x00,
+        0x00,
+        0x00,
+        0x00,
+        0x0A,
+        0x00,
+        0x00,
+        0x00,
+        0x00,
+        0x30,
+        0x01,
+        0x00,
+        0x00,
+        0x00,
+        0x00,
+    };
+\r
+    if (!write(request_sense, sizeof(request_sense))) {
+        return false;
+    }
+\r
+    return true;
+}
+\r
+void USBMSD::fail() {
+    csw.Status = CSW_FAILED;
+    sendCSW();
+}
+\r
+\r
+void USBMSD::CBWDecode(uint8_t * buf, uint16_t size) {
+    if (size == sizeof(cbw)) {
+        memcpy((uint8_t *)&cbw, buf, size);
+        if (cbw.Signature == CBW_Signature) {
+            csw.Tag = cbw.Tag;
+            csw.DataResidue = cbw.DataLength;
+            if ((cbw.CBLength <  1) || (cbw.CBLength > 16) ) {
+                fail();
+            } else {
+                switch (cbw.CB[0]) {
+                    case TEST_UNIT_READY:
+                        testUnitReady();
+                        break;
+                    case REQUEST_SENSE:
+                        requestSense();
+                        break;
+                    case INQUIRY:
+                        inquiryRequest();
+                        break;
+                    case MODE_SENSE6:
+                        modeSense6();
+                        break;
+                    case READ_FORMAT_CAPACITIES:
+                        readFormatCapacity();
+                        break;
+                    case READ_CAPACITY:
+                        readCapacity();
+                        break;
+                    case READ10:
+                    case READ12:
+                        if (infoTransfer()) {
+                            if ((cbw.Flags & 0x80)) {
+                                stage = PROCESS_CBW;
+                                memoryRead();
+                            } else {
+                                stallEndpoint(EPBULK_OUT);
+                                csw.Status = CSW_ERROR;
+                                sendCSW();
+                            }
+                        }
+                        break;
+                    case WRITE10:
+                    case WRITE12:
+                        if (infoTransfer()) {
+                            if (!(cbw.Flags & 0x80)) {
+                                stage = PROCESS_CBW;
+                            } else {
+                                stallEndpoint(EPBULK_IN);
+                                csw.Status = CSW_ERROR;
+                                sendCSW();
+                            }
+                        }
+                        break;
+                    case VERIFY10:
+                        if (!(cbw.CB[1] & 0x02)) {
+                            csw.Status = CSW_PASSED;
+                            sendCSW();
+                            break;
+                        }
+                        if (infoTransfer()) {
+                            if (!(cbw.Flags & 0x80)) {
+                                stage = PROCESS_CBW;
+                                memOK = true;
+                            } else {
+                                stallEndpoint(EPBULK_IN);
+                                csw.Status = CSW_ERROR;
+                                sendCSW();
+                            }
+                        }
+                        break;
+                    default:
+                        fail();
+                        break;
+                }
+            }
+        }
+    }
+}
+\r
+void USBMSD::testUnitReady (void) {
+\r
+    if (cbw.DataLength != 0) {
+        if ((cbw.Flags & 0x80) != 0) {
+            stallEndpoint(EPBULK_IN);
+        } else {
+            stallEndpoint(EPBULK_OUT);
+        }
+    }
+\r
+    csw.Status = CSW_PASSED;
+    sendCSW();
+}
+\r
+\r
+void USBMSD::memoryRead (void) {
+    uint32_t n;
+\r
+    n = (length > MAX_PACKET) ? MAX_PACKET : length;
+\r
+    if ((addr + n) > MemorySize) {
+        n = MemorySize - addr;
+        stage = ERROR;
+    }
+\r
+    // we read an entire block
+    if (!(addr%BlockSize))
+        disk_read((char *)page, addr/BlockSize);
+\r
+    // write data which are in RAM
+    writeNB(EPBULK_IN, &page[addr%BlockSize], n, MAX_PACKET_SIZE_EPBULK);
+\r
+    addr += n;
+    length -= n;
+\r
+    csw.DataResidue -= n;
+\r
+    if ( !length || (stage != PROCESS_CBW)) {
+        csw.Status = (stage == PROCESS_CBW) ? CSW_PASSED : CSW_FAILED;
+        stage = (stage == PROCESS_CBW) ? SEND_CSW : stage;
+    }
+}
+\r
+\r
+bool USBMSD::infoTransfer (void) {
+    uint32_t n;
+\r
+    // Logical Block Address of First Block
+    n = (cbw.CB[2] << 24) | (cbw.CB[3] << 16) | (cbw.CB[4] <<  8) | (cbw.CB[5] <<  0);
+\r
+    addr = n * BlockSize;
+\r
+    // Number of Blocks to transfer
+    switch (cbw.CB[0]) {
+        case READ10:
+        case WRITE10:
+        case VERIFY10:
+            n = (cbw.CB[7] <<  8) | (cbw.CB[8] <<  0);
+            break;
+\r
+        case READ12:
+        case WRITE12:
+            n = (cbw.CB[6] << 24) | (cbw.CB[7] << 16) | (cbw.CB[8] <<  8) | (cbw.CB[9] <<  0);
+            break;
+    }
+\r
+    length = n * BlockSize;
+\r
+    if (!cbw.DataLength) {              // host requests no data
+        csw.Status = CSW_FAILED;
+        sendCSW();
+        return false;
+    }
+\r
+    if (cbw.DataLength != length) {
+        if ((cbw.Flags & 0x80) != 0) {
+            stallEndpoint(EPBULK_IN);
+        } else {
+            stallEndpoint(EPBULK_OUT);
+        }
+\r
+        csw.Status = CSW_FAILED;
+        sendCSW();
+        return false;
+    }
+\r
+    return true;
+}
+\r
+\r
+\r
+\r
+\r
+// Called in ISR context
+// Set configuration. Return false if the
+// configuration is not supported.
+bool USBMSD::USBCallback_setConfiguration(uint8_t configuration) {
+    if (configuration != DEFAULT_CONFIGURATION) {
+        return false;
+    }
+\r
+    // Configure endpoints > 0
+    addEndpoint(EPBULK_IN, MAX_PACKET_SIZE_EPBULK);
+    addEndpoint(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+\r
+    //activate readings
+    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+    return true;
+}
+\r
+\r
+uint8_t * USBMSD::stringIinterfaceDesc() {
+    static uint8_t stringIinterfaceDescriptor[] = {
+        0x08,                           //bLength
+        STRING_DESCRIPTOR,              //bDescriptorType 0x03
+        'M',0,'S',0,'D',0               //bString iInterface - MSD
+    };
+    return stringIinterfaceDescriptor;
+}
+\r
+uint8_t * USBMSD::stringIproductDesc() {
+    static uint8_t stringIproductDescriptor[] = {
+        0x12,                                           //bLength
+        STRING_DESCRIPTOR,                              //bDescriptorType 0x03
+        'M',0,'b',0,'e',0,'d',0,' ',0,'M',0,'S',0,'D',0 //bString iProduct - Mbed Audio
+    };
+    return stringIproductDescriptor;
+}
+\r
+\r
+uint8_t * USBMSD::configurationDesc() {
+    static uint8_t configDescriptor[] = {
+\r
+        // Configuration 1
+        9,      // bLength
+        2,      // bDescriptorType
+        LSB(9 + 9 + 7 + 7), // wTotalLength
+        MSB(9 + 9 + 7 + 7),
+        0x01,   // bNumInterfaces
+        0x01,   // bConfigurationValue: 0x01 is used to select this configuration
+        0x00,   // iConfiguration: no string to describe this configuration
+        0xC0,   // bmAttributes
+        100,    // bMaxPower, device power consumption is 100 mA
+\r
+        // Interface 0, Alternate Setting 0, MSC Class
+        9,      // bLength
+        4,      // bDescriptorType
+        0x00,   // bInterfaceNumber
+        0x00,   // bAlternateSetting
+        0x02,   // bNumEndpoints
+        0x08,   // bInterfaceClass
+        0x06,   // bInterfaceSubClass
+        0x50,   // bInterfaceProtocol
+        0x04,   // iInterface
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                          // bLength
+        5,                          // bDescriptorType
+        PHY_TO_DESC(EPBULK_IN),     // bEndpointAddress
+        0x02,                       // bmAttributes (0x02=bulk)
+        LSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (MSB)
+        0,                          // bInterval
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                          // bLength
+        5,                          // bDescriptorType
+        PHY_TO_DESC(EPBULK_OUT),    // bEndpointAddress
+        0x02,                       // bmAttributes (0x02=bulk)
+        LSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPBULK),// wMaxPacketSize (MSB)
+        0                           // bInterval
+    };
+    return configDescriptor;
 }
\ No newline at end of file
index a2267b4..701f370 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-\r
-#ifndef USBMSD_H\r
-#define USBMSD_H\r
-\r
-/* These headers are included for child class. */\r
-#include "USBEndpoints.h"\r
-#include "USBDescriptor.h"\r
-#include "USBDevice_Types.h"\r
-\r
-#include "USBDevice.h"\r
-\r
-\r
-\r
-#ifdef __GNUC__\r
-    /* Packing for structs in GCC. */\r
-    #define PACK_STRUCT_STRUCT __attribute__((packed))\r
-    #define PACK_STRUCT_BEGIN\r
-    #define PACK_STRUCT_END\r
-#else /* !__GNUC__ */\r
-    /* Packing for structs in ARM compiler. */\r
-    #define PACK_STRUCT_STRUCT\r
-    #define PACK_STRUCT_BEGIN __packed\r
-    #define PACK_STRUCT_END\r
-#endif /* __GNUC__ */\r
-\r
-\r
-\r
-\r
-/**\r
- * USBMSD class: generic class in order to use all kinds of blocks storage chip\r
- *\r
- * Introduction\r
- *\r
- * The USBMSD implements the MSD protocol. It permits to access a memory chip (flash, sdcard,...)\r
- * from a computer over USB. But this class doesn't work standalone, you need to subclass this class\r
- * and define virtual functions which are called in USBMSD.\r
- *\r
- * How to use this class with your chip ?\r
- *\r
- * You have to inherit and define some pure virtual functions (mandatory step):\r
- *   - virtual int disk_read(char * data, int block): function to read a block\r
- *   - virtual int disk_write(const char * data, int block): function to write a block\r
- *   - virtual int disk_initialize(): function to initialize the memory\r
- *   - virtual int disk_sectors(): return the number of blocks\r
- *   - virtual int disk_size(): return the memory size\r
- *   - virtual int disk_status(): return the status of the storage chip (0: OK, 1: not initialized, 2: no medium in the drive, 4: write protection)\r
- *\r
- * All functions names are compatible with the fat filesystem library. So you can imagine using your own class with\r
- * USBMSD and the fat filesystem library in the same program. Just be careful because there are two different parts which\r
- * will access the sd card. You can do a master/slave system using the disk_status method.\r
- *\r
- * Once these functions defined, you can call connect() (at the end of the constructor of your class for instance)\r
- * of USBMSD to connect your mass storage device. connect() will first call disk_status() to test the status of the disk.\r
- * If disk_status() returns 1 (disk not initialized), then disk_initialize() is called. After this step, connect() will collect information\r
- * such as the number of blocks and the memory size.\r
- */\r
-class USBMSD: public USBDevice {\r
-public:\r
-\r
-    /**\r
-    * Constructor\r
-    *\r
-    * @param vendor_id Your vendor_id\r
-    * @param product_id Your product_id\r
-    * @param product_release Your preoduct_release\r
-    */\r
-    USBMSD(uint16_t vendor_id = 0x0703, uint16_t product_id = 0x0104, uint16_t product_release = 0x0001);\r
-\r
-    /**\r
-    * Connect the USB MSD device. Establish disk initialization before really connect the device.\r
-    *\r
-    * @returns true if successful\r
-    */\r
-    bool connect();\r
-\r
-\r
-protected:\r
-\r
-    /*\r
-    * read a block on a storage chip\r
-    *\r
-    * @param data pointer where will be stored read data\r
-    * @param block block number\r
-    * @returns 0 if successful\r
-    */\r
-    virtual int disk_read(char * data, int block) = 0;\r
-\r
-    /*\r
-    * write a block on a storage chip\r
-    *\r
-    * @param data data to write\r
-    * @param block block number\r
-    * @returns 0 if successful\r
-    */\r
-    virtual int disk_write(const char * data, int block) = 0;\r
-\r
-    /*\r
-    * Disk initilization\r
-    */\r
-    virtual int disk_initialize() = 0;\r
-\r
-    /*\r
-    * Return the number of blocks\r
-    *\r
-    * @returns number of blocks\r
-    */\r
-    virtual int disk_sectors() = 0;\r
-\r
-    /*\r
-    * Return memory size\r
-    *\r
-    * @returns memory size\r
-    */\r
-    virtual int disk_size() = 0;\r
-\r
-\r
-    /*\r
-    * To check the status of the storage chip\r
-    *\r
-    * @returns status: 0: OK, 1: disk not initialized, 2: no medium in the drive, 4: write protected\r
-    */\r
-    virtual int disk_status() = 0;\r
-\r
-    /*\r
-    * Get string product descriptor\r
-    *\r
-    * @returns pointer to the string product descriptor\r
-    */\r
-    virtual uint8_t * stringIproductDesc();\r
-\r
-    /*\r
-    * Get string interface descriptor\r
-    *\r
-    * @returns pointer to the string interface descriptor\r
-    */\r
-    virtual uint8_t * stringIinterfaceDesc();\r
-\r
-    /*\r
-    * Get configuration descriptor\r
-    *\r
-    * @returns pointer to the configuration descriptor\r
-    */\r
-    virtual uint8_t * configurationDesc();\r
-\r
-    /*\r
-    * Callback called when a packet is received\r
-    */\r
-    virtual bool EP2_OUT_callback();\r
-\r
-    /*\r
-    * Callback called when a packet has been sent\r
-    */\r
-    virtual bool EP2_IN_callback();\r
-\r
-    /*\r
-    * Set configuration of device. Add endpoints\r
-    */\r
-    virtual bool USBCallback_setConfiguration(uint8_t configuration);\r
-\r
-    /*\r
-    * Callback called to process class specific requests\r
-    */\r
-    virtual bool USBCallback_request();\r
-\r
-\r
-private:\r
-\r
-    // MSC Bulk-only Stage\r
-    enum Stage {\r
-        READ_CBW,     // wait a CBW\r
-        ERROR,        // error\r
-        PROCESS_CBW,  // process a CBW request\r
-        SEND_CSW,     // send a CSW\r
-        WAIT_CSW,     // wait that a CSW has been effectively sent\r
-    };\r
-\r
-    // Bulk-only CBW\r
-    typedef PACK_STRUCT_BEGIN struct {\r
-        uint32_t Signature;\r
-        uint32_t Tag;\r
-        uint32_t DataLength;\r
-        uint8_t  Flags;\r
-        uint8_t  LUN;\r
-        uint8_t  CBLength;\r
-        uint8_t  CB[16];\r
-    } PACK_STRUCT_STRUCT CBW;\r
-\r
-    // Bulk-only CSW\r
-    typedef PACK_STRUCT_BEGIN struct {\r
-        uint32_t Signature;\r
-        uint32_t Tag;\r
-        uint32_t DataResidue;\r
-        uint8_t  Status;\r
-    } PACK_STRUCT_STRUCT CSW;\r
-\r
-\r
-    //state of the bulk-only state machine\r
-    Stage stage;\r
-\r
-    // current CBW\r
-    CBW cbw;\r
-\r
-    // CSW which will be sent\r
-    CSW csw;\r
-\r
-    // addr where will be read or written data\r
-    uint32_t addr;\r
-\r
-    // length of a reading or writing\r
-    uint32_t length;\r
-\r
-    // memory OK (after a memoryVerify)\r
-    bool memOK;\r
-\r
-    // cache in RAM before writing in memory. Useful also to read a block.\r
-    uint8_t * page;\r
-\r
-    int BlockSize;\r
-    int MemorySize;\r
-    int BlockCount;\r
-\r
-    void CBWDecode(uint8_t * buf, uint16_t size);\r
-    void sendCSW (void);\r
-    bool inquiryRequest (void);\r
-    bool write (uint8_t * buf, uint16_t size);\r
-    bool readFormatCapacity();\r
-    bool readCapacity (void);\r
-    bool infoTransfer (void);\r
-    void memoryRead (void);\r
-    bool modeSense6 (void);\r
-    void testUnitReady (void);\r
-    bool requestSense (void);\r
-    void memoryVerify (uint8_t * buf, uint16_t size);\r
-    void memoryWrite (uint8_t * buf, uint16_t size);\r
-    void reset();\r
-    void fail();\r
-};\r
-\r
-#endif\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+\r
+#ifndef USBMSD_H
+#define USBMSD_H
+\r
+/* These headers are included for child class. */
+#include "USBEndpoints.h"
+#include "USBDescriptor.h"
+#include "USBDevice_Types.h"
+\r
+#include "USBDevice.h"
+\r
+\r
+\r
+#ifdef __GNUC__
+    /* Packing for structs in GCC. */
+    #define PACK_STRUCT_STRUCT __attribute__((packed))
+    #define PACK_STRUCT_BEGIN
+    #define PACK_STRUCT_END
+#else /* !__GNUC__ */
+    /* Packing for structs in ARM compiler. */
+    #define PACK_STRUCT_STRUCT
+    #define PACK_STRUCT_BEGIN __packed
+    #define PACK_STRUCT_END
+#endif /* __GNUC__ */
+\r
+\r
+\r
+\r
+/**
+ * USBMSD class: generic class in order to use all kinds of blocks storage chip
+ *
+ * Introduction
+ *
+ * The USBMSD implements the MSD protocol. It permits to access a memory chip (flash, sdcard,...)
+ * from a computer over USB. But this class doesn't work standalone, you need to subclass this class
+ * and define virtual functions which are called in USBMSD.
+ *
+ * How to use this class with your chip ?
+ *
+ * You have to inherit and define some pure virtual functions (mandatory step):
+ *   - virtual int disk_read(char * data, int block): function to read a block
+ *   - virtual int disk_write(const char * data, int block): function to write a block
+ *   - virtual int disk_initialize(): function to initialize the memory
+ *   - virtual int disk_sectors(): return the number of blocks
+ *   - virtual int disk_size(): return the memory size
+ *   - virtual int disk_status(): return the status of the storage chip (0: OK, 1: not initialized, 2: no medium in the drive, 4: write protection)
+ *
+ * All functions names are compatible with the fat filesystem library. So you can imagine using your own class with
+ * USBMSD and the fat filesystem library in the same program. Just be careful because there are two different parts which
+ * will access the sd card. You can do a master/slave system using the disk_status method.
+ *
+ * Once these functions defined, you can call connect() (at the end of the constructor of your class for instance)
+ * of USBMSD to connect your mass storage device. connect() will first call disk_status() to test the status of the disk.
+ * If disk_status() returns 1 (disk not initialized), then disk_initialize() is called. After this step, connect() will collect information
+ * such as the number of blocks and the memory size.
+ */
+class USBMSD: public USBDevice {
+public:
+\r
+    /**
+    * Constructor
+    *
+    * @param vendor_id Your vendor_id
+    * @param product_id Your product_id
+    * @param product_release Your preoduct_release
+    */
+    USBMSD(uint16_t vendor_id = 0x0703, uint16_t product_id = 0x0104, uint16_t product_release = 0x0001);
+\r
+    /**
+    * Connect the USB MSD device. Establish disk initialization before really connect the device.
+    *
+    * @returns true if successful
+    */
+    bool connect();
+\r
+\r
+protected:
+\r
+    /*
+    * read a block on a storage chip
+    *
+    * @param data pointer where will be stored read data
+    * @param block block number
+    * @returns 0 if successful
+    */
+    virtual int disk_read(char * data, int block) = 0;
+\r
+    /*
+    * write a block on a storage chip
+    *
+    * @param data data to write
+    * @param block block number
+    * @returns 0 if successful
+    */
+    virtual int disk_write(const char * data, int block) = 0;
+\r
+    /*
+    * Disk initilization
+    */
+    virtual int disk_initialize() = 0;
+\r
+    /*
+    * Return the number of blocks
+    *
+    * @returns number of blocks
+    */
+    virtual int disk_sectors() = 0;
+\r
+    /*
+    * Return memory size
+    *
+    * @returns memory size
+    */
+    virtual int disk_size() = 0;
+\r
+\r
+    /*
+    * To check the status of the storage chip
+    *
+    * @returns status: 0: OK, 1: disk not initialized, 2: no medium in the drive, 4: write protected
+    */
+    virtual int disk_status() = 0;
+\r
+    /*
+    * Get string product descriptor
+    *
+    * @returns pointer to the string product descriptor
+    */
+    virtual uint8_t * stringIproductDesc();
+\r
+    /*
+    * Get string interface descriptor
+    *
+    * @returns pointer to the string interface descriptor
+    */
+    virtual uint8_t * stringIinterfaceDesc();
+\r
+    /*
+    * Get configuration descriptor
+    *
+    * @returns pointer to the configuration descriptor
+    */
+    virtual uint8_t * configurationDesc();
+\r
+    /*
+    * Callback called when a packet is received
+    */
+    virtual bool EP2_OUT_callback();
+\r
+    /*
+    * Callback called when a packet has been sent
+    */
+    virtual bool EP2_IN_callback();
+\r
+    /*
+    * Set configuration of device. Add endpoints
+    */
+    virtual bool USBCallback_setConfiguration(uint8_t configuration);
+\r
+    /*
+    * Callback called to process class specific requests
+    */
+    virtual bool USBCallback_request();
+\r
+\r
+private:
+\r
+    // MSC Bulk-only Stage
+    enum Stage {
+        READ_CBW,     // wait a CBW
+        ERROR,        // error
+        PROCESS_CBW,  // process a CBW request
+        SEND_CSW,     // send a CSW
+        WAIT_CSW,     // wait that a CSW has been effectively sent
+    };
+\r
+    // Bulk-only CBW
+    typedef PACK_STRUCT_BEGIN struct {
+        uint32_t Signature;
+        uint32_t Tag;
+        uint32_t DataLength;
+        uint8_t  Flags;
+        uint8_t  LUN;
+        uint8_t  CBLength;
+        uint8_t  CB[16];
+    } PACK_STRUCT_STRUCT CBW;
+\r
+    // Bulk-only CSW
+    typedef PACK_STRUCT_BEGIN struct {
+        uint32_t Signature;
+        uint32_t Tag;
+        uint32_t DataResidue;
+        uint8_t  Status;
+    } PACK_STRUCT_STRUCT CSW;
+\r
+\r
+    //state of the bulk-only state machine
+    Stage stage;
+\r
+    // current CBW
+    CBW cbw;
+\r
+    // CSW which will be sent
+    CSW csw;
+\r
+    // addr where will be read or written data
+    uint32_t addr;
+\r
+    // length of a reading or writing
+    uint32_t length;
+\r
+    // memory OK (after a memoryVerify)
+    bool memOK;
+\r
+    // cache in RAM before writing in memory. Useful also to read a block.
+    uint8_t * page;
+\r
+    int BlockSize;
+    int MemorySize;
+    int BlockCount;
+\r
+    void CBWDecode(uint8_t * buf, uint16_t size);
+    void sendCSW (void);
+    bool inquiryRequest (void);
+    bool write (uint8_t * buf, uint16_t size);
+    bool readFormatCapacity();
+    bool readCapacity (void);
+    bool infoTransfer (void);
+    void memoryRead (void);
+    bool modeSense6 (void);
+    void testUnitReady (void);
+    bool requestSense (void);
+    void memoryVerify (uint8_t * buf, uint16_t size);
+    void memoryWrite (uint8_t * buf, uint16_t size);
+    void reset();
+    void fail();
+};
+\r
+#endif
index 93c0f9d..b200471 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
-\r
-#include "stdint.h"\r
-#include "USBCDC.h"\r
-#include "USBBusInterface.h"\r
-\r
-static uint8_t cdc_line_coding[7]= {0x80, 0x25, 0x00, 0x00, 0x00, 0x00, 0x08};\r
-\r
-#define DEFAULT_CONFIGURATION (1)\r
-\r
-#define CDC_SET_LINE_CODING        0x20\r
-#define CDC_GET_LINE_CODING        0x21\r
-#define CDC_SET_CONTROL_LINE_STATE 0x22\r
-\r
-#define MAX_CDC_REPORT_SIZE MAX_PACKET_SIZE_EPBULK\r
-\r
-USBCDC::USBCDC(uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release) {\r
-    USBDevice::connect();\r
-}\r
-\r
-bool USBCDC::USBCallback_request(void) {\r
-    /* Called in ISR context */\r
-\r
-    bool success = false;\r
-    CONTROL_TRANSFER * transfer = getTransferPtr();\r
-\r
-    /* Process class-specific requests */\r
-\r
-    if (transfer->setup.bmRequestType.Type == CLASS_TYPE) {\r
-        switch (transfer->setup.bRequest) {\r
-            case CDC_GET_LINE_CODING:\r
-                transfer->remaining = 7;\r
-                transfer->ptr = cdc_line_coding;\r
-                transfer->direction = DEVICE_TO_HOST;\r
-                success = true;\r
-                break;\r
-            case CDC_SET_LINE_CODING:\r
-                transfer->remaining = 7;\r
-                success = true;\r
-                break;\r
-            case CDC_SET_CONTROL_LINE_STATE:\r
-                success = true;\r
-                break;\r
-            default:\r
-                break;\r
-        }\r
-    }\r
-\r
-    return success;\r
-}\r
-\r
-\r
-// Called in ISR context\r
-// Set configuration. Return false if the\r
-// configuration is not supported.\r
-bool USBCDC::USBCallback_setConfiguration(uint8_t configuration) {\r
-    if (configuration != DEFAULT_CONFIGURATION) {\r
-        return false;\r
-    }\r
-\r
-    // Configure endpoints > 0\r
-    addEndpoint(EPINT_IN, MAX_PACKET_SIZE_EPINT);\r
-    addEndpoint(EPBULK_IN, MAX_PACKET_SIZE_EPBULK);\r
-    addEndpoint(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-\r
-    // We activate the endpoint to be able to recceive data\r
-    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-    return true;\r
-}\r
-\r
-bool USBCDC::send(uint8_t * buffer, uint16_t size) {\r
-    return USBDevice::write(EPBULK_IN, buffer, size, MAX_CDC_REPORT_SIZE);\r
-}\r
-\r
-bool USBCDC::readEP(uint8_t * buffer, uint16_t * size) {\r
-    if (!USBDevice::readEP(EPBULK_OUT, buffer, size, MAX_CDC_REPORT_SIZE))\r
-        return false;\r
-    if (!readStart(EPBULK_OUT, MAX_CDC_REPORT_SIZE))\r
-        return false;\r
-    return true;\r
-}\r
-\r
-bool USBCDC::readEP_NB(uint8_t * buffer, uint16_t * size) {\r
-    if (!USBDevice::readEP_NB(EPBULK_OUT, buffer, size, MAX_CDC_REPORT_SIZE))\r
-        return false;\r
-    if (!readStart(EPBULK_OUT, MAX_CDC_REPORT_SIZE))\r
-        return false;\r
-    return true;\r
-}\r
-\r
-\r
-uint8_t * USBCDC::deviceDesc() {\r
-    static uint8_t deviceDescriptor[] = {\r
-        18,                   // bLength\r
-        1,                    // bDescriptorType\r
-        0x10, 0x01,           // bcdUSB\r
-        2,                    // bDeviceClass\r
-        0,                    // bDeviceSubClass\r
-        0,                    // bDeviceProtocol\r
-        MAX_PACKET_SIZE_EP0,  // bMaxPacketSize0\r
-        LSB(VENDOR_ID), MSB(VENDOR_ID),  // idVendor\r
-        LSB(PRODUCT_ID), MSB(PRODUCT_ID),// idProduct\r
-        0x00, 0x01,           // bcdDevice\r
-        1,                    // iManufacturer\r
-        2,                    // iProduct\r
-        3,                    // iSerialNumber\r
-        1                     // bNumConfigurations\r
-    };\r
-    return deviceDescriptor;\r
-}\r
-\r
-uint8_t * USBCDC::stringIinterfaceDesc() {\r
-    static uint8_t stringIinterfaceDescriptor[] = {\r
-        0x08,\r
-        STRING_DESCRIPTOR,\r
-        'C',0,'D',0,'C',0,\r
-    };\r
-    return stringIinterfaceDescriptor;\r
-}\r
-\r
-uint8_t * USBCDC::stringIproductDesc() {\r
-    static uint8_t stringIproductDescriptor[] = {\r
-        0x16,\r
-        STRING_DESCRIPTOR,\r
-        'C',0,'D',0,'C',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0\r
-    };\r
-    return stringIproductDescriptor;\r
-}\r
-\r
-\r
-#define CONFIG1_DESC_SIZE (9+9+5+5+4+5+7+9+7+7)\r
-\r
-uint8_t * USBCDC::configurationDesc() {\r
-    static uint8_t configDescriptor[] = {\r
-        9,                      // bLength;\r
-        2,                      // bDescriptorType;\r
-        LSB(CONFIG1_DESC_SIZE), // wTotalLength\r
-        MSB(CONFIG1_DESC_SIZE),\r
-        2,                      // bNumInterfaces\r
-        1,                      // bConfigurationValue\r
-        0,                      // iConfiguration\r
-        0x80,                   // bmAttributes\r
-        50,                     // bMaxPower\r
-\r
-        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12\r
-        9,                      // bLength\r
-        4,                      // bDescriptorType\r
-        0,                      // bInterfaceNumber\r
-        0,                      // bAlternateSetting\r
-        1,                      // bNumEndpoints\r
-        0x02,                   // bInterfaceClass\r
-        0x02,                   // bInterfaceSubClass\r
-        0x01,                   // bInterfaceProtocol\r
-        0,                      // iInterface\r
-\r
-        // CDC Header Functional Descriptor, CDC Spec 5.2.3.1, Table 26\r
-        5,                      // bFunctionLength\r
-        0x24,                   // bDescriptorType\r
-        0x00,                   // bDescriptorSubtype\r
-        0x10, 0x01,             // bcdCDC\r
-\r
-        // Call Management Functional Descriptor, CDC Spec 5.2.3.2, Table 27\r
-        5,                      // bFunctionLength\r
-        0x24,                   // bDescriptorType\r
-        0x01,                   // bDescriptorSubtype\r
-        0x03,                   // bmCapabilities\r
-        1,                      // bDataInterface\r
-\r
-        // Abstract Control Management Functional Descriptor, CDC Spec 5.2.3.3, Table 28\r
-        4,                      // bFunctionLength\r
-        0x24,                   // bDescriptorType\r
-        0x02,                   // bDescriptorSubtype\r
-        0x06,                   // bmCapabilities\r
-\r
-        // Union Functional Descriptor, CDC Spec 5.2.3.8, Table 33\r
-        5,                      // bFunctionLength\r
-        0x24,                   // bDescriptorType\r
-        0x06,                   // bDescriptorSubtype\r
-        0,                      // bMasterInterface\r
-        1,                      // bSlaveInterface0\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        ENDPOINT_DESCRIPTOR_LENGTH,     // bLength\r
-        ENDPOINT_DESCRIPTOR,            // bDescriptorType\r
-        PHY_TO_DESC(EPINT_IN),          // bEndpointAddress\r
-        E_INTERRUPT,                    // bmAttributes (0x03=intr)\r
-        LSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (MSB)\r
-        16,                             // bInterval\r
-\r
-\r
-\r
-\r
-        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12\r
-        9,          // bLength\r
-        4,          // bDescriptorType\r
-        1,          // bInterfaceNumber\r
-        0,          // bAlternateSetting\r
-        2,          // bNumEndpoints\r
-        0x0A,       // bInterfaceClass\r
-        0x00,       // bInterfaceSubClass\r
-        0x00,       // bInterfaceProtocol\r
-        0,          // iInterface\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        7,                      // bLength\r
-        5,                      // bDescriptorType\r
-        PHY_TO_DESC(EPBULK_IN), // bEndpointAddress\r
-        0x02,                   // bmAttributes (0x02=bulk)\r
-        LSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (MSB)\r
-        0,                      // bInterval\r
-\r
-        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13\r
-        7,                      // bLength\r
-        5,                      // bDescriptorType\r
-        PHY_TO_DESC(EPBULK_OUT),// bEndpointAddress\r
-        0x02,                   // bmAttributes (0x02=bulk)\r
-        LSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (LSB)\r
-        MSB(MAX_PACKET_SIZE_EPBULK),     // wMaxPacketSize (MSB)\r
-        0                       // bInterval\r
-    };\r
-    return configDescriptor;\r
-}\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+\r
+#include "stdint.h"
+#include "USBCDC.h"
+#include "USBBusInterface.h"
+\r
+static uint8_t cdc_line_coding[7]= {0x80, 0x25, 0x00, 0x00, 0x00, 0x00, 0x08};
+\r
+#define DEFAULT_CONFIGURATION (1)
+\r
+#define CDC_SET_LINE_CODING        0x20
+#define CDC_GET_LINE_CODING        0x21
+#define CDC_SET_CONTROL_LINE_STATE 0x22
+\r
+#define MAX_CDC_REPORT_SIZE MAX_PACKET_SIZE_EPBULK
+\r
+USBCDC::USBCDC(uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release) {
+    USBDevice::connect();
+}
+\r
+bool USBCDC::USBCallback_request(void) {
+    /* Called in ISR context */
+\r
+    bool success = false;
+    CONTROL_TRANSFER * transfer = getTransferPtr();
+\r
+    /* Process class-specific requests */
+\r
+    if (transfer->setup.bmRequestType.Type == CLASS_TYPE) {
+        switch (transfer->setup.bRequest) {
+            case CDC_GET_LINE_CODING:
+                transfer->remaining = 7;
+                transfer->ptr = cdc_line_coding;
+                transfer->direction = DEVICE_TO_HOST;
+                success = true;
+                break;
+            case CDC_SET_LINE_CODING:
+                transfer->remaining = 7;
+                success = true;
+                break;
+            case CDC_SET_CONTROL_LINE_STATE:
+                success = true;
+                break;
+            default:
+                break;
+        }
+    }
+\r
+    return success;
+}
+\r
+\r
+// Called in ISR context
+// Set configuration. Return false if the
+// configuration is not supported.
+bool USBCDC::USBCallback_setConfiguration(uint8_t configuration) {
+    if (configuration != DEFAULT_CONFIGURATION) {
+        return false;
+    }
+\r
+    // Configure endpoints > 0
+    addEndpoint(EPINT_IN, MAX_PACKET_SIZE_EPINT);
+    addEndpoint(EPBULK_IN, MAX_PACKET_SIZE_EPBULK);
+    addEndpoint(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+\r
+    // We activate the endpoint to be able to recceive data
+    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+    return true;
+}
+\r
+bool USBCDC::send(uint8_t * buffer, uint16_t size) {
+    return USBDevice::write(EPBULK_IN, buffer, size, MAX_CDC_REPORT_SIZE);
+}
+\r
+bool USBCDC::readEP(uint8_t * buffer, uint16_t * size) {
+    if (!USBDevice::readEP(EPBULK_OUT, buffer, size, MAX_CDC_REPORT_SIZE))
+        return false;
+    if (!readStart(EPBULK_OUT, MAX_CDC_REPORT_SIZE))
+        return false;
+    return true;
+}
+\r
+bool USBCDC::readEP_NB(uint8_t * buffer, uint16_t * size) {
+    if (!USBDevice::readEP_NB(EPBULK_OUT, buffer, size, MAX_CDC_REPORT_SIZE))
+        return false;
+    if (!readStart(EPBULK_OUT, MAX_CDC_REPORT_SIZE))
+        return false;
+    return true;
+}
+\r
+\r
+uint8_t * USBCDC::deviceDesc() {
+    static uint8_t deviceDescriptor[] = {
+        18,                   // bLength
+        1,                    // bDescriptorType
+        0x10, 0x01,           // bcdUSB
+        2,                    // bDeviceClass
+        0,                    // bDeviceSubClass
+        0,                    // bDeviceProtocol
+        MAX_PACKET_SIZE_EP0,  // bMaxPacketSize0
+        LSB(VENDOR_ID), MSB(VENDOR_ID),  // idVendor
+        LSB(PRODUCT_ID), MSB(PRODUCT_ID),// idProduct
+        0x00, 0x01,           // bcdDevice
+        1,                    // iManufacturer
+        2,                    // iProduct
+        3,                    // iSerialNumber
+        1                     // bNumConfigurations
+    };
+    return deviceDescriptor;
+}
+\r
+uint8_t * USBCDC::stringIinterfaceDesc() {
+    static uint8_t stringIinterfaceDescriptor[] = {
+        0x08,
+        STRING_DESCRIPTOR,
+        'C',0,'D',0,'C',0,
+    };
+    return stringIinterfaceDescriptor;
+}
+\r
+uint8_t * USBCDC::stringIproductDesc() {
+    static uint8_t stringIproductDescriptor[] = {
+        0x16,
+        STRING_DESCRIPTOR,
+        'C',0,'D',0,'C',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0
+    };
+    return stringIproductDescriptor;
+}
+\r
+\r
+#define CONFIG1_DESC_SIZE (9+9+5+5+4+5+7+9+7+7)
+\r
+uint8_t * USBCDC::configurationDesc() {
+    static uint8_t configDescriptor[] = {
+        9,                      // bLength;
+        2,                      // bDescriptorType;
+        LSB(CONFIG1_DESC_SIZE), // wTotalLength
+        MSB(CONFIG1_DESC_SIZE),
+        2,                      // bNumInterfaces
+        1,                      // bConfigurationValue
+        0,                      // iConfiguration
+        0x80,                   // bmAttributes
+        50,                     // bMaxPower
+\r
+        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+        9,                      // bLength
+        4,                      // bDescriptorType
+        0,                      // bInterfaceNumber
+        0,                      // bAlternateSetting
+        1,                      // bNumEndpoints
+        0x02,                   // bInterfaceClass
+        0x02,                   // bInterfaceSubClass
+        0x01,                   // bInterfaceProtocol
+        0,                      // iInterface
+\r
+        // CDC Header Functional Descriptor, CDC Spec 5.2.3.1, Table 26
+        5,                      // bFunctionLength
+        0x24,                   // bDescriptorType
+        0x00,                   // bDescriptorSubtype
+        0x10, 0x01,             // bcdCDC
+\r
+        // Call Management Functional Descriptor, CDC Spec 5.2.3.2, Table 27
+        5,                      // bFunctionLength
+        0x24,                   // bDescriptorType
+        0x01,                   // bDescriptorSubtype
+        0x03,                   // bmCapabilities
+        1,                      // bDataInterface
+\r
+        // Abstract Control Management Functional Descriptor, CDC Spec 5.2.3.3, Table 28
+        4,                      // bFunctionLength
+        0x24,                   // bDescriptorType
+        0x02,                   // bDescriptorSubtype
+        0x06,                   // bmCapabilities
+\r
+        // Union Functional Descriptor, CDC Spec 5.2.3.8, Table 33
+        5,                      // bFunctionLength
+        0x24,                   // bDescriptorType
+        0x06,                   // bDescriptorSubtype
+        0,                      // bMasterInterface
+        1,                      // bSlaveInterface0
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        ENDPOINT_DESCRIPTOR_LENGTH,     // bLength
+        ENDPOINT_DESCRIPTOR,            // bDescriptorType
+        PHY_TO_DESC(EPINT_IN),          // bEndpointAddress
+        E_INTERRUPT,                    // bmAttributes (0x03=intr)
+        LSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPINT),     // wMaxPacketSize (MSB)
+        16,                             // bInterval
+\r
+\r
+\r
+\r
+        // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+        9,          // bLength
+        4,          // bDescriptorType
+        1,          // bInterfaceNumber
+        0,          // bAlternateSetting
+        2,          // bNumEndpoints
+        0x0A,       // bInterfaceClass
+        0x00,       // bInterfaceSubClass
+        0x00,       // bInterfaceProtocol
+        0,          // iInterface
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                      // bLength
+        5,                      // bDescriptorType
+        PHY_TO_DESC(EPBULK_IN), // bEndpointAddress
+        0x02,                   // bmAttributes (0x02=bulk)
+        LSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (MSB)
+        0,                      // bInterval
+\r
+        // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+        7,                      // bLength
+        5,                      // bDescriptorType
+        PHY_TO_DESC(EPBULK_OUT),// bEndpointAddress
+        0x02,                   // bmAttributes (0x02=bulk)
+        LSB(MAX_PACKET_SIZE_EPBULK),    // wMaxPacketSize (LSB)
+        MSB(MAX_PACKET_SIZE_EPBULK),     // wMaxPacketSize (MSB)
+        0                       // bInterval
+    };
+    return configDescriptor;
+}
index 56539c7..970dc40 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
 \r
-#ifndef USBCDC_H\r
-#define USBCDC_H\r
+#ifndef USBCDC_H
+#define USBCDC_H
 \r
-/* These headers are included for child class. */\r
-#include "USBEndpoints.h"\r
-#include "USBDescriptor.h"\r
-#include "USBDevice_Types.h"\r
+/* These headers are included for child class. */
+#include "USBEndpoints.h"
+#include "USBDescriptor.h"
+#include "USBDevice_Types.h"
 \r
-#include "USBDevice.h"\r
+#include "USBDevice.h"
 \r
 \r
 \r
-class USBCDC: public USBDevice {\r
-public:\r
+class USBCDC: public USBDevice {
+public:
 \r
-    /*\r
-    * Constructor\r
-    *\r
-    * @param vendor_id Your vendor_id\r
-    * @param product_id Your product_id\r
-    * @param product_release Your preoduct_release\r
-    */\r
-    USBCDC(uint16_t vendor_id, uint16_t product_id, uint16_t product_release);\r
+    /*
+    * Constructor
+    *
+    * @param vendor_id Your vendor_id
+    * @param product_id Your product_id
+    * @param product_release Your preoduct_release
+    */
+    USBCDC(uint16_t vendor_id, uint16_t product_id, uint16_t product_release);
 \r
-protected:\r
+protected:
     \r
-    /*\r
-    * Get device descriptor. Warning: this method has to store the length of the report descriptor in reportLength.\r
-    *\r
-    * @returns pointer to the device descriptor\r
-    */\r
-    virtual uint8_t * deviceDesc();\r
+    /*
+    * Get device descriptor. Warning: this method has to store the length of the report descriptor in reportLength.
+    *
+    * @returns pointer to the device descriptor
+    */
+    virtual uint8_t * deviceDesc();
     \r
-    /*\r
-    * Get string product descriptor\r
-    *\r
-    * @returns pointer to the string product descriptor\r
-    */\r
-    virtual uint8_t * stringIproductDesc();\r
+    /*
+    * Get string product descriptor
+    *
+    * @returns pointer to the string product descriptor
+    */
+    virtual uint8_t * stringIproductDesc();
     \r
-    /*\r
-    * Get string interface descriptor\r
-    *\r
-    * @returns pointer to the string interface descriptor\r
-    */\r
-    virtual uint8_t * stringIinterfaceDesc();\r
+    /*
+    * Get string interface descriptor
+    *
+    * @returns pointer to the string interface descriptor
+    */
+    virtual uint8_t * stringIinterfaceDesc();
     \r
-    /*\r
-    * Get configuration descriptor\r
-    *\r
-    * @returns pointer to the configuration descriptor\r
-    */\r
-    virtual uint8_t * configurationDesc();\r
+    /*
+    * Get configuration descriptor
+    *
+    * @returns pointer to the configuration descriptor
+    */
+    virtual uint8_t * configurationDesc();
     \r
-    /*\r
-    * Send a buffer\r
-    *\r
-    * @param endpoint endpoint which will be sent the buffer\r
-    * @param buffer buffer to be sent\r
-    * @param size length of the buffer\r
-    * @returns true if successful\r
-    */\r
-    bool send(uint8_t * buffer, uint16_t size);\r
+    /*
+    * Send a buffer
+    *
+    * @param endpoint endpoint which will be sent the buffer
+    * @param buffer buffer to be sent
+    * @param size length of the buffer
+    * @returns true if successful
+    */
+    bool send(uint8_t * buffer, uint16_t size);
     \r
-    /*\r
-    * Read a buffer from a certain endpoint. Warning: blocking\r
-    *\r
-    * @param endpoint endpoint to read\r
-    * @param buffer buffer where will be stored bytes\r
-    * @param size the number of bytes read will be stored in *size\r
-    * @param maxSize the maximum length that can be read\r
-    * @returns true if successful\r
-    */\r
-    bool readEP(uint8_t * buffer, uint16_t * size);\r
+    /*
+    * Read a buffer from a certain endpoint. Warning: blocking
+    *
+    * @param endpoint endpoint to read
+    * @param buffer buffer where will be stored bytes
+    * @param size the number of bytes read will be stored in *size
+    * @param maxSize the maximum length that can be read
+    * @returns true if successful
+    */
+    bool readEP(uint8_t * buffer, uint16_t * size);
     \r
-    /*\r
-    * Read a buffer from a certain endpoint. Warning: non blocking\r
-    *\r
-    * @param endpoint endpoint to read\r
-    * @param buffer buffer where will be stored bytes\r
-    * @param size the number of bytes read will be stored in *size\r
-    * @param maxSize the maximum length that can be read\r
-    * @returns true if successful\r
-    */\r
-    bool readEP_NB(uint8_t * buffer, uint16_t * size);\r
+    /*
+    * Read a buffer from a certain endpoint. Warning: non blocking
+    *
+    * @param endpoint endpoint to read
+    * @param buffer buffer where will be stored bytes
+    * @param size the number of bytes read will be stored in *size
+    * @param maxSize the maximum length that can be read
+    * @returns true if successful
+    */
+    bool readEP_NB(uint8_t * buffer, uint16_t * size);
 \r
-    virtual bool USBCallback_request();\r
-    virtual bool USBCallback_setConfiguration(uint8_t configuration);\r
+    virtual bool USBCallback_request();
+    virtual bool USBCallback_setConfiguration(uint8_t configuration);
 \r
-};\r
+};
 \r
-#endif\r
+#endif
index ead0f4b..598fe73 100644 (file)
@@ -1,70 +1,70 @@
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
 \r
-#include "stdint.h"\r
-#include "USBSerial.h"\r
-#include "USBBusInterface.h"\r
+#include "stdint.h"
+#include "USBSerial.h"
+#include "USBBusInterface.h"
 \r
 \r
-int USBSerial::_putc(int c) {\r
-    send((uint8_t *)&c, 1);\r
-    return 1;\r
-}\r
+int USBSerial::_putc(int c) {
+    send((uint8_t *)&c, 1);
+    return 1;
+}
 \r
-int USBSerial::_getc() {\r
-    uint8_t c = 0;\r
-    while (buf.isEmpty());\r
-    buf.dequeue(&c);\r
-    return c;\r
-}\r
+int USBSerial::_getc() {
+    uint8_t c = 0;
+    while (buf.isEmpty());
+    buf.dequeue(&c);
+    return c;
+}
 \r
 \r
-bool USBSerial::writeBlock(uint8_t * buf, uint16_t size) {\r
-    if(size > MAX_PACKET_SIZE_EPBULK) {\r
-        return false;\r
-    }\r
-    if(!send(buf, size)) {\r
-        return false;\r
-    }\r
-    return true;\r
-}\r
+bool USBSerial::writeBlock(uint8_t * buf, uint16_t size) {
+    if(size > MAX_PACKET_SIZE_EPBULK) {
+        return false;
+    }
+    if(!send(buf, size)) {
+        return false;
+    }
+    return true;
+}
 \r
 \r
 \r
-bool USBSerial::EP2_OUT_callback() {\r
-    uint8_t c[65];\r
-    uint16_t size = 0;\r
+bool USBSerial::EP2_OUT_callback() {
+    uint8_t c[65];
+    uint16_t size = 0;
 \r
-    //we read the packet received and put it on the circular buffer\r
-    readEP(c, &size);\r
-    for (int i = 0; i < size; i++) {\r
-        buf.queue(c[i]);\r
-    }\r
+    //we read the packet received and put it on the circular buffer
+    readEP(c, &size);
+    for (int i = 0; i < size; i++) {
+        buf.queue(c[i]);
+    }
 \r
-    //call a potential handler\r
-    rx.call();\r
+    //call a potential handler
+    rx.call();
 \r
-    // We reactivate the endpoint to receive next characters\r
-    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);\r
-    return true;\r
-}\r
+    // We reactivate the endpoint to receive next characters
+    readStart(EPBULK_OUT, MAX_PACKET_SIZE_EPBULK);
+    return true;
+}
 \r
-uint8_t USBSerial::available() {\r
-    return buf.available();\r
-}\r
+uint8_t USBSerial::available() {
+    return buf.available();
+}
 \r
index 5fe6c1c..fa6fd75 100644 (file)
-/* Copyright (c) 2010-2011 mbed.org, MIT License\r
-*\r
-* Permission is hereby granted, free of charge, to any person obtaining a copy of this software\r
-* and associated documentation files (the "Software"), to deal in the Software without\r
-* restriction, including without limitation the rights to use, copy, modify, merge, publish,\r
-* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the\r
-* Software is furnished to do so, subject to the following conditions:\r
-*\r
-* The above copyright notice and this permission notice shall be included in all copies or\r
-* substantial portions of the Software.\r
-*\r
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING\r
-* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\r
-* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\r
-* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
-* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
-*/\r
+/* Copyright (c) 2010-2011 mbed.org, MIT License
+*
+* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+* and associated documentation files (the "Software"), to deal in the Software without
+* restriction, including without limitation the rights to use, copy, modify, merge, publish,
+* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
+* Software is furnished to do so, subject to the following conditions:
+*
+* The above copyright notice and this permission notice shall be included in all copies or
+* substantial portions of the Software.
+*
+* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
+* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
 \r
-#ifndef USBSERIAL_H\r
-#define USBSERIAL_H\r
+#ifndef USBSERIAL_H
+#define USBSERIAL_H
 \r
-#include "USBCDC.h"\r
-#include "Stream.h"\r
-#include "CircBuffer.h"\r
+#include "USBCDC.h"
+#include "Stream.h"
+#include "CircBuffer.h"
 \r
 \r
-/**\r
-* USBSerial example\r
-*\r
-* @code\r
-* #include "mbed.h"\r
-* #include "USBSerial.h"\r
-*\r
-* //Virtual serial port over USB\r
-* USBSerial serial;\r
-*\r
-* int main(void) {\r
-*\r
-*    while(1)\r
-*    {\r
-*        serial.printf("I am a virtual serial port\n");\r
-*        wait(1);\r
-*    }\r
-* }\r
-* @endcode\r
-*/\r
-class USBSerial: public USBCDC, public Stream {\r
-public:\r
+/**
+* USBSerial example
+*
+* @code
+* #include "mbed.h"
+* #include "USBSerial.h"
+*
+* //Virtual serial port over USB
+* USBSerial serial;
+*
+* int main(void) {
+*
+*    while(1)
+*    {
+*        serial.printf("I am a virtual serial port\n");
+*        wait(1);
+*    }
+* }
+* @endcode
+*/
+class USBSerial: public USBCDC, public Stream {
+public:
 \r
-    /**\r
-    *   Constructor\r
-    *\r
-    * @param vendor_id Your vendor_id (default: 0x1f00)\r
-    * @param product_id Your product_id (default: 0x2012)\r
-    * @param product_release Your preoduct_release (default: 0x0001)\r
-    *\r
-    */\r
-    USBSerial(uint16_t vendor_id = 0x1f00, uint16_t product_id = 0x2012, uint16_t product_release = 0x0001): USBCDC(vendor_id, product_id, product_release), buf(128){ };\r
+    /**
+    *   Constructor
+    *
+    * @param vendor_id Your vendor_id (default: 0x1f00)
+    * @param product_id Your product_id (default: 0x2012)
+    * @param product_release Your preoduct_release (default: 0x0001)
+    *
+    */
+    USBSerial(uint16_t vendor_id = 0x1f00, uint16_t product_id = 0x2012, uint16_t product_release = 0x0001): USBCDC(vendor_id, product_id, product_release), buf(128){ };
 \r
 \r
-    /**\r
-    * Send a character. You can use puts, printf.\r
-    *\r
-    * @param c character to be sent\r
-    * @returns true if there is no error, false otherwise\r
-    */\r
-    virtual int _putc(int c);\r
+    /**
+    * Send a character. You can use puts, printf.
+    *
+    * @param c character to be sent
+    * @returns true if there is no error, false otherwise
+    */
+    virtual int _putc(int c);
     \r
-    /**\r
-    * Read a character: blocking\r
-    *\r
-    * @returns character read\r
-    */\r
-    virtual int _getc();\r
+    /**
+    * Read a character: blocking
+    *
+    * @returns character read
+    */
+    virtual int _getc();
     \r
-    /**\r
-    * Check the number of bytes available.\r
-    *\r
-    * @returns the number of bytes available\r
-    */\r
-    uint8_t available(); \r
+    /**
+    * Check the number of bytes available.
+    *
+    * @returns the number of bytes available
+    */
+    uint8_t available();
     \r
-    /**\r
-    * Write a block of data. \r
-    *\r
-    * For more efficiency, a block of size 64 (maximum size of a bulk endpoint) has to be written.\r
-    *\r
-    * @param buf pointer on data which will be written\r
-    * @param size size of the buffer. The maximum size of a block is limited by the size of the endpoint (64 bytes)\r
-    *\r
-    * @returns true if successfull\r
-    */\r
-    bool writeBlock(uint8_t * buf, uint16_t size);\r
+    /**
+    * Write a block of data.
+    *
+    * For more efficiency, a block of size 64 (maximum size of a bulk endpoint) has to be written.
+    *
+    * @param buf pointer on data which will be written
+    * @param size size of the buffer. The maximum size of a block is limited by the size of the endpoint (64 bytes)
+    *
+    * @returns true if successfull
+    */
+    bool writeBlock(uint8_t * buf, uint16_t size);
 \r
-    /**\r
-     *  Attach a member function to call when a packet is received. \r
-     *\r
-     *  @param tptr pointer to the object to call the member function on\r
-     *  @param mptr pointer to the member function to be called\r
-     */\r
-    template<typename T>\r
-    void attach(T* tptr, void (T::*mptr)(void)) {\r
-        if((mptr != NULL) && (tptr != NULL)) {\r
-            rx.attach(tptr, mptr);\r
-        }\r
-    }\r
+    /**
+     *  Attach a member function to call when a packet is received.
+     *
+     *  @param tptr pointer to the object to call the member function on
+     *  @param mptr pointer to the member function to be called
+     */
+    template<typename T>
+    void attach(T* tptr, void (T::*mptr)(void)) {
+        if((mptr != NULL) && (tptr != NULL)) {
+            rx.attach(tptr, mptr);
+        }
+    }
 \r
-    /**\r
-     * Attach a callback called when a packet is received\r
-     *\r
-     * @param fptr function pointer\r
-     */\r
-    void attach(void (*fn)(void)) {\r
-        if(fn != NULL) {\r
-            rx.attach(fn);\r
-        }\r
-    }\r
+    /**
+     * Attach a callback called when a packet is received
+     *
+     * @param fptr function pointer
+     */
+    void attach(void (*fn)(void)) {
+        if(fn != NULL) {
+            rx.attach(fn);
+        }
+    }
 \r
 \r
-protected:\r
-    virtual bool EP2_OUT_callback();\r
+protected:
+    virtual bool EP2_OUT_callback();
 \r
-private:\r
-    FunctionPointer rx;\r
-    CircBuffer<uint8_t> buf;\r
-};\r
+private:
+    FunctionPointer rx;
+    CircBuffer<uint8_t> buf;
+};
 \r
-#endif\r
+#endif
index 7b1cac7..0c3b1bd 100644 (file)
@@ -36,7 +36,7 @@ using std::string;
 #define clear_vector_double(a) memset(a, 0.0, sizeof(a))
 #define max(a,b) (((a) > (b)) ? (a) : (b))
 
-#define dd(...) LPC_GPIO2->FIODIR = 0xffff; LPC_GPIO2->FIOCLR = 0xffff; LPC_GPIO2->FIOSET = __VA_ARGS__ 
+#define dd(...) LPC_GPIO2->FIODIR = 0xffff; LPC_GPIO2->FIOCLR = 0xffff; LPC_GPIO2->FIOSET = __VA_ARGS__
 
 
 #endif
index 8d4ef9a..b2e26b4 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "libs/Kernel.h"
@@ -15,7 +15,7 @@ using std::string;
 
 
 uint16_t get_checksum(string to_check){
-   // From: http://en.wikipedia.org/wiki/Fletcher%27s_checksum 
+   // From: http://en.wikipedia.org/wiki/Fletcher%27s_checksum
    uint16_t sum1 = 0;
    uint16_t sum2 = 0;
    for( unsigned int index = 0; index < to_check.length(); ++index ){
@@ -31,7 +31,7 @@ void get_checksums(uint16_t check_sums[],string key){
     check_sums[1] = 0x0000;
     check_sums[2] = 0x0000;
     size_t begin_key = 0;
-    unsigned int counter = 0; 
+    unsigned int counter = 0;
     while( begin_key < key.size()-1 ){
         size_t end_key =  key.find_first_of(" .", begin_key);
         string key_node = key.substr(begin_key, end_key - begin_key);
@@ -55,7 +55,7 @@ string remove_non_number( string str ){
     size_t found=str.find_first_not_of(number_mask);
     while (found!=string::npos){
         //str[found]='*';
-        str.replace(found,1,""); 
+        str.replace(found,1,"");
         found=str.find_first_not_of(number_mask);
     }
     return str;
@@ -64,7 +64,7 @@ string remove_non_number( string str ){
 // Get the first parameter, and remove it from the original string
 string shift_parameter( string &parameters ){
     size_t beginning = parameters.find_first_of(" ");
-    if( beginning == string::npos ){ string temp = parameters; parameters = ""; return temp; } 
+    if( beginning == string::npos ){ string temp = parameters; parameters = ""; return temp; }
     string temp = parameters.substr( 0, beginning );
     parameters = parameters.substr(beginning+1, parameters.size());
     return temp;
@@ -73,7 +73,7 @@ string shift_parameter( string &parameters ){
 // Separate command from arguments
 string get_arguments( string possible_command ){
     size_t beginning = possible_command.find_first_of(" ");
-    if( beginning == string::npos ){ return ""; } 
+    if( beginning == string::npos ){ return ""; }
     return possible_command.substr( beginning+1, possible_command.size() - beginning);
 }
 
index fca27d2..47b4dab 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "libs/Kernel.h"
@@ -40,7 +40,7 @@ int main() {
     kernel->add_module( new CurrentControl() );
     kernel->add_module( new TemperatureControlPool() );
     kernel->add_module( new SwitchPool() );
-    kernel->add_module( new PauseButton() );   
+    kernel->add_module( new PauseButton() );
     kernel->add_module( new Endstops() );
 
     kernel->add_module( &cdcmsc );
index 53ac77b..6292ffd 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef GCODE_DISPATCH_H
index 778d635..4c33262 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include <string>
@@ -17,12 +17,12 @@ using std::string;
 #include "libs/StreamOutput.h"
 
 // Serial reading module
-// Treats every received line as a command and passes it ( via event call ) to the command dispatcher. 
+// Treats every received line as a command and passes it ( via event call ) to the command dispatcher.
 // The command dispatcher will then ask other modules if they can do something with it
 SerialConsole::SerialConsole( PinName rx_pin, PinName tx_pin, int baud_rate ){
     this->serial = new mbed::Serial( rx_pin, tx_pin );
     this->serial->baud(baud_rate);
-}  
+}
 
 // Called when the module has just been loaded
 void SerialConsole::on_module_loaded() {
@@ -42,7 +42,7 @@ void SerialConsole::on_serial_char_received(){
         char received = this->serial->getc();
         // convert CR to NL (for host OSs that don't send NL)
         if( received == '\r' ){ received = '\n'; }
-        this->buffer.push_back(received); 
+        this->buffer.push_back(received);
     }
 }
         
@@ -54,10 +54,10 @@ void SerialConsole::on_main_loop(void * argument){
            char c;
            this->buffer.pop_front(c);
            if( c == '\n' ){
-                struct SerialMessage message; 
+                struct SerialMessage message;
                 message.message = received;
                 message.stream = this;
-                this->kernel->call_event(ON_CONSOLE_LINE_RECEIVED, &message ); 
+                this->kernel->call_event(ON_CONSOLE_LINE_RECEIVED, &message );
                 return;
             }else{
                 received += c;
@@ -69,7 +69,7 @@ void SerialConsole::on_main_loop(void * argument){
 
 int SerialConsole::printf(const char* format, ...){
     va_list args;
-    int result; 
+    int result;
     va_start (args, format);
     result = vfprintf( this->serial->_file, format, args);
     va_end (args);
index 2104e82..5b29996 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef SERIALCONSOLE_H
index ef4c9a4..0d23625 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 
@@ -41,7 +41,7 @@ double Gcode::get_value( char letter ){
                 if( c != '.' && c != '-' && ( c < '0' || c > '9' ) ){
                     buffer[j-beginning] = '\0';
                     //__enable_irq();
-                    return atof(buffer); 
+                    return atof(buffer);
                 }else{
                     buffer[j-beginning] = c;
                 }
@@ -49,7 +49,7 @@ double Gcode::get_value( char letter ){
          }
     }
     //__enable_irq();
-    return 0; 
+    return 0;
 }
 
 void Gcode::prepare_cached_values(){
index 0966143..b7f579d 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 
index ab2c2fd..fbcd66f 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef BLOCK_H
@@ -26,7 +26,7 @@ class Block {
         double compute_factor_for_safe_speed();
         void calculate_trapezoid( double entry_factor, double exit_factor );
         double estimate_acceleration_distance( double initial_rate, double target_rate, double acceleration );
-        double intersection_distance(double initial_rate, double final_rate, double acceleration, double distance); 
+        double intersection_distance(double initial_rate, double final_rate, double acceleration, double distance);
         void reverse_pass(Block* previous, Block* next);
         void forward_pass(Block* previous, Block* next);
         void debug(Kernel* kernel);
index d987f86..b905acc 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl) with additions from Sungeun K. Jeon (https://github.com/chamnit/grbl)
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 using namespace std;
@@ -14,7 +14,7 @@ using namespace std;
 #include "libs/Kernel.h"
 #include "Block.h"
 #include "Planner.h"
-#include "Player.h" 
+#include "Player.h"
 
 
 Planner::Planner(){
@@ -31,7 +31,7 @@ void Planner::on_module_loaded(){
 void Planner::on_config_reload(void* argument){
     this->acceleration =       this->kernel->config->value(acceleration_checksum       )->by_default(100 )->as_number() * 60 * 60; // Acceleration is in mm/minute^2, see https://github.com/grbl/grbl/commit/9141ad282540eaa50a41283685f901f29c24ddbd#planner.c
     this->max_jerk =           this->kernel->config->value(max_jerk_checksum           )->by_default(100 )->as_number();
-    this->junction_deviation = this->kernel->config->value(junction_deviation_checksum )->by_default(0.05)->as_number(); 
+    this->junction_deviation = this->kernel->config->value(junction_deviation_checksum )->by_default(0.05)->as_number();
 }
 
 
@@ -44,29 +44,29 @@ void Planner::append_block( int target[], double feed_rate, double distance, dou
     this->kernel->player->wait_for_queue(2);
 
     Block* block = this->kernel->player->new_block();
-    block->planner = this;   
+    block->planner = this;
 
     // Direction bits
-    block->direction_bits = 0; 
-    for( int stepper=ALPHA_STEPPER; stepper<=GAMMA_STEPPER; stepper++){ 
-        if( target[stepper] < position[stepper] ){ block->direction_bits |= (1<<stepper); } 
+    block->direction_bits = 0;
+    for( int stepper=ALPHA_STEPPER; stepper<=GAMMA_STEPPER; stepper++){
+        if( target[stepper] < position[stepper] ){ block->direction_bits |= (1<<stepper); }
     }
     
     // Number of steps for each stepper
-    for( int stepper=ALPHA_STEPPER; stepper<=GAMMA_STEPPER; stepper++){ block->steps[stepper] = labs(target[stepper] - this->position[stepper]); } 
+    for( int stepper=ALPHA_STEPPER; stepper<=GAMMA_STEPPER; stepper++){ block->steps[stepper] = labs(target[stepper] - this->position[stepper]); }
     
     // Max number of steps, for all axes
     block->steps_event_count = max( block->steps[ALPHA_STEPPER], max( block->steps[BETA_STEPPER], block->steps[GAMMA_STEPPER] ) );
     //if( block->steps_event_count == 0 ){ this->computing = false; return; }
 
     block->millimeters = distance;
-    double inverse_millimeters = 0; 
+    double inverse_millimeters = 0;
     if( distance > 0 ){ inverse_millimeters = 1.0/distance; }
 
     // Calculate speed in mm/minute for each axis. No divide by zero due to previous checks.
     // NOTE: Minimum stepper speed is limited by MINIMUM_STEPS_PER_MINUTE in stepper.c
     double inverse_minute = feed_rate * inverse_millimeters;
-    if( distance > 0 ){ 
+    if( distance > 0 ){
         block->nominal_speed = block->millimeters * inverse_minute;           // (mm/min) Always > 0
         block->nominal_rate = ceil(block->steps_event_count * inverse_minute); // (step/min) Always > 0
     }else{
@@ -118,7 +118,7 @@ void Planner::append_block( int target[], double feed_rate, double distance, dou
           // Compute maximum junction velocity based on maximum acceleration and junction deviation
           double sin_theta_d2 = sqrt(0.5*(1.0-cos_theta)); // Trig half angle identity. Always positive.
           vmax_junction = min(vmax_junction,
-            sqrt(this->acceleration * this->junction_deviation * sin_theta_d2/(1.0-sin_theta_d2)) ); 
+            sqrt(this->acceleration * this->junction_deviation * sin_theta_d2/(1.0-sin_theta_d2)) );
         }
       }
     }
@@ -147,10 +147,10 @@ void Planner::append_block( int target[], double feed_rate, double distance, dou
     // Update current position
     memcpy(this->position, target, sizeof(int)*3);
 
-    // Math-heavy re-computing of the whole queue to take the new 
+    // Math-heavy re-computing of the whole queue to take the new
     this->recalculate();
     
-    // The block can now be used 
+    // The block can now be used
     block->ready();
 
 }
@@ -202,7 +202,7 @@ void Planner::reverse_pass(){
 // implements the forward pass.
 void Planner::forward_pass() {
     // For each block
-    int block_index = this->kernel->player->queue.head; 
+    int block_index = this->kernel->player->queue.head;
     Block* blocks[3] = {NULL,NULL,NULL};
 
     while(block_index!=this->kernel->player->queue.tail){
@@ -212,8 +212,8 @@ void Planner::forward_pass() {
         if( blocks[0] == NULL ){ continue; }
         blocks[1]->forward_pass(blocks[0],blocks[2]);
         block_index = this->kernel->player->queue.next_block_index( block_index );
-    } 
-    blocks[2]->forward_pass(blocks[1],NULL);   
+    }
+    blocks[2]->forward_pass(blocks[1],NULL);
 
 }
 
@@ -238,7 +238,7 @@ void Planner::recalculate_trapezoids() {
                 current->recalculate_flag = false;
             }
         }
-        block_index = this->kernel->player->queue.next_block_index( block_index ); 
+        block_index = this->kernel->player->queue.next_block_index( block_index );
     }
 
     // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
@@ -252,7 +252,7 @@ void Planner::dump_queue(){
     for( int index = 0; index <= this->kernel->player->queue.size()-1; index++ ){
        if( index > 10 && index < this->kernel->player->queue.size()-10 ){ continue; }
        this->kernel->streams->printf("block %03d > ", index);
-       this->kernel->player->queue.get_ref(index)->debug(this->kernel); 
+       this->kernel->player->queue.get_ref(index)->debug(this->kernel);
     }
 }
 
index 20fb7c3..f3fbc15 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef PLANNER_H
@@ -13,9 +13,9 @@
 #include "../communication/utils/Gcode.h"
 #include "Block.h"
 
-#define acceleration_checksum       25326  
-#define max_jerk_checksum           61012 
-#define junction_deviation_checksum 6035 
+#define acceleration_checksum       25326
+#define max_jerk_checksum           61012
+#define junction_deviation_checksum 6035
 
 // TODO: Get from config
 #define MINIMUM_PLANNER_SPEED 0.0
@@ -32,7 +32,7 @@ class Planner : public Module {
         void forward_pass();
         void recalculate_trapezoids();
         void dump_queue();
-        Block* get_current_block(); 
+        Block* get_current_block();
         void cleanup_queue();
         void on_module_loaded();
         void on_config_reload(void* argument);
index fa6d535..b07a3b3 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl) with additions from Sungeun K. Jeon (https://github.com/chamnit/grbl)
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 using namespace std;
@@ -32,14 +32,14 @@ Block* Player::new_block(){
     
     // Take the next untaken block on the queue ( the one after the last one )
     Block* block = this->queue.get_ref( this->queue.size() );
-    // Then clean it up 
+    // Then clean it up
     if( block->player == this ){
         for(unsigned int index=0; index<block->gcodes.size(); index++){
-            block->gcodes.pop_back(); 
-        }     
+            block->gcodes.pop_back();
+        }
     }
     
-    // Create a new virgin Block in the queue 
+    // Create a new virgin Block in the queue
     this->queue.push_back(Block());
     block = this->queue.get_ref( this->queue.size()-1 );
     while( block == NULL ){
@@ -67,12 +67,12 @@ void Player::pop_and_process_new_block(int debug){
 
     if( this->current_block != NULL ){ this->looking_for_new_block = false; return; }
 
-    // Return if queue is empty 
+    // Return if queue is empty
     if( this->queue.size() == 0 ){
-        this->current_block = NULL; 
-        // TODO : ON_QUEUE_EMPTY event 
+        this->current_block = NULL;
+        // TODO : ON_QUEUE_EMPTY event
         this->looking_for_new_block = false;
-        return; 
+        return;
     }
     
     // Get a new block
index 6f998f6..f28eee2 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef PLAYER_H
index 1b731a4..054a014 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl) with additions from Sungeun K. Jeon (https://github.com/chamnit/grbl)
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "libs/Module.h"
@@ -23,10 +23,10 @@ using std::string;
 Robot::Robot(){
     this->inch_mode = false;
     this->absolute_mode = true;
-    this->motion_mode =  MOTION_MODE_SEEK; 
+    this->motion_mode =  MOTION_MODE_SEEK;
     this->select_plane(X_AXIS, Y_AXIS, Z_AXIS);
     clear_vector(this->current_position);
-    clear_vector(this->last_milestone); 
+    clear_vector(this->last_milestone);
 }
 
 //Called when the module has just been loaded
@@ -38,14 +38,14 @@ void Robot::on_module_loaded() {
     this->on_config_reload(this);
 
     // Make our 3 StepperMotors
-    this->alpha_stepper_motor  = this->kernel->step_ticker->add_stepper_motor( new StepperMotor(this->alpha_step_pin,this->alpha_dir_pin,this->alpha_en_pin) );   
-    this->beta_stepper_motor   = this->kernel->step_ticker->add_stepper_motor( new StepperMotor(this->beta_step_pin, this->beta_dir_pin, this->beta_en_pin ) );   
-    this->gamma_stepper_motor  = this->kernel->step_ticker->add_stepper_motor( new StepperMotor(this->gamma_step_pin,this->gamma_dir_pin,this->gamma_en_pin) );   
+    this->alpha_stepper_motor  = this->kernel->step_ticker->add_stepper_motor( new StepperMotor(this->alpha_step_pin,this->alpha_dir_pin,this->alpha_en_pin) );
+    this->beta_stepper_motor   = this->kernel->step_ticker->add_stepper_motor( new StepperMotor(this->beta_step_pin, this->beta_dir_pin, this->beta_en_pin ) );
+    this->gamma_stepper_motor  = this->kernel->step_ticker->add_stepper_motor( new StepperMotor(this->gamma_step_pin,this->gamma_dir_pin,this->gamma_en_pin) );
 
 }
 
 void Robot::on_config_reload(void* argument){
-    this->feed_rate =           this->kernel->config->value(default_feed_rate_checksum  )->by_default(100)->as_number()/60; 
+    this->feed_rate =           this->kernel->config->value(default_feed_rate_checksum  )->by_default(100)->as_number()/60;
     this->seek_rate =           this->kernel->config->value(default_seek_rate_checksum  )->by_default(100)->as_number()/60;
     this->mm_per_line_segment = this->kernel->config->value(mm_per_line_segment_checksum)->by_default(0.1)->as_number();
     this->mm_per_arc_segment  = this->kernel->config->value(mm_per_arc_segment_checksum )->by_default(10 )->as_number();
@@ -68,15 +68,15 @@ void Robot::on_config_reload(void* argument){
 //A GCode has been received
 void Robot::on_gcode_received(void * argument){
     Gcode* gcode = static_cast<Gcode*>(argument);
-    gcode->call_on_gcode_execute_event_immediatly = false; 
+    gcode->call_on_gcode_execute_event_immediatly = false;
     gcode->on_gcode_execute_event_called = false;
     //If the queue is empty, execute immediatly, otherwise attach to the last added block
     if( this->kernel->player->queue.size() == 0 ){
         gcode->call_on_gcode_execute_event_immediatly = true;
         this->execute_gcode(gcode);
         if( gcode->on_gcode_execute_event_called == false ){
-            //printf("GCODE A: %s \r\n", gcode->command.c_str() ); 
-            this->kernel->call_event(ON_GCODE_EXECUTE, gcode ); 
+            //printf("GCODE A: %s \r\n", gcode->command.c_str() );
+            this->kernel->call_event(ON_GCODE_EXECUTE, gcode );
         }
     }else{
         Block* block = this->kernel->player->queue.get_ref( this->kernel->player->queue.size() - 1 );
@@ -108,17 +108,17 @@ void Robot::execute_gcode(Gcode* gcode){
            case 21:this->inch_mode = false; break;
            case 90:this->absolute_mode = true; break;
            case 91:this->absolute_mode = false; break;
-       } 
+       }
     }else{ return; }
     
    //Get parameters
     double target[3], offset[3];
-    clear_vector(target); clear_vector(offset); 
+    clear_vector(target); clear_vector(offset);
     
     memcpy(target, this->current_position, sizeof(target));    //default to last target
     
-    for(char letter = 'I'; letter <= 'K'; letter++){ if( gcode->has_letter(letter) ){ offset[letter-'I'] = this->to_millimeters(gcode->get_value(letter));                                                    } }     
-    for(char letter = 'X'; letter <= 'Z'; letter++){ if( gcode->has_letter(letter) ){ target[letter-'X'] = this->to_millimeters(gcode->get_value(letter)) + ( this->absolute_mode ? 0 : target[letter-'X']);  } }     
+    for(char letter = 'I'; letter <= 'K'; letter++){ if( gcode->has_letter(letter) ){ offset[letter-'I'] = this->to_millimeters(gcode->get_value(letter));                                                    } }
+    for(char letter = 'X'; letter <= 'Z'; letter++){ if( gcode->has_letter(letter) ){ target[letter-'X'] = this->to_millimeters(gcode->get_value(letter)) + ( this->absolute_mode ? 0 : target[letter-'X']);  } }
     
     if( gcode->has_letter('F') ){ if( this->motion_mode == MOTION_MODE_SEEK ){ this->seek_rate = this->to_millimeters( gcode->get_value('F') ) / 60; }else{ this->feed_rate = this->to_millimeters( gcode->get_value('F') ) / 60; } }
    
@@ -129,7 +129,7 @@ void Robot::execute_gcode(Gcode* gcode){
                 case MOTION_MODE_CANCEL: break;
                 case MOTION_MODE_SEEK  : this->append_line(gcode, target, this->seek_rate ); break;
                 case MOTION_MODE_LINEAR: this->append_line(gcode, target, this->feed_rate ); break;
-                case MOTION_MODE_CW_ARC: case MOTION_MODE_CCW_ARC: this->compute_arc(gcode, offset, target ); break; 
+                case MOTION_MODE_CW_ARC: case MOTION_MODE_CCW_ARC: this->compute_arc(gcode, offset, target ); break;
             }
             break;
     }
@@ -137,7 +137,7 @@ void Robot::execute_gcode(Gcode* gcode){
     // As far as the parser is concerned, the position is now == target. In reality the
     // motion control system might still be processing the action and the real tool position
     // in any intermediate location.
-    memcpy(this->current_position, target, sizeof(double)*3); // this->position[] = target[]; 
+    memcpy(this->current_position, target, sizeof(double)*3); // this->position[] = target[];
 
 }
 
@@ -151,54 +151,54 @@ void Robot::append_milestone( double target[], double rate ){
     for(int axis=X_AXIS;axis<=Z_AXIS;axis++){deltas[axis]=target[axis]-this->last_milestone[axis];}
 
     
-    double millimeters_of_travel = sqrt( pow( deltas[X_AXIS], 2 ) +  pow( deltas[Y_AXIS], 2 ) +  pow( deltas[Z_AXIS], 2 ) );      
+    double millimeters_of_travel = sqrt( pow( deltas[X_AXIS], 2 ) +  pow( deltas[Y_AXIS], 2 ) +  pow( deltas[Z_AXIS], 2 ) );
     
     double duration = 0;
     if( rate > 0 ){ duration = millimeters_of_travel / rate; }
 
     for(int axis=X_AXIS;axis<=Z_AXIS;axis++){
-        if( this->max_speeds[axis] > 0 ){ 
-            double axis_speed = ( fabs(deltas[axis]) / ( millimeters_of_travel / rate )) * 60; 
-            if( axis_speed > this->max_speeds[axis] ){ 
-                rate = rate * ( this->max_speeds[axis] / axis_speed ); 
+        if( this->max_speeds[axis] > 0 ){
+            double axis_speed = ( fabs(deltas[axis]) / ( millimeters_of_travel / rate )) * 60;
+            if( axis_speed > this->max_speeds[axis] ){
+                rate = rate * ( this->max_speeds[axis] / axis_speed );
             }
         }
     }
 
-    this->kernel->planner->append_block( steps, rate*60, millimeters_of_travel, deltas ); 
+    this->kernel->planner->append_block( steps, rate*60, millimeters_of_travel, deltas );
 
-    memcpy(this->last_milestone, target, sizeof(double)*3); // this->last_milestone[] = target[]; 
+    memcpy(this->last_milestone, target, sizeof(double)*3); // this->last_milestone[] = target[];
 
 }
 
 void Robot::append_line(Gcode* gcode, double target[], double rate ){
 
 
-    // We cut the line into smaller segments. This is not usefull in a cartesian robot, but necessary for robots with rotational axes. 
+    // We cut the line into smaller segments. This is not usefull in a cartesian robot, but necessary for robots with rotational axes.
     // In cartesian robot, a high "mm_per_line_segment" setting will prevent waste.
-    gcode->millimeters_of_travel = sqrt( pow( target[X_AXIS]-this->current_position[X_AXIS], 2 ) +  pow( target[Y_AXIS]-this->current_position[Y_AXIS], 2 ) +  pow( target[Z_AXIS]-this->current_position[Z_AXIS], 2 ) ); 
+    gcode->millimeters_of_travel = sqrt( pow( target[X_AXIS]-this->current_position[X_AXIS], 2 ) +  pow( target[Y_AXIS]-this->current_position[Y_AXIS], 2 ) +  pow( target[Z_AXIS]-this->current_position[Z_AXIS], 2 ) );
 
     if( gcode->call_on_gcode_execute_event_immediatly == true ){
-            //printf("GCODE B: %s \r\n", gcode->command.c_str() ); 
-            this->kernel->call_event(ON_GCODE_EXECUTE, gcode ); 
+            //printf("GCODE B: %s \r\n", gcode->command.c_str() );
+            this->kernel->call_event(ON_GCODE_EXECUTE, gcode );
             gcode->on_gcode_execute_event_called = true;
     }
 
-    if (gcode->millimeters_of_travel == 0.0) { 
+    if (gcode->millimeters_of_travel == 0.0) {
         this->append_milestone(this->current_position, 0.0);
-        return; 
+        return;
     }
 
-    uint16_t segments = ceil( gcode->millimeters_of_travel/ this->mm_per_line_segment); 
+    uint16_t segments = ceil( gcode->millimeters_of_travel/ this->mm_per_line_segment);
     // A vector to keep track of the endpoint of each segment
     double temp_target[3];
     //Initialize axes
-    memcpy( temp_target, this->current_position, sizeof(double)*3); // temp_target[] = this->current_position[];  
+    memcpy( temp_target, this->current_position, sizeof(double)*3); // temp_target[] = this->current_position[];
 
     //For each segment
     for( int i=0; i<segments-1; i++ ){
-        for(int axis=X_AXIS; axis <= Z_AXIS; axis++ ){ temp_target[axis] += ( target[axis]-this->current_position[axis] )/segments; }        
-        this->append_milestone(temp_target, rate); 
+        for(int axis=X_AXIS; axis <= Z_AXIS; axis++ ){ temp_target[axis] += ( target[axis]-this->current_position[axis] )/segments; }
+        this->append_milestone(temp_target, rate);
     }
     this->append_milestone(target, rate);
 }
@@ -222,14 +222,14 @@ void Robot::append_arc(Gcode* gcode, double target[], double offset[], double ra
     gcode->millimeters_of_travel = hypot(angular_travel*radius, fabs(linear_travel));
 
     if( gcode->call_on_gcode_execute_event_immediatly == true ){
-            //printf("GCODE C: %s \r\n", gcode->command.c_str() ); 
-            this->kernel->call_event(ON_GCODE_EXECUTE, gcode ); 
+            //printf("GCODE C: %s \r\n", gcode->command.c_str() );
+            this->kernel->call_event(ON_GCODE_EXECUTE, gcode );
             gcode->on_gcode_execute_event_called = true;
     }
 
-    if (gcode->millimeters_of_travel == 0.0) { 
+    if (gcode->millimeters_of_travel == 0.0) {
         this->append_milestone(this->current_position, 0.0);
-        return; 
+        return;
     }
  
     uint16_t segments = floor(gcode->millimeters_of_travel/this->mm_per_arc_segment);
@@ -311,7 +311,7 @@ void Robot::compute_arc(Gcode* gcode, double offset[], double target[]){
 
     // Set clockwise/counter-clockwise sign for mc_arc computations
     bool is_clockwise = false;
-    if( this->motion_mode == MOTION_MODE_CW_ARC ){ is_clockwise = true; } 
+    if( this->motion_mode == MOTION_MODE_CW_ARC ){ is_clockwise = true; }
 
     // Append arc
     this->append_arc(gcode, target, offset,  radius, is_clockwise );
@@ -321,7 +321,7 @@ void Robot::compute_arc(Gcode* gcode, double offset[], double target[]){
 
 // Convert from inches to millimeters ( our internal storage unit ) if needed
 inline double Robot::to_millimeters( double value ){
-        return this->inch_mode ? value/25.4 : value; 
+        return this->inch_mode ? value/25.4 : value;
 }
 
 double Robot::theta(double x, double y){
index 4673821..f3d2ecd 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef ROBOT_H
index a4b3bd3..55e0d6c 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef STEPPER_H
@@ -22,9 +22,9 @@
 #define alpha_dir_pin_checksum                      55887
 #define beta_dir_pin_checksum                       28644
 #define gamma_dir_pin_checksum                      46412
-#define alpha_en_pin_checksum                       35042  
-#define beta_en_pin_checksum                        34680 
-#define gamma_en_pin_checksum                       26335 
+#define alpha_en_pin_checksum                       35042
+#define beta_en_pin_checksum                        34680
+#define gamma_en_pin_checksum                       26335
 
 
 class Stepper : public Module {
@@ -49,18 +49,18 @@ class Stepper : public Module {
 
         Block* current_block;
         int counters[3];
-        int stepped[3]; 
-        int offsets[3]; 
+        int stepped[3];
+        int offsets[3];
         float counter_alpha;
         float counter_beta;
         float counter_gamma;
-        //int step_events_completed; 
-        unsigned int out_bits; 
+        //int step_events_completed;
+        unsigned int out_bits;
         double trapezoid_adjusted_rate;
         int trapezoid_tick_cycle_counter;
-        int cycles_per_step_event; 
+        int cycles_per_step_event;
         bool trapezoid_generator_busy;
-        int microseconds_per_step_pulse; 
+        int microseconds_per_step_pulse;
         int acceleration_ticks_per_second;
         int minimum_steps_per_minute;
         int base_stepping_frequency;
index 028822c..fb2a1e6 100644 (file)
@@ -3,4 +3,4 @@
 BaseSolution::BaseSolution(){}
 
 void BaseSolution::millimeters_to_steps( double millimeters[], int steps[] ){}
-void BaseSolution::steps_to_millimeters( int steps[], double millimeters[] ){} 
+void BaseSolution::steps_to_millimeters( int steps[], double millimeters[] ){}
index 46a8d14..edb22b2 100644 (file)
@@ -6,7 +6,7 @@ class BaseSolution {
     public:
         BaseSolution();
         virtual void millimeters_to_steps( double millimeters[], int steps[] );
-        virtual void steps_to_millimeters( int steps[], double millimeters[] ); 
+        virtual void steps_to_millimeters( int steps[], double millimeters[] );
 };
 
 #endif
index 97eabf9..c7183f8 100644 (file)
@@ -13,4 +13,4 @@ void CartesianSolution::millimeters_to_steps( double millimeters[], int steps[]
     steps[GAMMA_STEPPER] = lround( millimeters[Z_AXIS] * this->gamma_steps_per_mm );
 }
 
-void CartesianSolution::steps_to_millimeters( int steps[], double millimeters[] ){} 
+void CartesianSolution::steps_to_millimeters( int steps[], double millimeters[] ){}
index c133400..3dc9b9e 100644 (file)
@@ -15,7 +15,7 @@ class CartesianSolution : public BaseSolution {
     public:
         CartesianSolution(Config* passed_config);
         void millimeters_to_steps( double millimeters[], int steps[] );
-        void steps_to_millimeters( int steps[], double millimeters[] ); 
+        void steps_to_millimeters( int steps[], double millimeters[] );
 
         Config* config;
         double alpha_steps_per_mm;
index 45187c1..039c085 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "libs/Module.h"
@@ -53,7 +53,7 @@ void Endstops::on_gcode_received(void* argument){
     Gcode* gcode = static_cast<Gcode*>(argument);
     if( gcode->has_g){
         if( gcode->g == 28 ){
-            // G28 is received, we have homing to do  
+            // G28 is received, we have homing to do
 
             // First wait for the queue to be empty
             while(this->kernel->player->queue.size() > 0) { wait_us(500); }
@@ -62,28 +62,28 @@ void Endstops::on_gcode_received(void* argument){
             char axes_to_move = ( ( gcode->has_letter('X') || gcode->has_letter('Y') || gcode->has_letter('Z') ) ? 0x00 : 0xff );
             for( char c = 'X'; c <= 'Z'; c++ ){
                 if( gcode->has_letter(c) && this->pins[c - 'X']->connected() ){ axes_to_move += ( 1 << (c - 'X' ) ); }
-            } 
+            }
 
             // Start moving the axes to the origin
-            this->status = MOVING_TO_ORIGIN_FAST; 
+            this->status = MOVING_TO_ORIGIN_FAST;
             for( char c = 'X'; c <= 'Z'; c++ ){
                 if( ( axes_to_move >> ( c - 'X' ) ) & 1 ){
-                    this->steppers[c - 'X']->move(0,10000000); 
-                    this->steppers[c - 'X']->set_speed(this->fast_rates[c -'X']); 
+                    this->steppers[c - 'X']->move(0,10000000);
+                    this->steppers[c - 'X']->set_speed(this->fast_rates[c -'X']);
                 }
             }
 
             // Wait for all axes to have homed
             bool running = true;
             while(running){
-                running = false; 
+                running = false;
                 for( char c = 'X'; c <= 'Z'; c++ ){
                     if( ( axes_to_move >> ( c - 'X' ) ) & 1 ){
                          if( this->pins[c - 'X']->get() ){
                             // The endstop was hit, stop moving
-                            if( this->steppers[c - 'X']->moving ){ 
-                                this->steppers[c - 'X']->move(0,0); 
-                            }  
+                            if( this->steppers[c - 'X']->moving ){
+                                this->steppers[c - 'X']->move(0,0);
+                            }
                         }else{
                             // The endstop was not hit yet
                             running = true;
@@ -95,18 +95,18 @@ void Endstops::on_gcode_received(void* argument){
 
             printf("test a\r\n");
             // Move back a small distance
-            this->status = MOVING_BACK; 
+            this->status = MOVING_BACK;
             for( char c = 'X'; c <= 'Z'; c++ ){
                 if( ( axes_to_move >> ( c - 'X' ) ) & 1 ){
-                    this->steppers[c - 'X']->move(1,this->retract_steps[c - 'X']); 
-                    this->steppers[c - 'X']->set_speed(this->slow_rates[c - 'X']); 
+                    this->steppers[c - 'X']->move(1,this->retract_steps[c - 'X']);
+                    this->steppers[c - 'X']->set_speed(this->slow_rates[c - 'X']);
                 }
             }
 
             printf("test b\r\n");
             // Wait for moves to be done
             for( char c = 'X'; c <= 'Z'; c++ ){
-                if(  ( axes_to_move >> ( c - 'X' ) ) & 1 ){ 
+                if(  ( axes_to_move >> ( c - 'X' ) ) & 1 ){
                     printf("axis %c \r\n", c );
                     while( this->steppers[c - 'X']->moving ){ }
                 }
@@ -115,25 +115,25 @@ void Endstops::on_gcode_received(void* argument){
             printf("test c\r\n");
 
             // Start moving the axes to the origin slowly
-            this->status = MOVING_TO_ORIGIN_SLOW; 
+            this->status = MOVING_TO_ORIGIN_SLOW;
             for( char c = 'X'; c <= 'Z'; c++ ){
                 if( ( axes_to_move >> ( c - 'X' ) ) & 1 ){
-                    this->steppers[c - 'X']->move(0,10000000); 
-                    this->steppers[c - 'X']->set_speed(this->slow_rates[c -'X']); 
+                    this->steppers[c - 'X']->move(0,10000000);
+                    this->steppers[c - 'X']->set_speed(this->slow_rates[c -'X']);
                 }
             }
 
             // Wait for all axes to have homed
             running = true;
             while(running){
-                running = false; 
+                running = false;
                 for( char c = 'X'; c <= 'Z'; c++ ){
                     if( ( axes_to_move >> ( c - 'X' ) ) & 1 ){
                          if( this->pins[c - 'X']->get() ){
                             // The endstop was hit, stop moving
-                            if( this->steppers[c - 'X']->moving ){ 
-                                this->steppers[c - 'X']->move(0,0); 
-                            }  
+                            if( this->steppers[c - 'X']->moving ){
+                                this->steppers[c - 'X']->move(0,0);
+                            }
                         }else{
                             // The endstop was not hit yet
                             running = true;
index 0e37095..9db4a2b 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef ENDSTOPS_MODULE_H
 #define MOVING_BACK 2
 #define MOVING_TO_ORIGIN_SLOW 3
 
-#define alpha_min_endstop_checksum       28684 
-#define beta_min_endstop_checksum        23457  
-#define gamma_min_endstop_checksum       16137 
-#define alpha_fast_homing_rate_checksum  19720 
+#define alpha_min_endstop_checksum       28684
+#define beta_min_endstop_checksum        23457
+#define gamma_min_endstop_checksum       16137
+#define alpha_fast_homing_rate_checksum  19720
 #define beta_fast_homing_rate_checksum   9373
-#define gamma_fast_homing_rate_checksum  3333  
-#define alpha_slow_homing_rate_checksum  45599  
-#define beta_slow_homing_rate_checksum   35252 
+#define gamma_fast_homing_rate_checksum  3333
+#define alpha_slow_homing_rate_checksum  45599
+#define beta_slow_homing_rate_checksum   35252
 #define gamma_slow_homing_rate_checksum  29212
 #define alpha_homing_retract_checksum    4419
-#define beta_homing_retract_checksum     48344 
+#define beta_homing_retract_checksum     48344
 #define gamma_homing_retract_checksum    54848
 
 
index 7c6ff20..4a6d1ad 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "libs/Module.h"
@@ -39,14 +39,14 @@ void Switch::on_gcode_execute(void* argument){
     Gcode* gcode = static_cast<Gcode*>(argument);
     if( gcode->has_letter('M' )){
         int code = gcode->get_value('M');
-        if( code == this->on_m_code ){  
+        if( code == this->on_m_code ){
             // Turn pin on
             this->output_pin->set(1);
-        } 
-        if( code == this->off_m_code ){ 
-            // Turn pin off 
+        }
+        if( code == this->off_m_code ){
+            // Turn pin off
             this->output_pin->set(0);
-        } 
+        }
     }
 }
 
index 2d3a2e0..c7008b8 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       this file is part of smoothie (http://smoothieware.org/). the motion control part is heavily based on grbl (https://github.com/simen/grbl).
       smoothie is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version.
       smoothie is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details.
-      you should have received a copy of the gnu general public license along with smoothie. if not, see <http://www.gnu.org/licenses/>. 
+      you should have received a copy of the gnu general public license along with smoothie. if not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef SWITCH_H
 #include "libs/Pin.h"
 #include <math.h>
 
-#define    switch_checksum            15508 
-#define    on_m_code_checksum         29094 
-#define    off_m_code_checksum        14853 
-#define    output_pin_checksum        18779 
-#define    startup_state_checksum     37528 
+#define    switch_checksum            15508
+#define    on_m_code_checksum         29094
+#define    off_m_code_checksum        14853
+#define    output_pin_checksum        18779
+#define    startup_state_checksum     37528
 
 class Switch : public Module {
     public:
index 9485158..5f4ab11 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "libs/Module.h"
@@ -24,7 +24,7 @@ void SwitchPool::on_module_loaded(){
         // If module is enabled
         if( this->kernel->config->value(switch_checksum, modules[i], enable_checksum )->as_bool() == true ){
             Switch* controller = new Switch(modules[i]);
-            this->kernel->add_module(controller); 
+            this->kernel->add_module(controller);
             this->controllers.push_back( controller );
         }
     }
index 52c4552..01f629e 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       this file is part of smoothie (http://smoothieware.org/). the motion control part is heavily based on grbl (https://github.com/simen/grbl).
       smoothie is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version.
       smoothie is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details.
-      you should have received a copy of the gnu general public license along with smoothie. if not, see <http://www.gnu.org/licenses/>. 
+      you should have received a copy of the gnu general public license along with smoothie. if not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef SWITCHPOOL_H
@@ -13,7 +13,7 @@
 using namespace std;
 #include <vector>
 
-#define switch_checksum              15508 
+#define switch_checksum              15508
 #define enable_checksum              29545
 
 class SwitchPool : public Module {
index 735bab1..9ca55ac 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 // TODO : THIS FILE IS LAME, MUST BE MADE MUCH BETTER
@@ -17,7 +17,7 @@ TemperatureControl::TemperatureControl(){}
 
 TemperatureControl::TemperatureControl(uint16_t name){
     this->name_checksum = name;
-    this->error_count = 0; 
+    this->error_count = 0;
     this->waiting = false;
 }
 
@@ -34,8 +34,8 @@ void TemperatureControl::on_module_loaded(){
     this->kernel->slow_ticker->attach( 20, this, &TemperatureControl::thermistor_read_tick );
 
     // Register for events
-    this->register_for_event(ON_GCODE_EXECUTE); 
-    this->register_for_event(ON_MAIN_LOOP); 
+    this->register_for_event(ON_GCODE_EXECUTE);
+    this->register_for_event(ON_MAIN_LOOP);
 
 }
 
@@ -60,7 +60,7 @@ void TemperatureControl::on_config_reload(void* argument){
     this->r2   = 4700;
 
     // Preset values for various common types of thermistors
-    ConfigValue* thermistor = this->kernel->config->value(temperature_control_checksum, this->name_checksum, thermistor_checksum);    
+    ConfigValue* thermistor = this->kernel->config->value(temperature_control_checksum, this->name_checksum, thermistor_checksum);
     if(       thermistor->value.compare("EPCOS100K"    ) == 0 ){ // Default
     }else if( thermistor->value.compare("RRRF100K"     ) == 0 ){ this->beta = 3960;
     }else if( thermistor->value.compare("RRRF10K"      ) == 0 ){ this->beta = 3964; this->r0 = 10000; this->r1 = 680; this->r2 = 1600;
@@ -76,9 +76,9 @@ void TemperatureControl::on_config_reload(void* argument){
     this->r1 =                  this->kernel->config->value(temperature_control_checksum, this->name_checksum, r1_checksum  )->by_default(0     )->as_number();
     this->r2 =                  this->kernel->config->value(temperature_control_checksum, this->name_checksum, r2_checksum  )->by_default(4700  )->as_number();
     
-    // Thermistor math 
+    // Thermistor math
     this->k = this->r0 * exp( -this->beta / this->t0 );
-    if( r1 > 0 ){ this->vs = r1 * this->vcc / ( r1 + r2 ); this->rs = r1 * r2 / ( r1 + r2 ); }else{ this->vs = this->vcc; this->rs = r2; } 
+    if( r1 > 0 ){ this->vs = r1 * this->vcc / ( r1 + r2 ); this->rs = r1 * r2 / ( r1 + r2 ); }else{ this->vs = this->vcc; this->rs = r2; }
 
     // Thermistor pin for ADC readings
     this->thermistor_pin = this->kernel->config->value(temperature_control_checksum, this->name_checksum, thermistor_pin_checksum )->required()->as_pin();
@@ -100,20 +100,20 @@ void TemperatureControl::on_gcode_execute(void* argument){
         // Set temperature without waiting
         if( gcode->m == this->set_m_code && gcode->has_letter('S') ){
             //gcode->stream->printf("setting to %f meaning %u  \r\n", gcode->get_value('S'), this->temperature_to_adc_value( gcode->get_value('S') ) );
-            this->set_desired_temperature(gcode->get_value('S')); 
-        } 
+            this->set_desired_temperature(gcode->get_value('S'));
+        }
         // Set temperature and wait
         if( gcode->m == this->set_and_wait_m_code && gcode->has_letter('S') ){
             this->set_desired_temperature(gcode->get_value('S'));
-            // Pause 
-            this->kernel->pauser->take(); 
-            this->waiting = true; 
-        } 
+            // Pause
+            this->kernel->pauser->take();
+            this->waiting = true;
+        }
         // Get temperature
         if( gcode->m == this->get_m_code ){
             gcode->stream->printf("get temperature: %f current:%f target:%f bare_value:%u \r\n", this->get_temperature(), this->new_thermistor_reading(), this->desired_adc_value, this->kernel->adc->read(this->thermistor_pin)  );
         }
-    } 
+    }
 }
 
 //#pragma GCC pop_options
@@ -134,7 +134,7 @@ double TemperatureControl::adc_value_to_temperature(double adc_value){
 }
 
 double TemperatureControl::temperature_to_adc_value(double temperature){
-    double r = this->r0 * exp( this->beta * ( 1 / (temperature + 273.15) -1 / this->t0 ) ); // Resistance of the thermistor 
+    double r = this->r0 * exp( this->beta * ( 1 / (temperature + 273.15) -1 / this->t0 ) ); // Resistance of the thermistor
     double v = this->vs * r / ( this->rs + r );                                             // Voltage at the potential divider
     return v / this->vadc * 1.00000;                                               // The ADC reading
 }
@@ -142,12 +142,12 @@ double TemperatureControl::temperature_to_adc_value(double temperature){
 uint32_t TemperatureControl::thermistor_read_tick(uint32_t dummy){
     if( this->desired_adc_value != UNDEFINED ){
         if( this->new_thermistor_reading() > this->desired_adc_value ){
-            this->heater_pin->set(1); 
+            this->heater_pin->set(1);
         }else{
-            this->heater_pin->set(0); 
-            if( this->waiting ){ 
+            this->heater_pin->set(0);
+            if( this->waiting ){
                 this->kernel->pauser->release();
-                this->waiting = false; 
+                this->waiting = false;
             }
         }
     }
@@ -163,19 +163,19 @@ double TemperatureControl::new_thermistor_reading(){
         return new_reading;
     }else{
         double current_temp = this->average_adc_reading();
-        double error = fabs(new_reading - current_temp); 
+        double error = fabs(new_reading - current_temp);
         if( error < 0.1 ){
             this->error_count = 0;
             double test;
-            this->queue.pop_front(test); 
+            this->queue.pop_front(test);
             this->queue.push_back( new_reading );
         }else{
             this->error_count++;
             if( this->error_count > 4 ){
                 double test;
-                this->queue.pop_front(test); 
+                this->queue.pop_front(test);
             }
-        } 
+        }
         return current_temp;
     }
 }
index a823a2b..ca776fd 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       this file is part of smoothie (http://smoothieware.org/). the motion control part is heavily based on grbl (https://github.com/simen/grbl).
       smoothie is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version.
       smoothie is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details.
-      you should have received a copy of the gnu general public license along with smoothie. if not, see <http://www.gnu.org/licenses/>. 
+      you should have received a copy of the gnu general public license along with smoothie. if not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef temperaturecontrol_h
@@ -15,7 +15,7 @@
 
 #define thermistor_checksum                41045
 #define r0_checksum                        5538
-#define readings_per_second_checksum       18645 
+#define readings_per_second_checksum       18645
 #define t0_checksum                        6564
 #define beta_checksum                      1181
 #define vadc_checksum                      10911
 #define r1_checksum                        5795
 #define r2_checksum                        6052
 #define temperature_control_checksum       44054
-#define thermistor_pin_checksum            1788 
-#define heater_pin_checksum                35619 
+#define thermistor_pin_checksum            1788
+#define heater_pin_checksum                35619
 
-#define get_m_code_checksum                20746 
-#define set_m_code_checksum                51478 
-#define set_and_wait_m_code_checksum       4287 
+#define get_m_code_checksum                20746
+#define set_m_code_checksum                51478
+#define set_and_wait_m_code_checksum       4287
 
 
 class TemperatureControl : public Module {
index 0a5fe34..fdad1cc 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "libs/Module.h"
@@ -24,7 +24,7 @@ void TemperatureControlPool::on_module_loaded(){
         // If module is enabled
         if( this->kernel->config->value(temperature_control_checksum, modules[i], enable_checksum )->as_bool() == true ){
             TemperatureControl* controller = new TemperatureControl(modules[i]);
-            this->kernel->add_module(controller); 
+            this->kernel->add_module(controller);
             this->controllers.push_back( controller );
         }
     }
index 6c52f69..28d663c 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       this file is part of smoothie (http://smoothieware.org/). the motion control part is heavily based on grbl (https://github.com/simen/grbl).
       smoothie is free software: you can redistribute it and/or modify it under the terms of the gnu general public license as published by the free software foundation, either version 3 of the license, or (at your option) any later version.
       smoothie is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. see the gnu general public license for more details.
-      you should have received a copy of the gnu general public license along with smoothie. if not, see <http://www.gnu.org/licenses/>. 
+      you should have received a copy of the gnu general public license along with smoothie. if not, see <http://www.gnu.org/licenses/>.
 */
 
 #ifndef TEMPERATURECONTROLPOOL_H
index c8c7fa4..1cbc112 100644 (file)
@@ -2,7 +2,7 @@
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 
index 3805b3b..b0214d5 100644 (file)
@@ -2,7 +2,7 @@
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 
@@ -33,8 +33,8 @@ class Configurator : public Module {
         void on_gcode_received( void* argument );
         void on_main_loop( void* argument );
 
-        void config_get_command( string parameters, StreamOutput* stream ); 
-        void config_set_command( string parameters, StreamOutput* stream ); 
+        void config_get_command( string parameters, StreamOutput* stream );
+        void config_set_command( string parameters, StreamOutput* stream );
         void config_load_command(string parameters, StreamOutput* stream );
 };
 
index 64e6bc9..d478e94 100644 (file)
@@ -8,12 +8,12 @@ using namespace std;
 CurrentControl::CurrentControl(){}
 
 void CurrentControl::on_module_loaded(){
-    if( !this->kernel->config->value( currentcontrol_module_enable_checksum )->by_default(false)->as_bool() ){ return; } 
+    if( !this->kernel->config->value( currentcontrol_module_enable_checksum )->by_default(false)->as_bool() ){ return; }
 
     // Get configuration
-    this->alpha_current =           this->kernel->config->value(alpha_current_checksum  )->by_default(0.8)->as_number(); 
-    this->beta_current  =           this->kernel->config->value(beta_current_checksum   )->by_default(0.8)->as_number(); 
-    this->gamma_current =           this->kernel->config->value(gamma_current_checksum  )->by_default(0.8)->as_number(); 
+    this->alpha_current =           this->kernel->config->value(alpha_current_checksum  )->by_default(0.8)->as_number();
+    this->beta_current  =           this->kernel->config->value(beta_current_checksum   )->by_default(0.8)->as_number();
+    this->gamma_current =           this->kernel->config->value(gamma_current_checksum  )->by_default(0.8)->as_number();
     this->delta_current =           this->kernel->config->value(delta_current_checksum  )->by_default(0.8)->as_number();
 
     this->kernel->digipot->set_current(0, this->alpha_current);
index 2cdc243..1025751 100644 (file)
@@ -6,9 +6,9 @@
 #include "libs/utils.h"
 #include "libs/Pin.h"
 
-#define alpha_current_checksum   22381 
-#define beta_current_checksum    60163 
-#define gamma_current_checksum   12906 
+#define alpha_current_checksum   22381
+#define beta_current_checksum    60163
+#define gamma_current_checksum   12906
 #define delta_current_checksum   30321
 #define currentcontrol_module_enable_checksum 38842
 
@@ -21,7 +21,7 @@ class CurrentControl : public Module {
         double alpha_current;
         double beta_current;
         double gamma_current;
-        double delta_current; 
+        double delta_current;
 };
 
 
index 675cb1e..64fbe11 100644 (file)
@@ -22,19 +22,19 @@ void PauseButton::on_module_loaded(){
 //TODO: Make this use InterruptIn
 //Check the state of the button and act accordingly
 uint32_t PauseButton::button_tick(uint32_t dummy){
-    // If button changed 
-    if(this->button_state != this->button->get()){ 
+    // If button changed
+    if(this->button_state != this->button->get()){
         this->button_state = this->button->get();
-        // If button pressed 
+        // If button pressed
         if( this->button_state ){
             if( this->play_state ){
                 this->play_state = false;
-                this->kernel->pauser->take(); 
+                this->kernel->pauser->take();
             }else{
                 this->play_state = true;
-                this->kernel->pauser->release(); 
-            } 
-        } 
+                this->kernel->pauser->release();
+            }
+        }
     }
     return 0;
 }
index f30eaf2..06f5be2 100644 (file)
@@ -19,7 +19,7 @@ class PauseButton : public Module {
         void on_pause( void* argument );
         
         Pin*       button;
-        Pin*       led; 
+        Pin*       led;
         bool       button_state;
         bool       play_state;
 };
index 798e216..0fee088 100644 (file)
@@ -1,8 +1,8 @@
-/*  
+/*
       This file is part of Smoothie (http://smoothieware.org/). The motion control part is heavily based on Grbl (https://github.com/simen/grbl).
       Smoothie is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
       Smoothie is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
-      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>. 
+      You should have received a copy of the GNU General Public License along with Smoothie. If not, see <http://www.gnu.org/licenses/>.
 */
 
 
@@ -15,7 +15,7 @@
 #include "libs/StreamOutput.h"
 
 
-#define ls_command_checksum      19679 
+#define ls_command_checksum      19679
 #define cd_command_checksum      11207
 #define pwd_command_checksum     42060
 #define cat_command_checksum     24889
 #define reset_command_checksum   27429
 
 class SimpleShell : public Module {
-    public: 
+    public:
         SimpleShell(){}
 
         void on_module_loaded();
         void on_console_line_received( void* argument );
-        void on_main_loop( void* argument ); 
+        void on_main_loop( void* argument );
         string absolute_from_relative( string path );
         void ls_command(   string parameters, StreamOutput* stream );
         void cd_command(   string parameters, StreamOutput* stream );