Autor Tema: Proyecto PicUSB  (Leído 510572 veces)

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

Desconectado ekud

  • PIC16
  • ***
  • Mensajes: 120
    • mi pag... bueno no es mia pero ahi estoy
Re: Proyecto PicUSB
« Respuesta #450 en: 15 de Febrero de 2009, 03:54:59 »
Hola a todos!

bueno lo que pasa es ps soy nuevo con esto de los micros de la serie 18f y queria comenzar con una comunicacion usb muy basica.

pues bien leyendo y leyendo tengo entendido que la frecuencia con la que trabajan estos micros para el usb 2.0 es de 48Mhz, que esta frecuencia es independiente de la frecuencia de trabajo del micro pero que aun asi su fuente es el oscilador externo que siempre se pone, solo que con un pll se amplifica hasta los 48Mhz.. y en fin...

y pues bien siempre he programado micros en el mikrobasic que ya va por la version 7.2 (7.3 en beta), en el mikrobasic hay un alibreria que me permite comunicarme con el pc via usb, tambien en l mikrobasic se incluye una aplicacion (muy parecida a lo que hace el EasyHID) que me genera un archivo con los descriptores para el microcontrolador. y asi las cosas uno pensaria que este tema esta en bandeja de plata.. listo para usarlo y ya...

pues bien... a mi no me ha kerido dar resultado el dichoso ejemplo que se plantea en este lenguaje... el ejemplo lleva un micro 18f4550 trabajando con un crytal a 8Mhz y ya... es asi de basico...

el codigo es el siguiente

(archivo USB_HID_test.pbas)

Código: [Seleccionar]
' * Project name:
'     HIDtest (Testing the USB HID connection)
' * Copyright:
'     (c) MikroElektronika, 2005 - 2008
' * Revision History:
'     20050502:
'       - initial release;
' * Description:
'     This example establishes connection with the HID terminal that is active
'     on the PC. Upon connection establishment, the HID Device Name will appear
'     in the respective window. After that software will wait for data and
'     it will return received data back.
' * Test configuration:
'     MCU:             PIC18F4550
'     Dev.Board:       EasyPIC5
'     Oscillator:      HS 8.000 MHz  (USB osc. is raised with PLL to 48.000MHz)
'     Ext. Modules:    -
'     SW:              mikroBasic v7.1
' * NOTES:
'     - Be VERY careful about the configuration flags for the 18F4550 - there's
'       so much place for mistake!
       
program USB_HID_test

include "USBdsc"

dim
 k, i, ch       as  byte
 userWR_buffer  as  byte[64]
 userRD_buffer  as  byte[64]

'******************************************************************************
' Main Interrupt Routine
'******************************************************************************
sub procedure interrupt
'** this is a way to call a procedure from interrupt
  HID_InterruptProc
end sub
'******************************************************************************


'******************************************************************************
' Initialization Routine
'******************************************************************************
sub procedure Init_Main
'--------------------------------------
' Disable interrupts
'--------------------------------------
INTCON = 0                             ' Disable GIE, PEIE, TMR0IE,INT0IE,RBIE
INTCON2 = 0xF5
INTCON3 = 0xC0
RCON.IPEN = 0                          ' Disable Priority Levels on interrupts
PIE1 = 0
PIE2 = 0
PIR1 = 0
PIR2 = 0

ADCON1 = ADCON1 or 0x0F                ' Configure all ports with analog function as digital
'--------------------------------------
' Ports Configuration
'--------------------------------------
TRISA = 0xFF
TRISB = 0xFF
TRISC = 0xFF
TRISD = 0
TRISE = 0x07

LATA = 0
LATB = 0
LATC = 0
LATD = 0
LATE = 0
end sub



'******************************************************************************
' Main Program Routine
'******************************************************************************

main:
  Init_Main()
 
  HID_Enable(@userRD_buffer, @userWR_buffer)
  Delay_mS(1000)
  Delay_mS(1000)

  while true
      k = HID_Read()
      i = 0
      while i < k
          ch = userRD_buffer[0]
          userWR_buffer[0] = ch
          HID_Write(@userWR_buffer, 1)
          inc(i)
      wend
  wend
  HID_Disable()
 
end.


el archivo del inlude (USBdsc.pbas) que es el que se genera con la aplicacion de mikrobasic para generar los descritores HId  contiene el siguiente codigo:

Código: [Seleccionar]
module USBdsc
include "HIDconstant"
' File Version 1.01
'
'******************************************************************************

'******************************************************************************
' The number of bytes in each report,
' calculated from Report Size and Report Count in the report descriptor
'******************************************************************************
 const HID_INPUT_REPORT_BYTES      = 1
 const HID_OUTPUT_REPORT_BYTES     = 1

 const HID_FEATURE_REPORT_BYTES    = 2
'******************************************************************************
' Byte constants
'******************************************************************************
 const NUM_ENDPOINTS               = 2
 const ConfigDescr_wTotalLength    = USB_CONFIG_DESCRIPTOR_LEN + USB_INTERF_DESCRIPTOR_LEN + USB_HID_DESCRIPTOR_LEN + (NUM_ENDPOINTS * USB_ENDP_DESCRIPTOR_LEN)
 const HID_ReportDesc_len          = 47

 const Low_HID_ReportDesc_len      = HID_ReportDesc_len
 const High_HID_ReportDesc_len     = HID_ReportDesc_len >> 8

 const Low_HID_PACKET_SIZE         = HID_PACKET_SIZE
 const High_HID_PACKET_SIZE        = HID_PACKET_SIZE >> 8



