Autor Tema: ¿USB con compilador XC?  (Leído 12275 veces)

0 Usuarios y 2 Visitantes están viendo este tema.

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
¿USB con compilador XC?
« 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.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #1 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.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #2 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.
« Última modificación: 13 de Noviembre de 2013, 14:50:44 por AngelGris »
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #3 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
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #4 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. }

De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #5 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 ***************************************************/
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado elgarbe

  • Moderadores
  • PIC24H
  • *****
  • Mensajes: 2178
Re: ¿USB con compilador XC?
« Respuesta #6 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!
-
Leonardo Garberoglio

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #7 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,
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #8 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
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado pajaro

  • PIC24H
  • ******
  • Mensajes: 1121
Re: ¿USB con compilador XC?
« Respuesta #9 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.



Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #10 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.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado pajaro

  • PIC24H
  • ******
  • Mensajes: 1121
Re: ¿USB con compilador XC?
« Respuesta #11 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


Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #12 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
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado AngelGris

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 2480
Re: ¿USB con compilador XC?
« Respuesta #13 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.
De vez en cuando la vida
nos besa en la boca
y a colores se despliega
como un atlas

Desconectado pajaro

  • PIC24H
  • ******
  • Mensajes: 1121
Re: ¿USB con compilador XC?
« Respuesta #14 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.

« Última modificación: 26 de Noviembre de 2013, 22:40:57 por pajaro »


 

anything