Autor Tema: usb_rx_packet_size devuelve un cero  (Leído 4306 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
usb_rx_packet_size devuelve un cero
« en: 03 de Diciembre de 2010, 04:11:01 »
Hola amigos, estoy intentando implementar un USB HID en CCS por primera vez, y casi lo tengo gracias a la magnifica información del hilo de Santiago, pero hay algo que me tiene mosqueado.
Utilizo un PIC24F y CCS con sus librerías estándar y del lado del PC utilizo GenericHid.

Quiero utilizar un tamaño de reporte tanto entrante como saliente de 4 bytes, y así lo he definido.

Y el caso es que funciona, pero me he visto obligado a anular esta línea
i = usb_rx_packet_size(endpoint);

porque siempre devuelve un cero.

Haciéndole esta modificación mi programa funciona perfectamente:
i=4;

pero no me mola nada. ¿Me podéis dar alguna pista para resolverlo?
Gracias

Desconectado bmfranky

  • PIC16
  • ***
  • Mensajes: 165
    • La Tienda De Fran
Re: usb_rx_packet_size devuelve un cero
« Respuesta #1 en: 03 de Diciembre de 2010, 05:55:44 »
Hola Nocturno, has comprobado que la librería soporte esa función, para el micro que usas, igual no la implementa y por eso devuelve el default '0';
Visiten La Tienda De Fran ;-) Aqui. y mi nueva Web Aqui.

Desconectado migsantiago

  • Colaborador
  • DsPIC33
  • *****
  • Mensajes: 8257
    • Sitio de MigSantiago
Re: usb_rx_packet_size devuelve un cero
« Respuesta #2 en: 03 de Diciembre de 2010, 10:32:18 »
Hola Nocturno, endpoint debe valer 1 para que usb_rx_packet_size() devuelva el tamaño del contenido del endpoint 1.

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
Re: usb_rx_packet_size devuelve un cero
« Respuesta #3 en: 03 de Diciembre de 2010, 15:18:27 »
Sí, endpoint vale 1, Santiago.

Desconectado migsantiago

  • Colaborador
  • DsPIC33
  • *****
  • Mensajes: 8257
    • Sitio de MigSantiago
Re: usb_rx_packet_size devuelve un cero
« Respuesta #4 en: 03 de Diciembre de 2010, 15:25:14 »
OK. Si quieres pásanos más trozos del código.

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
Re: usb_rx_packet_size devuelve un cero
« Respuesta #5 en: 03 de Diciembre de 2010, 15:52:23 »
Vale, pues estos son los trozos de código involucrados, además, estoy seguro que te suenan un montón  :mrgreen:

Esta función es llamada desde el bucle principal del programa:
Código: C
  1. void AtiendeHID()
  2. {
  3. usb_task();
  4. if(usb_enumerated())
  5.    {
  6.    if(usb_kbhit(1))
  7.       {
  8.       usb_get_packet(1, buffer_in, USB_EP1_RX_SIZE);
  9.       atencion_comando();
  10.       }
  11.    }
  12. }