'******************************************************************************
' Descriptor Tables
'******************************************************************************
 const DescTables as byte[USB_DEVICE_DESCRIPTOR_ALL_LEN*2] = (

' Device Descriptor
    USB_DEVICE_DESCRIPTOR_LEN, 0,           ' bLength               - Length of Device descriptor (always 0x12)
    USB_DEVICE_DESCRIPTOR_TYPE, 0,          ' bDescriptorType       - 1 = DEVICE descriptor
    0x00, 0,                                ' bcdUSB                - USB revision 2.00 (low byte)
    0x02, 0,                                '                                           (high byte)
    0x00, 0,                                ' bDeviceClass          - Zero means each interface operates independently (class code in the interface descriptor)
    0x00, 0,                                ' bDeviceSubClass
    0x00, 0,                                ' bDeviceProtocol
    EP0_PACKET_SIZE, 0,                     ' bMaxPacketSize0       - maximum size of a data packet for a control transfer over EP0
    0x34, 0,                                ' idVendor              - Vendor  ID (low byte)
    0x12, 0,                                '                                    (high byte)
    0x01, 0,                                ' idProduct             - Product ID (low byte)
    0x00, 0,                                '                                    (high byte)
    0x01, 0,                                ' bcdDevice             - ( low byte)
    0x00, 0,                                '                         (high byte)
    0x01, 0,                                ' iManufacturer         - String1
    0x02, 0,                                ' iProduct              - String2
    0x00, 0,                                ' iSerialNumber         - ( None )
    0x01, 0,                                ' bNumConfigurations    - 1

' Configuration Descriptor
    USB_CONFIG_DESCRIPTOR_LEN, 0,           ' bLength               - Length of Configuration descriptor (always 0x09)
    USB_CONFIG_DESCRIPTOR_TYPE, 0,          ' bDescriptorType       - 2 = CONFIGURATION descriptor
    ConfigDescr_wTotalLength, 0,            ' wTotalLength          - Total length of this config. descriptor plus the interface and endpoint descriptors that are part of the configuration.
    0x00, 0,                                '                         ( high byte)
    0x01, 0,                                ' bNumInterfaces        - Number of interfaces
    0x01, 0,                                ' bConfigurationValue   - Configuration Value
    0x00, 0,                                ' iConfiguration        - String Index for this configuration ( None )
    0xA0, 0,                                ' bmAttributes          - attributes - "Bus powered" and "Remote wakeup"
    50, 0,                                  ' MaxPower              - bus-powered draws 50*2 mA from the bus.

' Interface Descriptor
    USB_INTERF_DESCRIPTOR_LEN, 0,           ' bLength               - Length of Interface descriptor (always 0x09)
    USB_INTERFACE_DESCRIPTOR_TYPE, 0,       ' bDescriptorType       - 4 = INTERFACE descriptor
    0x00, 0,                                ' bInterfaceNumber      - Number of interface, 0 based array
    0x00, 0,                                ' bAlternateSetting     - Alternate setting
    NUM_ENDPOINTS, 0,                       ' bNumEndPoints         - Number of endpoints used in this interface
    0x03, 0,                                ' bInterfaceClass       - assigned by the USB
    0x00, 0,                                ' bInterfaceSubClass    - Not A boot device
    0x00, 0,                                ' bInterfaceProtocol    - none
    0x00, 0,                                ' iInterface            - Index to string descriptor that describes this interface ( None )

' HID Descriptor
    USB_HID_DESCRIPTOR_LEN, 0,              ' bLength               - Length of HID descriptor (always 0x09)
    USB_HID_DESCRIPTOR_TYPE, 0,             ' bDescriptorType       - 0x21 = HID descriptor
    0x01, 0,                                ' HID class release number (1.01)
    0x01, 0,
    0x00, 0,                                ' Localized country code (none)
    0x01, 0,                                ' # of HID class descriptor to follow (1)
    0x22, 0,                                ' Report descriptor type (HID)
    Low_HID_ReportDesc_len, 0,
    High_HID_ReportDesc_len, 0,

' EP1_RX Descriptor
    USB_ENDP_DESCRIPTOR_LEN, 0,             ' bLength               - length of descriptor (always 0x07)
    USB_ENDPOINT_DESCRIPTOR_TYPE, 0,        ' bDescriptorType       - 5 = ENDPOINT descriptor
    0x81, 0,                                ' bEndpointAddress      - In, EP1
    USB_ENDPOINT_TYPE_INTERRUPT, 0,         ' bmAttributes          - Endpoint Type - Interrupt
    Low_HID_PACKET_SIZE, 0,                 ' wMaxPacketSize        - max packet size - low order byte
    High_HID_PACKET_SIZE, 0,                '                       - max packet size - high order byte
    1, 0,                                  ' bInterval             - polling interval (1 ms)

' EP1_TX Descriptor
    USB_ENDP_DESCRIPTOR_LEN, 0,             ' bLength               - length of descriptor (always 0x07)
    USB_ENDPOINT_DESCRIPTOR_TYPE, 0,        ' bDescriptorType       - 5 = ENDPOINT descriptor
    0x01, 0,                                ' bEndpointAddress      - Out, EP1
    USB_ENDPOINT_TYPE_INTERRUPT, 0,         ' bmAttributes          - Endpoint Type - Interrupt
    Low_HID_PACKET_SIZE, 0,                 ' wMaxPacketSize        - max packet size - low order byte
    High_HID_PACKET_SIZE, 0,                '                       - max packet size - high order byte
    1, 0,                                  ' bInterval             - polling interval (1 ms)

' HID_Report Descriptor
    0x06, 0,                                ' USAGE_PAGE (Vendor Defined)
    0xA0, 0,
    0xFF, 0,
    0x09, 0,                                ' USAGE ID (Vendor Usage 1)
    0x01, 0,
    0xA1, 0,                                ' COLLECTION (Application)
    0x01, 0,
'  The Input report
    0x09, 0,                                ' USAGE ID - Vendor defined
    0x03, 0,
    0x15, 0,                                '   LOGICAL_MINIMUM (0)
    0x00, 0,
    0x26, 0,                                '   LOGICAL_MAXIMUM (255)
    0x00, 0,
    0xFF, 0,
    0x75, 0,                                '   REPORT_SIZE (8)
    0x08, 0,
    0x95, 0,                                '   REPORT_COUNT (2)
    HID_INPUT_REPORT_BYTES, 0,
    0x81, 0,                                '   INPUT (Data,Var,Abs)
    0x02, 0,
'  The Output report
    0x09, 0,                                ' USAGE ID - Vendor defined
    0x04, 0,
    0x15, 0,                                '   LOGICAL_MINIMUM (0)
    0x00, 0,
    0x26, 0,                                '   LOGICAL_MAXIMUM (255)
    0x00, 0,
    0xFF, 0,
    0x75, 0,                                '   REPORT_SIZE (8)
    0x08, 0,
    0x95, 0,                                '   REPORT_COUNT (2)
    HID_OUTPUT_REPORT_BYTES, 0,
    0x91, 0,                                '   OUTPUT (Data,Var,Abs)
    0x02, 0,
'  The Feature report
    0x09, 0,                                ' USAGE ID - Vendor defined
    0x05, 0,
    0x15, 0,                                '   LOGICAL_MINIMUM (0)
    0x00, 0,
    0x26, 0,                                '   LOGICAL_MAXIMUM (255)
    0x00, 0,
    0xFF, 0,
    0x75, 0,                                '   REPORT_SIZE (8)
    0x08, 0,
    0x95, 0,                                '   REPORT_COUNT (2)
    HID_FEATURE_REPORT_BYTES, 0,
    0xB1, 0,                                '   FEATURE (Data,Var,Abs)
    0x02, 0,
'  End Collection
    0xC0, 0                                 ' END_COLLECTION
)
'******************************************************************************
 const LangIDDescr as byte[8] = (
    0x04, 0,
    USB_STRING_DESCRIPTOR_TYPE, 0,
    0x09, 0,                                ' LangID (0x0409) - Low
    0x04, 0                                 '                 - High
)
'******************************************************************************
 const ManufacturerDescr as byte[68] = (
    34, 0,
    USB_STRING_DESCRIPTOR_TYPE, 0,
    "m", 0, 0, 0,
    "i", 0, 0, 0,
    "k", 0, 0, 0,
    "r", 0, 0, 0,
    "o", 0, 0, 0,
    "E", 0, 0, 0,
    "l", 0, 0, 0,
    "e", 0, 0, 0,
    "k", 0, 0, 0,
    "t", 0, 0, 0,
    "r", 0, 0, 0,
    "o", 0, 0, 0,
    "n", 0, 0, 0,
    "i", 0, 0, 0,
    "k", 0, 0, 0,
    "a", 0, 0, 0
)
'******************************************************************************
 const ProductDescr as byte[48] = (
    24, 0,
    USB_STRING_DESCRIPTOR_TYPE, 0,
    "H", 0, 0, 0,
    "I", 0, 0, 0,
    "D", 0, 0, 0,
    " ", 0, 0, 0,
    "L", 0, 0, 0,
    "i", 0, 0, 0,
    "b", 0, 0, 0,
    "r", 0, 0, 0,
    "a", 0, 0, 0,
    "r", 0, 0, 0,
    "y", 0, 0, 0
)
'******************************************************************************
 const StrUnknownDescr as byte[4] = (
    2, 0,
    USB_STRING_DESCRIPTOR_TYPE, 0
)
'******************************************************************************







