Sie sind auf Seite 1von 29

07/03/2011

USB
(UNIVERSAL SERIAL BUS)
MC Nicols Quiroz Hernndez

Conectores USB tipo A y B


Tipo A
Macho

Tipo B
Macho

Mini USB

Hembra

Hembra

Micro USB

Nicols Quiroz

07/03/2011

Dependiendo del conector, el nmero de pines difiere entre ellos y tambin la disposicin de las seales

USB Velocidades
USB 1.0 La especificacin USB 1.0 (Denominada de Baja Velocidad) es la primera que se estableci en 1996, y debido a su baja velocidad (0.192MB/s) slo se utiliza para dispositivos de interfaz humana como ratones, teclados, trackballs, etc. Su tasa de transferencia es de hasta 1,5 Mbps (192 KB/s). USB 1.1 En 1998, se lanzara una nueva revisin USB 1.1 (Denominada de Velocidad Completa) que mejora la velocidad (hasta 1,5MB/s). Aunque es una mejora, se va volviendo cada vez ms insuficiente para transferir informacin de varios megas de peso a medida que pasa el tiempo. Su tasa de transferencia es de hasta 12 Mbps (1,5 MB/s).
Nicols Quiroz 4

07/03/2011

USB Velocidades
USB 2.0 En el 2000 es cuando surge USB 2.0 (Denominada de Alta Velocidad), un interfaz de alta velocidad (60MB/s) que consigue satisfacer las necesidades de transferencia y comienza a ser comercializado para discos duros externos, pendrives, etc. Su tasa de transferencia de hasta 480 Mbps (60 MB/s) pero por lo general es de hasta 125Mbps (16MB/s)

Nicols Quiroz

USB Velocidades
USB 3.0 Tiene una tasa de transferencia de hasta 4.8 Gbps (600 MB/s). Esta especificacin es diez veces mas veloz que la anterior 2.0 y se lanz a mediados de 2009 por USB Implementers Forum. Aunque actualmente cualquier distribucin GNU/Linux, Windows Vista y Windows 7 son capaces de soportar el nuevo estndar, sin embargo, an no hay hardware disponible. La velocidad del bus es diez veces ms rpida que la del USB 2.0, debido a que han incluido 5 conectores extra, desechando el conector de fibra ptica propuesto inicialmente, y ser compatible con los estndares anteriores. Se espera que los productos fabricados con esta tecnologa lleguen al consumidor entre 2009 y 2015.

Nicols Quiroz

07/03/2011

USB Velocidades
USB 1.0: baja velocidad (hasta 1.5Mbit/seg) usado en dispositivos de interfaz humana (HID) como ratones y teclados. USB 2.0: Alta Velocidad (hasta 480Mbit/seg) unos 60Mg/seg.

USB 3.0: Giga Velocidad, en fase experimental, (hasta 4.8Gbit/seg) unos 600 Mg/seg. Los buses son mucho ms rpido debido a la incorporacin de una fibra ptica al enlace de cobre.
Nicols Quiroz 7

Datos USB
La transmisin del USB se realiza mediante un cable de cobre de par trenzado con una impedancia de unos 90 ohms llamados D+ y D-. Estos pueden dar energa a dispositivos externos, con una tensin de 5V y un mximo de corriente de 500mA. Existe actualmente en el mercado el dispositivo llamado USB OTG (On The Go), permitiendo actuar a un dispositivo como una PDA como servidor del enlace de datos, es por ello que podemos conectar a la PDA otros dispositivos USB como teclados o ratones.

Nicols Quiroz

07/03/2011

Terminologa
Host: Dispositivo maestro que inicia la comunicacin (Generalmente la computadora).

Hub: Dispositivo que contiene uno o mas conectores o conexiones internas hacia otros dispositivos USB, el cual habilita la comunicacin entre el host y con diversos dispositivos. Cada conector representa un puerto USB.

Nicols Quiroz

Puntos terminales (Endpoints)