Aquí está el usb_desc_hid.h
Código: C
  1. ///////////////////////////////////////////////////////////////////////////
  2. ///                          usb_desc_hid.h                            ////
  3. ////                                                                   ////
  4. //// An example set of device / configuration descriptors for use with ////
  5. //// CCS's HID Demo example (see ex_usb_hid.c)                         ////
  6. ////                                                                   ////
  7. ///////////////////////////////////////////////////////////////////////////
  8. ////                                                                   ////
  9. //// Version History:                                                  ////
  10. ////                                                                   ////
  11. //// March 5th, 2009:                                                  ////
  12. ////   Cleanup for Wizard.                                             ////
  13. ////   PIC24 Initial release.                                          ////
  14. ////                                                                   ////
  15. //// June 20th, 2005:                                                  ////
  16. ////   PIC18Fxx5x initial release                                      ////
  17. ////                                                                   ////
  18. //// March 21st, 2005:                                                 ////
  19. ////   EP 0x01 and EP 0x81 now use USB_EP1_TX_SIZE and USB_EP1_RX_SIZE ////
  20. ////      to define max packet size, to make it easier for dynamically ////
  21. ////      changed code.                                                ////
  22. ////   EP 0x01 and EP 0x81 will now use 1ms polling interval if using  ////
  23. ////      a full speed device.                                         ////
  24. ////                                                                   ////
  25. //// May 4th, 2004: Optimization and cleanup.                          ////
  26. ////                Some definitions may have changed.                 ////
  27. ////                                                                   ////
  28. //// May 6th, 2003: Fixed non-HID descriptors pointing to faulty       ////
  29. ////                strings                                            ////
  30. ////                                                                   ////
  31. //// August 2nd, 2002: Initial Public Release                          ////
  32. ////                                                                   ////
  33. ////                                                                   ////
  34. ///////////////////////////////////////////////////////////////////////////
  35. ////        (C) Copyright 1996,2005 Custom Computer Services           ////
  36. //// This source code may only be used by licensed users of the CCS    ////
  37. //// C compiler.  This source code may only be distributed to other    ////
  38. //// licensed users of the CCS C compiler.  No other use,              ////
  39. //// reproduction or distribution is permitted without written         ////
  40. //// permission.  Derivative programs created using this software      ////
  41. //// in object code form are not restricted in any way.                ////
  42. ///////////////////////////////////////////////////////////////////////////
  43.  
  44. #IFNDEF __USB_DESCRIPTORS__
  45. #DEFINE __USB_DESCRIPTORS__
  46.  
  47. #ifndef USB_CONFIG_PID
  48.    #define USB_CONFIG_PID  0x0020
  49. #endif
  50.  
  51. #ifndef USB_CONFIG_VID
  52.    #define  USB_CONFIG_VID 0x0461
  53. #endif
  54.  
  55. #ifndef USB_CONFIG_BUS_POWER
  56.    //valid range is 0..500
  57.    #define  USB_CONFIG_BUS_POWER 100   //100mA
  58. #endif
  59.  
  60. #ifndef USB_CONFIG_VERSION
  61.    //version number that is stored into descriptor, in bcd.
  62.    //range is 00.00 to 99.99
  63.    #define  USB_CONFIG_VERSION   0x0100      //01.00
  64. #endif
  65.  
  66. #ifndef USB_CONFIG_HID_TX_SIZE
  67.    //valid range is 0-255
  68.    #define USB_CONFIG_HID_TX_SIZE   2     //compatible with hiddemo.exe
  69. #endif
  70.  
  71. #ifndef USB_CONFIG_HID_RX_SIZE
  72.    //valid range is 0-255
  73.    #define USB_CONFIG_HID_RX_SIZE   2     //compatible with hiddemo.exe
  74. #endif
  75.  
  76. #ifndef USB_CONFIG_HID_TX_POLL
  77.    // for full speed devices, valid range is 1-255
  78.    // for slow speed devices, valid range is 10-255
  79.    #define USB_CONFIG_HID_TX_POLL   10
  80. #endif
  81.  
  82. #ifndef USB_CONFIG_HID_RX_POLL
  83.    // for full speed devices, valid range is 1-255
  84.    // for slow speed devices, valid range is 10-255
  85.    #define USB_CONFIG_HID_RX_POLL   10
  86. #endif
  87.  
  88. //Tells the CCS PIC USB firmware to include HID handling code.
  89. #ifdef USB_HID_DEVICE
  90. #undef USB_HID_DEVICE
  91. #endif
  92.  
  93. #DEFINE USB_HID_DEVICE  TRUE
  94.  
  95. //the following defines needed for the CCS USB PIC driver to enable the TX endpoint 1
  96. // and allocate buffer space on the peripheral
  97. #ifdef USB_EP1_TX_ENABLE
  98. #undef USB_EP1_TX_ENABLE
  99. #endif
  100. #define USB_EP1_TX_ENABLE  USB_ENABLE_INTERRUPT   //turn on EP1 for IN bulk/interrupt transfers
  101.  
  102. #ifndef USB_EP1_TX_SIZE
  103.  #if (USB_CONFIG_HID_TX_SIZE >= 64)
  104.    // interrupt endpoint max packet size is 64.
  105.    #define USB_EP1_TX_SIZE    64
  106.  #else
  107.    // by making EP packet size larger than message size, we can send message in one packet.
  108.    #define USB_EP1_TX_SIZE    (USB_CONFIG_HID_TX_SIZE+1)
  109.  #endif
  110. #endif
  111.  
  112. #ifdef USB_EP1_RX_ENABLE
  113. #undef USB_EP1_RX_ENABLE
  114. #endif
  115. #define USB_EP1_RX_ENABLE  USB_ENABLE_INTERRUPT   //turn on EP1 for OUT bulk/interrupt transfers
  116.  
  117. #ifndef USB_EP1_RX_SIZE
  118.  #if (USB_CONFIG_HID_RX_SIZE >= 64)
  119.    // interrupt endpoint max packet size is 64.
  120.    #define USB_EP1_RX_SIZE    64
  121.  #else
  122.    // by making EP packet size larger than message size, we can send message in one packet.
  123.    #define USB_EP1_RX_SIZE    (USB_CONFIG_HID_RX_SIZE+1)
  124.  #endif
  125. #endif
  126.  
  127. #include <usb.h>
  128.  
  129.    //////////////////////////////////////////////////////////////////
  130.    ///
  131.    ///  HID Report.  Tells HID driver how to handle and deal with
  132.    ///  received data.  HID Reports can be extremely complex,
  133.    ///  see HID specifcation for help on writing your own.
  134.    ///
  135.    ///  CCS example uses a vendor specified usage, that sends and
  136.    ///  receives 2 absolute bytes ranging from 0 to 0xFF.
  137.    ///
  138.    //////////////////////////////////////////////////////////////////
  139.  
  140.    const char USB_CLASS_SPECIFIC_DESC[] =
  141.    {
  142.       6, 0, 255,        // Usage Page = Vendor Defined
  143.       9, 1,             // Usage = IO device
  144.       0xa1, 1,          // Collection = Application
  145.       0x19, 1,          // Usage minimum
  146.       0x29, 8,          // Usage maximum
  147.  
  148.       0x15, 0x80,       // Logical minimum (-128)
  149.       0x25, 0x7F,       // Logical maximum (127)
  150.  
  151.       0x75, 8,          // Report size = 8 (bits)
  152.       0x95, 4,          // Report count = (4 bytes)
  153.       0x81, 2,          // Input (Data, Var, Abs)
  154.       0x19, 1,          // Usage minimum
  155.       0x29, 8,          // Usage maximum
  156.       0x75, 8,          // Report size = 8 (bits)
  157.       0x95, 4  ,        // Report count = (4 bytes)
  158.       0x91, 2,          // Output (Data, Var, Abs)
  159.       0xc0              // End Collection
  160.    };
  161.  
  162.    //if a class has an extra descriptor not part of the config descriptor,
  163.    // this lookup table defines where to look for it in the const
  164.    // USB_CLASS_SPECIFIC_DESC[] array.
  165.    //first element is the config number (if your device has more than one config)
  166.    //second element is which interface number
  167.    //set element to 0xFFFF if this config/interface combo doesn't exist
  168.    const int16 USB_CLASS_SPECIFIC_DESC_LOOKUP[USB_NUM_CONFIGURATIONS][1] =
  169.    {
  170.    //config 1
  171.       //interface 0
  172.          0
  173.    };
  174.  
  175.    //if a class has an extra descriptor not part of the config descriptor,
  176.    // this lookup table defines the size of that descriptor.
  177.    //first element is the config number (if your device has more than one config)
  178.    //second element is which interface number
  179.    //set element to 0xFFFF if this config/interface combo doesn't exist
  180.    const int16 USB_CLASS_SPECIFIC_DESC_LOOKUP_SIZE[USB_NUM_CONFIGURATIONS][1] =
  181.    {
  182.    //config 1
  183.       //interface 0
  184.          32
  185.    };
  186.  
  187.  
  188. //////////////////////////////////////////////////////////////////
  189. ///
  190. ///   start config descriptor
  191. ///   right now we only support one configuration descriptor.
  192. ///   the config, interface, class, and endpoint goes into this array.
  193. ///
  194. //////////////////////////////////////////////////////////////////
  195.  
  196.    #DEFINE USB_TOTAL_CONFIG_LEN      41  //config+interface+class+endpoint+endpoint (2 endpoints)
  197.  
  198.    const char USB_CONFIG_DESC[] = {
  199.    //IN ORDER TO COMPLY WITH WINDOWS HOSTS, THE ORDER OF THIS ARRAY MUST BE:
  200.       //    config(s)
  201.       //    interface(s)
  202.       //    class(es)
  203.       //    endpoint(s)
  204.  
  205.    //config_descriptor for config index 1
  206.          USB_DESC_CONFIG_LEN, //length of descriptor size          ==1
  207.          USB_DESC_CONFIG_TYPE, //constant CONFIGURATION (CONFIGURATION 0x02)     ==2
  208.          USB_TOTAL_CONFIG_LEN,0, //size of all data returned for this config      ==3,4
  209.          1, //number of interfaces this device supports       ==5
  210.          0x01, //identifier for this configuration.  (IF we had more than one configurations)      ==6
  211.          0x00, //index of string descriptor for this configuration      ==7
  212.         #if USB_CONFIG_BUS_POWER
  213.          0xC0, //bit 6=1 if self powered, bit 5=1 if supports remote wakeup (we don't), bits 0-4 unused and bit7=1         ==8
  214.         #else
  215.          0x80, //bit 6=1 if self powered, bit 5=1 if supports remote wakeup (we don't), bits 0-4 unused and bit7=1         ==8
  216.         #endif
  217.          USB_CONFIG_BUS_POWER/2, //maximum bus power required (maximum milliamperes/2)  (0x32 = 100mA)
  218.  
  219.    //interface descriptor 1
  220.          USB_DESC_INTERFACE_LEN, //length of descriptor      =10
  221.          USB_DESC_INTERFACE_TYPE, //constant INTERFACE (INTERFACE 0x04)       =11
  222.          0x00, //number defining this interface (IF we had more than one interface)    ==12
  223.          0x00, //alternate setting     ==13
  224.          2, //number of endpoins, except 0 (pic167xx has , but we dont have to use all).       ==14
  225.          0x03, //class code, 03 = HID     ==15
  226.          0x00, //subclass code //boot     ==16
  227.          0x00, //protocol code      ==17
  228.          0x00, //index of string descriptor for interface      ==18
  229.  
  230.    //class descriptor 1  (HID)
  231.          USB_DESC_CLASS_LEN, //length of descriptor    ==19
  232.          USB_DESC_CLASS_TYPE, //dscriptor type (0x21 == HID)      ==20
  233.          0x00,0x01, //hid class release number (1.0)      ==21,22
  234.          0x00, //localized country code (0 = none)       ==23
  235.          0x01, //number of hid class descrptors that follow (1)      ==24
  236.          0x22, //report descriptor type (0x22 == HID)                ==25
  237.          USB_CLASS_SPECIFIC_DESC_LOOKUP_SIZE[0][0], 0x00, //length of report descriptor            ==26,27
  238.  
  239.    //endpoint descriptor
  240.          USB_DESC_ENDPOINT_LEN, //length of descriptor                   ==28
  241.          USB_DESC_ENDPOINT_TYPE, //constant ENDPOINT (ENDPOINT 0x05)          ==29
  242.          0x81, //endpoint number and direction (0x81 = EP1 IN)       ==30
  243.          USB_EP1_TX_ENABLE, //transfer type supported (0x03 is interrupt)         ==31
  244.          USB_EP1_TX_SIZE,0x00, //maximum packet size supported                  ==32,33
  245.          USB_CONFIG_HID_TX_POLL,  //polling interval, in ms.  (cant be smaller than 10 for slow speed)      ==34
  246.  
  247.    //endpoint descriptor
  248.          USB_DESC_ENDPOINT_LEN, //length of descriptor                   ==35
  249.          USB_DESC_ENDPOINT_TYPE, //constant ENDPOINT (ENDPOINT 0x05)          ==36
  250.          0x01, //endpoint number and direction (0x01 = EP1 OUT)      ==37
  251.          USB_EP1_RX_ENABLE, //transfer type supported (0x03 is interrupt)         ==38
  252.          USB_EP1_RX_SIZE,0x00, //maximum packet size supported                  ==39,40
  253.          USB_CONFIG_HID_RX_POLL //polling interval, in ms.  (cant be smaller than 10 for slow speed)    ==41
  254.    };
  255.  
  256.    //****** BEGIN CONFIG DESCRIPTOR LOOKUP TABLES ********
  257.    //since we can't make pointers to constants in certain pic16s, this is an offset table to find
  258.    //  a specific descriptor in the above table.
  259.  
  260.    //NOTE: DO TO A LIMITATION OF THE CCS CODE, ALL HID INTERFACES MUST START AT 0 AND BE SEQUENTIAL
  261.    //      FOR EXAMPLE, IF YOU HAVE 2 HID INTERFACES THEY MUST BE INTERFACE 0 AND INTERFACE 1
  262.    #define USB_NUM_HID_INTERFACES   1
  263.  
  264.    //the maximum number of interfaces seen on any config
  265.    //for example, if config 1 has 1 interface and config 2 has 2 interfaces you must define this as 2
  266.    #define USB_MAX_NUM_INTERFACES   1
  267.  
  268.    //define how many interfaces there are per config.  [0] is the first config, etc.
  269.    const char USB_NUM_INTERFACES[USB_NUM_CONFIGURATIONS]={1};
  270.  
  271.    //define where to find class descriptors
  272.    //first dimension is the config number
  273.    //second dimension specifies which interface
  274.    //last dimension specifies which class in this interface to get, but most will only have 1 class per interface
  275.    //if a class descriptor is not valid, set the value to 0xFFFF
  276.    const int16 USB_CLASS_DESCRIPTORS[USB_NUM_CONFIGURATIONS][1][1]=
  277.    {
  278.    //config 1
  279.       //interface 0
  280.          //class 1
  281.          18
  282.    };
  283.  
  284.    #if (sizeof(USB_CONFIG_DESC) != USB_TOTAL_CONFIG_LEN)
  285.       #error USB_TOTAL_CONFIG_LEN not defined correctly
  286.    #endif
  287.  
  288.  
  289. //////////////////////////////////////////////////////////////////
  290. ///
  291. ///   start device descriptors
  292. ///
  293. //////////////////////////////////////////////////////////////////
  294.  
  295.    const char USB_DEVICE_DESC[USB_DESC_DEVICE_LEN] ={
  296.       //starts of with device configuration. only one possible
  297.          USB_DESC_DEVICE_LEN, //the length of this report   ==1
  298.          0x01, //the constant DEVICE (DEVICE 0x01)  ==2
  299.          0x10,0x01, //usb version in bcd ==3,4
  300.          0x00, //class code ==5
  301.          0x00, //subclass code ==6
  302.          0x00, //protocol code ==7
  303.          USB_MAX_EP0_PACKET_LENGTH, //max packet size for endpoint 0. (SLOW SPEED SPECIFIES 8) ==8
  304.          USB_CONFIG_VID & 0xFF, ((USB_CONFIG_VID >> 8) & 0xFF), //vendor id       ==9, 10
  305.          USB_CONFIG_PID & 0xFF, ((USB_CONFIG_PID >> 8) & 0xFF), //product id, don't use 0xffff       ==11, 12
  306.          USB_CONFIG_VERSION & 0xFF, ((USB_CONFIG_VERSION >> 8) & 0xFF), //device release number  ==13,14
  307.          0x01, //index of string description of manufacturer. therefore we point to string_1 array (see below)  ==15
  308.          0x02, //index of string descriptor of the product  ==16
  309.          0x00, //index of string descriptor of serial number  ==17
  310.          USB_NUM_CONFIGURATIONS  //number of possible configurations  ==18
  311.    };
  312.  
  313.  
  314. //////////////////////////////////////////////////////////////////
  315. ///
  316. ///   start string descriptors
  317. ///   String 0 is a special language string, and must be defined.  People in U.S.A. can leave this alone.
  318. ///
  319. ///   You must define the length else get_next_string_character() will not see the string
  320. ///   Current code only supports 10 strings (0 thru 9)
  321. ///
  322. //////////////////////////////////////////////////////////////////
  323.  
  324. //the offset of the starting location of each string.  offset[0] is the start of string 0, offset[1] is the start of string 1, etc.
  325. char USB_STRING_DESC_OFFSET[]={0,4,12};
  326.  
  327. // Here is where the "CCS" Manufacturer string and "CCS HID Demo" are stored.
  328. // Strings are saved as unicode.
  329. // These strings are mostly only displayed during the add hardware wizard.
  330. // Once the operating system drivers have been installed it will usually display
  331. // the name from the drivers .INF.
  332. char const USB_STRING_DESC[]={
  333.    //string 0
  334.          4, //length of string index
  335.          USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
  336.          0x09,0x04,   //Microsoft Defined for US-English
  337.    //string 1
  338.          8, //length of string index
  339.          USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
  340.          'C',0,
  341.          'C',0,
  342.          'S',0,
  343.    //string 2
  344.          26, //length of string index
  345.          USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
  346.          'C',0,
  347.          'C',0,
  348.          'S',0,
  349.          ' ',0,
  350.          'H',0,
  351.          'I',0,
  352.          'D',0,
  353.          ' ',0,
  354.          'D',0,
  355.          'e',0,
  356.          'm',0,
  357.          'o',0
  358. };
  359.  
  360. #ENDIF