'******************************************************************************
' Initialization Function
'******************************************************************************
implements
sub procedure InitUSBdsc
dim dummy as byte  volatile register

dummy = NUM_ENDPOINTS
dummy = ConfigDescr_wTotalLength
dummy = HID_ReportDesc_len
dummy = Low_HID_ReportDesc_len
dummy = High_HID_ReportDesc_len
dummy = Low_HID_PACKET_SIZE
dummy = High_HID_PACKET_SIZE
dummy = HID_INPUT_REPORT_BYTES
dummy = HID_OUTPUT_REPORT_BYTES
dummy = HID_FEATURE_REPORT_BYTES
'******************************************************************************
' Byte constants
'******************************************************************************
dummy = NUM_ENDPOINTS
dummy = ConfigDescr_wTotalLength
dummy = HID_ReportDesc_len
dummy = Low_HID_ReportDesc_len
dummy = High_HID_ReportDesc_len
dummy = Low_HID_PACKET_SIZE
dummy = High_HID_PACKET_SIZE
dummy = @DescTables
dummy = @LangIDDescr
dummy = @ManufacturerDescr
dummy = @LangIDDescr
dummy = @ProductDescr
dummy = @StrUnknownDescr
end sub
end.


Y pues el circuito en el que estoy intentando simular es el siguiente:




y la verdad de todo esto no me funciona nada... el proteus ni se da por enterado cuando se simula la conexion de este micro al pc...

lo que me desmoraliza es que en los ejemplos del proteus hay varios que usan el usb y esos funcionan d mil maravillas... y ya estoy es como desesperado pk no doy con el error y llevo como 3 dias estankado en lo mismo... asi k ps si alguien pudiera hecharme una mano le estaria bastante agradecido.

ahh y ps no se uno nunca sabe si alguien desea los archivos aki los dejo para la descarga

http://rapidshare.com/files/198259931/P18F4550.rar.html
No cometas el crimen varon si no vas a cumplir la condena

Desconectado ASTROCAR

  • PIC24F
  • *****
  • Mensajes: 666
Re: Proyecto PicUSB
« Respuesta #451 en: 15 de Febrero de 2009, 08:22:35 »
Hermano ekud  veo que posteastes lo mismo dos veces eso lo que hace es recargar el foro lo mejor hubiera sido poner un link para que leyeran tu inquietud asi todos esten claro de tu problema espero no te moleste por eso pero es para mantener el foro y asi tener el mejor provecho del mismo.

Atten.
Alexander Santana.
Barcelona-Venezuela.

http://www.todopic.com.ar/foros/index.php?topic=22750.0
EL APRENDER ES NADA; MEJOR ES COMPARTIR EL APRENDIZAJE

Desconectado ekud

  • PIC16
  • ***
  • Mensajes: 120
    • mi pag... bueno no es mia pero ahi estoy
Re: Proyecto PicUSB
« Respuesta #452 en: 15 de Febrero de 2009, 13:17:01 »
jeje...

si ke pena lo siento... es que estoy un poco ensimismado con este tema...  :oops:
No cometas el crimen varon si no vas a cumplir la condena

Desconectado adrianjpc

  • PIC10
  • *
  • Mensajes: 10
    • uElectronika
Re: Proyecto PicUSB
« Respuesta #453 en: 19 de Febrero de 2009, 06:28:22 »
hola!
eh estado trabajando con labview pero no puedo establecer la comunicacion de labiew a usb
me podrias ayudar como hacerlo. me gustaria saber el codigo de labview que mencionas
se agradece tu ayuda

Desconectado LordLafebre

  • Moderador Global
  • DsPIC30
  • *****
  • Mensajes: 3529
    • Micros & micros
Re: Proyecto PicUSB
« Respuesta #454 en: 19 de Febrero de 2009, 13:47:11 »
Hola:

Revisa este mismo hilo, todo completo, J1M publicó un mensaje sobre algo de esto:

http://www.todopic.com.ar/foros/index.php?topic=2260.msg139211#msg139211

lee y usa el buscador y puedes tener muchas respuestas antes de preguntar.  :wink:

Desconectado pachueko

  • PIC10
  • *
  • Mensajes: 1
