CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

USB sample code PicUSB
Goto page 1, 2  Next
 
Post new topic   Reply to topic    CCS Forum Index -> Code Library
View previous topic :: View next topic  
Author Message
J1M



Joined: 15 Feb 2005
Posts: 21

View user's profile Send private message Visit poster's website

USB sample code PicUSB
PostPosted: Fri Aug 26, 2005 4:54 pm     Reply with quote

Antes de comenzar querría agradecer a Mat Clayton el valiosísimo aporte de su API para C#, sin la cual estaría aun dándome cabezazos intentando entender porqué no me leía la DLL!! Gracias Mat!
Dedico este proyectillo a todos los usuarios del foro TodoPIC, ese pedazo punto de encuentro para todos los PicManíacos!

PicUSB se ha hecho con la intención de proporcionar un primer empujón para todos aquellos que quieren arrancar con los diseños por USB y que como supongo que a muchos nos ha pasado, no saben por donde engancharlo!

El proyecto en sí es bastante sencillito, pretende mostrar como enviar/recibir datos por USB desde el PIC al PC, he intentado que el programa fuera entendible, por lo que realmente no tiene ninguna utilidad mas que como digo, servir de introducción al mundo del USB.

Está pensado para ser usado sobre la misma plaquita del programador GTP USB (en cualquiera de sus versiones), puesto que el funcionamiento del PicUSB se limita a encender/apagar cada uno de los colores del led bicolor, y a realizar una suma de dos operandos, y no tenía ganas de montarlo todo en una protoboard!, los que aún no tengáis el GTP USB, podréis encontrar el GTP USB Lite aquí:
http://perso.wanadoo.es/j1m/index.htm



El proyecto consta de tres partes:
- Programación de la aplicación para el PIC
- Programación de la aplicación para PC
- Edición del Driver suministrado por Microchip

Para la programación de la aplicación para el PIC se optó por usar el extendido compilador CCS, he utilizado para ello la versión 3.227, el cuál podréis encontrar por los medios habituales ;)
El código de la aplicación lo podéis encontrar en el PicUSB_CCS.zip, así como el .hex para ser programado en el PIC. Tanto el PicUSB.c, como el PicUSB.h está mas o menos documentado en un perfecto Spanglish, ya que el proyecto está basado en el ex_usb_scope.c suministrado por CCS, lo siento por quien no se lleve muy bien con el Inglés, pero hay cosas que no se como traducirlas al Español y me estreso!! Jeje.
Decidí usar el 18F2550 ya que era el que tenía por aquí disponible, pero puede usarse cualquiera de la serie 18Fxx5x que incorporan el USB 2.0.

Para la programación de la aplicación para PC se optó por usar el Visual C# Express 2005, actualmente va por la beta 2 y puede ser descargado gratuitamente de la página de Microsoft, aqui os pongo el link:
http://lab.msdn.microsoft.com/express/vcsharp/default.aspx
He decidido usar este lenguaje ya que no conocía ningún lenguaje y bueno, ya que había que empezar con alguno, pues me decidí a hacerlo con el más nuevo, además de que Microsoft lo suministra gratuitamente y eso no pasa todos los dias! Es un lenguaje con muchísimas posibilidades y es relativamente fácil empezar a hacer alguna cosilla con él.Los que no os descargueis esta version del Visual C#, necesitareis tener instalada la última version del .NET Framework, para poder ejecutar el PicUSB.exe, aquí lo podeis descargar:
http://www.microsoft.com/downloads/details.aspx?displaylang=es&FamilyID=7abd8c8f-287e-4c7e-9a4a-a4ecff40fc8e
Podéis encontrar el código fuente en PicUSB_VisualC#.zip, donde también veréis funciones_dll.txt en el que se detalla el uso de las funciones contenidas en la mpusbapi.dll proporcionada por Microchip, el código no está demasiado comentado, ya que he usado la API suministrada por Mat Clayton un poco a ojos cerrados, pero vamos creo que no hay problema para entender el uso de las funciones mas habituales.

El último paso ha sido la edición del Driver suministrado por Microchip para ser usado junto con la DLL, no tiene mucha historia, encontraréis un leeme.txt dentro de PicUSB_Driver.zip donde se explica como editar el PicUSB.inf, a continuación os explico como instalar el driver para los que no lo tengáis muy claro.