Es una localidad especifica dentro del dispositivo. El Endpoint es un buffer que almacena mltiples bytes dentro del microcontrolador. Todos lo dispositivos deben soportar el punto terminal 0. Este punto terminal es el que recibe todo el control y la peticiones de estado durante la enumeracin cuando el dispositivo esta sobre el bus.

Nicols Quiroz

10

07/03/2011

Enumeracin
Cuando se conecta un dispositivo USB a la PC se produce el proceso de Enumeracin, el cual consiste en que el host le pregunta al dispositivo que se presente y le diga cuales son sus parmetros, tales como: Consumo de energa expresada en unidades de Carga Numero y tipos de Puntos terminales Clase del producto. Tipo de transferencia Razn de escrutinio, etc.

El proceso de enumeracin es inicializado por el host cuando detecta que un nuevo dispositivo que ha sido adjuntado al Bus. El host le asigna una direccin al dispositivo adjuntado al bus y habilita su configuracin permitiendo la transferencia de datos sobre el bus.
Nicols Quiroz 11

Modos de Transferencia
Tuberas (Pipes): Es un enlace virtual entre el host (la PC) y el dispositivo USB, este enlace configura los parmetros asociados con el ancho de banda, que tipo de transferencia se va a utilizar (Control, Bulk, Iscrona o Interrupt) direccin del flujo de datos y el mximo y/o mnimo tamao de los paquetes. Cada enlace est caracterizado por su banda de paso (Token), su tipo de servicio, el nmero de punto terminal (End Point) y el tamao de los paquetes. Estos enlaces se definen y crean durante la inicializacin del USB. Siempre existe un enlace virtual 0 que permite tener acceso a la informacin de configuracin del perifrico USB (estado, control e informacin).
Nicols Quiroz 12

07/03/2011

Modo de Transferencia Control


Modo utilizado para realizar configuraciones, existe siempre sobre el Punto terminal 0 (EndPoint 0). Todos los dispositivos USB deben soportar este tipo de transferencia. Los datos de control sirven para configurar el perifrico en el momento de conectarse al USB. Algunos drivers especficos pueden utilizar este enlace para transmitir su propia informacin de control. Este enlace no tiene prdida de datos, puesto que los dispositivos de deteccin y de recuperacin de errores estn activos a nivel USB.

Nicols Quiroz

13

Modo de Transferencia Bulk


Se utiliza para la transmisin de grandes cantidades de informacin sin prdida de datos, encaso de error la transferencia se vuelve a intentar. Utiliza el ancho de banda disponible para el USB. til cuando la razn de transferencia no es critica. Puede ser unidireccional o bidireccional.

Ejemplos, el envi de un archivo a imprimir o la recepcin de datos desde un escner. En estas aplicaciones, la transferencia es rpida, pero puede esperar si fuera necesario. Solo los dispositivos de media y alta velocidad utilizan este tipo de transferencia.

Nicols Quiroz

14

07/03/2011

Modo de Transferencia Interrupt


Para transmisiones de pequeos paquetes, rpidos, orientados a percepciones humanas (ratn, punteros). Este tipo de transferencia son para dispositivos que deben recibir atencin peridicamente y lo utilizan los dispositivos de baja velocidad. Este tipo de transmisin garantiza la transferencia de pequeas cantidades de datos. El tiempo de respuesta no puede ser inferior al valor especificado por la interfaz. El ratn o cualquier otro dispositivo apuntador es una aplicacin tpica de este modo de transmisin. Transferencia unidireccional y slo hacia el host.

Nicols Quiroz

15

Interrupt transfer
Interrupt transfer is uni-directional and only inputs to the host. It is used to support data transfers that are small in size and happen infrequently. The interrupt transfer of USB is of a polling type; that is, the host asks if the interrupt endpoints have any data to send according to the frequency requested by the endpoints. For full speed devices, the endpoint can specify the polling period of 1 ms to 255 ms. For low speed devices, the polling period is from 10 ms to 255 ms. Thus, the fastest polling frequency is 1 kHz for full speed devices. In case of delivery failure due to errors, a retry of transfer will be carried out in the next polling period. A good example of a device using interrupt transfer is a keyboard, where it sends a small amount of data to the host when a key is pressed.
Nicols Quiroz 16