Re: Proyecto PicUSB
« Respuesta #455 en: 03 de Marzo de 2009, 21:08:40 »
 Saludos!! comom la mayoría de los que llegamos a este foro soy nuevo en él y aun mas nuevo con los PICs y el USB, tengo un programa en C# sencillo para iniciar, también he desarrollado programas en CCS para los PICs, todo esta bien y la PC no me registra ningun error al correr la aplicación C# sin embargo mi problema es en la identificación del dispositivo USB, le selecciono los controladores que he encontrado y no funciona muy bien.

Hace unas horas pude hacer la comunicación y todo salio bien, sin embargo en estos momentos no me reconoce el dispositivo, no me pide los controladores ni nada de eso, me meto en el panel de control para ver las propiedades del sistema y aparece mi dispositivo 18Fxx5x (uso un f4550), con el unico detalle que al lado del icono me aparece un signo de admiración rodeado de un circulo amarillo, no se que signifique eso, pero estoy seguro que es lo que me impide seguir con mi proyecto.

Espero poder solucionar el problema con ayuda de alguno de ustedes, de antemano muchas gracias, saludos!

Desconectado mariano_pic

  • PIC18
  • ****
  • Mensajes: 499
    • Software Electronica Microncontroladores
Re: Proyecto PicUSB
« Respuesta #456 en: 04 de Marzo de 2009, 02:05:53 »

[cambio la pregunta]  Hay alguna forma de implementar comunicacion hid, transmitiendo mas de dos bytes usando ccs, es posible o no es posible, que hay que hacer?
« Última modificación: 05 de Marzo de 2009, 12:12:43 por mariano_pic »

Desconectado jeremylf

  • Colaborador
  • PIC24H
  • *****
  • Mensajes: 1341
Re: Proyecto PicUSB
« Respuesta #457 en: 11 de Marzo de 2009, 16:22:23 »
pachueko, desisntalalo dandole en click direrecho a tu dispostivo en l administrador de dispositivos o ponlo a otro puerto usb o a otro computadora mejor...

mariano_pic, nunca use HID en ccs asi que nose a lo q te refieres, pero en la pag de Redpic hay info sobre esto.


Un saludo.

Desconectado PalitroqueZ

  • Moderadores
  • DsPIC33
  • *****
  • Mensajes: 5490
    • Electrónica Didacta
Re: Proyecto PicUSB
« Respuesta #458 en: 11 de Marzo de 2009, 17:01:27 »

[cambio la pregunta]  Hay alguna forma de implementar comunicacion hid, transmitiendo mas de dos bytes usando ccs, es posible o no es posible, que hay que hacer?

si es posible, mira el proyecto de semifluid en la sección de Source and Firmware

el autor usó una configuración de 8 bytes en usb_desc_hid 8-byte.h

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

Desconectado mariano_pic

  • PIC18
  • ****
  • Mensajes: 499
    • Software Electronica Microncontroladores
Re: Proyecto PicUSB
« Respuesta #459 en: 12 de Marzo de 2009, 15:16:01 »
Gracias palitrokez, esa seccion donde esta, en la pagina de ccs, en el foro o en la carpeta de instalacion de ccs? :mrgreen:

Desconectado RedPic

  • Administrador
  • DsPIC33
  • *******
  • Mensajes: 5552
    • Picmania by Redraven
Re: Proyecto PicUSB
« Respuesta #460 en: 12 de Marzo de 2009, 17:26:43 »
Contra la estupidez los propios dioses luchan en vano. Schiller
Mi Güeb : Picmania

Desconectado mariano_pic

  • PIC18
  • ****
  • Mensajes: 499
    • Software Electronica Microncontroladores
Re: Proyecto PicUSB
« Respuesta #461 en: 13 de Marzo de 2009, 13:09:28 »

  EXCELENTE!!!!

 

Desconectado washi_w_z_r

  • PIC10
  • *
  • Mensajes: 20