El resto de ficheros .H son los estándares de CCS sin modificar. Si necesitas algún fichero más dímelo.

Desconectado migsantiago

  • Colaborador
  • DsPIC33
  • *****
  • Mensajes: 8257
    • Sitio de MigSantiago
Re: usb_rx_packet_size devuelve un cero
« Respuesta #6 en: 03 de Diciembre de 2010, 16:11:14 »
Esa función AtiendeHID me resultó muy práctica.

En el código que pones no encuentro la función que te falla.  :huh:

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
Re: usb_rx_packet_size devuelve un cero
« Respuesta #7 en: 03 de Diciembre de 2010, 16:15:26 »
Ok, está en pic24_usb.c

Código: C
  1. /////////////////////////////////////////////////////////////////////////
  2. ////                          pic24_usb.c                            ////
  3. ////                                                                 ////
  4. //// Hardware layer for CCS's USB library.  See pic24_usb.h more     ////
  5. //// documentation about the PIC24 hardware layer.                   ////
  6. ////                                                                 ////
  7. //// This file is part of CCS's PIC USB driver code.  See USB.H      ////
  8. //// for more documentation and a list of examples.                  ////
  9. ////                                                                 ////
  10. /////////////////////////////////////////////////////////////////////////
  11. ////                                                                 ////
  12. //// Version History:                                                ////
  13. ////                                                                 ////
  14. //// March 5th, 2009:                                                ////
  15. ////   Cleanup for Wizard.                                           ////
  16. ////   PIC24 Initial release.                                        ////
  17. ////                                                                 ////
  18. /////////////////////////////////////////////////////////////////////////
  19. ////        (C) Copyright 1996,2009 Custom Computer Services         ////
  20. //// This source code may only be used by licensed users of the CCS  ////
  21. //// C compiler.  This source code may only be distributed to other  ////
  22. //// licensed users of the CCS C compiler.  No other use,            ////
  23. //// reproduction or distribution is permitted without written       ////
  24. //// permission.  Derivative programs created using this software    ////
  25. //// in object code form are not restricted in any way.              ////
  26. /////////////////////////////////////////////////////////////////////////
  27.  
  28. #IFNDEF __PIC24_USB_C__
  29. #DEFINE __PIC24_USB_C__
  30.  
  31. #INCLUDE <usb.h>
  32.  
  33. #if USB_EP15_TX_SIZE || USB_EP15_RX_SIZE
  34.  #define USB_LAST_DEFINED_ENDPOINT  15
  35. #elif USB_EP14_TX_SIZE || USB_EP14_RX_SIZE
  36.  #define USB_LAST_DEFINED_ENDPOINT  14
  37. #elif USB_EP13_TX_SIZE || USB_EP13_RX_SIZE
  38.  #define USB_LAST_DEFINED_ENDPOINT  13
  39. #elif USB_EP12_TX_SIZE || USB_EP12_RX_SIZE
  40.  #define USB_LAST_DEFINED_ENDPOINT  12
  41. #elif USB_EP11_TX_SIZE || USB_EP11_RX_SIZE
  42.  #define USB_LAST_DEFINED_ENDPOINT  11
  43. #elif USB_EP10_TX_SIZE || USB_EP10_RX_SIZE
  44.  #define USB_LAST_DEFINED_ENDPOINT  10
  45. #elif USB_EP9_TX_SIZE || USB_EP9_RX_SIZE
  46.  #define USB_LAST_DEFINED_ENDPOINT  9
  47. #elif USB_EP8_TX_SIZE || USB_EP8_RX_SIZE
  48.  #define USB_LAST_DEFINED_ENDPOINT  8
  49. #elif USB_EP7_TX_SIZE || USB_EP7_RX_SIZE
  50.  #define USB_LAST_DEFINED_ENDPOINT  7
  51. #elif USB_EP6_TX_SIZE || USB_EP6_RX_SIZE
  52.  #define USB_LAST_DEFINED_ENDPOINT  6
  53. #elif USB_EP5_TX_SIZE || USB_EP5_RX_SIZE
  54.  #define USB_LAST_DEFINED_ENDPOINT  5
  55. #elif USB_EP4_TX_SIZE || USB_EP4_RX_SIZE
  56.  #define USB_LAST_DEFINED_ENDPOINT  4
  57. #elif USB_EP3_TX_SIZE || USB_EP3_RX_SIZE
  58.  #define USB_LAST_DEFINED_ENDPOINT  3
  59. #elif USB_EP2_TX_SIZE || USB_EP2_RX_SIZE
  60.  #define USB_LAST_DEFINED_ENDPOINT  2
  61. #elif USB_EP1_TX_SIZE || USB_EP1_RX_SIZE
  62.  #define USB_LAST_DEFINED_ENDPOINT  1
  63. #else
  64.  #define USB_LAST_DEFINED_ENDPOINT  0
  65. #endif
  66.  
  67. #define USB_CONTROL_REGISTER_SIZE   ((USB_LAST_DEFINED_ENDPOINT+1)*8)
  68.  
  69. #define USB_DATA_BUFFER_NEEDED (USB_EP0_TX_SIZE+USB_EP0_RX_SIZE+USB_EP1_TX_SIZE+\
  70.                            USB_EP1_RX_SIZE+USB_EP2_TX_SIZE+USB_EP2_RX_SIZE+\
  71.                            USB_EP3_TX_SIZE+USB_EP3_RX_SIZE+USB_EP4_TX_SIZE+\
  72.                            USB_EP4_RX_SIZE+USB_EP5_TX_SIZE+USB_EP5_RX_SIZE+\
  73.                            USB_EP6_TX_SIZE+USB_EP6_RX_SIZE+USB_EP7_TX_SIZE+\
  74.                            USB_EP7_RX_SIZE+USB_EP8_TX_SIZE+USB_EP8_RX_SIZE+\
  75.                            USB_EP9_TX_SIZE+USB_EP9_RX_SIZE+USB_EP10_TX_SIZE+\
  76.                            USB_EP10_RX_SIZE+USB_EP11_TX_SIZE+USB_EP11_RX_SIZE+\
  77.                            USB_EP12_TX_SIZE+USB_EP12_RX_SIZE+USB_EP13_TX_SIZE+\
  78.                            USB_EP13_RX_SIZE+USB_EP14_TX_SIZE+USB_EP14_RX_SIZE+\
  79.                            USB_EP15_TX_SIZE+USB_EP15_RX_SIZE)
  80.  
  81. #if ((USB_DATA_BUFFER_NEEDED+USB_CONTROL_REGISTER_SIZE) > getenv("RAM"))
  82.  #error You are trying to allocate more memory for endpoints than the PIC can handle
  83. #endif
  84.  
  85. //reserve the control space needed
  86. union
  87. {
  88.    struct
  89.    {
  90.       unsigned int16 BDnSTo;
  91.       unsigned int16 BDnADo;
  92.       unsigned int16 BDnSTi;
  93.       unsigned int16 BDnADi;
  94.    } ep[USB_LAST_DEFINED_ENDPOINT+1];
  95.    char buffer[USB_CONTROL_REGISTER_SIZE];
  96. } usb_endpoint_control_registers;
  97. #locate usb_endpoint_control_registers=0xA00
  98. #error/warning usb_endpoint_control_registers needs to be positioned at the start of a 512 byte boundry
  99.  
  100. union
  101. {
  102.    struct
  103.    {
  104.       unsigned int8 ep0_rx_buffer[USB_MAX_EP0_PACKET_LENGTH];
  105.       unsigned int8 ep0_tx_buffer[USB_MAX_EP0_PACKET_LENGTH];
  106.          
  107.       //these buffer definitions needed for CDC library
  108.      #if USB_EP1_RX_SIZE
  109.       unsigned int8 ep1_rx_buffer[USB_EP1_RX_SIZE];
  110.      #endif
  111.      #if USB_EP1_TX_SIZE
  112.       unsigned int8 ep1_tx_buffer[USB_EP1_TX_SIZE];
  113.      #endif
  114.      #if USB_EP2_RX_SIZE
  115.       unsigned int8 ep2_rx_buffer[USB_EP2_RX_SIZE];
  116.      #endif
  117.      #if USB_EP2_TX_SIZE
  118.       unsigned int8 ep2_tx_buffer[USB_EP2_TX_SIZE];
  119.      #endif
  120.    };
  121.    unsigned int8 general[USB_DATA_BUFFER_NEEDED];
  122. } g_USBDataBuffer;
  123. #define USB_DATA_BUFFER_LOCATION &g_USBDataBuffer.general[0]
  124.  
  125. #define usb_ep0_rx_buffer  g_USBDataBuffer.ep0_rx_buffer
  126. #define usb_ep0_tx_buffer  g_USBDataBuffer.ep0_tx_buffer
  127.  
  128. //these buffer definitions needed for CDC library
  129. #define usb_ep1_rx_buffer g_USBDataBuffer.ep1_rx_buffer
  130. #define usb_ep1_tx_buffer g_USBDataBuffer.ep1_tx_buffer
  131. #define usb_ep2_rx_buffer g_USBDataBuffer.ep2_rx_buffer
  132. #define usb_ep2_tx_buffer g_USBDataBuffer.ep2_tx_buffer
  133.  
  134. #define debug_usb(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z)
  135. #define debug_putc(c)
  136.  
  137. #define debug_display_ram(x,y)
  138.  
  139. /*
  140. void debug_putc(char c) {putc(c);}
  141. #define debug_usb printf
  142. */
  143.  
  144. /*
  145. void debug_display_ram(unsigned int8 len, int8 *ptr) {
  146.    unsigned int8 max=16;
  147.    debug_usb(debug_putc,"%U - ",len);
  148.    if (max>len) {max=len;}
  149.    while(max--) {
  150.       debug_usb(debug_putc,"%X",*ptr);
  151.       len--;
  152.       ptr++;
  153.    }
  154.    if (len) {debug_usb(debug_putc,"...");}
  155. }
  156. */
  157.  
  158. //#define debug_putc putc_tbe
  159.  
  160. //if you are worried that the PIC is not receiving packets because a bug in the
  161. //DATA0/DATA1 synch code, you can set this to TRUE to ignore the DTS on
  162. //receiving.
  163. #ifndef USB_IGNORE_RX_DTS
  164.  #define USB_IGNORE_RX_DTS FALSE
  165. #endif
  166.  
  167. #ifndef USB_IGNORE_TX_DTS
  168.  #define USB_IGNORE_TX_DTS FALSE
  169. #endif
  170.  
  171. //if you enable this it will keep a counter of the 6 possible errors the
  172. //pic can detect.  disabling this will save you ROM, RAM and execution time.
  173. #if !defined(USB_USE_ERROR_COUNTER)
  174.    #define USB_USE_ERROR_COUNTER FALSE
  175. #endif
  176.  
  177. #define USB_PING_PONG_MODE_OFF   0  //no ping pong
  178. #define USB_PING_PONG_MODE_E0    1  //ping pong endpoint 0 only
  179. #define USB_PING_PONG_MODE_ON    2  //ping pong all endpoints
  180.  
  181. //NOTE - PING PONG MODE IS NOT SUPPORTED BY CCS!
  182. #if !defined(USB_PING_PONG_MODE)
  183.    #define USB_PING_PONG_MODE USB_PING_PONG_MODE_OFF
  184. #endif
  185.  
  186. #if (USB_PING_PONG_MODE==USB_PING_PONG_MODE_OFF)
  187.  #define EP_BDxST_O(x)    usb_endpoint_control_registers.ep[x].BDnSTo
  188.  #define EP_BDxADR_O(x)   usb_endpoint_control_registers.ep[x].BDnADo
  189.  #define EP_BDxST_I(x)    usb_endpoint_control_registers.ep[x].BDnSTi
  190.  #define EP_BDxADR_I(x)   usb_endpoint_control_registers.ep[x].BDnADi
  191. #else
  192. #error Right now this driver only supports no ping pong
  193. #endif
  194.  
  195. #define __BDST_UOWN     0x8000   //set = buffer control, clear = cpu control
  196. #define __BDST_DTS      0x4000   //set = data1 packet, clear = data0 packet
  197. #define __BDST_DTSEN    0x0800   //set = dts enabled, clear = disabled
  198. #define __BDST_BSTALL   0x0400   //set = buffer stalled
  199.  
  200. #if USB_USE_ERROR_COUNTER
  201.    int ERROR_COUNTER[6];
  202. #endif
  203.  
  204. //---pic24 memory locations
  205. #word UOTGIR  =  0x480
  206. #word UOTGIE  =  0x482
  207. #word UOTGCON =  0x486
  208. #word UPWRC   =  0x488
  209. #word UIR     =  0x48A
  210. #word UIE     =  0x48C
  211. #word UEIR    =  0x48E
  212. #word UEIE    =  0x490
  213. #word USTAT   =  0x492
  214. #word UCON    =  0x494
  215. #word UADDR   =  0x496
  216. #word UBDTP1  =  0x498
  217. #word UFRML   =  0x49A
  218. #word UFRMH   =  0x49C
  219. #word UCFG1   =  0x4A6
  220. #word UCFG2   =  0x4A8
  221. #define  UEP0_LOC 0x4AA
  222.  
  223. int16 UEP_SFR[16];
  224. #locate UEP_SFR=UEP0_LOC
  225.  
  226. #define UEP(x) UEP_SFR[x]
  227.  
  228. #define UIE_BIT_URST    0
  229. #define UIE_BIT_UERR    1
  230. #define UIE_BIT_SOF     2
  231. #define UIE_BIT_TRN     3
  232. #define UIE_BIT_IDLE    4
  233. #define UIE_BIT_STALL   7
  234.  
  235. #BIT UIE_SOF = UIE.UIE_BIT_SOF
  236. #BIT UIE_STALL = UIE.UIE_BIT_STALL
  237. #BIT UIE_IDLE = UIE.UIE_BIT_IDLE
  238. #BIT UIE_TRN = UIE.UIE_BIT_TRN
  239. #BIT UIE_UERR = UIE.UIE_BIT_UERR
  240. #BIT UIE_URST = UIE.UIE_BIT_URST
  241.  
  242. #define UOTGIE_BIT_ACTV 4
  243.  
  244. #BIT UOTGIE_ACTV=UOTGIE.UOTGIE_BIT_ACTV
  245.  
  246. #BIT UIR_SOF = UIR.UIE_BIT_SOF
  247. #BIT UIR_STALL = UIR.UIE_BIT_STALL
  248. #BIT UIR_IDLE = UIR.UIE_BIT_IDLE
  249. #BIT UIR_TRN = UIR.UIE_BIT_TRN
  250. #BIT UIR_UERR = UIR.UIE_BIT_UERR
  251. #BIT UIR_URST = UIR.UIE_BIT_URST
  252.  
  253. #BIT UOTGIR_ACTV=UOTGIR.UOTGIE_BIT_ACTV
  254.  
  255. #ifndef BIT
  256. #define BIT(x) (1<<x)
  257. #endif
  258.  
  259. #define __USB_UIF_RESET    BIT(UIE_BIT_URST)
  260. #define __USB_UIF_ERROR    BIT(UIE_BIT_UERR)
  261. #define __USB_UIF_TOKEN    BIT(UIE_BIT_TRN)
  262. #define __USB_UIF_IDLE     BIT(UIE_BIT_IDLE)
  263. #define __USB_UIF_STALL    BIT(UIE_BIT_STALL)
  264. #define __USB_UIF_SOF      BIT(UIE_BIT_SOF)
  265.  
  266. #if USB_USE_ERROR_COUNTER
  267.  #define STANDARD_INTS __USB_UIF_STALL|__USB_UIF_IDLE|__USB_UIF_TOKEN|__USB_UIF_ERROR|__USB_UIF_RESET
  268. #else
  269.  #define STANDARD_INTS __USB_UIF_STALL|__USB_UIF_IDLE|__USB_UIF_TOKEN|__USB_UIF_RESET
  270. #endif
  271.  
  272. //#bit UOTGCON_DPPULUP = UOTGCON.7
  273. //#bit UOTGCON_DPMULUP = UOTGCON.6
  274.  
  275. #bit UCON_SE0=UCON.6
  276. #bit UCON_PKTDIS=UCON.5
  277. #bit UCON_USBEN=UCON.0
  278. #bit UCON_RESUME=UCON.2
  279. #bit UCON_PPBRST=UCON.1
  280.  
  281. #bit UPWRC_USBPWR=UPWRC.0
  282. #bit UPWRC_SUSPND=UPWRC.1
  283. #define UCON_SUSPND UPWRC_SUSPND
  284.  
  285. //See UEPn (0xF70-0xF7F)
  286. #define ENDPT_DISABLED   0x00   //endpoint not used
  287. #define ENDPT_IN_ONLY   0x04    //endpoint supports IN transactions only
  288. #define ENDPT_OUT_ONLY   0x08    //endpoint supports OUT transactions only
  289. #define ENDPT_CONTROL   0x0C    //Supports IN, OUT and CONTROL transactions - Only use with EP0
  290. #define ENDPT_NON_CONTROL 0x1C  //Supports both IN and OUT transactions
  291.  
  292. #define __UEP_EPHSK  0x01
  293.  
  294. //Define the states that the USB interface can be in
  295. enum {USB_STATE_DETACHED=0, USB_STATE_ATTACHED=1, USB_STATE_POWERED=2, USB_STATE_DEFAULT=3,
  296.     USB_STATE_ADDRESS=4, USB_STATE_CONFIGURED=5} usb_state=0;
  297.  
  298. #define USTAT_IN_E0        8
  299. #define USTAT_OUT_SETUP_E0 0
  300.  
  301. #define __USB_UCFG1_UTEYE   0x80
  302. #define __USB_UCFG1_UOEMON  0x40
  303.  
  304. #define __USB_UCFG2_PUVBUS  0x10 //microchip calls this USB_PULLUP_ENABLE
  305. #define __USB_UCFG2_UTRDIS  0x01 //microchip calls this USB_EXTERNAL_TRANSCEIVER
  306.  
  307. //#define __UCFG1_VAL_ENABLED__ USB_PING_PONG_MODE
  308. #define __UCFG1_VAL_ENABLED__ USB_PING_PONG_MODE
  309. #define __UCFG2_VAL_ENABLED__ __USB_UCFG2_PUVBUS
  310.  
  311. #define __UCFG1_VAL_DISABLED__   0
  312. #define __UCFG2_VAL_DISABLED__ 0
  313.  
  314. int8 __setup_0_tx_size;
  315.  
  316. //interrupt handler, specific to PIC24 peripheral only
  317. void usb_handle_interrupt(void);
  318. void usb_isr_rst(void);
  319. void usb_isr_uerr(void);
  320. void usb_isr_sof(void);
  321. void usb_isr_activity(void);
  322. void usb_isr_uidle(void);
  323. void usb_isr_tok_dne(void);
  324. void usb_isr_stall(void);
  325. void usb_init_ep0_setup(void);
  326.  
  327. //following functions standard part of CCS PIC USB driver, and used by usb.c
  328. unsigned int16 usb_get_packet_buffer(int8 endpoint, int8 *ptr, unsigned int16 max);
  329.  
  330. static void usb_clear_trn(void);
  331.  
  332. static void usb_clear_isr_flag(int16 *sfr, int8 bit);
  333. static void usb_clear_isr_reg(int16 *sfr);
  334.  
  335. //// BEGIN User Functions:
  336.  
  337. // see usb_hw_layer.h for documentation
  338. int1 usb_kbhit(int8 en)
  339. {
  340.    return((UEP(en) != ENDPT_DISABLED) && ((EP_BDxST_O(en) & __BDST_UOWN) == 0));
  341. }
  342.  
  343. // see usb_hw_layer.h for documentation
  344. int1 usb_tbe(int8 en)
  345. {
  346.    return((UEP(en)!=ENDPT_DISABLED) && ((EP_BDxST_I(en) & __BDST_UOWN) == 0));
  347. }
  348.  
  349. // see usb_hw_layer.h for documentation
  350. void usb_detach(void)
  351. {
  352.    UCON = 0;  //disable USB hardware
  353.    UIE = 0;   //disable USB interrupts
  354.    usb_clear_isr_reg(&UEIR);
  355.    usb_clear_isr_reg(&UIR);  
  356.    UOTGIE = 0;
  357.    UPWRC_USBPWR = 1;
  358.    UCFG1 = __UCFG1_VAL_DISABLED__;
  359.    UCFG2 = __UCFG2_VAL_DISABLED__;
  360.    UCON_PPBRST = 1;
  361.    UCON_PPBRST = 0;
  362.    //UOTGCON_DPPULUP = 0;
  363.    //set_tris_g(get_tris_g() | 0x0C); //set d+/d- pins to input //pin_g2 and pin_g3
  364.    usb_state=USB_STATE_DETACHED;
  365.    UADDR = 0;
  366.    
  367.    memset(&UEP_SFR[0], 0x00, sizeof(UEP_SFR));
  368.    
  369.    memset(&usb_endpoint_control_registers, 0x00, sizeof(usb_endpoint_control_registers));
  370.    
  371.    UBDTP1 = &usb_endpoint_control_registers >> 8;
  372.    usb_token_reset();              //clear the chapter9 stack
  373.    UCON_PKTDIS=0;
  374.    //__usb_kbhit_status=0;
  375.  
  376.    /*
  377.    UCON = 0;  //disable USB hardware
  378.    UIE = 0;   //disable USB interrupts
  379.    usb_state = USB_STATE_DETACHED;
  380.    */
  381. }
  382.  
  383. // see usb_hw_layer.h for documentation
  384. void usb_init_cs(void)
  385. {
  386.    /* microchip
  387.       UCON = 0;
  388.       UIE = 0;
  389.       UEIE = 0;
  390.    usb_clear_isr_reg(&UEIR);
  391.    usb_clear_isr_reg(&UIR);
  392.    
  393.    UPWRC_USBPWR = 1;
  394.    
  395.    UBDTP1 = &usb_endpoint_control_registers >> 8;
  396.  
  397.    UCON_PPBRST = 1;
  398.    UCON_PPBRST = 0;
  399.  
  400.    UADDR = 0;
  401.    
  402.    memset(&UEP_SFR[0], 0x00, sizeof(UEP_SFR));
  403.    
  404.    memset(&usb_endpoint_control_registers, 0x00, sizeof(usb_endpoint_control_registers));
  405.  
  406.    UEP(0) = ENDPT_CONTROL | __UEP_EPHSK;  
  407.  
  408.    while (UIR_TRN)
  409.    {
  410.       usb_clear_trn();
  411.    }
  412.  
  413.    UCON_PKTDIS = 0;  //enable
  414.    
  415.    usb_state = USB_STATE_ATTACHED;      // Defined in usbmmap.c & .h
  416.    */
  417.  
  418.    usb_detach();
  419.    
  420.    /* not sure where this came from
  421.    usb_token_reset();
  422.     UCON = 0;
  423.     UIE = 0;                                // Mask all USB interrupts
  424.     UPWRC_USBPWR = 0;
  425.     UCFG1 = __UCFG1_VAL_ENABLED__;
  426.     UCFG2 = __UCFG2_VAL_ENABLED__;
  427.     //UOTGCON_DPPULUP = 1;
  428.     while (!UCON_USBEN) UCON_USBEN = 1;                     // Enable module & attach to bus
  429.     UPWRC_USBPWR = 1;
  430.     usb_state = USB_STATE_ATTACHED;      // Defined in usbmmap.c & .h
  431.     */
  432. }
  433.  
  434. // see usb_hw_layer.h for documentation
  435. static void usb_attach(void) {
  436.    usb_token_reset();
  437.     UCON = 0;
  438.     UIE = 0;                                // Mask all USB interrupts
  439.     UCFG1 = __UCFG1_VAL_ENABLED__;
  440.     UCFG2 = __UCFG2_VAL_ENABLED__;
  441.     while (!UCON_USBEN) {UCON_USBEN = 1;}  // Enable module & attach to bus
  442.     usb_state = USB_STATE_ATTACHED;      // Defined in usbmmap.c & .h
  443. }
  444.  
  445. // see usb_hw_layer.h for documentation
  446. void usb_task(void) {
  447.    if (usb_attached()) {
  448.       if (UCON_USBEN==0) {
  449.          debug_usb(debug_putc, "\r\n\nUSB TASK: ATTACH");
  450.          usb_attach();
  451.          //delay_ms(50);
  452.       }
  453.    }
  454.    else {
  455.       if (UCON_USBEN==1)  {
  456.          debug_usb(debug_putc, "\r\n\nUSB TASK: DE-ATTACH");
  457.          usb_detach();
  458.       }
  459.    }
  460.  
  461.    if ((usb_state == USB_STATE_ATTACHED)&&(!UCON_SE0))
  462.    {
  463.       usb_clear_isr_reg(&UIR);
  464.       UIE=0;
  465.       enable_interrupts(INT_USB);
  466.       enable_interrupts(INTR_GLOBAL);
  467.       UIE=__USB_UIF_IDLE | __USB_UIF_RESET;  //enable IDLE and RESET USB interrupt
  468.       usb_state=USB_STATE_POWERED;
  469.       debug_usb(debug_putc, "\r\n\nUSB TASK: POWERED");
  470.    }
  471. }
  472.  
  473. // see usb_hw_layer.h for documentation
  474. void usb_init(void)
  475. {
  476.    usb_init_cs();
  477.  
  478.    do
  479.    {
  480.       usb_task();
  481.    } while (usb_state != USB_STATE_POWERED);
  482. }
  483.  
  484. // see pic24_usb.h for documentation
  485. int1 usb_flush_in(int8 endpoint, unsigned int16 len, USB_DTS_BIT tgl)
  486. {
  487.    int16 oldBD, newBD = 0;
  488.    
  489.    debug_usb(debug_putc,"\r\nPUT %X %U %LU %LX", endpoint, tgl, len, EP_BDxST_I(endpoint));
  490.  
  491.    if (usb_tbe(endpoint))
  492.    {
  493.       newBD = len;
  494.  
  495.       debug_display_ram(len, EP_BDxADR_I(endpoint));
  496.  
  497.      #if USB_IGNORE_TX_DTS
  498.       newBD |= __BDST_UOWN;
  499.      #else
  500.       if (tgl == USB_DTS_TOGGLE)
  501.       {
  502.          oldBD = EP_BDxST_I(endpoint);
  503.          if ((oldBD & __BDST_DTS) == __BDST_DTS)   //(bit_test(i,14))
  504.             tgl=USB_DTS_DATA0;  //was DATA1, goto DATA0
  505.          else
  506.             tgl=USB_DTS_DATA1;  //was DATA0, goto DATA1
  507.       }
  508.       else if (tgl == USB_DTS_USERX)
  509.       {
  510.          oldBD = EP_BDxST_O(endpoint);
  511.          if ((oldBD & __BDST_DTS) == __BDST_DTS)   //(bit_test(i,14))
  512.             tgl = USB_DTS_DATA1;
  513.          else
  514.             tgl = USB_DTS_DATA0;
  515.       }
  516.       if (tgl == USB_DTS_DATA1)
  517.          newBD |= __BDST_UOWN | __BDST_DTS | __BDST_DTSEN;  //DATA1, UOWN
  518.       else //if (tgl == USB_DTS_DATA0)
  519.          newBD |= __BDST_UOWN | __BDST_DTSEN; //DATA0, UOWN
  520.      #endif
  521.  
  522.       debug_usb(debug_putc," %X", newBD);
  523.  
  524.       EP_BDxST_I(endpoint) = newBD;//save changes
  525.      
  526.       return(1);
  527.    }
  528.     else {
  529.          debug_usb(debug_putc,"\r\nPUT ERR");
  530.     }
  531.    return(0);
  532. }
  533.  
  534. // see usb_hw_layer.h for documentation.
  535. int1 usb_put_packet(int8 endpoint, int8 * ptr, unsigned int16 len, USB_DTS_BIT tgl)
  536. {
  537.    int8 * buff_add;    
  538.  
  539.    if (usb_tbe(endpoint))
  540.    {
  541.       buff_add=EP_BDxADR_I(endpoint);
  542.       memcpy(buff_add, ptr, len);    
  543.      
  544.       return(usb_flush_in(endpoint, len, tgl));
  545.    }
  546.    else
  547.    {
  548.       debug_usb(debug_putc,"\r\nPUT ERR");
  549.    }
  550.  
  551.    return(0);
  552. }
  553.  
  554. /// END User Functions
  555.  
  556.  
  557. /// BEGIN Hardware layer functions required by USB.C
  558.  
  559. // see pic24_usb.h for documentation
  560. void usb_flush_out(int8 endpoint, USB_DTS_BIT tgl)
  561. {
  562.    int16 oldBD, newBD;
  563.    int16 len;
  564.  
  565.      #if USB_IGNORE_RX_DTS
  566.       if (tgl == USB_DTS_STALL)
  567.       {
  568.          debug_usb(debug_putc, '*');
  569.          EP_BDxST_I(endpoint) = __BDST_UOWN | __BDST_BSTALL;
  570.          EP_BDxST_O(endpoint) = __BDST_UOWN | __BDST_BSTALL;
  571.          return;
  572.       }
  573.       else
  574.          newBD = __BDST_UOWN;
  575.      #else
  576.       oldBD = EP_BDxST_O(endpoint);
  577.       if (tgl == USB_DTS_TOGGLE)
  578.       {
  579.          if ((oldBD & __BDST_DTS) == __BDST_DTS)   //(bit_test(i,14))
  580.             tgl = USB_DTS_DATA0;  //was DATA1, goto DATA0
  581.          else
  582.             tgl  =USB_DTS_DATA1;  //was DATA0, goto DATA1
  583.       }
  584.       if (tgl == USB_DTS_STALL)
  585.       {
  586.          newBD = __BDST_UOWN | __BDST_BSTALL;
  587.          EP_BDxST_I(endpoint) = __BDST_UOWN | __BDST_BSTALL; //stall both in and out endpoints
  588.       }
  589.       else if (tgl == USB_DTS_DATA1)
  590.       {
  591.          newBD = __BDST_UOWN | __BDST_DTS | __BDST_DTSEN;  //DATA1, UOWN
  592.       }
  593.       else //if (tgl == USB_DTS_DATA0)
  594.       {
  595.          newBD = __BDST_UOWN | __BDST_DTSEN; //DATA0, UOWN
  596.       }
  597.      #endif
  598.  
  599.    //bit_clear(__usb_kbhit_status,endpoint);
  600.  
  601.    len=usb_ep_rx_size[endpoint];
  602.  
  603.    newBD |= len;
  604.  
  605.    EP_BDxST_O(endpoint) = newBD;
  606. }
  607.  
  608. // see pic24_usb.h for documentation
  609. unsigned int16 usb_rx_packet_size(int8 endpoint)
  610. {
  611.    return(EP_BDxST_O(endpoint) & 0x03FF);
  612. }
  613.  
  614. /*******************************************************************************
  615. /* usb_get_packet_buffer(endpoint, *ptr, max)
  616. /*
  617. /* Input: endpoint - endpoint to get data from
  618. /*        ptr - where to save data to local PIC RAM
  619. /*        max - max amount of data to receive from buffer
  620. /*
  621. /* Output: the amount of data taken from the buffer.
  622. /*
  623. /* Summary: Gets a packet of data from the USB buffer and puts into local PIC RAM.
  624. /*          Does not mark the endpoint as ready for more data.  Once you are
  625. /*          done with data, call usb_flush_out() to mark the endpoint ready
  626. /*          to receive more data.
  627. /*
  628. /********************************************************************************/
  629. unsigned int16 usb_get_packet_buffer(int8 endpoint, int8 *ptr, unsigned int16 max)
  630. {
  631.    int8 *al;
  632.    unsigned int16 i;
  633.  
  634.    al = EP_BDxADR_O(endpoint);
  635.    //i = usb_rx_packet_size(endpoint);
  636.         i=4;
  637.    //printf("\r\nUSB GET PACKET ST:%LX %U I=%LX MAX=%LX %X%X ", EP_BDxST_O(endpoint), endpoint, i, max, al[0], al[1]);
  638.  
  639.  
  640.    if (i<max) {max=i;}
  641.    
  642.    if (max > 1)  
  643.       memcpy(ptr,al,max);
  644.    else if (max == 1)
  645.       *ptr = *al;
  646.  
  647.    //printf("%X%X\r\n", ptr[0], ptr[1]);
  648.  
  649.    return(max);
  650. }
  651.  
  652. // see usb_hw_layer.h
  653. unsigned int16 usb_get_packet(int8 endpoint, int8 * ptr, unsigned int16 max)
  654. {
  655.    max=usb_get_packet_buffer(endpoint,ptr,max);
  656.    usb_flush_out(endpoint, USB_DTS_TOGGLE);
  657.  
  658.    return(max);
  659. }
  660.  
  661. // see usb_hw_layer.h
  662. void usb_stall_ep(int8 endpoint)
  663. {
  664.    int1 direction;
  665.    
  666.    direction=bit_test(endpoint,7);
  667.    endpoint&=0x7F;
  668.    
  669.    if (direction)
  670.    {
  671.       EP_BDxST_I(endpoint) = __BDST_UOWN | __BDST_BSTALL;
  672.    }
  673.    else
  674.    {
  675.       EP_BDxST_O(endpoint) = __BDST_UOWN | __BDST_BSTALL;
  676.    }
  677. }
  678.  
  679. // see usb_hw_layer.h for documentation
  680. void usb_unstall_ep(int8 endpoint)
  681. {
  682.    int1 direction;
  683.  
  684.    direction=bit_test(endpoint,7);
  685.    endpoint&=0x7F;
  686.    
  687.    if (direction) {
  688.       #if USB_IGNORE_RX_DTS
  689.       EP_BDxST_I(endpoint) = __BDST_UOWN;
  690.       #else
  691.       EP_BDxST_I(endpoint) = __BDST_UOWN | __BDST_DTSEN;
  692.       #endif
  693.    }
  694.    else {
  695.       EP_BDxST_O(endpoint) = 0x00;
  696.    }
  697. }
  698.  
  699. // see usb_hw_layer.h for documentation
  700. int1 usb_endpoint_stalled(int8 endpoint)
  701. {
  702.    int1 direction;
  703.    int16 st;
  704.    
  705.    direction = bit_test(endpoint,7);
  706.    endpoint &= 0x7F;
  707.    
  708.    if (direction)
  709.    {
  710.       st = EP_BDxST_I(endpoint);
  711.    }
  712.    else
  713.    {
  714.       st = EP_BDxST_O(endpoint);
  715.    }
  716.    
  717.    return(
  718.             ((st & __BDST_UOWN) == __BDST_UOWN) &&
  719.             ((st & __BDST_UOWN) == __BDST_BSTALL)
  720.          );
  721. }
  722.  
  723. // see usb_hw_layer.h for documentation
  724. void usb_set_address(int8 address)
  725. {
  726.    UADDR = address;
  727.    
  728.    if (address)
  729.       usb_state = USB_STATE_ADDRESS;
  730.    else
  731.       usb_state = USB_STATE_POWERED;
  732. }
  733.  
  734. // see usb_hw_layer.h for documentation
  735. void usb_set_configured(int8 config)
  736. {
  737.    unsigned int8 en;
  738.    unsigned int16 addy;
  739.    int8 new_uep;
  740.    unsigned int16 len;
  741.    int16 newBD;
  742.    
  743.       if (config == 0)
  744.       {  //if config=0 then set addressed state
  745.          usb_state = USB_STATE_ADDRESS;
  746.          usb_disable_endpoints();
  747.       }
  748.       else
  749.       {
  750.          usb_state = USB_STATE_CONFIGURED; //else set configed state
  751.          addy = USB_DATA_BUFFER_LOCATION + (2*USB_MAX_EP0_PACKET_LENGTH); //skip ep0
  752.          for (en=1; en<16; en++)
  753.          {
  754.             usb_disable_endpoint(en);        
  755.             new_uep = 0;
  756.             if (usb_ep_rx_type[en] != USB_ENABLE_DISABLED)
  757.             {
  758.                new_uep = ENDPT_OUT_ONLY;
  759.                
  760.                len = usb_ep_rx_size[en];
  761.                
  762.                EP_BDxADR_O(en) = addy;
  763.                addy += usb_ep_rx_size[en];
  764.                
  765.                #if USB_IGNORE_RX_DTS
  766.                   newBD = __BDST_UOWN;
  767.                #else
  768.                   newBD = __BDST_UOWN | __BDST_DTSEN;
  769.                #endif
  770.                
  771.                newBD |= len;
  772.                EP_BDxST_O(en) = newBD;
  773.             }
  774.             if (usb_ep_tx_type[en] != USB_ENABLE_DISABLED)
  775.             {
  776.                new_uep |= ENDPT_IN_ONLY;
  777.                
  778.                EP_BDxADR_I(en) = addy;
  779.                addy += usb_ep_tx_size[en];
  780.                
  781.                EP_BDxST_I(en) = __BDST_DTS;
  782.             }
  783.            
  784.             if (new_uep == (ENDPT_IN_ONLY | ENDPT_OUT_ONLY))
  785.                new_uep = ENDPT_NON_CONTROL;
  786.                
  787.             if (usb_ep_tx_type[en] != USB_ENABLE_ISOCHRONOUS)
  788.                new_uep |= __UEP_EPHSK;
  789.                
  790.             UEP(en)=new_uep;
  791.          }
  792.       }
  793. }
  794.  
  795. /// END Hardware layer functions required by USB.C
  796.  
  797.  
  798. /// BEGIN USB Interrupt Service Routine
  799.  
  800. static void usb_clear_trn(void)
  801. {
  802.    usb_clear_isr_flag(&UIR, UIE_BIT_TRN);
  803.    delay_cycles(6);
  804. }
  805.  
  806. /*******************************************************************************
  807. /* usb_handle_interrupt()
  808. /*
  809. /* Summary: Checks the interrupt, and acts upon event.  Processing finished
  810. /*          tokens is the majority of this code, and is handled by usb.c
  811. /*
  812. /* NOTE: If you wish to change to a polling method (and not an interrupt method),
  813. /*       then you must call this function rapidly.  If there is more than 10ms
  814. /*       latency the PC may think the USB device is stalled and disable it.
  815. /*       To switch to a polling method, remove the #int_usb line above this fuction.
  816. /*       Also, goto usb_init() and remove the code that enables the USB interrupt.
  817. /********************************************************************************/
  818. #int_usb
  819. void usb_isr(void)
  820. {
  821.    int8 TRNAttempts = 0;
  822.    
  823.    debug_putc('.');
  824.    
  825.    if (usb_state==USB_STATE_DETACHED) return;   //should never happen, though
  826.    if (UIR || UOTGIR)
  827.    {
  828.       //debug_usb(debug_putc,"\r\n\n[%X%X%U] ",(int8)UIR, (int8)UOTGIR, UCON_SUSPND);
  829.       if (UOTGIR_ACTV && UOTGIE_ACTV) {usb_isr_activity();}  //activity detected.  (only enable after sleep)
  830.  
  831.       if (UCON_SUSPND) return;
  832.  
  833.       if (UIR_STALL && UIE_STALL) {usb_isr_stall();}        //a stall handshake was sent
  834.  
  835.       if (UIR_UERR && UIE_UERR) {usb_isr_uerr();}          //error has been detected
  836.  
  837.       if (UIR_URST && UIE_URST) {usb_isr_rst();}        //usb reset has been detected
  838.  
  839.       if (UIR_IDLE && UIE_IDLE) {usb_isr_uidle();}        //idle time, we can go to sleep
  840.       if (UIR_SOF && UIE_SOF) {usb_isr_sof();}
  841.       //if (UIR_STALL && UIE_STALL) {usb_isr_stall();}        //a stall handshake was sent
  842.  
  843.       do
  844.       {
  845.          if (UIR_TRN && UIE_TRN) {
  846.             usb_isr_tok_dne();
  847.             //UIR_TRN=0;    // clear the token done interrupt., 0x190.3
  848.          }    //a token has been detected (majority of isrs)
  849.          else
  850.             break;
  851.       }
  852.       while (TRNAttempts++ < 4);
  853.    }
  854. }
  855.  
  856. //SOF interrupt not handled.  user must add this depending on application
  857. void usb_isr_sof(void)
  858. {
  859.    debug_usb(debug_putc,"\r\nSOF");
  860.    usb_clear_isr_flag(&UIR, UIE_BIT_SOF);
  861. }
  862.  
  863. // see usb_hw_layer.h for documentation
  864. void usb_disable_endpoint(int8 en)
  865. {
  866.    UEP(en)=ENDPT_DISABLED;
  867.    EP_BDxST_O(en) = 0;   //clear state, deque if necessary      
  868.    EP_BDxST_I(en) = 0;   //clear state, deque if necessary
  869. }
  870.  
  871. // see usb_hw_layer.h for documentation
  872. void usb_disable_endpoints(void)
  873. {
  874.    unsigned int8 i;
  875.    
  876.    for (i=1;i<16;i++)
  877.       usb_disable_endpoint(i);
  878.      
  879.    //__usb_kbhit_status=0;
  880. }
  881.  
  882. /*******************************************************************************
  883. /* usb_isr_rst()
  884. /*
  885. /* Summary: The host (computer) sent us a RESET command.  Reset USB device
  886. /*          and token handler code to initial state.
  887. /*
  888. /********************************************************************************/
  889. void usb_isr_rst(void) {
  890.    debug_usb(debug_putc,"R");
  891.  
  892.    usb_clear_isr_reg(&UEIR);
  893.    usb_clear_isr_reg(&UIR);
  894.    UEIE = 0x9F;
  895.    UIE = STANDARD_INTS;
  896.  
  897.    UADDR=0;
  898.  
  899.    usb_token_reset();
  900.  
  901.    usb_disable_endpoints();
  902.  
  903.    UEP(0) = ENDPT_CONTROL | __UEP_EPHSK;
  904.  
  905.    while (UIR_TRN)
  906.    {
  907.       usb_clear_trn();
  908.    }
  909.  
  910.    UCON_PKTDIS=0; //SIE token and packet processing enabled
  911.  
  912.    usb_init_ep0_setup();
  913.  
  914.    usb_state=USB_STATE_DEFAULT; //put usb mcu into default state
  915. }
  916.  
  917. /*****************************************************************************
  918. /* usb_init_ep0_setup()
  919. /*
  920. /* Summary: Configure EP0 to receive setup packets
  921. /*
  922. /*****************************************************************************/
  923. void usb_init_ep0_setup(void)
  924. {
  925.    int16 newBD;
  926.    
  927.    newBD = USB_MAX_EP0_PACKET_LENGTH;
  928.    EP_BDxADR_O(0) = USB_DATA_BUFFER_LOCATION;
  929.   #if USB_IGNORE_RX_DTS
  930.    newBD |= __BDST_UOWN;
  931.   #else
  932.    newBD |= __BDST_UOWN | __BDST_DTSEN;   //give control to SIE, DATA0, data toggle synch on
  933.   #endif
  934.    EP_BDxST_O(0) = newBD;
  935.  
  936.    EP_BDxST_I(0) = 0;
  937.    EP_BDxADR_I(0) = USB_DATA_BUFFER_LOCATION + (int16)USB_MAX_EP0_PACKET_LENGTH;
  938. }
  939.  
  940. /*******************************************************************************
  941. /* usb_isr_uerr()
  942. /*
  943. /* Summary: The USB peripheral had an error.  If user specified, error counter
  944. /*          will incerement.  If having problems check the status of these 8 bytes.
  945. /*
  946. /* NOTE: This code is not enabled by default.
  947. /********************************************************************************/
  948. void usb_isr_uerr(void) {
  949. #if USB_USE_ERROR_COUNTER
  950.    int ints;
  951. #endif
  952.  
  953.    debug_usb(debug_putc,"E %X ",UEIR);
  954.  
  955. #if USB_USE_ERROR_COUNTER
  956.  
  957.    ints=UEIR & UEIE; //mask off the flags with the ones that are enabled
  958.  
  959.    if ( bit_test(ints,0) ) { //increment pid_error counter
  960.       debug_usb(debug_putc,"PID ");
  961.       ERROR_COUNTER[0]++;
  962.    }
  963.  
  964.    if ( bit_test(ints,1) ) {  //increment crc5 error counter
  965.       debug_usb(debug_putc,"CRC5 ");
  966.       ERROR_COUNTER[1]++;
  967.    }
  968.  
  969.    if ( bit_test(ints,2) ) {  //increment crc16 error counter
  970.       debug_usb(debug_putc,"CRC16 ");
  971.       ERROR_COUNTER[2]++;
  972.    }
  973.  
  974.    if ( bit_test(ints,3) ) {  //increment dfn8 error counter
  975.       debug_usb(debug_putc,"DFN8 ");
  976.       ERROR_COUNTER[3]++;
  977.    }
  978.  
  979.    if ( bit_test(ints,4) ) {  //increment bto error counter
  980.       debug_usb(debug_putc,"BTO ");
  981.       ERROR_COUNTER[4]++;
  982.    }
  983.  
  984.    if ( bit_test(ints,7) ) { //increment bts error counter
  985.       debug_usb(debug_putc,"BTS ");
  986.       ERROR_COUNTER[5]++;
  987.    }
  988. #endif
  989.  
  990.    usb_clear_isr_reg(&UEIR);
  991.    usb_clear_isr_flag(&UIR, UIE_BIT_UERR);
  992. }
  993.  
  994. /*******************************************************************************
  995. /* usb_isr_uidle()
  996. /*
  997. /* Summary: USB peripheral detected IDLE.  Put the USB peripheral to sleep.
  998. /*
  999. /********************************************************************************/
  1000. void usb_isr_uidle(void)
  1001. {
  1002.    debug_usb(debug_putc,"I");
  1003.  
  1004.    UOTGIE_ACTV=1;   //enable activity interrupt flag.
  1005.    usb_clear_isr_flag(&UIR, UIE_BIT_IDLE);
  1006.    //UCON_SUSPND=1; //set suspend. we are now suspended
  1007. }
  1008.  
  1009.  
  1010. /*******************************************************************************
  1011. /* usb_isr_activity()
  1012. /*
  1013. /* Summary: USB peripheral detected activity on the USB device.  Wake-up the USB
  1014. /*          peripheral.
  1015. /*
  1016. /********************************************************************************/
  1017. void usb_isr_activity(void)
  1018. {
  1019.    debug_usb(debug_putc,"A");
  1020.  
  1021.    UCON_SUSPND=0; //turn off low power suspending
  1022.    UOTGIE_ACTV=0; //clear activity interupt enabling
  1023.    usb_clear_isr_flag(&UOTGIR, UOTGIE_BIT_ACTV);
  1024. }
  1025.  
  1026. /*******************************************************************************
  1027. /* usb_isr_stall()
  1028. /*
  1029. /* Summary: Stall handshake detected.
  1030. /*
  1031. /********************************************************************************/
  1032. void usb_isr_stall(void)
  1033. {
  1034.    debug_usb(debug_putc,"S");
  1035.    
  1036.    
  1037.    if (bit_test(UEP(0),1)) {
  1038.       usb_init_ep0_setup();
  1039.       bit_clear(UEP(0),1);
  1040.    }
  1041.    usb_clear_isr_flag(&UIR, UIE_BIT_STALL);
  1042. }
  1043.  
  1044. /*******************************************************************************
  1045. /* usb_isr_tok_dne()
  1046. /*
  1047. /* Summary: A Token (IN/OUT/SETUP) has been received by the USB peripheral.
  1048. /*          If a setup token on EP0 was received, run the chapter 9 code and
  1049. /*          handle the request.
  1050. /*          If an IN token on EP0 was received, continue transmitting any
  1051. /*          unfinished requests that may take more than one packet to transmit
  1052. /*          (if necessary).
  1053. /*          If an OUT token on any other EP was received, mark that EP as ready
  1054. /*          for a usb_get_packet().
  1055. /*          Does not handle any IN or OUT tokens on EP0.
  1056. /*
  1057. /********************************************************************************/
  1058. void usb_isr_tok_dne(void)
  1059. {
  1060.    int8 en;
  1061.  
  1062.    en=USTAT>>4;
  1063.  
  1064.    debug_usb(debug_putc,"T ");
  1065.    debug_usb(debug_putc,"%X ", USTAT);
  1066.  
  1067.    if ((USTAT & 0x00F8) == USTAT_OUT_SETUP_E0)
  1068.    {
  1069.       //new out or setup token in the buffer
  1070.       int16 pidKey;
  1071.      
  1072.       debug_usb(debug_putc,"%LX ", EP_BDxST_O(0));
  1073.      
  1074.       pidKey = EP_BDxST_O(0) & (int16)0x3C00;  //save PID
  1075.       pidKey >>= 10;
  1076.      
  1077.       EP_BDxST_O(0) &= (int16)0x43FF;  //clear pid, prevent bdstal/pid confusion
  1078.       usb_clear_trn();
  1079.      
  1080.       if (pidKey == PID_SETUP)
  1081.       {
  1082.          EP_BDxST_I(0)=0;   // return the in buffer to us (dequeue any pending requests)
  1083.  
  1084.          debug_usb(debug_putc,"%LU ", EP_BDxST_O(0) & 0x3FF);
  1085.          debug_display_ram(EP_BDxST_O(0) & 0x3FF, usb_ep0_rx_buffer);
  1086.  
  1087.          usb_isr_tok_setup_dne();
  1088.  
  1089.          UCON_PKTDIS=0;       // UCON,PKT_DIS ; Assuming there is nothing to dequeue, clear the packet disable bit
  1090.  
  1091.          //if setup_0_tx_size==0xFF - stall ep0 (unhandled request)
  1092.          //if setup_0_tx_size==0xFE - get EP0OUT ready for a data packet, leave EP0IN alone
  1093.          //else setup_0_tx_size=size of response, get EP0OUT ready for a setup packet, mark EPOIN ready for transmit
  1094.          if (__setup_0_tx_size==0xFF)
  1095.             usb_flush_out(0,USB_DTS_STALL);
  1096.          else
  1097.          {
  1098.             usb_flush_out(0,USB_DTS_TOGGLE);
  1099.             if (__setup_0_tx_size!=0xFE)
  1100.                usb_flush_in(0,__setup_0_tx_size,USB_DTS_USERX);
  1101.  
  1102.          }
  1103.          //why was this here?
  1104.          //UCON_PKTDIS=0;       // UCON,PKT_DIS ; Assuming there is nothing to dequeue, clear the packet disable bit
  1105.       }
  1106.       else if (pidKey == PID_OUT)
  1107.       {
  1108.          usb_isr_tok_out_dne(0);
  1109.          usb_flush_out(0,USB_DTS_TOGGLE);
  1110.          if ((__setup_0_tx_size!=0xFE)&&(__setup_0_tx_size!=0xFF))
  1111.                usb_flush_in(0,__setup_0_tx_size,USB_DTS_DATA1);   //send response (usually a 0len)
  1112.       }
  1113.    }
  1114.    else if ((USTAT & 0x00F8) == USTAT_IN_E0)
  1115.    {
  1116.       //pic -> host transfer completed
  1117.       EP_BDxST_I(0) = EP_BDxST_I(0) & 0x4300;   //clear up any BDSTAL confusion
  1118.       usb_clear_trn();
  1119.       __setup_0_tx_size=0xFF;
  1120.       usb_isr_tok_in_dne(0);
  1121.       if (__setup_0_tx_size!=0xFF)
  1122.          usb_flush_in(0,__setup_0_tx_size,USB_DTS_TOGGLE);
  1123.       else
  1124.          usb_init_ep0_setup();
  1125.    }
  1126.    else
  1127.    {
  1128.       if (!bit_test(USTAT, 3))
  1129.       {
  1130.          EP_BDxST_O(en) = EP_BDxST_O(en) & 0x43FF;   //clear up any BDSTAL confusion
  1131.          usb_clear_trn();
  1132.          usb_isr_tok_out_dne(en);
  1133.       }
  1134.       else
  1135.       {
  1136.          EP_BDxST_I(en) = EP_BDxST_I(en) & 0x4300;   //clear up any BDSTAL confusion
  1137.          usb_clear_trn();
  1138.          usb_isr_tok_in_dne(en);
  1139.       }
  1140.    }
  1141. }
  1142.  
  1143. // see usb_hw_layer.h for documentation
  1144. void usb_request_send_response(unsigned int8 len) {__setup_0_tx_size=len;}
  1145. void usb_request_get_data(void) {__setup_0_tx_size=0xFE;}
  1146. void usb_request_stall(void) {__setup_0_tx_size=0xFF;}
  1147.  
  1148.  
  1149. /// END USB Interrupt Service Routine
  1150.  
  1151. static void usb_clear_isr_flag(int16 *sfr, int8 bit)
  1152. {
  1153.    *sfr = (int16)1 << bit;
  1154. }
  1155.  
  1156. static void usb_clear_isr_reg(int16 *sfr)
  1157. {
  1158.    *sfr = 0xFFFF;
  1159. }
  1160.  
  1161. #ENDIF