07/03/2011

Modo de Transferencia Iscrona


(Isochronous Transfer)
Tambin llamado Flujo en tiempo real Utilizado para la transmisin de audio o video comprimido. Transmisin en tiempo real (modo de mayor prioridad). Garantiza el acceso a USB con latencia delimitada, y no volver a intentar en caso de un error en la entrega. El tamao mximo de paquete para la transferencia iscrona es 1023 bytes por frame USB de 1 ms. Esto implica que la transferencia mxima alcanzable utilizando la transferencia iscrona es 8,184 Mbps. Transferencia unidireccional o bidireccional.
A good application example of this transfer type is 64 kbps Pulse Code Modulation (PCM) voice data. The voice data requires a constant rate and can tolerate errors (typically up to a bit error rate of 1x10-3).
Nicols Quiroz 17

Universal Serial Bus Features PIC18F4550 o PIC18F2550


USB V2.0 Compliant Low Speed (1.5 Mb/s) and Full Speed (12 Mb/s) Supports Control, Interrupt, Isochronous and Bulk Transfers

Supports up to 32 Endpoints (16 bidirectional)


1 Kbyte Dual Access RAM for USB On-Chip USB Transceiver with On-Chip Voltage Regulator Interface for Off-Chip USB Transceiver Streaming Parallel Port (SPP) for USB streaming transfers (40/44-pin devices only)

Nicols Quiroz

18

07/03/2011

PIC utilizado PIC18F4550


Vamos a usar un PIC 18F4550 que gestione mediante software la comunicacin USB2.0 con la computadora, tambin se puede usar un PIC18F2550, Tambin hay que configurar dos parmetros esenciales en todo dispositivo que son el VID y PID. VID (Vendor ID): Es el identificador de la empresa. Cada empresa tiene un identificador, el cual puede vender diferentes productos a los que se les incluye el ID. PID (Product ID): Es el identificador del producto. Por tanto un dispositivo tendr un VID e ID fijos que les hace nicos con lo que no pueden sufrir incompatibilidad con otros dispositivos.
http://www.pcidatabase.com
Nicols Quiroz 19

Connection of external resistors in a full speed device

For low speed devices, the 1.5 k 5% resistor must be tied from the D- wire to a voltage source between 3.0 and 3.6 v.

Nicols Quiroz

20

10

07/03/2011

Power Supply from USB Wires


The voltage supply is between 4.75v-5.25v. A bus-powered device can draw a maximum of 500 mA. The definition of a bus-powered device is that the device draw current from the USB bus directly. Devices that have their own power supply are called self-powered devices. Before the requested amount of current is granted by the USB host, the device must draw no more than 100 mA from the USB when it first attaches to the bus. For devices that are attached to a bus-powered hub, the maximum amount of current supply permitted is 100 mA.

Nicols Quiroz

21

USB Packet Formats


USB packets fit into one of these types:
Token SOF Data Handshake Special packets.

Nicols Quiroz

22

11

07/03/2011

Token Packets
USB transaction are always initiated by the host and are started with a token packet in the format shown in figure:
SYNC PID ADDR ENDP CRC

SYNC
All packets begin with a synchronization (SYNC) field. It is used by the input circuitry to align incoming data with the local clock and it is 8 bits in length.

PID
A packet identifier (PID) immediately follows the SYNC field. A PID consists of four bits followed by a four-bit check field, as shown in figure:
PID0 PID1 PID2 PID3 PID0 PID1 PID2 PID3

Nicols Quiroz

23

Token Packets
The PID indicates the type of packet that is transmitted (differentiated by PID0 and PID1); either token, data, handshake or special packet. These four types of packets are subdivided into various identifiers (differentiated by PID2 and PID3): Packet type PID Name PID3:PID2 PID1:PID0 Token Token SOF Token Data Data Handshake Handshake Handshake Special
Nicols Quiroz