Re: Proyecto PicUSB
« Respuesta #462 en: 27 de Abril de 2009, 23:45:24 »
Hola amigos: Alguna idea por que cuando asigno mas de un endpoint la PC ya no reconoce mi dispositivo aca el cod que modifique en picusb.h
Código: C#
  1. #IFNDEF __USB_DESCRIPTORS__
  2. #DEFINE __USB_DESCRIPTORS__
  3.  
  4. #include <usb.h>
  5.  
  6. //////////////////////////////////////////////////////////////////
  7. ///
  8. ///   start config descriptor
  9. ///   right now we only support one configuration descriptor.
  10. ///   the config, interface, class, and endpoint goes into this array.
  11. ///
  12. //////////////////////////////////////////////////////////////////
  13.  
  14.    #DEFINE USB_TOTAL_CONFIG_LEN      88 //config+interface+class+endpoint
  15.  
  16.    //configuration descriptor
  17.    char const USB_CONFIG_DESC[] = {
  18.    //config_descriptor for config index 1
  19.          USB_DESC_CONFIG_LEN,     //length of descriptor size
  20.          USB_DESC_CONFIG_TYPE,         //constant CONFIGURATION (0x02)
  21.          USB_TOTAL_CONFIG_LEN,0,  //size of all data returned for this config
  22.          1,      //number of interfaces this device supports
  23.          0x01,                //identifier for this configuration.  (IF we had more than one configurations)
  24.          0x00,                //index of string descriptor for this configuration
  25.          0xC0,                //bit 6=1 if self powered, bit 5=1 if supports remote wakeup (we don't), bits 0-4 reserved and bit7=1
  26.          0x32,                //maximum bus power required (maximum milliamperes/2)  (0x32 = 100mA)
  27.  
  28.    //interface descriptor 0 alt 0
  29.          USB_DESC_INTERFACE_LEN,  //length of descriptor
  30.          USB_DESC_INTERFACE_TYPE,      //constant INTERFACE (0x04)
  31.          0x00,                //number defining this interface (IF we had more than one interface)
  32.          0x00,                //alternate setting
  33.          6,       //number of endpoints, not counting endpoint 0.
  34.          0xFF,                //class code, FF = vendor defined
  35.          0xFF,                //subclass code, FF = vendor
  36.          0xFF,                //protocol code, FF = vendor
  37.          0x00,                //index of string descriptor for interface
  38.  
  39.    //endpoint descriptor
  40.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  41.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  42.          0x81,              //endpoint number and direction (0x81 = EP1 IN)
  43.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  44.          USB_EP1_TX_SIZE,0x00,         //maximum packet size supported
  45.          0x01,              //polling interval in ms. (for interrupt transfers ONLY)
  46.  
  47.    //endpoint descriptor
  48.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  49.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  50.          0x01,              //endpoint number and direction (0x01 = EP1 OUT)
  51.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  52.          USB_EP1_RX_SIZE,0x00,         //maximum packet size supported
  53.          0x01,              //polling interval in ms. (for interrupt transfers ONLY)
  54. //*******************************************************************//
  55.     //endpoint descriptor
  56.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  57.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  58.          0x82,              //endpoint number and direction (0x82 = EP1 IN)
  59.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  60.          USB_EP2_TX_SIZE,0x00,         //maximum packet size supported
  61.          0x01,              //polling interval in ms. (for interrupt transfers ONLY)
  62.  
  63.    //endpoint descriptor
  64.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  65.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  66.          0x02,              //endpoint number and direction (0x02 = EP1 OUT)
  67.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  68.          USB_EP2_RX_SIZE,0x00,         //maximum packet size supported
  69.          0x01,
  70. //46///////////////////////////////////////////////////////////////
  71. //**********************************************************************//
  72.     //endpoint descriptor
  73.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  74.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  75.          0x83,              //endpoint number and direction (0x83 = EP1 IN)
  76.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  77.          USB_EP3_TX_SIZE,0x00,         //maximum packet size supported
  78.          0x01,              //polling interval in ms. (for interrupt transfers ONLY)
  79.  
  80.    //endpoint descriptor
  81.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  82.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  83.          0x03,              //endpoint number and direction (0x03 = EP1 OUT)
  84.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  85.          USB_EP3_RX_SIZE,0x00,         //maximum packet size supported
  86.          0x01,
  87.  //*******************************58*************************************//
  88.     //endpoint descriptor
  89.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  90.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  91.          0x84,              //endpoint number and direction (0x84 = EP1 IN)
  92.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  93.          USB_EP4_TX_SIZE,0x00,         //maximum packet size supported
  94.          0x01,              //polling interval in ms. (for interrupt transfers ONLY)
  95.  
  96.    //endpoint descriptor
  97.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  98.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  99.          0x04,              //endpoint number and direction (0x04 = EP1 OUT)
  100.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  101.          USB_EP4_RX_SIZE,0x00,         //maximum packet size supported
  102.          0x01,
  103.  //*********************************70************************************//
  104.     //endpoint descriptor
  105.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  106.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  107.          0x85,              //endpoint number and direction (0x85 = EP1 IN)
  108.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  109.          USB_EP5_TX_SIZE,0x00,         //maximum packet size supported
  110.          0x01,              //polling interval in ms. (for interrupt transfers ONLY)
  111.  
  112.    //endpoint descriptor
  113.          USB_DESC_ENDPOINT_LEN, //length of descriptor
  114.          USB_DESC_ENDPOINT_TYPE,     //constant ENDPOINT (0x05)
  115.          0x05,              //endpoint number and direction (0x05 = EP1 OUT)
  116.          0x02,              //transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
  117.          USB_EP5_RX_SIZE,0x00,         //maximum packet size supported
  118.          0x01,
  119.    };
  120.  
  121.    //****** BEGIN CONFIG DESCRIPTOR LOOKUP TABLES ********
  122.    //since we can't make pointers to constants in certain pic16s, this is an offset table to find
  123.    //  a specific descriptor in the above table.
  124.  
  125.    //NOTE: DO TO A LIMITATION OF THE CCS CODE, ALL HID INTERFACES MUST START AT 0 AND BE SEQUENTIAL
  126.    //      FOR EXAMPLE, IF YOU HAVE 2 HID INTERFACES THEY MUST BE INTERFACE 0 AND INTERFACE 1
  127.    #define USB_NUM_HID_INTERFACES   0
  128.  
  129.    //the maximum number of interfaces seen on any config
  130.    //for example, if config 1 has 1 interface and config 2 has 2 interfaces you must define this as 2
  131.    #define USB_MAX_NUM_INTERFACES   1
  132.  
  133.    //define how many interfaces there are per config.  [0] is the first config, etc.
  134.    const char USB_NUM_INTERFACES[USB_NUM_CONFIGURATIONS]={1};
  135.  
  136.    #if (sizeof(USB_CONFIG_DESC) != USB_TOTAL_CONFIG_LEN)
  137.       #error USB_TOTAL_CONFIG_LEN not defined correctly
  138.    #endif
  139.  
  140.  
  141. //////////////////////////////////////////////////////////////////
  142. ///
  143. ///   start device descriptors
  144. ///
  145. //////////////////////////////////////////////////////////////////
  146.  
  147.    //device descriptor
  148.    char const USB_DEVICE_DESC[] ={
  149.          USB_DESC_DEVICE_LEN,          //the length of this report
  150.          0x01,                //constant DEVICE (0x01)
  151.          0x10,0x01,           //usb version in bcd
  152.          0x00,                //class code (if 0, interface defines class.  FF is vendor defined)
  153.          0x00,                //subclass code
  154.          0x00,                //protocol code
  155.          USB_MAX_EP0_PACKET_LENGTH,   //max packet size for endpoint 0. (SLOW SPEED SPECIFIES 8)
  156.          0xD8,0x04,           //vendor id (0x04D8 is Microchip)
  157.          0x09,0x00,           //product id, me gusta el 11 ;)
  158.          0x01,0x00,           //device release number
  159.          0x01,                //index of string description of manufacturer. therefore we point to string_1 array (see below)
  160.          0x02,                //index of string descriptor of the product
  161.          0x00,                //index of string descriptor of serial number
  162.          USB_NUM_CONFIGURATIONS   //number of possible configurations
  163.    };
  164.  
  165.  
  166. //////////////////////////////////////////////////////////////////
  167. ///
  168. ///   start string descriptors
  169. ///   String 0 is a special language string, and must be defined.  People in U.S.A. can leave this alone.
  170. ///
  171. ///   You must define the length else get_next_string_character() will not see the string
  172. ///   Current code only supports 10 strings (0 thru 9)
  173. ///
  174. //////////////////////////////////////////////////////////////////
  175.  
  176. //the offset of the starting location of each string.
  177. //offset[0] is the start of string 0, offset[1] is the start of string 1, etc.
  178. const char USB_STRING_DESC_OFFSET[]={0,4,12};
  179.  
  180. #define USB_STRING_DESC_COUNT sizeof(USB_STRING_DESC_OFFSET)
  181.  
  182. char const USB_STRING_DESC[]={
  183.    //string 0
  184.          4, //length of string index
  185.          USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
  186.          0x09,0x04,   //Microsoft Defined for US-English
  187.    //string 1 --> la compañia del producto ???
  188.          8, //length of string index
  189.          USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
  190.          'J',0,
  191.          '1',0,
  192.          'M',0,
  193.    //string 2 --> nombre del dispositivo
  194.          22, //length of string index
  195.          USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
  196.          'J',0,
  197.          '1',0,
  198.          'M',0,
  199.          ' ',0,
  200.          'P',0,
  201.          'i',0,
  202.          'c',0,
  203.          'U',0,
  204.          'S',0,
  205.          'B',0
  206. };
  207.  
  208.  
  209. #ENDIF
