TODOPIC

Microcontroladores PIC => Lenguaje C para microcontroladores PIC => Mensaje iniciado por: AngelGris en 05 de Noviembre de 2013, 11:21:44

Título: ¿USB con compilador XC?
Publicado por: AngelGris en 05 de Noviembre de 2013, 11:21:44
  Hola gente, abro este tema ya que no tengo idea del manejo de USB con los PIC. He tratado de leer el libro "USB Complete" pero sinceramente me fue muy tedioso. Creo tener una mínima noción de los endpoint y distintos tipos de comunicación, pero al no haber incursionado todavía en hacer algo no tengo muy firmes los conceptos.

  He visto algunos ejemplos en CCS y me parecieron muy sencillos, también he visto algo en C18 y me parecieron un poco más complejo y más aún porque nunca utilicé dicho compilador.

  Estoy utilizando XC8 como compilador y buscando algo de USB para este compilador me encontré con este sitio http://www.signal11.us/oss/m-stack/ ¿Alguien lo ha probado?

  Intentaré hacer algo con estas librerías y ver que pasa... ya estaré consultando y/o comentando los resultados en cuanto me pueda poner con bastante tiempo.
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 10 de Noviembre de 2013, 19:24:39
  Después de luchar un poco para que compile, aún así no logré que funcionase.

  Modifiqué el archivo "usb_hal.h" y como comenté logré compilar un ejemplo para el 18F2550 pero cuando lo simulo en ISIS comienza todo el proceso de enumerado y en determinado momento el status devuelto en un endpoint es "halted" y el sistema operativo indica que no se pudo configurar correctamente el dispositivo.
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 12 de Noviembre de 2013, 21:28:05
  Sigo luchando y como no podía hacer funcionar dicha librería seguí buscando por internet para ver si encontraba alguna solución o alguna librería que funcionase con el compilador XC8.

  Llegué al siguiente hilo dentro del foro de microchip http://www.microchip.com/forums/m679588-p2.aspx  En el mensaje número 30 el usuario jtemples sube tres archivos del stack de microchip, modificado por él mismo y menciona como lograr erradicar algunos errores que arrojaba el stack al intentar compilarlo con XC8.

  Al intentar usar dichos archivos seguía apareciendo un error que indicaba una redeclaración de variable dentro de la función BOOL USER_USB_CALLBACK_EVENT_HANDLER (en el archivo usb_device.c). La declaración del archivo subido por jtemples es

Código: C
  1. BOOL USER_USB_CALLBACK_EVENT_HANDLER(int event, void *pdata, WORD size);

cuando lo correcto es que sea

Código: C
  1. BOOL USER_USB_CALLBACK_EVENT_HANDLER(USB_EVENT event, void *pdata, WORD size);

  Luego de ello tomé el archivo usb_config.h y usb_descriptors.c del stack de microchip en el ejemplo de "CDC basic", tal cual lo aconseja jfmateos2 en este hilo http://www.todopic.com.ar/foros/index.php?topic=33699.0. Hice casi todo lo mostrado por jfmateos2 a excepción de los bis de configuración del PIC ya que utilicé un 18F2550 como si tuviera un cristal de 20MHz.

  Lo simulé en ISIS en el circuito de ejemplo que ya trae del PICDEM FS USB (que en realidad utiliza un 18F4550) Y logró enumerar el dispositvo. Luego vi en al administrador de dispositivos y estaba el COM3. Abrí Hyperterminal y al presionar una letra, me respondía con el siguiente mensaje "Ha pulsado:" y a continuación la letra pulsada.

  Adjunto una captura de pantalla

Citar
Agregado 13/11

  Hoy probé cambiando la forma de trabajo de la función USBDeviceTask() de polling a interrupción (tiene que estar alojada en la interrupción de alta prioridad) y éste ejemplo de CDC sigue funcionando perfectamente.
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 14 de Noviembre de 2013, 22:39:00
  Ahora le llegó el turno al HID, en este caso tratando de implementar un joystick.

  He creado un HID-Report para que el "joystick" tenga únicamente un botón.

  Al simularlo en ISIS se enumera bien el dispositivo y hasta puedo verlo desde windows en Panel de control-->Dispositivos para juegos (o algo similar, es el que tiene el icono de un joystick).

  El circuito tiene un pulsador conectado a RB7 y cuando se presiona el pulsador, envía el dato "1" por el puerto USB (al menos es lo que se ve desde del debbuger de USB de ISIS) pero el problema es que en "Panel de control"-->"Dispositivos para juegos" no se enciende el indicador que avisa que se presionó un botón.

  No sé si será un problema por la simulación o es un error en el HID-report.

  Este es el descriptor

Código: C
  1. 0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
  2.     0x09, 0x04,                    // USAGE (Joystick)
  3.     0xa1, 0x01,                    // COLLECTION (Application)
  4.     0xa1, 0x00,                    //   COLLECTION (Physical)
  5.     0x05, 0x09,                    //     USAGE_PAGE (Button)
  6.     0x19, 0x01,                    //     USAGE_MINIMUM (Button 1)
  7.     0x29, 0x01,                    //     USAGE_MAXIMUM (Button 1)
  8.     0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
  9.     0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
  10.     0x75, 0x01,                    //     REPORT_SIZE (1)
  11.     0x95, 0x01,                    //     REPORT_COUNT (1)
  12.     0x81, 0x02,                    //     INPUT (Data,Var,Abs)
  13.     0x75, 0x07,                    //     REPORT_SIZE (7)
  14.     0x95, 0x01,                    //     REPORT_COUNT (1)
  15.     0x81, 0x03,                    //     INPUT (Cnst,Var,Abs)
  16.     0xc0,                          //   END_COLLECTION
  17.     0xc0                           // END_COLLECTION

  Voy a probar con el ejemplo de joystick que trae el propio stack
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 15 de Noviembre de 2013, 10:48:18
  Al final el problema resulto ser una pavada... cuando yo presionaba el botón en ISIS, la ventana de configuración del joystick cambiaba a segundo plano y por ello no actualizaba el estado del botón. Coloqué en ISIS una llave para poder "dejar presionado" el botón y a su vez poner en primer plano la ventana de configuración del joystick y así sí se actualiza el estado.


  Separo el mensaje porque al querer publicarlo me indicaba que excedía el límite de caracteres.