OUT IN SOF SETUP DATA0 DATA1 ACK NAK STALL PRE

00 10 01 11 00 10 00 10 11 11

01 01 01 01 11 11 10 10 10 00
24

12

07/03/2011

Token Packets
ADDR
The 7-bit function address (ADDR) field specifies which device the packet is intended for. The host assigns a unique address to each device during USB enumeration process when it is first attached to the bus.

ENDP
The 4-bit endpoint (ENDP) further specifies which tiny pipe of the device the packet is intended for. For example, a device has endpoint 0 and endpoint 1 configured, the host can choose to communicate to endpoint 0 of this device at this instant, ignoring endpoint 1.

CRC
Cyclic Redundancy Checks (CRCs) provide error checking for the non-PID fields of the USB packet. The PID is not protected by this CRC as it has self error checking.
Nicols Quiroz 25

Start of Frame Packets


Start of Frame (SOF) packets, as shown in figure, are broadcast by the host once every 1.00 ms 0.05.
SYNC PID Frame Number CRC

Nicols Quiroz

26

13

07/03/2011

Data Packets
The host performs the management of the bus, and devices respond to requests from the host. If the host requests information from a device it will send an IN token addressed to that device endpoint and the device will response with a USB data packet. The format of the data packet is as shown in figure, with the PID indicating DATA0 or DATA1.
SYNC PID DATA CRC

If the transfer type of this particular endpoint is bulk, control or interrupt, the host will response with an acknowledgment when it receives the data without error. If the transfer type is isochronous, no handshake packet will be sent. The host will send an OUT token followed by a data packet if it wishes to transfer data to the device.
Nicols Quiroz

27

Handshake Packets
The handshake packets consist of only a PID, as shown in figure. They are used to report ACK, NACK or STALL (as indicated by the PID) for transactions that require handshakes.

SYNC

PID

Nicols Quiroz

28

14

07/03/2011

Special Packets
The special preamble (PRE) packet is sent by the host when it wishes to communicate to low speed devices. The host will send this PRE packet first, before sending low speed 1.5 Mbps packets to communicate with low speed devices.

Nicols Quiroz

29

USB Protocol by Transfer Types

15

07/03/2011

Control Transfers
Control transfers have two or three stages:
Setup Data (may or may not be required) Status stage

The best way to understand how a control transfer works is to look at an example, as shown in figure. It shows a complete control transfer between a function and a host, as captured by a CATC USB bus analyzer.

Nicols Quiroz

31

178

Sync (0000001) SOF(0x A5) Frame#(0x 12C)CRC5(0x1F)

Nicols Quiroz

32

16

07/03/2011

MC Nicols Quiroz

COMUNICACIN USB 2.0 PC <------> PIC


Nicols Quiroz 33

Ejemplo Comunicacin USB


Realizar una interfaz con la PC a travs del puerto USB y un PIC18F4550. 1. Para controlar un led 2. Para controlar dos leds (verde y rojo)

3. Motor
Realizar un programa en VC++ 6
Una interfaz de usuario para controlar led

Un programa en PICC para el microcontrolador Realizar un circuito para la comunicacin USB Instalar el driver

Nicols Quiroz

34

17

07/03/2011

Pasos para realizar el programa en C++


Crear un nuevo proyecto Basado en un cuadro de dialogo Copiar los archivos siguientes en el directorio raz del proyecto: usb2550.dll, usb2550.lib, usb2550.h, USB.cpp y USB.h Agregar los archivos siguientes al proyecto: USB.cpp, usb2550.h, y USB.h Se enlaza la librera usb2550.lib.
Barra de herramientas: Project -> Setting o se pulsa Alt+F7, donde saldr el cuadro de dilogo: Project Settings. Ir pestaa Link -> En Object/library modules escribir usb2550.lib y oprimir OK.

Con esto ya se tiene enlazado el proyecto con las MFC y la librera de USB de microchip.
Nicols Quiroz 35