Cuando envio datos hacia la pc con un solo endpoint no tengo problemas, pero al configurar estos 5 endpoint , ni el driver instala obviamente no reconoce al dispositivo

Desconectado umov

  • PIC10
  • *
  • Mensajes: 1
Re: Proyecto PicUSB
« Respuesta #463 en: 11 de Mayo de 2009, 12:51:27 »
HOla amigos de TodoPIC, soy nuevo en este foro,

actualmente estoy desarrollando una aplicacion para comunicar informacion del PIC al PC y viceverza via USB, pues me he orientado gracias a un articulo que encontre por alli (internet) en donde se basaban en el trabajo que ustedes vienen realizando en este foro.

en mi proyecto inicialmente partimos con lo basico que en él estaba implementado (encender y apagar led´s con un PIC18f4550 desde una programa elaborado en java, ademas hacer la peticion de una respuesta de la version del firmware implementada en el PIC ).

ahora nosotros ademas hemos implementado en el proyecto la recepcion de datos por medio del Conversor Analogo Digital del PIC, estos datos son enviados al programa (en java) en el PC, ademas estamos manejando tres tipos de interrupciones (dos utilizando RTCC y timer1, y otra que es interrupcion externa en el pin B0).

nuestra inquietud sobre este proyecto esta en que la velocidad con la que se ejecutan los eventos (apagar y encender led) aveeces funciona y aveces no funciona, ademas cuando funciona tarda un tiempo no deseado en responder (aveces 3, 5 y hastya 10seg), cosa que no sucedia inicialmente.

estamos curiosos de saber lo que sucede, nos hemos preguntado si tal vez sera alguna opcion relacionada con la transferencia de datos via USB.

hemos incluso deshabilitado el codigo que nosotros hemos implementado adicional y funciona igual.

acontinuacion les dejamos nuestro codigo y el del archivo de cabecera que estamos utilizando:

CODIGO DEL ARCHIVO CABECERA: HEADER.H

#IFNDEF __USB_DESCRIPTORS__
#DEFINE __USB_DESCRIPTORS__

#include <usb.h>

////////////////////////////////////////////////////////////////////////////////
///
/// start config descriptor
/// right now we only support one configuration descriptor.
/// the config, interface, class, and endpoint goes into this array.
///
////////////////////////////////////////////////////////////////////////////////

#DEFINE USB_TOTAL_CONFIG_LEN 32 // config+interface+class+endpoint

// configuration descriptor
char const USB_CONFIG_DESC[] = {

// config_descriptor for config index 1
USB_DESC_CONFIG_LEN,    // length of descriptor size
USB_DESC_CONFIG_TYPE,   // constant CONFIGURATION (0x02)
USB_TOTAL_CONFIG_LEN,0, // size of all data returned for this config
1,                      // number of interfaces this device supports
0x01,                   // identifier for this configuration. (IF we had more than one configurations)
0x00,                   // index of string descriptor for this configuration
0xC0,                   // bit 6=1 if self powered, bit 5=1 if supports remote wakeup (we don't), bits 0-4 reserved and bit7=1
0x32,                   // maximum bus power required (maximum milliamperes/2) (0x32 = 100mA)

// interface descriptor 0 alt 0
USB_DESC_INTERFACE_LEN,    // length of descriptor
USB_DESC_INTERFACE_TYPE,   // constant INTERFACE (0x04)
0x00,                      // number defining this interface (IF we had more than one interface)
0x00,                      // alternate setting
2,                         // number of endpoints, not counting endpoint 0.
0xFF,                      // class code, FF = vendor defined
0xFF,                      // subclass code, FF = vendor
0xFF,                      // protocol code, FF = vendor
0x00,                      // index of string descriptor for interface

// endpoint descriptor
USB_DESC_ENDPOINT_LEN,  // length of descriptor
USB_DESC_ENDPOINT_TYPE, // constant ENDPOINT (0x05)
0x81,                   // endpoint number and direction (0x81 = EP1 IN)
0x02,                   // transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
USB_EP1_TX_SIZE,0x00,   // maximum packet size supported
0x01,                   // polling interval in ms. (for interrupt transfers ONLY)

// endpoint descriptor
USB_DESC_ENDPOINT_LEN,  // length of descriptor
USB_DESC_ENDPOINT_TYPE, // constant ENDPOINT (0x05)
0x01,                   // endpoint number and direction (0x01 = EP1 OUT)
0x02,                   // transfer type supported (0 is control, 1 is iso, 2 is bulk, 3 is interrupt)
USB_EP1_RX_SIZE,0x00,   // maximum packet size supported
0x01,                   // polling interval in ms. (for interrupt transfers ONLY)

};
////////////////////////////////////////////////////////////////////////////////
//******************* BEGIN CONFIG DESCRIPTOR LOOKUP TABLES ********************
// since we can't make pointers to constants in certain pic16s, this is an offset table to find
// a specific descriptor in the above table.
////////////////////////////////////////////////////////////////////////////////
// NOTE: DO TO A LIMITATION OF THE CCS CODE, ALL HID INTERFACES MUST START AT 0 AND BE SEQUENTIAL
// FOR EXAMPLE, IF YOU HAVE 2 HID INTERFACES THEY MUST BE INTERFACE 0 AND INTERFACE 1
#define USB_NUM_HID_INTERFACES 0
//
////////////////////////////////////////////////////////////////////////////////
// the maximum number of interfaces seen on any config for example, if config 1
// has 1 interface and config 2 has 2 interfaces you must define this as 2
#define USB_MAX_NUM_INTERFACES 1
//
////////////////////////////////////////////////////////////////////////////////
//define how many interfaces there are per config.
  • is the first config, etc.

const char USB_NUM_INTERFACES[USB_NUM_CONFIGURATIONS]={1};

#if (sizeof(USB_CONFIG_DESC) != USB_TOTAL_CONFIG_LEN)
#error USB_TOTAL_CONFIG_LEN not defined correctly
#endif