programa principal
Código: C
  1. /*
  2.  
  3.  Programa que simula un joystick de u solo boton por puerto USB
  4.  
  5.  Las rutinas de USB se ejecutan medianta la funcion USBDeviceTask()
  6.   del stack de Microchip
  7.  
  8.  En este ejemplo se utiliza USB por interrupciones en lugar de polling
  9. */
  10.  
  11.  
  12. #include <xc.h>
  13.  
  14. // CONFIG1L
  15. #pragma config PLLDIV = 5       // PLL Prescaler Selection bits (Divide by 5 (20 MHz oscillator input))
  16. #pragma config CPUDIV = OSC1_PLL2// System Clock Postscaler Selection bits ([Primary Oscillator Src: /1][96 MHz PLL Src: /2])
  17. #pragma config USBDIV = 2       // USB Clock Selection bit (used in Full-Speed USB mode only; UCFG:FSEN = 1) (USB clock source comes from the 96 MHz PLL divided by 2)
  18.  
  19. // CONFIG1H
  20. #pragma config FOSC = HSPLL_HS  // Oscillator Selection bits (HS oscillator, PLL enabled (HSPLL))
  21. #pragma config FCMEN = OFF      // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
  22. #pragma config IESO = OFF       // Internal/External Oscillator Switchover bit (Oscillator Switchover mode disabled)
  23.  
  24. // CONFIG2L
  25. #pragma config PWRT = OFF       // Power-up Timer Enable bit (PWRT disabled)
  26. #pragma config BOR = OFF        // Brown-out Reset Enable bits (Brown-out Reset disabled in hardware and software)
  27. #pragma config BORV = 3         // Brown-out Reset Voltage bits (Minimum setting)
  28. #pragma config VREGEN = ON      // USB Voltage Regulator Enable bit (USB voltage regulator enabled)
  29.  
  30. // CONFIG2H
  31. #pragma config WDT = OFF        // Watchdog Timer Enable bit (WDT disabled (control is placed on the SWDTEN bit))
  32. #pragma config WDTPS = 32768    // Watchdog Timer Postscale Select bits (1:32768)
  33.  
  34. // CONFIG3H
  35. #pragma config CCP2MX = ON      // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
  36. #pragma config PBADEN = OFF     // PORTB A/D Enable bit (PORTB<4:0> pins are configured as digital I/O on Reset)
  37. #pragma config LPT1OSC = OFF    // Low-Power Timer 1 Oscillator Enable bit (Timer1 configured for higher power operation)
  38. #pragma config MCLRE = ON       // MCLR Pin Enable bit (MCLR pin enabled; RE3 input pin disabled)
  39.  
  40. // CONFIG4L
  41. #pragma config STVREN = ON      // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)
  42. #pragma config LVP = OFF        // Single-Supply ICSP Enable bit (Single-Supply ICSP disabled)
  43. #pragma config XINST = OFF      // Extended Instruction Set Enable bit (Instruction set extension and Indexed Addressing mode disabled (Legacy mode))
  44.  
  45. // CONFIG5L
  46. #pragma config CP0 = OFF        // Code Protection bit (Block 0 (000800-001FFFh) is not code-protected)
  47. #pragma config CP1 = OFF        // Code Protection bit (Block 1 (002000-003FFFh) is not code-protected)
  48. #pragma config CP2 = OFF        // Code Protection bit (Block 2 (004000-005FFFh) is not code-protected)
  49. #pragma config CP3 = OFF        // Code Protection bit (Block 3 (006000-007FFFh) is not code-protected)
  50.  
  51. // CONFIG5H
  52. #pragma config CPB = OFF        // Boot Block Code Protection bit (Boot block (000000-0007FFh) is not code-protected)
  53. #pragma config CPD = OFF        // Data EEPROM Code Protection bit (Data EEPROM is not code-protected)
  54.  
  55. // CONFIG6L
  56. #pragma config WRT0 = OFF       // Write Protection bit (Block 0 (000800-001FFFh) is not write-protected)
  57. #pragma config WRT1 = OFF       // Write Protection bit (Block 1 (002000-003FFFh) is not write-protected)
  58. #pragma config WRT2 = OFF       // Write Protection bit (Block 2 (004000-005FFFh) is not write-protected)
  59. #pragma config WRT3 = OFF       // Write Protection bit (Block 3 (006000-007FFFh) is not write-protected)
  60.  
  61. // CONFIG6H
  62. #pragma config WRTC = OFF       // Configuration Register Write Protection bit (Configuration registers (300000-3000FFh) are not write-protected)
  63. #pragma config WRTB = OFF       // Boot Block Write Protection bit (Boot block (000000-0007FFh) is not write-protected)
  64. #pragma config WRTD = OFF       // Data EEPROM Write Protection bit (Data EEPROM is not write-protected)
  65.  
  66. // CONFIG7L
  67. #pragma config EBTR0 = OFF      // Table Read Protection bit (Block 0 (000800-001FFFh) is not protected from table reads executed in other blocks)
  68. #pragma config EBTR1 = OFF      // Table Read Protection bit (Block 1 (002000-003FFFh) is not protected from table reads executed in other blocks)
  69. #pragma config EBTR2 = OFF      // Table Read Protection bit (Block 2 (004000-005FFFh) is not protected from table reads executed in other blocks)
  70. #pragma config EBTR3 = OFF      // Table Read Protection bit (Block 3 (006000-007FFFh) is not protected from table reads executed in other blocks)
  71.  
  72. // CONFIG7H
  73. #pragma config EBTRB = OFF      // Boot Block Table Read Protection bit (Boot block (000000-0007FFh) is not protected from table reads executed in other blocks)
  74.  
  75. #include "HardwareProfile.h"
  76. #include "usb_config.h"
  77. #include "./USB/usb.h"
  78. #include "./USB/usb_function_hid.h"
  79.  
  80. /*
  81.  * Algunas variables
  82. */
  83.  
  84. #if defined(__XC8)
  85.     #if defined(_18F14K50) || defined(_18F13K50) || defined(_18LF14K50) || defined(_18LF13K50)
  86.         #define INPUT_CONTROLS_ADDRESS 0x260
  87.         #define HID_REPORT_ADDRESS (INPUT_CONTROLS_ADDRESS + HID_INT_IN_EP_SIZE)
  88.         #define INPUT_CONTROLS_ADDRESS_TAG @INPUT_CONTROLS_ADDRESS
  89.         #define HID_REPORT_ADDRESS_TAG @HID_REPORT_ADDRESS
  90.     #elif  defined(_18F2455)   || defined(_18F2550)   || defined(_18F4455)  || defined(_18F4550)\
  91.         || defined(_18F2458)   || defined(_18F2453)   || defined(_18F4558)  || defined(_18F4553)\
  92.         || defined(_18LF24K50) || defined(_18F24K50)  || defined(_18LF25K50)\
  93.         || defined(_18F25K50)  || defined(_18LF45K50) || defined(_18F45K50)
  94.         #define INPUT_CONTROLS_ADDRESS 0x500
  95.         #define HID_REPORT_ADDRESS (INPUT_CONTROLS_ADDRESS + HID_INT_IN_EP_SIZE)
  96.         #define INPUT_CONTROLS_ADDRESS_TAG @INPUT_CONTROLS_ADDRESS
  97.         #define HID_REPORT_ADDRESS_TAG @HID_REPORT_ADDRESS
  98.     #elif defined(_18F4450) || defined(_18F2450)
  99.         #define INPUT_CONTROLS_ADDRESS 0x480
  100.         #define HID_REPORT_ADDRESS (INPUT_CONTROLS_ADDRESS + HID_INT_IN_EP_SIZE)
  101.         #define INPUT_CONTROLS_ADDRESS_TAG @INPUT_CONTROLS_ADDRESS
  102.         #define HID_REPORT_ADDRESS_TAG @HID_REPORT_ADDRESS
  103.     #elif defined(_16F1459)
  104.         #define INPUT_CONTROLS_ADDRESS 0x2050
  105.         #define HID_REPORT_ADDRESS (INPUT_CONTROLS_ADDRESS + HID_INT_IN_EP_SIZE)
  106.         #define INPUT_CONTROLS_ADDRESS_TAG @INPUT_CONTROLS_ADDRESS
  107.         #define HID_REPORT_ADDRESS_TAG @HID_REPORT_ADDRESS
  108.     #else
  109.         #define INPUT_CONTROLS_ADDRESS_TAG
  110.         #define HID_REPORT_ADDRESS_TAG
  111.     #endif
  112. #else
  113.     #define INPUT_CONTROLS_ADDRESS_TAG
  114.     #define HID_REPORT_ADDRESS_TAG
  115. #endif
  116.  
  117. USB_HANDLE lastTransmission;
  118.  
  119. unsigned char dato INPUT_CONTROLS_ADDRESS_TAG;
  120.  
  121. BYTE hid_report[8] HID_REPORT_ADDRESS_TAG;
  122.  
  123.  
  124. void ProcesoPersonal(void);
  125.  
  126. void interrupt high_priority ISR(void)
  127. {
  128.     USBDeviceTasks();
  129. }
  130.  
  131. void main(void)
  132. {
  133.  
  134.     TRISBbits.TRISB7 = 1;
  135.     lastTransmission = 0;
  136.     USBDeviceInit();
  137.  
  138.     #if defined(USB_INTERRUPT)
  139.         USBDeviceAttach();
  140.     #endif
  141.  
  142.     while(1)
  143.     {
  144.         ProcesoPersonal();
  145.     }
  146.  
  147. }
  148.  
  149.  
  150.  
  151. void ProcesoPersonal(void)
  152. {
  153.     if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;
  154.  
  155.     dato = PORTBbits.RB7;
  156.  
  157.     if(!HIDTxHandleBusy(lastTransmission))
  158.     {
  159.         lastTransmission = HIDTxPacket(HID_EP, (BYTE*)&dato, sizeof(dato));
  160.     }
  161. }
  162.  
  163.  
  164.  
  165. // ******************************************************************************************************
  166. // ************** USB Callback Functions ****************************************************************
  167. // ******************************************************************************************************
  168. // The USB firmware stack will call the callback functions USBCBxxx() in response to certain USB related
  169. // events.  For example, if the host PC is powering down, it will stop sending out Start of Frame (SOF)
  170. // packets to your device.  In response to this, all USB devices are supposed to decrease their power
  171. // consumption from the USB Vbus to <2.5mA* each.  The USB module detects this condition (which according
  172. // to the USB specifications is 3+ms of no bus activity/SOF packets) and then calls the USBCBSuspend()
  173. // function.  You should modify these callback functions to take appropriate actions for each of these
  174. // conditions.  For example, in the USBCBSuspend(), you may wish to add code that will decrease power
  175. // consumption from Vbus to <2.5mA (such as by clock switching, turning off LEDs, putting the
  176. // microcontroller to sleep, etc.).  Then, in the USBCBWakeFromSuspend() function, you may then wish to
  177. // add code that undoes the power saving things done in the USBCBSuspend() function.
  178.  
  179. // The USBCBSendResume() function is special, in that the USB stack will not automatically call this
  180. // function.  This function is meant to be called from the application firmware instead.  See the
  181. // additional comments near the function.
  182.  
  183. // Note *: The "usb_20.pdf" specs indicate 500uA or 2.5mA, depending upon device classification. However,
  184. // the USB-IF has officially issued an ECN (engineering change notice) changing this to 2.5mA for all
  185. // devices.  Make sure to re-download the latest specifications to get all of the newest ECNs.
  186.  
  187. /******************************************************************************
  188.  * Function:        void USBCBSuspend(void)
  189.  *
  190.  * PreCondition:    None
  191.  *
  192.  * Input:           None
  193.  *
  194.  * Output:          None
  195.  *
  196.  * Side Effects:    None
  197.  *
  198.  * Overview:        Call back that is invoked when a USB suspend is detected
  199.  *
  200.  * Note:            None
  201.  *****************************************************************************/
  202. void USBCBSuspend(void)
  203. {
  204.         //Example power saving code.  Insert appropriate code here for the desired
  205.         //application behavior.  If the microcontroller will be put to sleep, a
  206.         //process similar to that shown below may be used:
  207.  
  208.         //ConfigureIOPinsForLowPower();
  209.         //SaveStateOfAllInterruptEnableBits();
  210.         //DisableAllInterruptEnableBits();
  211.         //EnableOnlyTheInterruptsWhichWillBeUsedToWakeTheMicro();       //should enable at least USBActivityIF as a wake source
  212.         //Sleep();
  213.         //RestoreStateOfAllPreviouslySavedInterruptEnableBits();        //Preferrably, this should be done in the USBCBWakeFromSuspend() function instead.
  214.         //RestoreIOPinsToNormal();                                                                      //Preferrably, this should be done in the USBCBWakeFromSuspend() function instead.
  215.  
  216.         //Alternatively, the microcontorller may use clock switching to reduce current consumption.
  217.         #if defined(__18CXX)
  218.         //Configure device for low power consumption
  219.         //mLED_1_Off();
  220.         //mLED_2_Off();
  221.         //Should also configure all other I/O pins for lowest power consumption.
  222.         //Typically this is done by driving unused I/O pins as outputs and driving them high or low.
  223.         //In this example, this is not done however, in case the user is expecting the I/O pins
  224.         //to remain tri-state and has hooked something up to them.
  225.         //Leaving the I/O pins floating will waste power and should not be done in a
  226.         //real application.
  227.  
  228.         //Note: The clock switching code needed is processor specific, as the
  229.         //clock trees and registers aren't identical accross all PIC18 USB device
  230.         //families.
  231.         #if defined(PIC18F97J94_FAMILY)
  232.             OSCCON = 0x06;  //FRC / 16 = 500kHz selected.
  233.         #else
  234.                 OSCCON = 0x13;  //Sleep on sleep, 125kHz selected as microcontroller clock source
  235.         #endif
  236.         #endif
  237.  
  238.         //IMPORTANT NOTE: Do not clear the USBActivityIF (ACTVIF) bit here.  This bit is
  239.         //cleared inside the usb_device.c file.  Clearing USBActivityIF here will cause
  240.         //things to not work as intended.
  241.  
  242. }
  243.  
  244. /******************************************************************************
  245.  * Function:        void USBCBWakeFromSuspend(void)
  246.  *
  247.  * PreCondition:    None
  248.  *
  249.  * Input:           None
  250.  *
  251.  * Output:          None
  252.  *
  253.  * Side Effects:    None
  254.  *
  255.  * Overview:        The host may put USB peripheral devices in low power
  256.  *                                      suspend mode (by "sending" 3+ms of idle).  Once in suspend
  257.  *                                      mode, the host may wake the device back up by sending non-
  258.  *                                      idle state signalling.
  259.  *
  260.  *                                      This call back is invoked when a wakeup from USB suspend
  261.  *                                      is detected.
  262.  *
  263.  * Note:            None
  264.  *****************************************************************************/
  265. void USBCBWakeFromSuspend(void)
  266. {
  267.         // If clock switching or other power savings measures were taken when
  268.         // executing the USBCBSuspend() function, now would be a good time to
  269.         // switch back to normal full power run mode conditions.  The host allows
  270.         // 10+ milliseconds of wakeup time, after which the device must be
  271.         // fully back to normal, and capable of receiving and processing USB
  272.         // packets.  In order to do this, the USB module must receive proper
  273.         // clocking (IE: 48MHz clock must be available to SIE for full speed USB
  274.         // operation).
  275.         // Make sure the selected oscillator settings are consistant with USB operation
  276.         // before returning from this function.
  277.  
  278.         //Switch clock back to main clock source necessary for USB operation
  279.         //Previous clock source was something low frequency as set in the
  280.         //USBCBSuspend() function.
  281.         #if defined(__18CXX)
  282.         #if defined(PIC18F97J94_FAMILY)
  283.             OSCCON3 = 0x01; //8MHz FRC / 2 = 4MHz output
  284.             OSCCON = 0x01;  //FRC with PLL selected
  285.             while(OSCCON2bits.LOCK == 0);   //Wait for PLL lock
  286.         #elif defined(PIC18F45K50_FAMILY)
  287.             OSCCON = 0x70;  //Switch to 16MHz HFINTOSC (+ PLL)
  288.             while(OSCCON2bits.PLLRDY != 1);   //Wait for PLL lock
  289.         #else
  290.                 OSCCON = 0x60;          //Primary clock source selected.
  291.             //Adding a software start up delay will ensure
  292.             //that the primary oscillator and PLL are running before executing any other
  293.             //code.  If the PLL isn't being used, (ex: primary osc = 48MHz externally applied EC)
  294.             //then this code adds a small unnecessary delay, but it is harmless to execute anyway.
  295.                 {
  296.                 unsigned int pll_startup_counter = 800; //Long delay at 31kHz, but ~0.8ms at 48MHz
  297.                 while(pll_startup_counter--);                   //Clock will switch over while executing this delay loop
  298.             }
  299.         #endif
  300.         #endif
  301. }
  302.  
  303. /********************************************************************
  304.  * Function:        void USBCB_SOF_Handler(void)
  305.  *
  306.  * PreCondition:    None
  307.  *
  308.  * Input:           None
  309.  *
  310.  * Output:          None
  311.  *
  312.  * Side Effects:    None
  313.  *
  314.  * Overview:        The USB host sends out a SOF packet to full-speed
  315.  *                  devices every 1 ms. This interrupt may be useful
  316.  *                  for isochronous pipes. End designers should
  317.  *                  implement callback routine as necessary.
  318.  *
  319.  * Note:            None
  320.  *******************************************************************/
  321. void USBCB_SOF_Handler(void)
  322. {
  323.     // No need to clear UIRbits.SOFIF to 0 here.
  324.     // Callback caller is already doing that.
  325. }
  326.  
  327. /*******************************************************************
  328.  * Function:        void USBCBErrorHandler(void)
  329.  *
  330.  * PreCondition:    None
  331.  *
  332.  * Input:           None
  333.  *
  334.  * Output:          None
  335.  *
  336.  * Side Effects:    None
  337.  *
  338.  * Overview:        The purpose of this callback is mainly for
  339.  *                  debugging during development. Check UEIR to see
  340.  *                  which error causes the interrupt.
  341.  *
  342.  * Note:            None
  343.  *******************************************************************/
  344. void USBCBErrorHandler(void)
  345. {
  346.     // No need to clear UEIR to 0 here.
  347.     // Callback caller is already doing that.
  348.  
  349.         // Typically, user firmware does not need to do anything special
  350.         // if a USB error occurs.  For example, if the host sends an OUT
  351.         // packet to your device, but the packet gets corrupted (ex:
  352.         // because of a bad connection, or the user unplugs the
  353.         // USB cable during the transmission) this will typically set
  354.         // one or more USB error interrupt flags.  Nothing specific
  355.         // needs to be done however, since the SIE will automatically
  356.         // send a "NAK" packet to the host.  In response to this, the
  357.         // host will normally retry to send the packet again, and no
  358.         // data loss occurs.  The system will typically recover
  359.         // automatically, without the need for application firmware
  360.         // intervention.
  361.  
  362.         // Nevertheless, this callback function is provided, such as
  363.         // for debugging purposes.
  364. }
  365.  
  366.  
  367. /*******************************************************************
  368.  * Function:        void USBCBCheckOtherReq(void)
  369.  *
  370.  * PreCondition:    None
  371.  *
  372.  * Input:           None
  373.  *
  374.  * Output:          None
  375.  *
  376.  * Side Effects:    None
  377.  *
  378.  * Overview:        When SETUP packets arrive from the host, some
  379.  *                                      firmware must process the request and respond
  380.  *                                      appropriately to fulfill the request.  Some of
  381.  *                                      the SETUP packets will be for standard
  382.  *                                      USB "chapter 9" (as in, fulfilling chapter 9 of
  383.  *                                      the official USB specifications) requests, while
  384.  *                                      others may be specific to the USB device class
  385.  *                                      that is being implemented.  For example, a HID
  386.  *                                      class device needs to be able to respond to
  387.  *                                      "GET REPORT" type of requests.  This
  388.  *                                      is not a standard USB chapter 9 request, and
  389.  *                                      therefore not handled by usb_device.c.  Instead
  390.  *                                      this request should be handled by class specific
  391.  *                                      firmware, such as that contained in usb_function_hid.c.
  392.  *
  393.  * Note:            None
  394.  *******************************************************************/
  395. void USBCBCheckOtherReq(void)
  396. {
  397.     USBCheckHIDRequest();
  398. }//end
  399.  
  400.  
  401. /*******************************************************************
  402.  * Function:        void USBCBStdSetDscHandler(void)
  403.  *
  404.  * PreCondition:    None
  405.  *
  406.  * Input:           None
  407.  *
  408.  * Output:          None
  409.  *
  410.  * Side Effects:    None
  411.  *
  412.  * Overview:        The USBCBStdSetDscHandler() callback function is
  413.  *                                      called when a SETUP, bRequest: SET_DESCRIPTOR request
  414.  *                                      arrives.  Typically SET_DESCRIPTOR requests are
  415.  *                                      not used in most applications, and it is
  416.  *                                      optional to support this type of request.
  417.  *
  418.  * Note:            None
  419.  *******************************************************************/
  420. void USBCBStdSetDscHandler(void)
  421. {
  422.     // Must claim session ownership if supporting this request
  423. }//end
  424.  
  425.  
  426. /*******************************************************************
  427.  * Function:        void USBCBInitEP(void)
  428.  *
  429.  * PreCondition:    None
  430.  *
  431.  * Input:           None
  432.  *
  433.  * Output:          None
  434.  *
  435.  * Side Effects:    None
  436.  *
  437.  * Overview:        This function is called when the device becomes
  438.  *                  initialized, which occurs after the host sends a
  439.  *                                      SET_CONFIGURATION (wValue not = 0) request.  This
  440.  *                                      callback function should initialize the endpoints
  441.  *                                      for the device's usage according to the current
  442.  *                                      configuration.
  443.  *
  444.  * Note:            None
  445.  *******************************************************************/
  446. void USBCBInitEP(void)
  447. {
  448.     //enable the HID endpoint
  449.     USBEnableEndpoint(HID_EP,USB_OUT_ENABLED|USB_IN_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
  450. }
  451.  
  452. /********************************************************************
  453.  * Function:        void USBCBSendResume(void)
  454.  *
  455.  * PreCondition:    None
  456.  *
  457.  * Input:           None
  458.  *
  459.  * Output:          None
  460.  *
  461.  * Side Effects:    None
  462.  *
  463.  * Overview:        The USB specifications allow some types of USB
  464.  *                                      peripheral devices to wake up a host PC (such
  465.  *                                      as if it is in a low power suspend to RAM state).
  466.  *                                      This can be a very useful feature in some
  467.  *                                      USB applications, such as an Infrared remote
  468.  *                                      control receiver.  If a user presses the "power"
  469.  *                                      button on a remote control, it is nice that the
  470.  *                                      IR receiver can detect this signalling, and then
  471.  *                                      send a USB "command" to the PC to wake up.
  472.  *
  473.  *                                      The USBCBSendResume() "callback" function is used
  474.  *                                      to send this special USB signalling which wakes
  475.  *                                      up the PC.  This function may be called by
  476.  *                                      application firmware to wake up the PC.  This
  477.  *                                      function will only be able to wake up the host if
  478.  *                  all of the below are true:
  479.  *
  480.  *                                      1.  The USB driver used on the host PC supports
  481.  *                                              the remote wakeup capability.
  482.  *                                      2.  The USB configuration descriptor indicates
  483.  *                                              the device is remote wakeup capable in the
  484.  *                                              bmAttributes field.
  485.  *                                      3.  The USB host PC is currently sleeping,
  486.  *                                              and has previously sent your device a SET
  487.  *                                              FEATURE setup packet which "armed" the
  488.  *                                              remote wakeup capability.
  489.  *
  490.  *                  If the host has not armed the device to perform remote wakeup,
  491.  *                  then this function will return without actually performing a
  492.  *                  remote wakeup sequence.  This is the required behavior,
  493.  *                  as a USB device that has not been armed to perform remote
  494.  *                  wakeup must not drive remote wakeup signalling onto the bus;
  495.  *                  doing so will cause USB compliance testing failure.
  496.  *
  497.  *                                      This callback should send a RESUME signal that
  498.  *                  has the period of 1-15ms.
  499.  *
  500.  * Note:            This function does nothing and returns quickly, if the USB
  501.  *                  bus and host are not in a suspended condition, or are
  502.  *                  otherwise not in a remote wakeup ready state.  Therefore, it
  503.  *                  is safe to optionally call this function regularly, ex:
  504.  *                  anytime application stimulus occurs, as the function will
  505.  *                  have no effect, until the bus really is in a state ready
  506.  *                  to accept remote wakeup.
  507.  *
  508.  *                  When this function executes, it may perform clock switching,
  509.  *                  depending upon the application specific code in
  510.  *                  USBCBWakeFromSuspend().  This is needed, since the USB
  511.  *                  bus will no longer be suspended by the time this function
  512.  *                  returns.  Therefore, the USB module will need to be ready
  513.  *                  to receive traffic from the host.
  514.  *
  515.  *                  The modifiable section in this routine may be changed
  516.  *                  to meet the application needs. Current implementation
  517.  *                  temporary blocks other functions from executing for a
  518.  *                  period of ~3-15 ms depending on the core frequency.
  519.  *
  520.  *                  According to USB 2.0 specification section 7.1.7.7,
  521.  *                  "The remote wakeup device must hold the resume signaling
  522.  *                  for at least 1 ms but for no more than 15 ms."
  523.  *                  The idea here is to use a delay counter loop, using a
  524.  *                  common value that would work over a wide range of core
  525.  *                  frequencies.
  526.  *                  That value selected is 1800. See table below:
  527.  *                  ==========================================================
  528.  *                  Core Freq(MHz)      MIP         RESUME Signal Period (ms)
  529.  *                  ==========================================================
  530.  *                      48              12          1.05
  531.  *                       4              1           12.6
  532.  *                  ==========================================================
  533.  *                  * These timing could be incorrect when using code
  534.  *                    optimization or extended instruction mode,
  535.  *                    or when having other interrupts enabled.
  536.  *                    Make sure to verify using the MPLAB SIM's Stopwatch
  537.  *                    and verify the actual signal on an oscilloscope.
  538.  *******************************************************************/
  539. void USBCBSendResume(void)
  540. {
  541.     static WORD delay_count;
  542.  
  543.     //First verify that the host has armed us to perform remote wakeup.
  544.     //It does this by sending a SET_FEATURE request to enable remote wakeup,
  545.     //usually just before the host goes to standby mode (note: it will only
  546.     //send this SET_FEATURE request if the configuration descriptor declares
  547.     //the device as remote wakeup capable, AND, if the feature is enabled
  548.     //on the host (ex: on Windows based hosts, in the device manager
  549.     //properties page for the USB device, power management tab, the
  550.     //"Allow this device to bring the computer out of standby." checkbox
  551.     //should be checked).
  552.     if(USBGetRemoteWakeupStatus() == TRUE)
  553.     {
  554.         //Verify that the USB bus is in fact suspended, before we send
  555.         //remote wakeup signalling.
  556.         if(USBIsBusSuspended() == TRUE)
  557.         {
  558.             USBMaskInterrupts();
  559.  
  560.             //Clock switch to settings consistent with normal USB operation.
  561.             USBCBWakeFromSuspend();
  562.             USBSuspendControl = 0;
  563.             USBBusIsSuspended = FALSE;  //So we don't execute this code again,
  564.                                         //until a new suspend condition is detected.
  565.  
  566.             //Section 7.1.7.7 of the USB 2.0 specifications indicates a USB
  567.             //device must continuously see 5ms+ of idle on the bus, before it sends
  568.             //remote wakeup signalling.  One way to be certain that this parameter
  569.             //gets met, is to add a 2ms+ blocking delay here (2ms plus at
  570.             //least 3ms from bus idle to USBIsBusSuspended() == TRUE, yeilds
  571.             //5ms+ total delay since start of idle).
  572.             delay_count = 3600U;
  573.             do
  574.             {
  575.                 delay_count--;
  576.             }while(delay_count);
  577.  
  578.             //Now drive the resume K-state signalling onto the USB bus.
  579.             USBResumeControl = 1;       // Start RESUME signaling
  580.             delay_count = 1800U;        // Set RESUME line for 1-13 ms
  581.             do
  582.             {
  583.                 delay_count--;
  584.             }while(delay_count);
  585.             USBResumeControl = 0;       //Finished driving resume signalling
  586.  
  587.             USBUnmaskInterrupts();
  588.         }
  589.     }
  590. }
  591.  
  592.  
  593. /*******************************************************************
  594.  * Function:        BOOL USER_USB_CALLBACK_EVENT_HANDLER(
  595.  *                        int event, void *pdata, WORD size)
  596.  *
  597.  * PreCondition:    None
  598.  *
  599.  * Input:           int event - the type of event
  600.  *                  void *pdata - pointer to the event data
  601.  *                  WORD size - size of the event data
  602.  *
  603.  * Output:          None
  604.  *
  605.  * Side Effects:    None
  606.  *
  607.  * Overview:        This function is called from the USB stack to
  608.  *                  notify a user application that a USB event
  609.  *                  occured.  This callback is in interrupt context
  610.  *                  when the USB_INTERRUPT option is selected.
  611.  *
  612.  * Note:            None
  613.  *******************************************************************/
  614. BOOL USER_USB_CALLBACK_EVENT_HANDLER(USB_EVENT event, void *pdata, WORD size)
  615. {
  616.     switch( event )
  617.     {
  618.         case EVENT_TRANSFER:
  619.             //Add application specific callback task or callback function here if desired.
  620.             break;
  621.         case EVENT_SOF:
  622.             USBCB_SOF_Handler();
  623.             break;
  624.         case EVENT_SUSPEND:
  625.             USBCBSuspend();
  626.             break;
  627.         case EVENT_RESUME:
  628.             USBCBWakeFromSuspend();
  629.             break;
  630.         case EVENT_CONFIGURED:
  631.             USBCBInitEP();
  632.             break;
  633.         case EVENT_SET_DESCRIPTOR:
  634.             USBCBStdSetDscHandler();
  635.             break;
  636.         case EVENT_EP0_REQUEST:
  637.             USBCBCheckOtherReq();
  638.             break;
  639.         case EVENT_BUS_ERROR:
  640.             USBCBErrorHandler();
  641.             break;
  642.         case EVENT_TRANSFER_TERMINATED:
  643.             //Add application specific callback task or callback function here if desired.
  644.             //The EVENT_TRANSFER_TERMINATED event occurs when the host performs a CLEAR
  645.             //FEATURE (endpoint halt) request on an application endpoint which was
  646.             //previously armed (UOWN was = 1).  Here would be a good place to:
  647.             //1.  Determine which endpoint the transaction that just got terminated was
  648.             //      on, by checking the handle value in the *pdata.
  649.             //2.  Re-arm the endpoint if desired (typically would be the case for OUT
  650.             //      endpoints).
  651.             break;
  652.         default:
  653.             break;
  654.     }
  655.     return TRUE;
  656. }

Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 15 de Noviembre de 2013, 10:49:28
  Sigo con los archivos del ejemplo HID

usb_config.h
Código: C
  1. /********************************************************************
  2.  FileName:      usb_config.h
  3.  Dependencies:  Always: GenericTypeDefs.h, usb_device.h
  4.                 Situational: usb_function_hid.h, usb_function_cdc.h, usb_function_msd.h, etc.
  5.  Processor:             PIC18 or PIC24 USB Microcontrollers
  6.  Hardware:              The code is natively intended to be used on the following
  7.                                 hardware platforms: PICDEM™ FS USB Demo Board,
  8.                                 PIC18F87J50 FS USB Plug-In Module, or
  9.                                 Explorer 16 + PIC24 USB PIM.  The firmware may be
  10.                                 modified for use on other USB platforms by editing the
  11.                                 HardwareProfile.h file.
  12.  Complier:      Microchip C18 (for PIC18) or C30 (for PIC24)
  13.  Company:               Microchip Technology, Inc.
  14.  
  15.  Software License Agreement:
  16.  
  17.  The software supplied herewith by Microchip Technology Incorporated
  18.  (the “Company”) for its PIC® Microcontroller is intended and
  19.  supplied to you, the Company’s customer, for use solely and
  20.  exclusively on Microchip PIC Microcontroller products. The
  21.  software is owned by the Company and/or its supplier, and is
  22.  protected under applicable copyright laws. All rights are reserved.
  23.  Any use in violation of the foregoing restrictions may subject the
  24.  user to criminal sanctions under applicable laws, as well as to
  25.  civil liability for the breach of the terms and conditions of this
  26.  license.
  27.  
  28.  THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
  29.  WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
  30.  TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  31.  PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
  32.  IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
  33.  CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
  34.  
  35. ********************************************************************
  36.  File Description:
  37.  
  38.  Change History:
  39.   Rev   Date         Description
  40.   1.0   11/19/2004   Initial release
  41.   2.1   02/26/2007   Updated for simplicity and to use common
  42.                      coding style
  43.  *******************************************************************/
  44.  
  45. /*********************************************************************
  46.  * Descriptor specific type definitions are defined in: usbd.h
  47.  ********************************************************************/
  48.  
  49. #ifndef USBCFG_H
  50. #define USBCFG_H
  51.  
  52. /** DEFINITIONS ****************************************************/
  53. #define USB_EP0_BUFF_SIZE               8       // Valid Options: 8, 16, 32, or 64 bytes.
  54.                                                                 // Using larger options take more SRAM, but
  55.                                                                 // does not provide much advantage in most types
  56.                                                                 // of applications.  Exceptions to this, are applications
  57.                                                                 // that use EP0 IN or OUT for sending large amounts of
  58.                                                                 // application related data.
  59.                                                                        
  60. #define USB_MAX_NUM_INT         1   // For tracking Alternate Setting
  61. #define USB_MAX_EP_NUMBER           1
  62.  
  63. //Device descriptor - if these two definitions are not defined then
  64. //  a ROM USB_DEVICE_DESCRIPTOR variable by the exact name of device_dsc
  65. //  must exist.
  66. #define USB_USER_DEVICE_DESCRIPTOR &device_dsc
  67. #define USB_USER_DEVICE_DESCRIPTOR_INCLUDE extern ROM USB_DEVICE_DESCRIPTOR device_dsc
  68.  
  69. //Configuration descriptors - if these two definitions do not exist then
  70. //  a ROM BYTE *ROM variable named exactly USB_CD_Ptr[] must exist.
  71. #define USB_USER_CONFIG_DESCRIPTOR USB_CD_Ptr
  72. #define USB_USER_CONFIG_DESCRIPTOR_INCLUDE extern ROM BYTE *ROM USB_CD_Ptr[]
  73.  
  74. //Make sure only one of the below "#define USB_PING_PONG_MODE"
  75. //is uncommented.
  76. //#define USB_PING_PONG_MODE USB_PING_PONG__NO_PING_PONG
  77. #define USB_PING_PONG_MODE USB_PING_PONG__FULL_PING_PONG
  78. //#define USB_PING_PONG_MODE USB_PING_PONG__EP0_OUT_ONLY
  79. //#define USB_PING_PONG_MODE USB_PING_PONG__ALL_BUT_EP0         //NOTE: This mode is not supported in PIC18F4550 family rev A3 devices
  80.  
  81. #define USB_FULL_PING_PONG
  82. #define USB_EP0_OUT_ONLY
  83.  
  84.  
  85. //#define USB_POLLING
  86. #define USB_INTERRUPT
  87.  
  88. /* Parameter definitions are defined in usb_device.h */
  89. #define USB_PULLUP_OPTION USB_PULLUP_ENABLE
  90. //#define USB_PULLUP_OPTION USB_PULLUP_DISABLED
  91.  
  92. #define USB_TRANSCEIVER_OPTION USB_INTERNAL_TRANSCEIVER
  93. //External Transceiver support is not available on all product families.  Please
  94. //  refer to the product family datasheet for more information if this feature
  95. //  is available on the target processor.
  96. //#define USB_TRANSCEIVER_OPTION USB_EXTERNAL_TRANSCEIVER
  97.  
  98. #define USB_SPEED_OPTION USB_FULL_SPEED
  99. //#define USB_SPEED_OPTION USB_LOW_SPEED //(not valid option for PIC24F devices)
  100.  
  101. #define MY_VID 0x04D8
  102. #define MY_PID 0x005E
  103.  
  104. //------------------------------------------------------------------------------------------------------------------
  105. //Option to enable auto-arming of the status stage of control transfers, if no
  106. //"progress" has been made for the USB_STATUS_STAGE_TIMEOUT value.
  107. //If progress is made (any successful transactions completing on EP0 IN or OUT)
  108. //the timeout counter gets reset to the USB_STATUS_STAGE_TIMEOUT value.
  109. //
  110. //During normal control transfer processing, the USB stack or the application
  111. //firmware will call USBCtrlEPAllowStatusStage() as soon as the firmware is finished
  112. //processing the control transfer.  Therefore, the status stage completes as
  113. //quickly as is physically possible.  The USB_ENABLE_STATUS_STAGE_TIMEOUTS
  114. //feature, and the USB_STATUS_STAGE_TIMEOUT value are only relevant, when:
  115. //1.  The application uses the USBDeferStatusStage() API function, but never calls
  116. //      USBCtrlEPAllowStatusStage().  Or:
  117. //2.  The application uses host to device (OUT) control transfers with data stage,
  118. //      and some abnormal error occurs, where the host might try to abort the control
  119. //      transfer, before it has sent all of the data it claimed it was going to send.
  120. //
  121. //If the application firmware never uses the USBDeferStatusStage() API function,
  122. //and it never uses host to device control transfers with data stage, then
  123. //it is not required to enable the USB_ENABLE_STATUS_STAGE_TIMEOUTS feature.
  124.  
  125. #define USB_ENABLE_STATUS_STAGE_TIMEOUTS    //Comment this out to disable this feature.  
  126.  
  127. //Section 9.2.6 of the USB 2.0 specifications indicate that:
  128. //1.  Control transfers with no data stage: Status stage must complete within
  129. //      50ms of the start of the control transfer.
  130. //2.  Control transfers with (IN) data stage: Status stage must complete within
  131. //      50ms of sending the last IN data packet in fullfilment of the data stage.
  132. //3.  Control transfers with (OUT) data stage: No specific status stage timing
  133. //      requirement.  However, the total time of the entire control transfer (ex:
  134. //      including the OUT data stage and IN status stage) must not exceed 5 seconds.
  135. //
  136. //Therefore, if the USB_ENABLE_STATUS_STAGE_TIMEOUTS feature is used, it is suggested
  137. //to set the USB_STATUS_STAGE_TIMEOUT value to timeout in less than 50ms.  If the
  138. //USB_ENABLE_STATUS_STAGE_TIMEOUTS feature is not enabled, then the USB_STATUS_STAGE_TIMEOUT
  139. //parameter is not relevant.
  140.  
  141. #define USB_STATUS_STAGE_TIMEOUT     (BYTE)45   //Approximate timeout in milliseconds, except when
  142.                                                 //USB_POLLING mode is used, and USBDeviceTasks() is called at < 1kHz
  143.                                                 //In this special case, the timeout becomes approximately:
  144. //Timeout(in milliseconds) = ((1000 * (USB_STATUS_STAGE_TIMEOUT - 1)) / (USBDeviceTasks() polling frequency in Hz))
  145. //------------------------------------------------------------------------------------------------------------------
  146.  
  147. #define USB_SUPPORT_DEVICE
  148.  
  149. #define USB_NUM_STRING_DESCRIPTORS 3
  150.  
  151. //#define USB_INTERRUPT_LEGACY_CALLBACKS
  152. #define USB_ENABLE_ALL_HANDLERS
  153. //#define USB_ENABLE_SUSPEND_HANDLER
  154. //#define USB_ENABLE_WAKEUP_FROM_SUSPEND_HANDLER
  155. //#define USB_ENABLE_SOF_HANDLER
  156. //#define USB_ENABLE_ERROR_HANDLER
  157. //#define USB_ENABLE_OTHER_REQUEST_HANDLER
  158. //#define USB_ENABLE_SET_DESCRIPTOR_HANDLER
  159. //#define USB_ENABLE_INIT_EP_HANDLER
  160. //#define USB_ENABLE_EP0_DATA_HANDLER
  161. //#define USB_ENABLE_TRANSFER_COMPLETE_HANDLER
  162.  
  163. /** DEVICE CLASS USAGE *********************************************/
  164. #define USB_USE_HID
  165.  
  166. /** ENDPOINTS ALLOCATION *******************************************/
  167.  
  168. /* HID */
  169. #define HID_INTF_ID             0x00
  170. #define HID_EP                                  1
  171. #define HID_INT_OUT_EP_SIZE     64
  172. #define HID_INT_IN_EP_SIZE      64
  173. #define HID_NUM_OF_DSC          1
  174. #define HID_RPT01_SIZE          32
  175.  
  176. /** DEFINITIONS ****************************************************/
  177.  
  178. #endif //USBCFG_H


usb_descriptors.c
Código: C
  1. /********************************************************************
  2.  FileName:      usb_descriptors.c
  3.  Dependencies:  See INCLUDES section
  4.  Processor:             PIC18 or PIC24 USB Microcontrollers
  5.  Hardware:              The code is natively intended to be used on the following
  6.                                 hardware platforms: PICDEM™ FS USB Demo Board,
  7.                                 PIC18F87J50 FS USB Plug-In Module, or
  8.                                 Explorer 16 + PIC24 USB PIM.  The firmware may be
  9.                                 modified for use on other USB platforms by editing the
  10.                                 HardwareProfile.h file.
  11.  Complier:      Microchip C18 (for PIC18) or C30 (for PIC24)
  12.  Company:               Microchip Technology, Inc.
  13.  
  14.  Software License Agreement:
  15.  
  16.  The software supplied herewith by Microchip Technology Incorporated
  17.  (the “Company”) for its PIC® Microcontroller is intended and
  18.  supplied to you, the Company’s customer, for use solely and
  19.  exclusively on Microchip PIC Microcontroller products. The
  20.  software is owned by the Company and/or its supplier, and is
  21.  protected under applicable copyright laws. All rights are reserved.
  22.  Any use in violation of the foregoing restrictions may subject the
  23.  user to criminal sanctions under applicable laws, as well as to
  24.  civil liability for the breach of the terms and conditions of this
  25.  license.
  26.  
  27.  THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
  28.  WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
  29.  TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  30.  PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
  31.  IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
  32.  CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
  33.  
  34. *********************************************************************
  35. -usb_descriptors.c-
  36. -------------------------------------------------------------------
  37. Filling in the descriptor values in the usb_descriptors.c file:
  38. -------------------------------------------------------------------
  39.  
  40. [Device Descriptors]
  41. The device descriptor is defined as a USB_DEVICE_DESCRIPTOR type.  
  42. This type is defined in usb_ch9.h  Each entry into this structure
  43. needs to be the correct length for the data type of the entry.
  44.  
  45. [Configuration Descriptors]
  46. The configuration descriptor was changed in v2.x from a structure
  47. to a BYTE array.  Given that the configuration is now a byte array
  48. each byte of multi-byte fields must be listed individually.  This
  49. means that for fields like the total size of the configuration where
  50. the field is a 16-bit value "64,0," is the correct entry for a
  51. configuration that is only 64 bytes long and not "64," which is one
  52. too few bytes.
  53.  
  54. The configuration attribute must always have the _DEFAULT
  55. definition at the minimum. Additional options can be ORed
  56. to the _DEFAULT attribute. Available options are _SELF and _RWU.
  57. These definitions are defined in the usb_device.h file. The
  58. _SELF tells the USB host that this device is self-powered. The
  59. _RWU tells the USB host that this device supports Remote Wakeup.
  60.  
  61. [Endpoint Descriptors]
  62. Like the configuration descriptor, the endpoint descriptors were
  63. changed in v2.x of the stack from a structure to a BYTE array.  As
  64. endpoint descriptors also has a field that are multi-byte entities,
  65. please be sure to specify both bytes of the field.  For example, for
  66. the endpoint size an endpoint that is 64 bytes needs to have the size
  67. defined as "64,0," instead of "64,"
  68.  
  69. Take the following example:
  70.     // Endpoint Descriptor //
  71.     0x07,                       //the size of this descriptor //
  72.     USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
  73.     _EP02_IN,                   //EndpointAddress
  74.     _INT,                       //Attributes
  75.     0x08,0x00,                  //size (note: 2 bytes)
  76.     0x02,                       //Interval
  77.  
  78. The first two parameters are self-explanatory. They specify the
  79. length of this endpoint descriptor (7) and the descriptor type.
  80. The next parameter identifies the endpoint, the definitions are
  81. defined in usb_device.h and has the following naming
  82. convention:
  83. _EP<##>_<dir>
  84. where ## is the endpoint number and dir is the direction of
  85. transfer. The dir has the value of either 'OUT' or 'IN'.
  86. The next parameter identifies the type of the endpoint. Available
  87. options are _BULK, _INT, _ISO, and _CTRL. The _CTRL is not
  88. typically used because the default control transfer endpoint is
  89. not defined in the USB descriptors. When _ISO option is used,
  90. addition options can be ORed to _ISO. Example:
  91. _ISO|_AD|_FE
  92. This describes the endpoint as an isochronous pipe with adaptive
  93. and feedback attributes. See usb_device.h and the USB
  94. specification for details. The next parameter defines the size of
  95. the endpoint. The last parameter in the polling interval.
  96.  
  97. -------------------------------------------------------------------
  98. Adding a USB String
  99. -------------------------------------------------------------------
  100. A string descriptor array should have the following format:
  101.  
  102. rom struct{byte bLength;byte bDscType;word string[size];}sdxxx={
  103. sizeof(sdxxx),DSC_STR,<text>};
  104.  
  105. The above structure provides a means for the C compiler to
  106. calculate the length of string descriptor sdxxx, where xxx is the
  107. index number. The first two bytes of the descriptor are descriptor
  108. length and type. The rest <text> are string texts which must be
  109. in the unicode format. The unicode format is achieved by declaring
  110. each character as a word type. The whole text string is declared
  111. as a word array with the number of characters equals to <size>.
  112. <size> has to be manually counted and entered into the array
  113. declaration. Let's study this through an example:
  114. if the string is "USB" , then the string descriptor should be:
  115. (Using index 02)
  116. rom struct{byte bLength;byte bDscType;word string[3];}sd002={
  117. sizeof(sd002),DSC_STR,'U','S','B'};
  118.  
  119. A USB project may have multiple strings and the firmware supports
  120. the management of multiple strings through a look-up table.
  121. The look-up table is defined as:
  122. rom const unsigned char *rom USB_SD_Ptr[]={&sd000,&sd001,&sd002};
  123.  
  124. The above declaration has 3 strings, sd000, sd001, and sd002.
  125. Strings can be removed or added. sd000 is a specialized string
  126. descriptor. It defines the language code, usually this is
  127. US English (0x0409). The index of the string must match the index
  128. position of the USB_SD_Ptr array, &sd000 must be in position
  129. USB_SD_Ptr[0], &sd001 must be in position USB_SD_Ptr[1] and so on.
  130. The look-up table USB_SD_Ptr is used by the get string handler
  131. function.
  132.  
  133. -------------------------------------------------------------------
  134.  
  135. The look-up table scheme also applies to the configuration
  136. descriptor. A USB device may have multiple configuration
  137. descriptors, i.e. CFG01, CFG02, etc. To add a configuration
  138. descriptor, user must implement a structure similar to CFG01.
  139. The next step is to add the configuration descriptor name, i.e.
  140. cfg01, cfg02,.., to the look-up table USB_CD_Ptr. USB_CD_Ptr[0]
  141. is a dummy place holder since configuration 0 is the un-configured
  142. state according to the definition in the USB specification.
  143.  
  144. ********************************************************************/
  145.  
  146. /*********************************************************************
  147.  * Descriptor specific type definitions are defined in:
  148.  * usb_device.h
  149.  *
  150.  * Configuration options are defined in:
  151.  * usb_config.h
  152.  ********************************************************************/
  153. #ifndef __USB_DESCRIPTORS_C
  154. #define __USB_DESCRIPTORS_C
  155.  
  156. /** INCLUDES *******************************************************/
  157. #include "./USB/usb.h"
  158. #include "./USB/usb_function_hid.h"
  159.  
  160. /** CONSTANTS ******************************************************/
  161. #if defined (COMPILER_MPLAB_C18)
  162. #pragma romdata
  163. #endif
  164.  
  165. /* Device Descriptor */
  166. ROM USB_DEVICE_DESCRIPTOR device_dsc=
  167. {
  168.     0x12,    // Size of this descriptor in bytes
  169.     USB_DESCRIPTOR_DEVICE,                // DEVICE descriptor type
  170.     0x0200,                 // USB Spec Release Number in BCD format
  171.     0x00,                   // Class Code
  172.     0x00,                   // Subclass code
  173.     0x00,                   // Protocol code
  174.     USB_EP0_BUFF_SIZE,      // Max packet size for EP0, see usb_config.h
  175.     MY_VID,                 // Vendor ID, see usb_config.h
  176.     MY_PID,                 // Product ID, see usb_config.h
  177.     0x0001,                 // Device release number in BCD format
  178.     0x01,                   // Manufacturer string index
  179.     0x02,                   // Product string index
  180.     0x00,                   // Device serial number string index
  181.     0x01                    // Number of possible configurations
  182. };
  183.  
  184. /* Configuration 1 Descriptor */
  185. ROM BYTE configDescriptor1[]={
  186.     /* Configuration Descriptor */
  187.     0x09,//sizeof(USB_CFG_DSC),    // Size of this descriptor in bytes
  188.     USB_DESCRIPTOR_CONFIGURATION,                // CONFIGURATION descriptor type
  189.     DESC_CONFIG_WORD(0x0029),   // Total length of data for this cfg
  190.     1,                      // Number of interfaces in this cfg
  191.     1,                      // Index value of this configuration
  192.     0,                      // Configuration string index
  193.     _DEFAULT | _SELF,               // Attributes, see usb_device.h
  194.     50,                     // Max power consumption (2X mA)
  195.  
  196.     /* Interface Descriptor */
  197.     0x09,//sizeof(USB_INTF_DSC),   // Size of this descriptor in bytes
  198.     USB_DESCRIPTOR_INTERFACE,               // INTERFACE descriptor type
  199.     0,                      // Interface Number
  200.     0,                      // Alternate Setting Number
  201.     2,                      // Number of endpoints in this intf
  202.     HID_INTF,               // Class code
  203.     0,     // Subclass code
  204.     0,     // Protocol code
  205.     0,                      // Interface string index
  206.  
  207.     /* HID Class-Specific Descriptor */
  208.     0x09,//sizeof(USB_HID_DSC)+3,    // Size of this descriptor in bytes RRoj hack
  209.     DSC_HID,                // HID descriptor type
  210.     DESC_CONFIG_WORD(0x0111),                 // HID Spec Release Number in BCD format (1.11)
  211.     0x00,                   // Country Code (0x00 for Not supported)
  212.     HID_NUM_OF_DSC,         // Number of class descriptors, see usbcfg.h
  213.     DSC_RPT,                // Report descriptor type
  214.     DESC_CONFIG_WORD(HID_RPT01_SIZE),   //sizeof(hid_rpt01),      // Size of the report descriptor
  215.    
  216.     /* Endpoint Descriptor */
  217.     0x07,/*sizeof(USB_EP_DSC)*/
  218.     USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
  219.     HID_EP | _EP_IN,            //EndpointAddress
  220.     _INTERRUPT,                       //Attributes
  221.     DESC_CONFIG_WORD(64),        //size
  222.     0x01,                        //Interval
  223.  
  224.     /* Endpoint Descriptor */
  225.     0x07,/*sizeof(USB_EP_DSC)*/
  226.     USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
  227.     HID_EP | _EP_OUT,            //EndpointAddress
  228.     _INTERRUPT,                       //Attributes
  229.     DESC_CONFIG_WORD(64),        //size
  230.     0x01                        //Interval
  231. };
  232.  
  233.  
  234. //Language code string descriptor
  235. ROM struct{BYTE bLength;BYTE bDscType;WORD string[1];}sd000={
  236. sizeof(sd000),USB_DESCRIPTOR_STRING,{0x0409
  237. }};
  238.  
  239. //Manufacturer string descriptor
  240. ROM struct{BYTE bLength;BYTE bDscType;WORD string[25];}sd001={
  241. sizeof(sd001),USB_DESCRIPTOR_STRING,
  242. {'M','i','c','r','o','c','h','i','p',' ',
  243. 'T','e','c','h','n','o','l','o','g','y',' ','I','n','c','.'
  244. }};
  245.  
  246. //Product string descriptor
  247. ROM struct{BYTE bLength;BYTE bDscType;WORD string[22];}sd002={
  248. sizeof(sd002),USB_DESCRIPTOR_STRING,
  249. {'J','o','y','s','t','i','c','k',' ','D','e','m','o'
  250. }};
  251.  
  252. //Array of configuration descriptors
  253. ROM BYTE *ROM USB_CD_Ptr[]=
  254. {
  255.     (ROM BYTE *ROM)&configDescriptor1
  256. };
  257.  
  258. //Array of string descriptors
  259. ROM BYTE *ROM USB_SD_Ptr[]=
  260. {
  261.     (ROM BYTE *ROM)&sd000,
  262.     (ROM BYTE *ROM)&sd001,
  263.     (ROM BYTE *ROM)&sd002
  264. };
  265.  
  266. ROM struct{BYTE report[HID_RPT01_SIZE];}hid_rpt01={{
  267.     0x05, 0x01,                    // USAGE_PAGE (Generic Desktop)
  268.     0x09, 0x04,                    // USAGE (Joystick)
  269.     0xa1, 0x01,                    // COLLECTION (Application)
  270.     0xa1, 0x00,                    //   COLLECTION (Physical)
  271.     0x05, 0x09,                    //     USAGE_PAGE (Button)
  272.     0x19, 0x01,                    //     USAGE_MINIMUM (Button 1)
  273.     0x29, 0x01,                    //     USAGE_MAXIMUM (Button 1)
  274.     0x15, 0x00,                    //     LOGICAL_MINIMUM (0)
  275.     0x25, 0x01,                    //     LOGICAL_MAXIMUM (1)
  276.     0x75, 0x01,                    //     REPORT_SIZE (1)
  277.     0x95, 0x01,                    //     REPORT_COUNT (1)
  278.     0x81, 0x02,                    //     INPUT (Data,Var,Abs,NPrf)
  279.     0x75, 0x07,                    //     REPORT_SIZE (7)
  280.     0x95, 0x01,                    //     REPORT_COUNT (1)
  281.     0x81, 0x03,                    //     INPUT (Cnst,Var,Abs,NPrf)
  282.     0xc0,                          //   END_COLLECTION
  283.     0xc0
  284. }
  285. };
  286. /** EOF usb_descriptors.c ***************************************************/
Título: Re: ¿USB con compilador XC?
Publicado por: elgarbe en 15 de Noviembre de 2013, 13:54:13
Sigo de cerca el tema. en breve me gustaría comenzar con algunas pruebitas con usb.
Podrías hacer una breve introduccion como para hubicarme, que es cdc, hid, stack, algo de hardware y que programa usas en la pc para comunicarte con el pic? un par de líneas nada mas, como para entrar en tema, despues veré de ampliar por mi parte cuando lo necesite...

Saludos y gracias!
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 15 de Noviembre de 2013, 20:45:33
Sigo de cerca el tema. en breve me gustaría comenzar con algunas pruebitas con usb.
Podrías hacer una breve introduccion como para hubicarme, que es cdc, hid, stack, algo de hardware y que programa usas en la pc para comunicarte con el pic? un par de líneas nada mas, como para entrar en tema, despues veré de ampliar por mi parte cuando lo necesite...

Saludos y gracias!

  Tendrías que buscar información acerca del protocolo USB. El tema es muy complejo y escapa a mis conocimientos.
Básicamente existen diferentes "clases" de dispositivos. Las clases definen un comportamiento común o similar así, por ejemplo, la clase HID define "parámetros" comunes para aquellos dispositivos orientados a los usuarios (teclados, mouse, joystick)... aunque también se puede adaptar a necesidades propias.
  También existen distintos tipos de comunicación.



  CDC: Comunications Device Class. Básicamente es para comunicación y es la utilizada por los adaptadores USB-RS232
  HID: Human Interface Device: Básicamente son dispositivos que interactúan con las personas

  Como Hardare, algún PIC que posea módulo USB.

  En cuanto a programas, depende lo que quieras hacer. En el caso del Joystick basta con cualquier juego  :D En el caso de un dispositivo CDC, puedes comunicarte con cualquier elemento que requiera un puerto RS232.


  Por supuesto hay muchísimas más cosas,
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 23 de Noviembre de 2013, 17:31:09
  Aquí tienen información en castellano acerca de USB http://devel.no-ip.org/hardware/USB0000/index.html , no comprobé todos los artículos, pero algunos parecen ser una traducción de este otro sitio http://www.beyondlogic.org/usbnutshell/usb1.shtml .

  Estoy armando un PDF con todo lo extraído del sitio en castellano y me encuentro con algunos párrafos un tanto extraños -tal vez debido a la traducción- así me tomaré un tiempo mayor y en la medida de los posible iré cotejando está información con la encontrada en las especificaciones del standar USB www.usb.org Éste último sitio es el oficial por lo tanto también encontrarán información necesaria referida a las distintas clases. Además, hay una utilidad llamada DescriptorTool que sirve para generar el "report descriptor" para dispositivos HID
Título: Re: ¿USB con compilador XC?
Publicado por: pajaro en 24 de Noviembre de 2013, 15:04:42
Hola AngelGris

No via antes este hilo...
a veces me los marca como leidos... no se por que lo hace...,
compañero me parece muy interesante tu hilo, pero muy interesante,

yo al igual que vos simpre he querido saber sobre el usb en los PIC , mire hace ya tiempos por el foro,
en la web de redpic, en la de MigSantiago y otras ... los diseños son muy parecidos.
Pero la documentación se me hacia muy pesada de leer, soy más de "poco pan y más chicha".

Desde hace un tiempo tengo montas 2 placas blancas y en una tengo un pic18F2550
y en la otra un PIC18F4550, muchas veces he retomado el tema,
pero por el momento simpre termina la cosa igual, y ahi esta...

Esta puede que sea mi oportunidad de arrancar de una vez por todas.
Yo por el momento programo en C con el ide de CCS, y me "ayudo" de la simulación de proteus,
actualmnete estos mirando otros compiladores para C e IDEs y me atrae el eclipse bajo linux,
me gustaria unirme al hilo y ir probando cosas ¿como lo ves compañero?

creo que puede llegar a ser hasta divertido.

voy a leer tu hilo desde el principio con más detalle.

Un Saluso.


Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 24 de Noviembre de 2013, 16:34:08
  ¿Y quién soy yo para decir que no entres al hilo? Por supuesto que te puedes unir, como cualquier otro usuario... entre mas gente opine y comente sus resultados (mas experiencias sumadas) seguro será mejor para todos.
Título: Re: ¿USB con compilador XC?
Publicado por: pajaro en 24 de Noviembre de 2013, 21:44:06
Hola AngelGris

La invitación no era para entrar en el hilo,...   :D
sino era para convertirlo en una especie de juego  :mrgreen:

y la invitacion era para ver si querias jugar
...y si se une a este juego mas gente....  :-/  pues mejor.

Por el momemto no has contado con que hardware cuentas.
¿lo estas simulando con proteus o fisicamente en placa?

entre lineas puedo leer que lo programas en XC
pero sobre que sistema operativo , window, linux,..?
¿el IDE es MPLAB...?

un saludo

Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 24 de Noviembre de 2013, 22:14:00
Hola AngelGris

La invitación no era para entrar en el hilo,...   :D
sino era para convertirlo en una especie de juego  :mrgreen:

y la invitacion era para ver si querias jugar
...y si se une a este juego mas gente....  :-/  pues mejor.



  Es que mi raciocinio es tan escaso que no da para esas interpretaciones  :oops:



Por el momemto no has contado con que hardware cuentas.
¿lo estas simulando con proteus o fisicamente en placa?

entre lineas puedo leer que lo programas en XC
pero sobre que sistema operativo , window, linux,..?
¿el IDE es MPLAB...?

un saludo



  Como IDE estoy utilizando MPLABX y el compilador es XC8. Lo uso desde linux, Debian Wheezy amd64.
No tengo nada hecho en físico simplemente por el momento estoy simulando en Proteus desde una máquina virtual con XP en VirtualBox.

  Anteriormente utilizaba el compilador HiTech y había una versión para familias 12F-16F y otra para la 18F. Éste compilador que fue adquirido por Microchip (en realidad supongo que adquirieron toda la compañía HTSoft) ahora pasó a llamarse XC. Existe XC8 para 10F, 12F, 16F y 18F; XC16 y XC32.

  El stack original de Microchip era para C18 (que es otro compilador) y por lo que estuve leyendo hubo gente que ya había probado con éxito dicho stack con el compilador XC32, pero en XC8 fallaba.

  Ahora, gracias a las modificaciones sugeridas por el usuario jtemples del foro de microchip por fin funciona el stack con el compilador XC8
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 25 de Noviembre de 2013, 18:22:40
  Adjunto el pdf armado con la información del sitio que mencionaba con anterioridad. Efectivamente tuve que corregir algunos párrafos.
Título: Re: ¿USB con compilador XC?
Publicado por: pajaro en 25 de Noviembre de 2013, 21:26:19
Hola AngelGris

voy a bajarlo y le pongo un ojo,
luego te cuento,...

hola..
 estoy en la lectura aun, la verdad es que hay mucha info, casi 40 hojas
es estoy en la lectura comprensiva..aun estoy en la hoja 10.. :D

luego te preguntare algunas cosas,...

AngelGris cuantos dias llevas con este estudio..?

si montaramos un circuito de pic 18F2550

¿cual seria el primer paso a realizar despues de leer el pdf?


un Saludo.

Título: Re: ¿USB con compilador XC?
Publicado por: calavia en 23 de Enero de 2014, 20:40:18
AngelGris, veras soy algo nuevo en esto y necesito ayuda en este tema.

¿Tu usas MPLAB X? esque a la hora de la configuración de donde tiene que buscar los archivos el compilador cambia. Yo también uso el compilador XC8 de ahí que me interese este tema.

Por otro lado... estoy intentando hacer un CDC, tenía un FTDI para la conversión RS232 USB, pero es demasiado caro tener que conseguir uno cada vez que utilizo un pic para un proyecto nuevo. Y he intentado como tienes puesto ahí arriba, pero no tengo manera de conseguir que me compile... me va sacando fallos por todos lados.

¿Cómo configuras en este caso el PIC para que te reconozca la interrupción del USB y para leer los datos que se han mandado?
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 23 de Enero de 2014, 21:06:18
Hola AngelGris

voy a bajarlo y le pongo un ojo,
luego te cuento,...

hola..
 estoy en la lectura aun, la verdad es que hay mucha info, casi 40 hojas
es estoy en la lectura comprensiva..aun estoy en la hoja 10.. :D

luego te preguntare algunas cosas,...

AngelGris cuantos dias llevas con este estudio..?

si montaramos un circuito de pic 18F2550

¿cual seria el primer paso a realizar despues de leer el pdf?


un Saludo.



  Hola pajaro, no recuerdo haber tenido una notificación de tu mensaje. Te pido disculpas si no te contesté anteriormente, te aseguro que no fue mala voluntad.

  De estudio te diría que fueron muchísimos, porque primeramente había leido algo pero me mareaba un poco tanta información y no poder hacer funcionar nada y lo dejé de lado. Luego lo volvía a agarrar y lo empecé a leer mas detenidamente y como había encontrado la forma de que funcionen con XC las librerías de microchip me entusiasmé y prestaba más atención a algunas cosas. Pero ciertamente no dejo de pensar que es bastante complejo el tema del USB.

  En cuanto a montar un circuito, supongo que dependerá un poco que lo que quieras armar... como mencioné en otro mensaje, logré simular tanto CDC como un joystick HID. Supongo que se podría experimentar con una clase propia.... pero todavía no llegué a ese punto
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 23 de Enero de 2014, 21:11:26
AngelGris, veras soy algo nuevo en esto y necesito ayuda en este tema.

¿Tu usas MPLAB X? esque a la hora de la configuración de donde tiene que buscar los archivos el compilador cambia. Yo también uso el compilador XC8 de ahí que me interese este tema.

Por otro lado... estoy intentando hacer un CDC, tenía un FTDI para la conversión RS232 USB, pero es demasiado caro tener que conseguir uno cada vez que utilizo un pic para un proyecto nuevo. Y he intentado como tienes puesto ahí arriba, pero no tengo manera de conseguir que me compile... me va sacando fallos por todos lados.

¿Cómo configuras en este caso el PIC para que te reconozca la interrupción del USB y para leer los datos que se han mandado?

  Sí, utilizo MPLABX desde debian.
  Luego te subo el ejemplo que tengo compilado para CDC. Te recomiendo la lectura del post de jfmateos2 Dicho ejemplo es simplemente un echo... el pic recibe un dato por el puerto RS232 virtual y lo devuelve y aparece en el terminal.
Título: Re: ¿USB con compilador XC?
Publicado por: calavia en 23 de Enero de 2014, 21:19:16
  Sí, utilizo MPLABX desde debian.
  Luego te subo el ejemplo que tengo compilado para CDC. Te recomiendo la lectura del post de jfmateos2 Dicho ejemplo es simplemente un echo... el pic recibe un dato por el puerto RS232 virtual y lo devuelve y aparece en el terminal.

He leido lo que has subido ahí, pero el problema lo tengo a la hora de incluir al compilador la ruta donde están los demás archivos
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 23 de Enero de 2014, 23:46:28
  En el stack de microchip hay distintos archivos ya sea .C o .H, según lo que se quiera armar. Por ejemplo para un dispositivo HID, el archivo .C a utilizar es usb_function_hid.c, para CDC es usb_function_cdc.c. Lo que hago es tomar el archivo que necesite y copiarlo en la carpeta de mi proyecto. También copio en la carpeta del proyecto el archivo usb_device.c

  Además en la carpeta del proyecto debe existir un archivo llamado usb_descriptor.c, otro llamado usb_config.h y otro llamado HardwareProfile.h

  También hay que configurar en el proyecto los PATH para que apunten a un par de carpetas del stack USB..

  Los archivos .C que están dentro de la carpeta del proyecto los agrego al mismo en la opción Sources Files

  Te adjunto una captura de pantalla donde se aprecia los archivos agregados a Sources Files, y los PAHT agregados en la opción del compilador
Título: Re: ¿USB con compilador XC?
Publicado por: calavia en 24 de Enero de 2014, 05:48:06
He hecho lo que tienes ahí puesto, vaya me da ahora menos errores, pero sigo con problemas en el archivo "usb_function_cdc.h"

EDITO: he conseguido que compile, pero no me reconoce el dispositivo en el ISIS en el ejemplo que has dicho al principio. Problema del ISIS no es, porque si ejecuto ese mismo ejemplo me reconoce un nuevo dispositivo :(
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 24 de Enero de 2014, 09:55:35

EDITO: he conseguido que compile, pero no me reconoce el dispositivo en el ISIS en el ejemplo que has dicho al principio. Problema del ISIS no es, porque si ejecuto ese mismo ejemplo me reconoce un nuevo dispositivo :(

  No entiendo.  :oops: ¿Cuál ejemplo es el que funciona, el que trae el propio ISIS?

  Estos son los archivos que utilicé para la simulación...

  main.c
Código: C
  1. #include <xc.h>
  2.  
  3.  
  4. // CONFIG1L
  5. #pragma config PLLDIV = 5       // PLL Prescaler Selection bits (Divide by 5 (20 MHz oscillator input))
  6. #pragma config CPUDIV = OSC1_PLL2// System Clock Postscaler Selection bits ([Primary Oscillator Src: /1][96 MHz PLL Src: /2])
  7. #pragma config USBDIV = 2       // USB Clock Selection bit (used in Full-Speed USB mode only; UCFG:FSEN = 1) (USB clock source comes from the 96 MHz PLL divided by 2)
  8.  
  9. // CONFIG1H
  10. #pragma config FOSC = HSPLL_HS  // Oscillator Selection bits (HS oscillator, PLL enabled (HSPLL))
  11. #pragma config FCMEN = OFF      // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor disabled)
  12. #pragma config IESO = OFF       // Internal/External Oscillator Switchover bit (Oscillator Switchover mode disabled)
  13.  
  14. // CONFIG2L
  15. #pragma config PWRT = OFF       // Power-up Timer Enable bit (PWRT disabled)
  16. #pragma config BOR = ON         // Brown-out Reset Enable bits (Brown-out Reset enabled in hardware only (SBOREN is disabled))
  17. #pragma config BORV = 3         // Brown-out Reset Voltage bits (Minimum setting)
  18. #pragma config VREGEN = ON      // USB Voltage Regulator Enable bit (USB voltage regulator enabled)
  19.  
  20. // CONFIG2H
  21. #pragma config WDT = OFF        // Watchdog Timer Enable bit (WDT disabled (control is placed on the SWDTEN bit))
  22. #pragma config WDTPS = 32768    // Watchdog Timer Postscale Select bits (1:32768)
  23.  
  24. // CONFIG3H
  25. #pragma config CCP2MX = ON      // CCP2 MUX bit (CCP2 input/output is multiplexed with RC1)
  26. #pragma config PBADEN = OFF     // PORTB A/D Enable bit (PORTB<4:0> pins are configured as digital I/O on Reset)
  27. #pragma config LPT1OSC = OFF    // Low-Power Timer 1 Oscillator Enable bit (Timer1 configured for higher power operation)
  28. #pragma config MCLRE = ON       // MCLR Pin Enable bit (MCLR pin enabled; RE3 input pin disabled)
  29.  
  30. // CONFIG4L
  31. #pragma config STVREN = ON      // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)
  32. #pragma config LVP = OFF        // Single-Supply ICSP Enable bit (Single-Supply ICSP disabled)
  33. #pragma config XINST = OFF      // Extended Instruction Set Enable bit (Instruction set extension and Indexed Addressing mode disabled (Legacy mode))
  34.  
  35. // CONFIG5L
  36. #pragma config CP0 = OFF        // Code Protection bit (Block 0 (000800-001FFFh) is not code-protected)
  37. #pragma config CP1 = OFF        // Code Protection bit (Block 1 (002000-003FFFh) is not code-protected)
  38. #pragma config CP2 = OFF        // Code Protection bit (Block 2 (004000-005FFFh) is not code-protected)
  39. #pragma config CP3 = OFF        // Code Protection bit (Block 3 (006000-007FFFh) is not code-protected)
  40.  
  41. // CONFIG5H
  42. #pragma config CPB = OFF        // Boot Block Code Protection bit (Boot block (000000-0007FFh) is not code-protected)
  43. #pragma config CPD = OFF        // Data EEPROM Code Protection bit (Data EEPROM is not code-protected)
  44.  
  45. // CONFIG6L
  46. #pragma config WRT0 = OFF       // Write Protection bit (Block 0 (000800-001FFFh) is not write-protected)
  47. #pragma config WRT1 = OFF       // Write Protection bit (Block 1 (002000-003FFFh) is not write-protected)
  48. #pragma config WRT2 = OFF       // Write Protection bit (Block 2 (004000-005FFFh) is not write-protected)
  49. #pragma config WRT3 = OFF       // Write Protection bit (Block 3 (006000-007FFFh) is not write-protected)
  50.  
  51. // CONFIG6H
  52. #pragma config WRTC = OFF       // Configuration Register Write Protection bit (Configuration registers (300000-3000FFh) are not write-protected)
  53. #pragma config WRTB = OFF       // Boot Block Write Protection bit (Boot block (000000-0007FFh) is not write-protected)
  54. #pragma config WRTD = OFF       // Data EEPROM Write Protection bit (Data EEPROM is not write-protected)
  55.  
  56. // CONFIG7L
  57. #pragma config EBTR0 = OFF      // Table Read Protection bit (Block 0 (000800-001FFFh) is not protected from table reads executed in other blocks)
  58. #pragma config EBTR1 = OFF      // Table Read Protection bit (Block 1 (002000-003FFFh) is not protected from table reads executed in other blocks)
  59. #pragma config EBTR2 = OFF      // Table Read Protection bit (Block 2 (004000-005FFFh) is not protected from table reads executed in other blocks)
  60. #pragma config EBTR3 = OFF      // Table Read Protection bit (Block 3 (006000-007FFFh) is not protected from table reads executed in other blocks)
  61.  
  62. // CONFIG7H
  63. #pragma config EBTRB = OFF      // Boot Block Table Read Protection bit (Boot block (000000-0007FFh) is not protected from table reads executed in other blocks)
  64.  
  65.  
  66.  
  67.  
  68. //#include <stdio.h>
  69. //#include <string.h>
  70. /** I N C L U D E S **********************************************************/
  71. #include "usb_config.h"
  72. #include "HardwareProfile.h"
  73. #include "./USB/usb.h"
  74. #include "./USB/usb_function_cdc.h"
  75.  
  76.  
  77. /** V A R I A B L E S ********************************************************/
  78. char USB_Out_Buffer[64];
  79. char buffer[64];
  80.  
  81.  
  82.  
  83. /** P R I V A T E  P R O T O T Y P E S ***************************************/
  84. void ProcessIO(void);
  85.  
  86.  
  87. void interrupt high_priority isr(void)
  88. {
  89.     USBDeviceTasks();
  90. }
  91.  
  92.  
  93. /** DECLARATIONS ***************************************************/
  94. void main(void)
  95. {
  96.     TRISA = 0xFF;
  97.     ADCON1 = 0x0F;      // entradas digitales
  98.  
  99.  
  100.     USBDeviceInit();    //usb_device.c.  Initializes USB module SFRs and firmware
  101.                                         //variables to known states.
  102.  
  103.     while(1)
  104.     {
  105.         //USBDeviceTasks();
  106.         #if defined(USB_INTERRUPT)
  107.             if(USB_BUS_SENSE && (USBGetDeviceState() == DETACHED_STATE))
  108.             {
  109.                 USBDeviceAttach();
  110.             }
  111.         #endif
  112.         ProcessIO();
  113.     }//end while
  114. }//end main
  115.  
  116.  
  117.  
  118. /********************************************************************
  119.  * Function:        void ProcessIO(void)
  120.  *
  121.  * PreCondition:    None
  122.  *
  123.  * Input:           None
  124.  *
  125.  * Output:          None
  126.  *
  127.  * Side Effects:    None
  128.  *
  129.  * Overview:        This function is a place holder for other user
  130.  *                  routines. It is a mixture of both USB and
  131.  *                  non-USB tasks.
  132.  *
  133.  * Note:            None
  134.  *******************************************************************/
  135. void ProcessIO(void)
  136. {
  137.     BYTE numBytesRead;
  138.  
  139.     // User Application USB tasks
  140.     if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;
  141.  
  142.     if(USBUSARTIsTxTrfReady())
  143.     {
  144.                 numBytesRead = getsUSBUSART(USB_Out_Buffer,64);
  145.                 if(numBytesRead != 0)
  146.                 {
  147.                         strcpypgm2ram(buffer,(const rom far char *)"Ha pulsado: ");
  148.                         strncat(buffer,USB_Out_Buffer,numBytesRead);
  149.                         strcatpgm2ram(buffer,(const rom far char *)"\r\n");
  150.                         putsUSBUSART(buffer);
  151.                 }
  152.         }
  153.     CDCTxService();
  154. }               //end ProcessIO
  155.  
  156.  
  157.  
  158.  
  159.  
  160. // ******************************************************************************************************
  161. // ************** USB Callback Functions ****************************************************************
  162. // ******************************************************************************************************
  163. // The USB firmware stack will call the callback functions USBCBxxx() in response to certain USB related
  164. // events.  For example, if the host PC is powering down, it will stop sending out Start of Frame (SOF)
  165. // packets to your device.  In response to this, all USB devices are supposed to decrease their power
  166. // consumption from the USB Vbus to <2.5mA each.  The USB module detects this condition (which according
  167. // to the USB specifications is 3+ms of no bus activity/SOF packets) and then calls the USBCBSuspend()
  168. // function.  You should modify these callback functions to take appropriate actions for each of these
  169. // conditions.  For example, in the USBCBSuspend(), you may wish to add code that will decrease power
  170. // consumption from Vbus to <2.5mA (such as by clock switching, turning off LEDs, putting the
  171. // microcontroller to sleep, etc.).  Then, in the USBCBWakeFromSuspend() function, you may then wish to
  172. // add code that undoes the power saving things done in the USBCBSuspend() function.
  173.  
  174. // The USBCBSendResume() function is special, in that the USB stack will not automatically call this
  175. // function.  This function is meant to be called from the application firmware instead.  See the
  176. // additional comments near the function.
  177.  
  178.  
  179. /*******************************************************************
  180.  * Function:        void USBCBCheckOtherReq(void)
  181.  *
  182.  * PreCondition:    None
  183.  *
  184.  * Input:           None
  185.  *
  186.  * Output:          None
  187.  *
  188.  * Side Effects:    None
  189.  *
  190.  * Overview:        When SETUP packets arrive from the host, some
  191.  *                                      firmware must process the request and respond
  192.  *                                      appropriately to fulfill the request.  Some of
  193.  *                                      the SETUP packets will be for standard
  194.  *                                      USB "chapter 9" (as in, fulfilling chapter 9 of
  195.  *                                      the official USB specifications) requests, while
  196.  *                                      others may be specific to the USB device class
  197.  *                                      that is being implemented.  For example, a HID
  198.  *                                      class device needs to be able to respond to
  199.  *                                      "GET REPORT" type of requests.  This
  200.  *                                      is not a standard USB chapter 9 request, and
  201.  *                                      therefore not handled by usb_device.c.  Instead
  202.  *                                      this request should be handled by class specific
  203.  *                                      firmware, such as that contained in usb_function_hid.c.
  204.  *
  205.  * Note:            None
  206.  *******************************************************************/
  207. void USBCBCheckOtherReq(void)
  208. {
  209.     USBCheckCDCRequest();
  210. }//end
  211.  
  212.  
  213.  
  214. /*******************************************************************
  215.  * Function:        void USBCBInitEP(void)
  216.  *
  217.  * PreCondition:    None
  218.  *
  219.  * Input:           None
  220.  *
  221.  * Output:          None
  222.  *
  223.  * Side Effects:    None
  224.  *
  225.  * Overview:        This function is called when the device becomes
  226.  *                  initialized, which occurs after the host sends a
  227.  *                                      SET_CONFIGURATION (wValue not = 0) request.  This
  228.  *                                      callback function should initialize the endpoints
  229.  *                                      for the device's usage according to the current
  230.  *                                      configuration.
  231.  *
  232.  * Note:            None
  233.  *******************************************************************/
  234. void USBCBInitEP(void)
  235. {
  236.     CDCInitEP();
  237. }
  238.  
  239.  
  240.  
  241. /*******************************************************************
  242.  * Function:        BOOL USER_USB_CALLBACK_EVENT_HANDLER(
  243.  *                        USB_EVENT event, void *pdata, WORD size)
  244.  *
  245.  * PreCondition:    None
  246.  *
  247.  * Input:           USB_EVENT event - the type of event
  248.  *                  void *pdata - pointer to the event data
  249.  *                  WORD size - size of the event data
  250.  *
  251.  * Output:          None
  252.  *
  253.  * Side Effects:    None
  254.  *
  255.  * Overview:        This function is called from the USB stack to
  256.  *                  notify a user application that a USB event
  257.  *                  occured.  This callback is in interrupt context
  258.  *                  when the USB_INTERRUPT option is selected.
  259.  *
  260.  * Note:            None
  261.  *******************************************************************/
  262. BOOL USER_USB_CALLBACK_EVENT_HANDLER(USB_EVENT event, void *pdata, WORD size)
  263. {
  264.     switch(event)
  265.     {
  266.         case EVENT_CONFIGURED:
  267.             USBCBInitEP();
  268.             break;
  269.         case EVENT_EP0_REQUEST:
  270.             USBCBCheckOtherReq();
  271.             break;
  272.         default:
  273.             break;
  274.     }
  275.     return TRUE;
  276. }
  277.  
  278.  
  279. /** EOF main.c *************************************************/

usb_descriptor.c
Código: C
  1. /********************************************************************
  2.  FileName:      usb_descriptors.c
  3.  Dependencies:  See INCLUDES section
  4.  Processor:             PIC18 or PIC24 USB Microcontrollers
  5.  Hardware:              The code is natively intended to be used on the following
  6.                                 hardware platforms: PICDEM™ FS USB Demo Board,
  7.                                 PIC18F87J50 FS USB Plug-In Module, or
  8.                                 Explorer 16 + PIC24 USB PIM.  The firmware may be
  9.                                 modified for use on other USB platforms by editing the
  10.                                 HardwareProfile.h file.
  11.  Complier:      Microchip C18 (for PIC18) or C30 (for PIC24)
  12.  Company:               Microchip Technology, Inc.
  13.  
  14.  Software License Agreement:
  15.  
  16.  The software supplied herewith by Microchip Technology Incorporated
  17.  (the “Company”) for its PIC® Microcontroller is intended and
  18.  supplied to you, the Company’s customer, for use solely and
  19.  exclusively on Microchip PIC Microcontroller products. The
  20.  software is owned by the Company and/or its supplier, and is
  21.  protected under applicable copyright laws. All rights are reserved.
  22.  Any use in violation of the foregoing restrictions may subject the
  23.  user to criminal sanctions under applicable laws, as well as to
  24.  civil liability for the breach of the terms and conditions of this
  25.  license.
  26.  
  27.  THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
  28.  WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
  29.  TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  30.  PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
  31.  IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
  32.  CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
  33.  
  34. *********************************************************************
  35. -usb_descriptors.c-
  36. -------------------------------------------------------------------
  37. Filling in the descriptor values in the usb_descriptors.c file:
  38. -------------------------------------------------------------------
  39.  
  40. [Device Descriptors]
  41. The device descriptor is defined as a USB_DEVICE_DESCRIPTOR type.  
  42. This type is defined in usb_ch9.h  Each entry into this structure
  43. needs to be the correct length for the data type of the entry.
  44.  
  45. [Configuration Descriptors]
  46. The configuration descriptor was changed in v2.x from a structure
  47. to a BYTE array.  Given that the configuration is now a byte array
  48. each byte of multi-byte fields must be listed individually.  This
  49. means that for fields like the total size of the configuration where
  50. the field is a 16-bit value "64,0," is the correct entry for a
  51. configuration that is only 64 bytes long and not "64," which is one
  52. too few bytes.
  53.  
  54. The configuration attribute must always have the _DEFAULT
  55. definition at the minimum. Additional options can be ORed
  56. to the _DEFAULT attribute. Available options are _SELF and _RWU.
  57. These definitions are defined in the usb_device.h file. The
  58. _SELF tells the USB host that this device is self-powered. The
  59. _RWU tells the USB host that this device supports Remote Wakeup.
  60.  
  61. [Endpoint Descriptors]
  62. Like the configuration descriptor, the endpoint descriptors were
  63. changed in v2.x of the stack from a structure to a BYTE array.  As
  64. endpoint descriptors also has a field that are multi-byte entities,
  65. please be sure to specify both bytes of the field.  For example, for
  66. the endpoint size an endpoint that is 64 bytes needs to have the size
  67. defined as "64,0," instead of "64,"
  68.  
  69. Take the following example:
  70.     // Endpoint Descriptor //
  71.     0x07,                       //the size of this descriptor //
  72.     USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
  73.     _EP02_IN,                   //EndpointAddress
  74.     _INT,                       //Attributes
  75.     0x08,0x00,                  //size (note: 2 bytes)
  76.     0x02,                       //Interval
  77.  
  78. The first two parameters are self-explanatory. They specify the
  79. length of this endpoint descriptor (7) and the descriptor type.
  80. The next parameter identifies the endpoint, the definitions are
  81. defined in usb_device.h and has the following naming
  82. convention:
  83. _EP<##>_<dir>
  84. where ## is the endpoint number and dir is the direction of
  85. transfer. The dir has the value of either 'OUT' or 'IN'.
  86. The next parameter identifies the type of the endpoint. Available
  87. options are _BULK, _INT, _ISO, and _CTRL. The _CTRL is not
  88. typically used because the default control transfer endpoint is
  89. not defined in the USB descriptors. When _ISO option is used,
  90. addition options can be ORed to _ISO. Example:
  91. _ISO|_AD|_FE
  92. This describes the endpoint as an isochronous pipe with adaptive
  93. and feedback attributes. See usb_device.h and the USB
  94. specification for details. The next parameter defines the size of
  95. the endpoint. The last parameter in the polling interval.
  96.  
  97. -------------------------------------------------------------------
  98. Adding a USB String
  99. -------------------------------------------------------------------
  100. A string descriptor array should have the following format:
  101.  
  102. rom struct{byte bLength;byte bDscType;word string[size];}sdxxx={
  103. sizeof(sdxxx),DSC_STR,<text>};
  104.  
  105. The above structure provides a means for the C compiler to
  106. calculate the length of string descriptor sdxxx, where xxx is the
  107. index number. The first two bytes of the descriptor are descriptor
  108. length and type. The rest <text> are string texts which must be
  109. in the unicode format. The unicode format is achieved by declaring
  110. each character as a word type. The whole text string is declared
  111. as a word array with the number of characters equals to <size>.
  112. <size> has to be manually counted and entered into the array
  113. declaration. Let's study this through an example:
  114. if the string is "USB" , then the string descriptor should be:
  115. (Using index 02)
  116. rom struct{byte bLength;byte bDscType;word string[3];}sd002={
  117. sizeof(sd002),DSC_STR,'U','S','B'};
  118.  
  119. A USB project may have multiple strings and the firmware supports
  120. the management of multiple strings through a look-up table.
  121. The look-up table is defined as:
  122. rom const unsigned char *rom USB_SD_Ptr[]={&sd000,&sd001,&sd002};
  123.  
  124. The above declaration has 3 strings, sd000, sd001, and sd002.
  125. Strings can be removed or added. sd000 is a specialized string
  126. descriptor. It defines the language code, usually this is
  127. US English (0x0409). The index of the string must match the index
  128. position of the USB_SD_Ptr array, &sd000 must be in position
  129. USB_SD_Ptr[0], &sd001 must be in position USB_SD_Ptr[1] and so on.
  130. The look-up table USB_SD_Ptr is used by the get string handler
  131. function.
  132.  
  133. -------------------------------------------------------------------
  134.  
  135. The look-up table scheme also applies to the configuration
  136. descriptor. A USB device may have multiple configuration
  137. descriptors, i.e. CFG01, CFG02, etc. To add a configuration
  138. descriptor, user must implement a structure similar to CFG01.
  139. The next step is to add the configuration descriptor name, i.e.
  140. cfg01, cfg02,.., to the look-up table USB_CD_Ptr. USB_CD_Ptr[0]
  141. is a dummy place holder since configuration 0 is the un-configured
  142. state according to the definition in the USB specification.
  143.  
  144. ********************************************************************/
  145.  
  146. /*********************************************************************
  147.  * Descriptor specific type definitions are defined in:
  148.  * usb_device.h
  149.  *
  150.  * Configuration options are defined in:
  151.  * usb_config.h
  152.  ********************************************************************/
  153. #ifndef __USB_DESCRIPTORS_C
  154. #define __USB_DESCRIPTORS_C
  155.  
  156. /** INCLUDES *******************************************************/
  157. #include "./USB/usb.h"
  158. #include "./USB/usb_function_cdc.h"
  159.  
  160. /** CONSTANTS ******************************************************/
  161.  
  162. /*
  163. #if defined(__18CXX)
  164. #pragma romdata
  165. #endif
  166. */
  167.  
  168. /* Device Descriptor */
  169. ROM USB_DEVICE_DESCRIPTOR device_dsc=
  170. {
  171.     0x12,                   // Size of this descriptor in bytes
  172.     USB_DESCRIPTOR_DEVICE,  // DEVICE descriptor type
  173.     0x0200,                 // USB Spec Release Number in BCD format
  174.     CDC_DEVICE,             // Class Code
  175.     0x00,                   // Subclass code
  176.     0x00,                   // Protocol code
  177.     USB_EP0_BUFF_SIZE,      // Max packet size for EP0, see usb_config.h
  178.     0x04D8,                 // Vendor ID
  179.     0x000A,                 // Product ID: CDC RS-232 Emulation Demo
  180.     0x0100,                 // Device release number in BCD format
  181.     0x01,                   // Manufacturer string index
  182.     0x02,                   // Product string index
  183.     0x00,                   // Device serial number string index
  184.     0x01                    // Number of possible configurations
  185. };
  186.  
  187. /* Configuration 1 Descriptor */
  188. ROM BYTE configDescriptor1[]={
  189.     /* Configuration Descriptor */
  190.     0x09,//sizeof(USB_CFG_DSC),    // Size of this descriptor in bytes
  191.     USB_DESCRIPTOR_CONFIGURATION,                // CONFIGURATION descriptor type
  192.     67,0,                   // Total length of data for this cfg
  193.     2,                      // Number of interfaces in this cfg
  194.     1,                      // Index value of this configuration
  195.     0,                      // Configuration string index
  196.     _DEFAULT | _SELF,               // Attributes, see usb_device.h
  197.     50,                     // Max power consumption (2X mA)
  198.                                                        
  199.     /* Interface Descriptor */
  200.     9,//sizeof(USB_INTF_DSC),   // Size of this descriptor in bytes
  201.     USB_DESCRIPTOR_INTERFACE,               // INTERFACE descriptor type
  202.     0,                      // Interface Number
  203.     0,                      // Alternate Setting Number
  204.     1,                      // Number of endpoints in this intf
  205.     COMM_INTF,              // Class code
  206.     ABSTRACT_CONTROL_MODEL, // Subclass code
  207.     V25TER,                 // Protocol code
  208.     0,                      // Interface string index
  209.  
  210.     /* CDC Class-Specific Descriptors */
  211.     sizeof(USB_CDC_HEADER_FN_DSC),
  212.     CS_INTERFACE,
  213.     DSC_FN_HEADER,
  214.     0x10,0x01,
  215.  
  216.     sizeof(USB_CDC_ACM_FN_DSC),
  217.     CS_INTERFACE,
  218.     DSC_FN_ACM,
  219.     USB_CDC_ACM_FN_DSC_VAL,
  220.  
  221.     sizeof(USB_CDC_UNION_FN_DSC),
  222.     CS_INTERFACE,
  223.     DSC_FN_UNION,
  224.     CDC_COMM_INTF_ID,
  225.     CDC_DATA_INTF_ID,
  226.  
  227.     sizeof(USB_CDC_CALL_MGT_FN_DSC),
  228.     CS_INTERFACE,
  229.     DSC_FN_CALL_MGT,
  230.     0x00,
  231.     CDC_DATA_INTF_ID,
  232.  
  233.     /* Endpoint Descriptor */
  234.     //sizeof(USB_EP_DSC),DSC_EP,_EP02_IN,_INT,CDC_INT_EP_SIZE,0x02,
  235.     0x07,/*sizeof(USB_EP_DSC)*/
  236.     USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
  237.     _EP01_IN,            //EndpointAddress
  238.     _INTERRUPT,                       //Attributes
  239.     0x08,0x00,                  //size
  240.     0x02,                       //Interval
  241.  
  242.     /* Interface Descriptor */
  243.     9,//sizeof(USB_INTF_DSC),   // Size of this descriptor in bytes
  244.     USB_DESCRIPTOR_INTERFACE,               // INTERFACE descriptor type
  245.     1,                      // Interface Number
  246.     0,                      // Alternate Setting Number
  247.     2,                      // Number of endpoints in this intf
  248.     DATA_INTF,              // Class code
  249.     0,                      // Subclass code
  250.     NO_PROTOCOL,            // Protocol code
  251.     0,                      // Interface string index
  252.    
  253.     /* Endpoint Descriptor */
  254.     //sizeof(USB_EP_DSC),DSC_EP,_EP03_OUT,_BULK,CDC_BULK_OUT_EP_SIZE,0x00,
  255.     0x07,/*sizeof(USB_EP_DSC)*/
  256.     USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
  257.     _EP02_OUT,            //EndpointAddress
  258.     _BULK,                       //Attributes
  259.     0x40,0x00,                  //size
  260.     0x00,                       //Interval
  261.  
  262.     /* Endpoint Descriptor */
  263.     //sizeof(USB_EP_DSC),DSC_EP,_EP03_IN,_BULK,CDC_BULK_IN_EP_SIZE,0x00
  264.     0x07,/*sizeof(USB_EP_DSC)*/
  265.     USB_DESCRIPTOR_ENDPOINT,    //Endpoint Descriptor
  266.     _EP02_IN,            //EndpointAddress
  267.     _BULK,                       //Attributes
  268.     0x40,0x00,                  //size
  269.     0x00,                       //Interval
  270. };
  271.  
  272.  
  273. //Language code string descriptor
  274. ROM struct{BYTE bLength;BYTE bDscType;WORD string[1];}sd000={
  275. sizeof(sd000),USB_DESCRIPTOR_STRING,{0x0409}};
  276.  
  277. //Manufacturer string descriptor
  278. ROM struct{BYTE bLength;BYTE bDscType;WORD string[25];}sd001={
  279. sizeof(sd001),USB_DESCRIPTOR_STRING,
  280. {'M','i','c','r','o','c','h','i','p',' ',
  281. 'T','e','c','h','n','o','l','o','g','y',' ','I','n','c','.'
  282. }};
  283.  
  284. //Product string descriptor
  285. ROM struct{BYTE bLength;BYTE bDscType;WORD string[25];}sd002={
  286. sizeof(sd002),USB_DESCRIPTOR_STRING,
  287. {'C','D','C',' ','R','S','-','2','3','2',' ',
  288. 'E','m','u','l','a','t','i','o','n',' ','D','e','m','o'}
  289. };
  290.  
  291. //Array of configuration descriptors
  292. ROM BYTE *ROM USB_CD_Ptr[]=
  293. {
  294.     (ROM BYTE *ROM)&configDescriptor1
  295. };
  296. //Array of string descriptors
  297. ROM BYTE *ROM USB_SD_Ptr[USB_NUM_STRING_DESCRIPTORS]=
  298. {
  299.     (ROM BYTE *ROM)&sd000,
  300.     (ROM BYTE *ROM)&sd001,
  301.     (ROM BYTE *ROM)&sd002
  302. };
  303.  
  304. /*
  305. #if defined(__18CXX)
  306.     #pragma code
  307. #endif
  308. */
  309.  
  310. #endif
  311. /** EOF usb_descriptors.c ****************************************************/
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 24 de Enero de 2014, 09:58:44
usb_config.h
Código: C
  1. /********************************************************************
  2.  FileName:      usb_config.h
  3.  Dependencies:  Always: GenericTypeDefs.h, usb_device.h
  4.                 Situational: usb_function_hid.h, usb_function_cdc.h, usb_function_msd.h, etc.
  5.  Processor:             PIC18 or PIC24 USB Microcontrollers
  6.  Hardware:              The code is natively intended to be used on the following
  7.                                 hardware platforms: PICDEM™ FS USB Demo Board,
  8.                                 PIC18F87J50 FS USB Plug-In Module, or
  9.                                 Explorer 16 + PIC24 USB PIM.  The firmware may be
  10.                                 modified for use on other USB platforms by editing the
  11.                                 HardwareProfile.h file.
  12.  Complier:      Microchip C18 (for PIC18) or C30 (for PIC24)
  13.  Company:               Microchip Technology, Inc.
  14.  
  15.  Software License Agreement:
  16.  
  17.  The software supplied herewith by Microchip Technology Incorporated
  18.  (the “Company”) for its PIC® Microcontroller is intended and
  19.  supplied to you, the Company’s customer, for use solely and
  20.  exclusively on Microchip PIC Microcontroller products. The
  21.  software is owned by the Company and/or its supplier, and is
  22.  protected under applicable copyright laws. All rights are reserved.
  23.  Any use in violation of the foregoing restrictions may subject the
  24.  user to criminal sanctions under applicable laws, as well as to
  25.  civil liability for the breach of the terms and conditions of this
  26.  license.
  27.  
  28.  THIS SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION. NO WARRANTIES,
  29.  WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT NOT LIMITED
  30.  TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  31.  PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. THE COMPANY SHALL NOT,
  32.  IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL OR
  33.  CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
  34.  
  35. ********************************************************************
  36.  File Description:
  37.  
  38.  Change History:
  39.   Rev   Date         Description
  40.   2.8   8 Oct 2010   Added definitions for supporting new
  41.                      USB_ENABLE_STATUS_STAGE_TIMEOUTS feature.
  42.                      Changed the CDC comm EP and data EP from 2,3
  43.                      (respectively) to 1,2 respectively, so as to
  44.                      save RAM.
  45.  *******************************************************************/
  46.  
  47. /*********************************************************************
  48.  * Descriptor specific type definitions are defined in: usbd.h
  49.  ********************************************************************/
  50.  
  51. #ifndef USBCFG_H
  52. #define USBCFG_H
  53.  
  54. /** DEFINITIONS ****************************************************/
  55. #define USB_EP0_BUFF_SIZE               8       // Valid Options: 8, 16, 32, or 64 bytes.
  56.                                                                 // Using larger options take more SRAM, but
  57.                                                                 // does not provide much advantage in most types
  58.                                                                 // of applications.  Exceptions to this, are applications
  59.                                                                 // that use EP0 IN or OUT for sending large amounts of
  60.                                                                 // application related data.
  61.                                                                        
  62. #define USB_MAX_NUM_INT         2   // For tracking Alternate Setting
  63.  
  64. //Device descriptor - if these two definitions are not defined then
  65. //  a ROM USB_DEVICE_DESCRIPTOR variable by the exact name of device_dsc
  66. //  must exist.
  67. #define USB_USER_DEVICE_DESCRIPTOR &device_dsc
  68. #define USB_USER_DEVICE_DESCRIPTOR_INCLUDE extern ROM USB_DEVICE_DESCRIPTOR device_dsc
  69.  
  70. //Configuration descriptors - if these two definitions do not exist then
  71. //  a ROM BYTE *ROM variable named exactly USB_CD_Ptr[] must exist.
  72. #define USB_USER_CONFIG_DESCRIPTOR USB_CD_Ptr
  73. #define USB_USER_CONFIG_DESCRIPTOR_INCLUDE extern ROM BYTE *ROM USB_CD_Ptr[]
  74.  
  75. //Make sure only one of the below "#define USB_PING_PONG_MODE"
  76. //is uncommented.
  77. //#define USB_PING_PONG_MODE USB_PING_PONG__NO_PING_PONG
  78. #define USB_PING_PONG_MODE USB_PING_PONG__FULL_PING_PONG
  79. //#define USB_PING_PONG_MODE USB_PING_PONG__EP0_OUT_ONLY
  80. //#define USB_PING_PONG_MODE USB_PING_PONG__ALL_BUT_EP0         //NOTE: This mode is not supported in PIC18F4550 family rev A3 devices
  81.  
  82.  
  83. //#define USB_POLLING
  84. #define USB_INTERRUPT
  85.  
  86. /* Parameter definitions are defined in usb_device.h */
  87. #define USB_PULLUP_OPTION USB_PULLUP_ENABLE
  88. //#define USB_PULLUP_OPTION USB_PULLUP_DISABLED
  89.  
  90. #define USB_TRANSCEIVER_OPTION USB_INTERNAL_TRANSCEIVER
  91. //External Transceiver support is not available on all product families.  Please
  92. //  refer to the product family datasheet for more information if this feature
  93. //  is available on the target processor.
  94. //#define USB_TRANSCEIVER_OPTION USB_EXTERNAL_TRANSCEIVER
  95.  
  96. #define USB_SPEED_OPTION USB_FULL_SPEED
  97. //#define USB_SPEED_OPTION USB_LOW_SPEED //(not valid option for PIC24F devices)
  98.  
  99. //------------------------------------------------------------------------------------------------------------------
  100. //Option to enable auto-arming of the status stage of control transfers, if no
  101. //"progress" has been made for the USB_STATUS_STAGE_TIMEOUT value.
  102. //If progress is made (any successful transactions completing on EP0 IN or OUT)
  103. //the timeout counter gets reset to the USB_STATUS_STAGE_TIMEOUT value.
  104. //
  105. //During normal control transfer processing, the USB stack or the application
  106. //firmware will call USBCtrlEPAllowStatusStage() as soon as the firmware is finished
  107. //processing the control transfer.  Therefore, the status stage completes as
  108. //quickly as is physically possible.  The USB_ENABLE_STATUS_STAGE_TIMEOUTS
  109. //feature, and the USB_STATUS_STAGE_TIMEOUT value are only relevant, when:
  110. //1.  The application uses the USBDeferStatusStage() API function, but never calls
  111. //      USBCtrlEPAllowStatusStage().  Or:
  112. //2.  The application uses host to device (OUT) control transfers with data stage,
  113. //      and some abnormal error occurs, where the host might try to abort the control
  114. //      transfer, before it has sent all of the data it claimed it was going to send.
  115. //
  116. //If the application firmware never uses the USBDeferStatusStage() API function,
  117. //and it never uses host to device control transfers with data stage, then
  118. //it is not required to enable the USB_ENABLE_STATUS_STAGE_TIMEOUTS feature.
  119.  
  120. #define USB_ENABLE_STATUS_STAGE_TIMEOUTS    //Comment this out to disable this feature.  
  121.  
  122. //Section 9.2.6 of the USB 2.0 specifications indicate that:
  123. //1.  Control transfers with no data stage: Status stage must complete within
  124. //      50ms of the start of the control transfer.
  125. //2.  Control transfers with (IN) data stage: Status stage must complete within
  126. //      50ms of sending the last IN data packet in fullfilment of the data stage.
  127. //3.  Control transfers with (OUT) data stage: No specific status stage timing
  128. //      requirement.  However, the total time of the entire control transfer (ex:
  129. //      including the OUT data stage and IN status stage) must not exceed 5 seconds.
  130. //
  131. //Therefore, if the USB_ENABLE_STATUS_STAGE_TIMEOUTS feature is used, it is suggested
  132. //to set the USB_STATUS_STAGE_TIMEOUT value to timeout in less than 50ms.  If the
  133. //USB_ENABLE_STATUS_STAGE_TIMEOUTS feature is not enabled, then the USB_STATUS_STAGE_TIMEOUT
  134. //parameter is not relevant.
  135.  
  136. #define USB_STATUS_STAGE_TIMEOUT     (BYTE)45   //Approximate timeout in milliseconds, except when
  137.                                                 //USB_POLLING mode is used, and USBDeviceTasks() is called at < 1kHz
  138.                                                 //In this special case, the timeout becomes approximately:
  139. //Timeout(in milliseconds) = ((1000 * (USB_STATUS_STAGE_TIMEOUT - 1)) / (USBDeviceTasks() polling frequency in Hz))
  140. //------------------------------------------------------------------------------------------------------------------
  141.  
  142. #define USB_SUPPORT_DEVICE
  143.  
  144. #define USB_NUM_STRING_DESCRIPTORS 3
  145.  
  146. //#define USB_INTERRUPT_LEGACY_CALLBACKS
  147. #define USB_ENABLE_ALL_HANDLERS
  148. //#define USB_ENABLE_SUSPEND_HANDLER
  149. //#define USB_ENABLE_WAKEUP_FROM_SUSPEND_HANDLER
  150. //#define USB_ENABLE_SOF_HANDLER
  151. //#define USB_ENABLE_ERROR_HANDLER
  152. //#define USB_ENABLE_OTHER_REQUEST_HANDLER
  153. //#define USB_ENABLE_SET_DESCRIPTOR_HANDLER
  154. //#define USB_ENABLE_INIT_EP_HANDLER
  155. //#define USB_ENABLE_EP0_DATA_HANDLER
  156. //#define USB_ENABLE_TRANSFER_COMPLETE_HANDLER
  157.  
  158. /** DEVICE CLASS USAGE *********************************************/
  159. #define USB_USE_CDC
  160.  
  161. /** ENDPOINTS ALLOCATION *******************************************/
  162. #define USB_MAX_EP_NUMBER           2
  163.  
  164. /* CDC */
  165. #define CDC_COMM_INTF_ID        0x0
  166. #define CDC_COMM_EP              1
  167. #define CDC_COMM_IN_EP_SIZE      10
  168.  
  169. #define CDC_DATA_INTF_ID        0x01
  170. #define CDC_DATA_EP             2
  171. #define CDC_DATA_OUT_EP_SIZE    64
  172. #define CDC_DATA_IN_EP_SIZE     64
  173.  
  174. //#define USB_CDC_SUPPORT_ABSTRACT_CONTROL_MANAGEMENT_CAPABILITIES_D2 //Send_Break command
  175. #define USB_CDC_SUPPORT_ABSTRACT_CONTROL_MANAGEMENT_CAPABILITIES_D1 //Set_Line_Coding, Set_Control_Line_State, Get_Line_Coding, and Serial_State commands
  176. /** DEFINITIONS ****************************************************/
  177.  
  178. #endif //USBCFG_H

HardwareProfile.h
Código: C
  1. /*
  2.  * File:   HardWareProfile.h
  3.  * Author: sebastian
  4.  *
  5.  * Created on 12 de noviembre de 2013, 15:46
  6.  */
  7.  
  8. #ifndef HARDWAREPROFILE_H
  9. #define HARDWAREPROFILE_H
  10.  
  11. #define DEMO_BOARD USER_DEFINED_BOARD
  12. #define self_power          1
  13. #define USE_USB_BUS_SENSE_IO
  14. #define USB_BUS_SENSE       PORTAbits.RA1
  15.  
  16. #endif  /* HARDWAREPROFILE_H */
Título: Re: ¿USB con compilador XC?
Publicado por: calavia en 24 de Enero de 2014, 10:22:32
Pues yo no se que estoy haciendo mal, porque tengo todo igual que tu, la unica diferencia es que uso el PIC18F4550 y no me lo detecta.
Mira la imagen
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 24 de Enero de 2014, 10:32:30
  Yo estoy utilizando la versión 1.12 del compilador, tal vez esté allí la diferencia. Intenta compilar el ejemplo con los archivos que subí en un 18f2550 para ver que ocurre.
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 24 de Enero de 2014, 10:49:03
  Acabo de compilar el mismo ejemplo sin modificar nada, para un PIC18f4550 y funcionó bien. En estos ejemplos el PIC debe trabajar a 48MHz, por lo tanto configuro esa velocidad en ISIS.
Título: Re: ¿USB con compilador XC?
Publicado por: calavia en 24 de Enero de 2014, 10:53:25
No funciona no se porque... bueno voy a intentar a ver como va la cosa.
Muchas gracias por la ayuda
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 24 de Enero de 2014, 11:34:40
¿Estás utilizando exactamente el mismo código que yo he utilizado?

¿Qué pasa si intentas compilar y simular el ejemplo de joystick HID? El botón va del pin RB7 a vcc, dicho pin lleva una resistencia de pulldown (10K a gnd).

Aquí el archivo HardwareProfile.h para el joystick
Código: C
  1. /*
  2.  * File:   HardwareProfile.h
  3.  * Author: sebastian
  4.  *
  5.  * Created on 13 de noviembre de 2013, 18:05
  6.  */
  7.  
  8. #ifndef HARDWAREPROFILE_H
  9. #define HARDWAREPROFILE_H
  10.  
  11. #define DEMO_BOARD USER_DEFINED_BOARD
  12.  
  13. #define self_power 0
  14. #define USB_SENSE
  15.  
  16. #endif  /* HARDWAREPROFILE_H */
Título: Re: ¿USB con compilador XC?
Publicado por: calavia en 24 de Enero de 2014, 14:56:49
Si si, si lo tengo todo montado pero usando un FTDI para realizar la conversión, pero preferiría que la hiciese el PIC. Pero bueno q no importa q si no puedo da igual.

Muchas gracias por todo
Título: Re: ¿USB con compilador XC?
Publicado por: chapoton en 21 de Febrero de 2014, 14:42:51
Hola. He intentado seguir el hilo y todavía no he podido compilar ningun proyecto con USB con las librearías mla. ¿Existe alguna posibilidad que suban algun proyecto realizado en mplabx así puedo compilarlo? Estoy tratando de realizar una comunicación con un PIC18F4550.
Como aporte he encontrado que no se tienen que compilar con la versión de XC8 1.3 sino con la versión 1.12.

Saludos
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 21 de Febrero de 2014, 15:23:58
Hola. He intentado seguir el hilo y todavía no he podido compilar ningun proyecto con USB con las librearías mla. ¿Existe alguna posibilidad que suban algun proyecto realizado en mplabx así puedo compilarlo? Estoy tratando de realizar una comunicación con un PIC18F4550.
Como aporte he encontrado que no se tienen que compilar con la versión de XC8 1.3 sino con la versión 1.12.

Saludos


  ¿Modificaste los archivos como indicaba el usuario Jtemples, del foro de microchip? ¿Intentaste compilar el ejemplo del JoyStick? ¿Agregaste los archivos .C a tu proyecto, como se aprecia en la captura? ¿Modificaste los PATH, como también se aprecia en la captura?
Título: Re: ¿USB con compilador XC?
Publicado por: chapoton en 24 de Febrero de 2014, 09:14:08
Hola AngelGris. Estuve todo el fin de semana intententando compilarlo pero no pude. Segui todo los indicado por Jtemples. Intenté compilar varios de los ejemplos. La única diferencia que tengo con la captura es que no me deja poner el proyecto dentro del path diciendome que ya estan como relativos al proyecto. La unica diferencia que pude notar con todo lo publicado es la versión de MLA. Quizas tenga que instalar la anterior y probarla.
Creo que el principal problema que tengo son los PATH. Me pide que incluya el system.h y el system_config.h. Cuando lo hago aparece el error

usb_common.h:537: error: (103) #error: "Application must define support mode in usb_config.h". Pero lo tengo definida a la aplicación.

voy a probar con una versión anterior de MLA, ya que tiene la estructura de directorios diferentes.
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 24 de Febrero de 2014, 10:21:29
  Yo estoy utilizando MPLAB v1.6, XC8 v1.12 y las librerías son las del 15-06-2013
Título: Re: ¿USB con compilador XC?
Publicado por: marcoj2560456* en 30 de Septiembre de 2015, 12:59:29
hola AngelGris yo estoy programando en MPLAB X IDE v3.10 xc16 v1.25 ....System: Windows 8.1 version 6.3 running on amd64; Cp1252; es_VE (mplab) ... con las librerias de MLA v 2015_08_10 he intento conectar un lector de codigo de barras a mi pic24fj64gb002 trabajando en modo host pero no he podido compilar las librerias me salen errores si me pudieras guiar tengo el vid y pid del lector pero no se conecta lo intente hacerlo por datasheet sin las librerias pero tampoco funciono aqui dejo la configuracion por datasheet qwue hice :

Código: [Seleccionar]
// INCLUDES
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include <libpic30.h>

// DEFINICIONES
#define LED1 PORTAbits.RA1
#define LED0 PORTAbits.RA0
#define _XTAL_FREQ 20000000
#define __delay_ms(x) __delay32((unsigned long)((x)*(_XTAL_FREQ/10000.0)))

// CONFIG1
#pragma config WINDIS = OFF      // Windowed WDT (Standard Watchdog Timer enabled,(Windowed-mode is disabled))
#pragma config GCP = OFF         // General Segment Code Protect (Code protection is disabled)
#pragma config JTAGEN = ON       // JTAG Port Enable (JTAG port is enabled)

// CONFIG2
#pragma config POSCMOD = XT
#pragma config PLL96MHZ = ON            // 96MHz PLL Startup Select (96 MHz PLL Startup is enabled automatically on start-up)
#pragma config PLLDIV = DIV5            // USB 96 MHz PLL Prescaler Select (Oscillator input divided by 5 (20 MHz input))


void host(void)
{
  //1
     U1CONbits.HOSTEN = 1 ;  //esteeeeeeeeeeeee

     //2
     U1OTGCONbits.DMPULDWN = 1;
     U1OTGCONbits.DPPULDWN = 1;
     U1OTGCONbits.DMPULUP = 0;
     U1OTGCONbits.DPPULUP = 0;

     //3
     U1CONbits.SOFEN = 0;
 
     //4
     U1IEbits.ATTACHIE = 1;

     //5
       while(U1IRbits.ATTACHIF!=1)
       {
       }
     //6
     while (1)
      {
       
     if (U1CONbits.SE0==1)
        { __delay_ms(100);
          break;
        }
      }
   
         
     if (U1CONbits.JSTATE==1)
             {
         U1ADDRbits.LSPDEN = 0;
         U1EP0bits.LSPD = 0;
             }
     else
        {
         U1ADDRbits.LSPDEN = 1;
         U1EP0bits.LSPD = 1;
        }
     //7
      U1CONbits.USBRST = 1;
      __delay_ms(50);
      U1CONbits.USBRST = 0;
      __delay_ms(10);
      //8
      U1CONbits.SOFEN = 1;
     
      __delay_ms(10);
 
}
int main (void)
{
 
     TRISA = 0X00; // puertos A como salida.
     PORTA = 0;
     
     host(); // ENABLE HOST MODE AND DISCOVER A CONNECTED DEVICE
     
     while(1)
     {
     LED0=1;
     __delay_ms(500);
     LED0=0;
     __delay_ms(500);
     }
   
}
Título: Re: ¿USB con compilador XC?
Publicado por: antayhua en 05 de Octubre de 2015, 13:55:29
Yo quisiera hacer andar el pic 18f4550 usando el puerto usb y xc8 pero veo que es complicado con este compilador nose ni por donde comenzar incluso nose que es hid y cdc, lo único es esperar a que uno de ustedes ponga un código funcional para poder probarlo, me gustaría ayudar pero nose como.
Título: Re: ¿USB con compilador XC?
Publicado por: AngelGris en 07 de Octubre de 2015, 19:35:25
  marcoj2560456*
                                Yo sólo hice una pruebitas utilizando al pic como dispositivo y no como host.

  antayhua
                  Fijate que yo dejé un par de links e incluso un zip con información acerca de USB, y en este foro también encontrarás mucha información al respecto. Tengo que volver a hacer pruebas con nuevas versiones del compilador y de las librerías porque hace rato que no toco nada de esto.
Título: Re:¿USB con compilador XC?
Publicado por: electroipod en 19 de Octubre de 2015, 18:39:24
Hola a todos este tema lleva ya un tiempo, quisiera saber si alguno de ustedes logro hacer funcionar el usb con xc8.
Título: Re:¿USB con compilador XC?
Publicado por: AngelGris en 19 de Octubre de 2015, 19:11:42
  Pues como mencioné en su momento, sí lo hice funcionar. De hecho, hasta hice un joystick de un botón que funcionó muy bien y eso lo probé en físico bajo linux.