Al conectar el PicUSB por primera vez, nos saldrá el asistente para la instalación de nuevo hardware, marcamos la opción de "instalar desde una lista o ubicación específica", le damos a siguiente, en la siguiente pantalla marcamos la opción de "Buscar el controlador más adecuado en estas ubicaciones", pinchamos sobre "Incluir esta ubicación en la búsqueda", le damos a Examinar, y seleccionamos la carpeta PicUSB_Driver, le damos a Aceptar, y a Siguiente, nos saldrá una pantalla de advertencia, le damos a aceptar, y la instalación del Driver estará terminada y el led del GTP USB Lite habrá pasado de estar rojo a verde y estará listo para ser usado.

Dentro del PicUSB_APP.zip podréis encontrar la aplicación PicUSB.exe así como la dll necesaria suministrada por Microchip. El funcionamiento es sencillo



En la parte superior podemos encontrar el sumador, introducimos dos números del 00 hasta el 99 en cada uno de los sumandos, pinchamos sobre PIC Suma! Y estos dos operandos serán enviados al PIC, donde se procesará la suma, devolviendo entonces el resultado que se mostrará en la tercera casilla.
Por otro lado tenemos los botones, Leds Off, Led Verde On y Led Rojo On, que envían el código correspondiente para cada uno de los casos.
Al hacer click sobre la imagen se abrirá vuestro explorador web por defecto para llevaos a mi página J1MWeB :p

Para programar el PIC os recomiendo usar el WinPIC800 creado por Sisco, podéis descargarlo de aquí:
http://perso.wanadoo.es/siscobf/winpic800.htm

Os dejo a continuación el link para descargar el proyecto:
http://perso.wanadoo.es/j1m/index.htm
http://perso.wanadoo.es/j1m/proyectos/picusb/picusb.zip

Para cualquier duda podéis encontrarme en: jim2k2@hotmail.com

Jaime Fernández-Caro Belmonte
Rocket



Joined: 29 Aug 2005
Posts: 27

View user's profile Send private message

PostPosted: Mon Aug 29, 2005 10:37 am     Reply with quote

Hi J1M.
For those who only speak english, could you please translate when you have time?

Thanks.

Kind regards.
_________________
J.I.L.
PCM programmer



Joined: 06 Sep 2003
Posts: 21708

View user's profile Send private message

PostPosted: Mon Aug 29, 2005 11:34 am     Reply with quote

You can use this online translator:
http://babelfish.altavista.com/
Go down to the bottom of that page, and just copy in the whole URL
of this page into the box "for Translate a Web page". Then select
"Spanish to English", click the Translate button and wait a short time.
The translation is basically readable.
yolanda1



Joined: 06 Sep 2005
Posts: 0

View user's profile Send private message

PostPosted: Fri Sep 09, 2005 2:12 am     Reply with quote

Hi

All in this example work Ok, but is posible change parameters in picusb.h by change icon "??" in control panel ?

Windows assign "??" to PicUsb

This is picusb.h

Thanks for help


/////////////////////////////////////////////////////////////////////////
//// PicUSB.h ////
//// ////
//// Este ejemplo muestra como configurar el dispositivo USB y sus ////
//// descriptores. Los únicos cambios con respecto a su verión ////
//// original (usb_desc_scope.h) han sido realizados en el apartado ////
//// start device descriptors, concretamente el vendor y product id ////
//// y en apartado de start string descriptors, para definir el ////
//// nombre del dispositivo y la compañia. ////
//// ////
//// Realizado con el compilador CCS PCWH 3.227 ////
//// ////
//// Por: Jaime Fernández-Caro Belmonte jim2k2@hotmail.com ////
//// ////
//// http://perso.wanadoo.es/j1m/index.htm ////
/////////////////////////////////////////////////////////////////////////

#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. [0] 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)
0x11,0x00, //product id, me gusta el 11 ;)
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,12};

#define USB_STRING_DESC_COUNT sizeof(USB_STRING_DESC_OFFSET)

char const USB_STRING_DESC[]={
//string 0
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 ???
8, //length of string index
USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
'J',0,
'1',0,
'M',0,
//string 2 --> nombre del dispositivo
22, //length of string index
USB_DESC_STRING_TYPE, //descriptor type 0x03 (STRING)
'J',0,
'1',0,
'M',0,
' ',0,
'P',0,
'i',0,
'c',0,
'U',0,
'S',0,
'B',0
};