////////////////////////////////////////////////////////////////////////////////
///
/// start device descriptors
///
////////////////////////////////////////////////////////////////////////////////
//
//device descriptor
char const USB_DEVICE_DESC[] ={
USB_DESC_DEVICE_LEN,       //the length of this report
0x01,                      //constant DEVICE (0x01)
0x10,0x01,                 //usb version in bcd
0x00,                      //class code (if 0, interface defines class. FF is vendor defined)
0x00,                      //subclass code
0x00,                      //protocol code
USB_MAX_EP0_PACKET_LENGTH, //max packet size for endpoint 0. (SLOW SPEED SPECIFIES 8)
0xD8,0x04,                 //vendor id (0x04D8 is Microchip)
0x0B,0x00,                 //product id
0x01,0x00,                 //device release number
0x01,                      //index of string description of manufacturer. therefore we point to string_1 array (see below)
0x02,                      //index of string descriptor of the product
0x00,                      //index of string descriptor of serial number
USB_NUM_CONFIGURATIONS     //number of possible configurations
};
//
////////////////////////////////////////////////////////////////////////////////
///
/// start string descriptors
/// String 0 is a special language string, and must be defined. People in U.S.A.
/// can leave this alone.
/// You must define the length else get_next_string_character() will not see the string
/// Current code only supports 10 strings (0 thru 9)
///
////////////////////////////////////////////////////////////////////////////////
//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.
//
const char USB_STRING_DESC_OFFSET[]={0,4,20};

#define USB_STRING_DESC_COUNT sizeof(USB_STRING_DESC_OFFSET)

char const USB_STRING_DESC[]={
                        //string 0 Codificacion de la tabla ???
4,                      //length of string index
USB_DESC_STRING_TYPE,   //descriptor type 0x03 (STRING)
0x09,0x04,              //Microsoft Defined for US-English
                        //string 1 --> la compañia del producto ???
16,                     //length of string index
USB_DESC_STRING_TYPE,   //descriptor type 0x03 (STRING)
'j',0,
'P',0,
'i',0,
'c',0,
'U',0,
's',0,
'b',0,
                        //string 2 --> nombre del dispositivo
18,                     //length of string index
USB_DESC_STRING_TYPE,   //descriptor type 0x03 (STRING)
'J',0,
'E',0,
'C',0,
'R',0,
' ',0,
'U',0,
'S',0,
'B',0,
};
#ENDIF   
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


AHORA EL CODIGO CORRESPONDIENTE AL PROGRAMA PRINCIPAL
FIRMWARE 18F4550.C