Desconectado migsantiago

  • Colaborador
  • DsPIC33
  • *****
  • Mensajes: 8257
    • Sitio de MigSantiago
Re: usb_rx_packet_size devuelve un cero
« Respuesta #8 en: 03 de Diciembre de 2010, 16:26:12 »
Se me ocurre que en la aplicación de la PC estás mandando mal los datos.

Debes declarar un buffer TX de 5 bytes para mandar 4 bytes. El primer byte siempre es cero.

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
Re: usb_rx_packet_size devuelve un cero
« Respuesta #9 en: 03 de Diciembre de 2010, 16:28:23 »
Eso es correcto, es lo que hago, y de hecho lo veo en el log de actividad de GenericHID.

Desconectado bmfranky

  • PIC16
  • ***
  • Mensajes: 165
    • La Tienda De Fran
Re: usb_rx_packet_size devuelve un cero
« Respuesta #10 en: 03 de Diciembre de 2010, 16:41:10 »
Hola Nocturno, mi ingles no es  muy bueno, pero en la declaración, dice que hay que borrar el bufer después de adquirir los datos, ¿sera por eso que no funciona?

Citar
/**************************************************************
/* usb_rx_packet_size()
/*
/* Input: endpoint - which endpoint to mark to check
/*
/* Output: Returns the number of bytes in the endpoint's receive buffer.
/*
/* Summary: Read the number of data stored in the receive buffer.  When you
/*    have handled the data, use usb_flush_out() to clear the buffer.  The
/*    result may be invalid if usb_kbhit() returns false for this endpoint.
/*    This routine is not necessary if you use usb_get_packet().
/***************************************************************/