Lo primero es crear un objeto que contenga las propiedades de las libreras USB. Abrir el archivo PicUSBDlg.h y aadir las siguientes directivas e instanciacin del objeto USB:
#include "usb.h" #include "usb2550.h"

Y agregar un miembro pblico a la clase public: USB MiUSB;


Nicols Quiroz 36

18

07/03/2011

Se muestra el archivo PicUSBDlg.h Donde se agregaron las directivas, y la declaracin del objeto MiUSB de la clase USB.
// PicUSBDlg.h: archivo de encabezado // #pragma once #include "afxwin.h" #include "usb.h" #include "usb2550.h" // Cuadro de dilogo de CPicCalculadoraUSBDlg class CPicUSBDlg : public CDialog { ..... ..... ..... DECLARE_MESSAGE_MAP() public: USB MiUSB; //Esto es mi objeto USB }

Nicols Quiroz

37

Cdigo para botones


Agregar un 2 botones con caption: Led O&N y Led O&FF Agregar dos mtodos para el evento clic. Para botn Led ON: OnBtnLedOn() con el siguiente cdigo:
Utilizar el mtodo miUSB.SendPacket(Arreglo, Tam_bytes) Esta funcin enviar un arreglo Arreglo de bytes de longitud Tam_bytes, por el puerto USB.
void CPicUSBDlg::OnBtnLedOn() { // TODO: Agregue aqu su cdigo BYTE Datos[1]; Datos[0]=1; MiUSB.SendPacket(Datos,1); }

Para el botn Led_OFF slo cambia el dato enviado Datos[0]=0;

Agregar los archivos usb.h y usb.cpp al proyecto


Nicols Quiroz 38

19

07/03/2011

Funciones para enviar y recibir datos


Recibir datos desde el PIC void ReceivePacket(BYTE *ReceiveData, DWORD *ReceiveLength); ReceiveData Bfer donde se almacenan los datos recibidos ReceiveLength- Cuantos datos se reciben Enviar datos al PIC void SendPacket(BYTE *SendData, DWORD SendLength);

SendData- Direccin de los datos a enviar


SendLength- cantidad de datos a enviar.

Nicols Quiroz

39

Archivo USB.cpp
Verificar que al inicio del archivo USB.cpp Que los Ids son "vid_04d8&pid_0011"; Estos valores deben coincidir con el programa desarrollado para el PIC.
// Global Vars PCHAR vid_pid = "vid_04d8&pid_0011"; //VID y PID PCHAR out_pipe= "\\MCHP_EP1"; PCHAR in_pipe= "\\MCHP_EP1"; HANDLE myOutPipe; HANDLE myInPipe;

Nicols Quiroz

40

20

07/03/2011

Las libreras suministradas


Pic_usb.h: driver de capa hardware de la familia PICl6C765. Pic_l8usb.h: driver de capa hardware de la familia PIC18F4550.

usbn960x.h: driver de capa hardware para el dispositivo externo USBN9603/USBN9604. De esta forma, se puede utilizar el bus USB en cualquier PIC.
Usb.h: definiciones y prototipos utilizados en el driver USB. usb.c: El USB stack, que maneja las interrupciones; USB y el USB Setup Requests en Endpoint 0. usb-cdc.h: driver que permite utilizar una clase de dispositivo CDC USB, emulando un dispositivo RS232 y lo muestra como un puerto COM en Windows.

Las funciones ms importantes


usb_init(): inicializa el hardware USB. Espera en un bucle infinito hasta que el perifrico USB es conectado al bus (aunque eso no significa que ha sido enumerado por el PC). Habilita y utiliza la interrupcin USB. usb_task(): Si se utiliza una deteccin de conexin para la inicializacin, entonces se debe llamar peridicamente a esta funcin para controlar el pin de deteccin de conexin. Cuando el PIC es conectado o desconectado del bus, esta funcin inicializa el perifrico USB o resetea el USB stack y el perifrico.

21

07/03/2011

Funciones USB
usb_enumerated: Devuelve un TRUE si el dispositivo ha sido enumerado por el PC y, en este caso, el dispositivo entra en modo de operacin normal y puede enviar y recibir paquetes de datos. Existen funciones especficas para CDC, entre ellas: usb_cdc_putc(c): Es idntica a put(c) y enva un carcter. Coloca un carcter en el bfer de transmisin; en el caso de que est lleno esperara hasta que pueda enviarlo. usb_cdc_getc(c): Es idntica a get(c) y lee un carcter. Recibe un carcter del bfer de transmisin; y el caso de estar vaco esperar hasta que se reciba.

Programacin PIC
USB 2.0 Microchip

22

07/03/2011

Comunicacin USB
Microchip permite mediante la programacin de sus PIC realizar una comunicacin PIC<---->PC de forma sencilla y eficaz. Utilizando la librera MPUSBAPI, para escribir y leer en el PIC. La velocidad es de hasta 12Mbit/seg.

Nicols Quiroz

45

Comunicacin USB
On slow speed devices the max packet size is 8. On a full speed device the max packet size is 64. Data is obtained on the host / PC through polling the HID device (PC polls the PIC)

On a full speed device, max polling rate is 1 transaction per 1ms. This is 64000 bytes per second (64 byte packets every 1ms).
On a slow speed device, max polling rate is 1 transaction per 10ms. This is 800 bytes per second (8 byte packets every 10ms) No guarantee that polls will happen at a guaranteed rate. If you want guaranteed transfer rate you must use Isochronous transfers, which HID is not.

Nicols Quiroz

46

23

07/03/2011

Material
1 PIC18F4550 1 cristal de 12 MHz 1 capacitor electroltico de 47uF/16V 2 capacitores de 15 pF 1 conector USB tipo A macho 1 cable con 4 hilos (1 m) (o de un ratn) 1 tira de pines (solo 4 pines)

1 resistencia 10K Ohms


2 resistencias de 330 Ohms 2 Leds (verde y rojo)

Nicols Quiroz

47

Circuito de conexiones

Nicols Quiroz

48

24

07/03/2011

Diagrama elctrico del PIC18F4550


Checar las conexiones para el pic de 40 pines. Conectar los leds a los pines Rojo -> pin 40 (RB7) Verde -> pin 39 (RB6)

Nicols Quiroz

49

PIC
Programacin del PIC se utiliza el compilador PIC C de la empresa CCS. El cdigo principal para crear nuestro USB 2.0 es el siguiente:

Nicols Quiroz

50

25

07/03/2011

Relevant Functions
usb_init() Initializes the USB hardware. Will then wait in an infinite loop for the USB peripheral to be connected to bus (but that doesn't mean it has been enumerated by the PC). Will enable and use the USB interrupt. usb_task() If you use connection sense, and the usb_init_cs() for initialization, then you must periodically call this function to keep an eye on the connection sense pin. When the PIC is connected to the BUS, this function will then perpare the USB peripheral. When the PIC is disconnected from the BUS, it will reset the USB stack and peripheral. Will enable and use the USB interrupt. usb_enumerated() Returns TRUE if the device has been enumerated by the PC. If the device has been enumerated by the PC, that means it is in normal operation mode and you can send/receive packets.

Nicols Quiroz

51

Relevant Functions
usb_put_packet(endpoint, data, len, tgl) Places the packet of data into the specified endpoint buffer. Returns TRUE if success, FALSE if the buffer is still full with the last packet. usb_get_packet(endpoint, ptr, max) Reads up to max bytes from the specified endpoint buffer and saves it to the pointer ptr. Returns the number of bytes saved to ptr. usb_kbhit(endpoint) Returns TRUE if the specified endpoint has data in it's receive buffer

Nicols Quiroz

52

26

07/03/2011

usb_put_packet(endpoint, *ptr, len, toggle)


Input: endpoint - endpoint to send packet to ptr - points to data to send len - amount of data to send toggle - whether to send data with a DATA0 pid, a DATA1 pid, or toggle from the last DATAx pid. Output: TRUE if data was sent correctly, FALSE if it was not. The only reason it will return FALSE is if because the TX buffer is still full from the last time you tried to send a packet. Summary: Sends one packet out the EP to the host. Notice that there is a difference between a packet and a message. If you wanted to send a 512 byte message you would accomplish this by sending 8 64-byte packets, followed by a 0 length packet. If the last (or only packet) being sent is less than the max packet size defined in your descriptor then you do not need to send a 0 length packet to identify an end of message. usb_puts() (provided in usb.c) will send a multi-packet message correctly.
Nicols Quiroz 53

Ejemplo
usb_put_packet(endpoint, data, len, tgl) usb_put_packet(1, data, 1, USB_DTS_TOGGLE);

endpoint-> 1, EP1 a la pC
data-> direccin del bfer de datos len -> cuandos se envian en bytes tgl -> USB_DTS_TOGGLE

Nicols Quiroz

54

27

07/03/2011

Checar los IDs


vendor id = 0x04D8 y product id = 0x0011 en el archivo PicUsb.h
////////////////////////////////////////////////////////////////// /// start device descriptors ////////////////////////////////////////////////////////////////// //device descriptor char const USB_DEVICE_DESC[] ={ USB_DESC_DEVICE_LEN, 0x01, 0x10,0x01, 0x00, 0x00, 0x00, //the length of this report //constant DEVICE (0x01) //usb version in bcd //class code (if 0, interface defines class. FF is vendor defined) //subclass code //protocol code

USB_MAX_EP0_PACKET_LENGTH, //max packet size for endpoint 0. (SLOW SPEED SPECIFIES 8)

0xD8,0x04, 0x11,0x00,
0x01,0x00, 0x01, 0x02, 0x00, };

//vendor id (0x04D8 is Microchip) //product id, puede ser el 0x0011


//device release number

//index of string description of manufacturer. therefore we point to string_1 array (see below) //index of string descriptor of the product //index of string descriptor of serial number

USB_NUM_CONFIGURATIONS //number of possible configurations

Nicols Quiroz

55

void main(void) { int8 datos[3]; usb_init(); usb_task(); while (TRUE) { if(usb_enumerated()) { if (usb_kbhit(1)) { //declaramos variables //inicializamos el USB

Cdigo en el PIC
//habilita periferico usb e interrupciones //esperamos hasta que el PicUSB sea configurado por el host //si el PicUSB est configurado //si el endpoint contiene datos del host

usb_wait_for_enumeration();

usb_get_packet(1, datos, 1); //obtiene el paquete de tamao 1 bytes del EP1 //y almacenamos en datos if (datos[0] == 0) { } if (datos[0] == 1) // Modo_Led { } } } } }
Nicols Quiroz 56

output_low(PIN_B7); // Apaga led

output_high(PIN_B7); //// Enciende led

28

07/03/2011

USB usb.h
USB_EPx_RX_ENABLE (USB_ENABLE_DISABLED) Where x is the endpoint number. Change this define to specify what kind of transfer method this RX (PC to device) endpoint uses. Here is the list of valid transfer methods: USB_ENABLE_CONTROL USB_ENABLE_ISOCHRONOUS USB_ENABLE_BULK USB_ENABLE_INTERRUPT USB_ENABLE_DISABLED Don't forget that you must specify the transfer method properly in your endpoint descriptor, too.

Nicols Quiroz

57

USB
usb.h
USB_EPx_TX_ENABLE (USB_ENABLE_DISABLED) Where x is the endpoint number. Change this define to specify what kind of transfer method this TX (device to PC) endpoint uses. Here is the list of valid transfer methods: USB_ENABLE_CONTROL USB_ENABLE_ISOCHRONOUS USB_ENABLE_BULK USB_ENABLE_INTERRUPT USB_ENABLE_DISABLED Don't forget that you must specify the transfer method properly in your endpoint descriptor, too. USB_EPx_TX_SIZE (0) For some hardware it is important to know how much memory to reserve for transmitting packets.

Nicols Quiroz

58

29

Das könnte Ihnen auch gefallen