#include <18F4550.h>                                                    // Declaracion del microcontrolador a utilizar
//#device *=8
#device ADC=16
#fuses HSPLL,NOMCLR,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL1,CPUDIV1,VREGEN   // Configuracion del microcontrolador
// Fuses utilizados:
/**
HSPLL: utilizamos un cristal HS de alta velocidad, en conjunto con el PLL para generar los 48Mhz.
NOMCLR: Utilizamos reset por software, y dejamos el pin 1 del micro como entrada/salida digital.
NOWDT: No utilizamos el perro guardían.
NOPROTECT: Desactivamos la protección de código.
NOLVP: Desactivamos la programación a bajo voltaje.
NODEBUG: No entramos al modo debug.
USBDIV: signfica que el clock del usb se tomará del PLL/2 = 96Mhz/2 = 48Mhz.
PLL5: significa que el PLL prescaler dividirá en 5 la frecuencia del cristal. para HS = 20Mhz/5 = 4Mhz.
CPUDIV1: El PLL postscaler decide la división en 2 de la frecuencia de salida del PLL de 96MHZ, si queremos 48MHZ, lo dejamos como está.
VREGEN: habilita el regulador de 3.3 volts que usa el módulo USB
*/
#use delay(clock=48000000)                                              // Configuracion del relog a utilizar
//#define use_portb_lcd TRUE                                              // definir portb lcd
//#include <lcd.c>                                                        // Se declara periferico a utilizar -> LCD.
//#use rs232(baud=19200, xmit=PIN_C6,rcv=PIN_C7,stream=HOSTPC)             // Se declara periferico a utilizar -> rs232.
///////////////////////////////////////////////////////////////////////////////////////////////////
// CCS Library dynamic defines. For dynamic configuration of the CCS Library
// for your application several defines need to be made. See the comments
// at usb.h for more information
///////////////////////////////////////////////////////////////////////////////////////////////////
#define INTS_PER_SECOND 30                                              // (4000000/(2*256*256))
#define USB_HID_DEVICE FALSE              // deshabilitamos el uso de las directivas HID
#define USB_EP1_TX_ENABLE USB_ENABLE_BULK // turn on EP1(EndPoint1) for IN bulk/interrupt transfers (activacion de traferencia masiva en USB configurando el EndPoint 1 de transmision)
#define USB_EP1_RX_ENABLE USB_ENABLE_BULK // turn on EP1(EndPoint1) for OUT bulk/interrupt transfers (activacion de traferencia masiva en USB configurando el EndPoint 1 de recepcion)
#define USB_EP1_TX_SIZE 32                // size to allocate for the tx endpoint 1 buffer (tamaño del buffer de transferencia en la transmision entre 1 y 32 bytes para USB 2.0)
#define USB_EP1_RX_SIZE 32                // size to allocate for the rx endpoint 1 buffer (tamaño del buffer de transferencia en la recepcion entre 1 y 32 bytes para USB 2.0)
///////////////////////////////////////////////////////////////////////////////////////////////////
// Include the CCS USB Libraries. See the comments at the top of these
// files for more information
////////////////////////////////////////////////////////////////////////////////
#include <pic18_usb.h>  // Microchip PIC18Fxx5x Hardware layer for CCS's PIC USB driver
#include <header.h>     // Configuración del USB y los descriptores para este dispositivo
#include <usb.c>        // Handles usb setup tokens and get descriptor reports
#include <stdlib.h>
#include <stdio.h>      //
////////////////////////////////////////////////////////////////////////////////
//#define Enciende Output_High
//#define Apaga Output_Low
//#define Conmuta Output_Toggle
#define RecCommand recbuf[0]     //
#define LedParam recbuf[1]
#define COMMAND_TEMPERATURA 1   
#define COMMAND_LEDS 2
#byte PORT_E = 5
#define LedState PORT_E,2
////////////////////////////////////////////////////////////////////////////////
// RAM, RAM, RAM
////////////////////////////////////////////////////////////////////////////////
const int8 Lenbuf = 32;  //32        //Longitud del Buffer de lectura en el puerto USB.
int16 conversion;//,min=0,max=1023; //Se declaran Variable enteras a 16Bits.
float temp;                         //Decalracion de una variable flotante.
char ctemp[5];
int8 recbuf[Lenbuf];
//char cLedParam;
int8 i=0;
int8 LedParam_copy=0;
//int8 sndbuf[Lenbuf];
BYTE int_count;                  // Número de interrupciones que faltan antes que haya transcurrido un segundo
////////////////////////////////////////////////////////////////////////////////
// M A I N
////////////////////////////////////////////////////////////////////////////////
#INT_RTCC
void Led_State()                   //Interrupción utilizada para el manejo del bit de estado.
{
   if(--int_count==0)
   {  output_bit(Pin_E2,!bit_test(LedState)); //Llega aquí cada segundo.
      int_count=INTS_PER_SECOND;
   }
}
#INT_TIMER1
void interrupcion_timer1(){
   i++;
   if (i==40){
      output_d(0x00);
      i=0;
   }
   set_timer1(0);
   set_timer1(3036);
}
#INT_EXT                               //Interrupcion a aplicar cuando se active el sensor de movimiento
void sensor_movimiento_isr(){

   if (LedParam_copy == 0x02){
      output_d(0x00);
      i=0;
   }
   else{
      set_timer1(0);
      setup_timer_1( T1_INTERNAL | T1_DIV_BY_8 );
      output_d(0x01);
      i = 0;
      set_timer1(3036);                            // 256-(15/(4/48000000))
   }
}
/**

#int_ext1                              //Interrupcion a aplicar cuando se active el sensor de humo
void sensor_humo_isr(){
   output_d(LedParam);
   delay_ms(1000);
   output_d(LedParam);
}
*/
//******************************************************************************
ConvenVoltio()
{
   temp=((0.0078125*conversion)-0.5);  //Calculo de la temperatura
   sprintf(ctemp, "%f", temp);         //Convierte un numero de tipo coma flotante a tipo cadena
   //sprintf(cRecCommand, "%u", RecCommand);
   //itoa(LedParam, 10, cLedParam);
   return ctemp;
}
//******************************************************************************
void main(void){
   delay_ms(500);                                        //Retardo de 0.5 seg
   usb_init();                                           //Inicializa el Modulo de Comunicacion USB
   usb_task();                                           //
   usb_wait_for_enumeration();                           //Se situa en un bucle infinito mientras la comunicacion USB es enumerada
   
   set_tris_a(0000001);             //Configuracion del Pin A0 como entrada
   set_tris_b(00001111);            //Configuracion del Pin b0 como entrada
   setup_adc(ADC_CLOCK_DIV_4);   //
   setup_adc_ports(AN0);         //Configuracion del puerto como entrada Analoga
   set_adc_channel(0);           //Seleccion del canal de conversion en este caso el cero
 
   int_count=INTS_PER_SECOND;
   set_timer0(0);
   setup_counters( RTCC_INTERNAL, RTCC_DIV_256 | RTCC_8_BIT );
   
   // 48 mhz clock, no prescaler, set timer 0
   // to overflow in 15seg
   
   enable_interrupts(INT_RTCC);                          //
   enable_interrupts(INT_TIMER1); //
   enable_interrupts(INT_EXT);                           //
   //ext_int_edge (L_TO_H);
   //port_b_pullups(true);
   //enable_interrupts(int_ext1);                          //
   enable_interrupts(GLOBAL);                            //Inabilita las demas interrupciones
   //do
   while(true)
   {
      if(usb_enumerated()){                              //¿El sistema operativo de la PC nos ha reconocidos como conectados y ha enumerado la Comunicacion USB?
         if (usb_kbhit(1)){                              //Verifica si se han recibido datos provenientes del PC
             usb_get_packet(1, recbuf, Lenbuf);          //Toma los dos bytes que llegan y los guarda en recbuf,
                                                         //y luego son guardos en RecCommand y LedParam respectivamente
            if(RecCommand==COMMAND_TEMPERATURA){            //Verifica si el byte 0 (RecCommad) que llega es igual a COMMAND_FIRMWARE
               usb_put_packet(1,ctemp,4,USB_DTS_TOGGLE); //Escribe en el Puerto USB el valor de la temperatura
               //usb_put_packet(1,cLedParam,4,USB_DTS_TOGGLE); //Escribe en el Puerto USB el valor de recbuf               
               //printf("Data leida de USB: %u",LedParam);   //Supuestamente envia el dato leido por el puerto RS232
               //printf("Data leida de USB: %s",cLedParam);   //Supuestamente envia el dato leido por el puerto RS232
               //delay_ms(1000);
               //printf("Data leida de USB: %s",Lenbuf);
            }
          if(RecCommand==COMMAND_LEDS){                //Verifica si el dato que llega es igual a COMMAND_LEDS
            LedParam_copy = LedParam; 
            //output_d(LedParam);                       //Escribe por el puerto D los leds que va a encender
            //printf("Data leida de USB: %u",recbuf);
            //printf("Data leida de USB: %s",Lenbuf);
            } 
         }
      }
      delay_us(10);
      conversion = read_adc();                                          //Lectura del conversor del ADC
      //printf("%Lu",conversion);                                         //Formato de envio del valor de la temperatura por RS232
      //setup_adc( ADC_OFF );
      ConvenVoltio();
      //usb_put_packet(1,temp,5,USB_DTS_TOGGLE);                        //Escribe en el Puerto USB la version del firmware
      //printf(" %1.1f ",temp);                                         //Formato de envio del valor de la temperatura por RS232
      //printf(lcd_putc,"\f  Temperatura:  \n     %1.1f oC    ",temp);  //Impresion del dato en la LCD
      //delay_ms(100);                                                    //Retardo de 1 usegundo
      //usb_token_reset();
   }//while(true);
}

Desconectado headhead

  • PIC10
  • *
  • Mensajes: 1
Re: Proyecto PicUSB
« Respuesta #464 en: 20 de Mayo de 2009, 23:56:15 »
Buenas. Buscando en la red encontre una web que esta en construccion pero promete mucho parece que va a ser una exelente web. En esta pagina encontre un proyecto usb hecho en C# y un 18f2550 programado en ccs. Se trata de un programa con una interfaz grafica muy bien hecha la cual controla un display 7 segmentos por el puerto usb. espero ayude de algo mi aporte :mrgreen: :mrgreen:. aqui esta la pagina www.colpic.co.cc