también dice:
Citar
The result may be invalid if usb_kbhit() returns false for this endpoint.

Osea, que si preguntas antes de que hayan datos, te devolverá 0, :?, o lo he entendido mal.

Por cierto, donde usas esto?:
Citar
i = usb_rx_packet_size(endpoint);
« Última modificación: 03 de Diciembre de 2010, 16:45:50 por bmfranky »
Visiten La Tienda De Fran ;-) Aqui. y mi nueva Web Aqui.

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
Re: usb_rx_packet_size devuelve un cero
« Respuesta #11 en: 04 de Diciembre de 2010, 08:07:15 »
¡Resuelto! :-/

Al final resultó tratarse de una jugarreta del CCS. Estaba compilando con 4.093 cuando fallaba.
He cambiado a 4.104 y ya va perfecto.

Gracias por vuestra ayuda.

Desconectado PalitroqueZ

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 5474
    • Electrónica Didacta
Re: usb_rx_packet_size devuelve un cero
« Respuesta #12 en: 04 de Diciembre de 2010, 11:09:11 »
...Al final resultó tratarse de una jugarreta del CCS. Estaba compilando con 4.093 cuando fallaba.
He cambiado a 4.104 y ya va perfecto.
...

 :shock:







La propiedad privada es la mayor garantía de libertad.
Friedrich August von Hayek

Desconectado migsantiago

  • Colaborador
  • DsPIC33
  • *****
  • Mensajes: 8257
    • Sitio de MigSantiago
Re: usb_rx_packet_size devuelve un cero
« Respuesta #13 en: 04 de Diciembre de 2010, 11:52:14 »
Yo por eso ya uso a Microchip y HiTech.  ;-)

Desconectado Nocturno

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 18286
    • MicroPIC
Re: usb_rx_packet_size devuelve un cero
« Respuesta #14 en: 04 de Diciembre de 2010, 12:39:38 »
Me da pereza cambiar de compilador por el tiempo de adaptación que necesitare, pero este problema de CCS ya me ha hecho perder un buen puñado de horas.