#ENDIF
ymoona



Joined: 20 Mar 2005
Posts: 32
Location: Heiloo, the Netherlands

View user's profile Send private message Visit poster's website

PostPosted: Mon May 22, 2006 1:33 pm     Reply with quote

is it possible to make is work with a 6, 16 or 20MHz crystal.

Im confused how to set up the crystal
_________________
checkout my site: www.ymoona.com/wiki
Mark



Joined: 07 Sep 2003
Posts: 2838
Location: Atlanta, GA

View user's profile Send private message Send e-mail

PostPosted: Mon May 22, 2006 1:40 pm     Reply with quote

The datasheet for the PIC. It is in there.
ymoona



Joined: 20 Mar 2005
Posts: 32
Location: Heiloo, the Netherlands

View user's profile Send private message Visit poster's website

PostPosted: Mon May 22, 2006 2:10 pm     Reply with quote

Mark wrote:
The the datasheet for the PIC. It is in there.


what I get from the data sheet on page 30 (32 of 430)
I should only change the pll prescaler from PLL3 to PLL4

but that doesn't work, am I forgetting something?
_________________
checkout my site: www.ymoona.com/wiki
ymoona



Joined: 20 Mar 2005
Posts: 32
Location: Heiloo, the Netherlands

View user's profile Send private message Visit poster's website

PostPosted: Wed May 24, 2006 7:01 am     Reply with quote

nobody?
_________________
checkout my site: www.ymoona.com/wiki
Mark



Joined: 07 Sep 2003
Posts: 2838
Location: Atlanta, GA

View user's profile Send private message Send e-mail

PostPosted: Wed May 24, 2006 7:11 am     Reply with quote

Post your setup code and the frequency of your xtal. Also whether you are trying to do low or full speed.
ymoona



Joined: 20 Mar 2005
Posts: 32
Location: Heiloo, the Netherlands

View user's profile Send private message Visit poster's website

PostPosted: Wed May 24, 2006 11:21 am     Reply with quote

this is my code so far.

Code:

#include <18F2550.h>
#fuses HSPLL,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL4,VREGEN,CPUDIV1
#use delay(clock=48000000)


// hardware pin defines
#define LED1 PIN_B0
#define LED2 PIN_B1
#define LED3 PIN_B2
#define LED4 PIN_B3
#define LED5 PIN_B4
#define LED6 PIN_B5

#define SW1 input(PIN_A4)
#define SW2 input(PIN_A5)
#define SW3 input(PIN_C0)
#define SW4 input(PIN_C6)
#define SW5 input(PIN_C7)

/////////////////////////////////////////////////////////////////////////////
//
// 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 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
#define USB_EP1_RX_ENABLE  USB_ENABLE_BULK   //turn on EP1(EndPoint1) for OUT bulk/interrupt transfers
#define USB_EP1_TX_SIZE    1                 //size to allocate for the tx endpoint 1 buffer
#define USB_EP1_RX_SIZE    3                 //size to allocate for the rx endpoint 1 buffer

#include <pic18_usb.h>     //Microchip PIC18Fxx5x Hardware layer for CCS's PIC USB driver
#include <PicUSB.h>          //Configuración del USB y los descriptores para este dispositivo
#include <usb.c>           //handles usb setup tokens and get descriptor reports

#define modo      recibe[0]
#define param1    recibe[1]
#define param2    recibe[2]
#define resultado envia[0]

void main(void) {

   int8 recibe[3];                  //declaramos variables
   int8 envia[1];

   output_low(LED1);                   //encendemos led rojo
   output_high(LED2);

   usb_init();                      //inicializamos el USB

   usb_task();                      //habilita periferico usb e interrupciones
   usb_wait_for_enumeration();      //esperamos hasta que el PicUSB sea configurado por el host

   output_low(LED2);
   output_high(LED1);                    //encendemos led verde

   while (TRUE)
   {
      if(usb_enumerated())          //si el PicUSB está configurado
      {
         if (usb_kbhit(1))          //si el endpoint de salida contiene datos del host
         {
            usb_get_packet(1, recibe, 3); //cojemos el paquete de tamaño 3bytes del EP1 y almacenamos en recibe

            if (modo == 0) // Modo_Suma
            {
               resultado = param1 + param2;  //hacemos la suma

               usb_put_packet(1, envia, 1, USB_DTS_TOGGLE); //enviamos el paquete de tamaño 1byte del EP1 al PC
            }

            if (modo == 1) // Modo_Led
            {
               if (param1 == 0) {output_low(LED1); output_low(LED2);} //apagamos los leds
               if (param1 == 1) {output_high(LED1); output_low(LED2);} //encendemos led verde
               if (param1 == 2) {output_low(LED1); output_high(LED2);} //encendemos led rojo
            }
         }
      }
   }
}


