Beruflich Dokumente
Kultur Dokumente
USB
(UNIVERSAL SERIAL BUS)
MC Nicols Quiroz Hernndez
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
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
Nicols Quiroz
13
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
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
Nicols Quiroz
18
07/03/2011
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
Nicols Quiroz
21
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
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
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
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
Nicols Quiroz
32
16
07/03/2011
MC Nicols Quiroz
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
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"
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
19
07/03/2011
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
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.
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)
Nicols Quiroz
47
Circuito de conexiones
Nicols Quiroz
48
24
07/03/2011
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
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
0xD8,0x04, 0x11,0x00,
0x01,0x00, 0x01, 0x02, 0x00, };
//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
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
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