right now I use a 16MHz xtal.
I'm trying to use full speed USB (12Mb/s)

when plug in the USB cable led1 is off and led2 is on. but my laptop doesn't show any new hardware

the hardware I use is
http://www.velleman.be/nl/en/product/view/?id=351346
_________________
checkout my site: www.ymoona.com/wiki
Mark



Joined: 07 Sep 2003
Posts: 2838
Location: Atlanta, GA

View user's profile Send private message Send e-mail

PostPosted: Wed May 24, 2006 12:09 pm     Reply with quote

The schematic for that board show a 6MHz xtal. Did you change this? Did you use the right capacitors? The schematic also shows a pullup on D- which is for low speed. If you want full speed, the pullup should be on D+.
ymoona



Joined: 20 Mar 2005
Posts: 32
Location: Heiloo, the Netherlands

View user's profile Send private message Visit poster's website

PostPosted: Wed May 24, 2006 12:35 pm     Reply with quote

Mark wrote:
The schematic for that board show a 6MHz xtal. Did you change this? Did you use the right capacitors? The schematic also shows a pullup on D- which is for low speed. If you want full speed, the pullup should be on D+.


I did change the xtal because i tought 6MHz was a problem, I didn't change the caps (I will do it now). low speed isnt a problem, shoult I change the software, to make it lowspeed?

the caps are now 22pf so that should be fine now for a 16Mhz xtal.
_________________
checkout my site: www.ymoona.com/wiki
Mark



Joined: 07 Sep 2003
Posts: 2838
Location: Atlanta, GA

View user's profile Send private message Send e-mail

PostPosted: Wed May 24, 2006 2:02 pm     Reply with quote

For low speed the osc configuration is not as flexible. Reread the section in the datasheet. For a 16MHz operation, you'll need full speed. You can either move the pullup to the other pin (D+) or remove it and use the internal pullup.
ymoona



Joined: 20 Mar 2005
Posts: 32
Location: Heiloo, the Netherlands

View user's profile Send private message Visit poster's website

PostPosted: Wed May 24, 2006 3:32 pm     Reply with quote

Mark wrote:
For low speed the osc configuration is not as flexible. Reread the section in the datasheet. For a 16MHz operation, you'll need full speed. You can either move the pullup to the other pin (D+) or remove it and use the internal pullup.


I've adjusted the restor.
looking on the data sheet on page 24
I configure an
HSPLL
I put the PLL prescaler on PPL4 so the output is 4MHz, so USB freq should 96/2= 48MHz
I turn on the CPUDIV1 so the working frequency of the PIC is 96/2 = 48MHz

this is the config so far

#include <18F2550.h>
#fuses HSPLL,NOWDT,NOPROTECT,NOLVP,NODEBUG,USBDIV,PLL4,CPUDIV1,VREGEN
#use delay(clock=48000000)


some times when I connect the device windows tells me "unkows device"
so I think I'm making some progress....

but do you see thing why it shouldn'y work?
_________________
checkout my site: www.ymoona.com/wiki
ymoona



Joined: 20 Mar 2005
Posts: 32
Location: Heiloo, the Netherlands

View user's profile Send private message Visit poster's website

PostPosted: Fri May 26, 2006 6:43 am     Reply with quote

Ive now remode r35, the resistor on D+.
and now the hardware works fine and in recogniced and installed by windows.

but I face another problem, the PC software...
every time I start it up. It craches, no error codes.

Is this a familliar problem?

btv Ive installed .NET framework 2.0

edit:
Ive recompiled the source and now it working just fine!!
_________________
checkout my site: www.ymoona.com/wiki
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> Code Library All times are GMT - 6 Hours
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group