USB curso y potencia

71
USB (UNIVERSAL SERIAL BUS) MC Nicolás Quiroz Hernández

Transcript of USB curso y potencia

Page 1: USB curso y potencia

USB(UNIVERSAL SERIAL BUS)

MC Nicolás Quiroz Hernández

Page 2: USB curso y potencia

Conectores USB tipo A y B

Nicolás Quiroz 2

Hembra

Macho

Hembra

Macho

Tipo ATipo B Mini USB

Micro USB

Page 3: USB curso y potencia

Dependiendo del conector, el número de pines difiere entre

ellos y también la disposición de las señales

Page 4: USB curso y potencia

USB

Velocidades

USB 1.0

La especificación USB 1.0 (Denominada de Baja Velocidad)

es la primera que se estableció en 1996, y debido a su baja

velocidad (0.192MB/s) sólo 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 lanzaría una nueva revisión USB 1.1

(Denominada de Velocidad Completa) que mejora la

velocidad (hasta 1,5MB/s). Aunque es una mejora, se va

volviendo cada vez más insuficiente para transferir

información de varios megas de peso a medida que pasa el

tiempo.

Su tasa de transferencia es de hasta 12 Mbps (1,5 MB/s).

Nicolás Quiroz 4

Page 5: USB curso y potencia

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)

Nicolás Quiroz 5

Page 6: USB curso y potencia

USB

Velocidades

USB 3.0

Tiene una tasa de transferencia de hasta 4.8 Gbps (600

MB/s). Esta especificación es diez veces mas veloz que la

anterior 2.0 y se lanzó a mediados de 2009 por USB

Implementers Forum. Aunque actualmente cualquier

distribución GNU/Linux, Windows Vista y Windows 7 son

capaces de soportar el nuevo estándar, sin embargo, aún no

hay hardware disponible. La velocidad del bus es diez veces

más rápida 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 estándares

anteriores. Se espera que los productos fabricados con esta

tecnología lleguen al consumidor entre 2009 y 2015.

Nicolás Quiroz 6

Page 7: USB curso y potencia

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 más rápido

debido a la incorporación de una

fibra óptica al enlace de cobre.

Nicolás Quiroz 7

Page 8: USB curso y potencia

Datos USB

La transmisión 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 energía a

dispositivos externos, con una tensión de 5V y un máximo

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.

Nicolás Quiroz 8

Page 9: USB curso y potencia

Terminología

Host: Dispositivo maestro que inicia la comunicación

(Generalmente la computadora).

Hub: Dispositivo que contiene uno o mas conectores o

conexiones internas hacia otros dispositivos USB, el cual

habilita la comunicación entre el host y con diversos

dispositivos. Cada conector representa un puerto USB.

Nicolás Quiroz 9

Page 10: USB curso y potencia

Puntos terminales (Endpoints)

Es una localidad especifica dentro del dispositivo. El

Endpoint es un buffer que almacena múltiples 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

enumeración cuando el dispositivo esta sobre el bus.

Nicolás Quiroz 10

Page 11: USB curso y potencia

Enumeración

Cuando se conecta un dispositivo USB a la PC se produce el

proceso de Enumeración, el cual consiste en que el host le

pregunta al dispositivo que se presente y le diga cuales son

sus parámetros, tales como:

• Consumo de energía expresada en unidades de Carga

• Numero y tipos de Puntos terminales

• Clase del producto.

• Tipo de transferencia

• Razón de escrutinio, etc.

El proceso de enumeración es inicializado por el host

cuando detecta que un nuevo dispositivo que ha sido

adjuntado al Bus. El host le asigna una dirección al

dispositivo adjuntado al bus y habilita su configuración

permitiendo la transferencia de datos sobre el bus.

Nicolás Quiroz11

Page 12: USB curso y potencia

Modos de Transferencia

Tuberías (Pipes): Es un enlace virtual entre el host (la

PC) y el dispositivo USB, este enlace configura los

parámetros asociados con el ancho de banda, que tipo de

transferencia se va a utilizar (Control, Bulk, Isócrona o

Interrupt) dirección del flujo de datos y el máximo y/o

mínimo tamaño de los paquetes.

Cada enlace está caracterizado por su banda de paso

(Token), su tipo de servicio, el número de punto terminal

(End Point) y el tamaño de los paquetes. Estos enlaces se

definen y crean durante la inicialización del USB. Siempre

existe un enlace virtual 0 que permite tener acceso a la

información de configuración del periférico USB (estado,

control e información).

Nicolás Quiroz 12

Page 13: USB curso y potencia

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 periférico en

el momento de conectarse al USB. Algunos drivers

específicos pueden utilizar este enlace para transmitir su

propia información de control. Este enlace no tiene pérdida

de datos, puesto que los dispositivos de detección y de

recuperación de errores están activos a nivel USB.

Nicolás Quiroz 13

Page 14: USB curso y potencia

Modo de Transferencia Bulk

Este modo se utiliza para la transmisión de importantes

cantidades de información. Como el tipo control, de este

enlace no tiene pérdida de datos. Este tipo de transferencia

es útil cuando la razón de transferencia no es critica como

por ejemplo , el envió de un archivo a imprimir o la recepción

de datos desde un escáner. En estas aplicaciones, la

transferencia es rápida, pero puede esperar si fuera

necesario. Solo los dispositivos de media y alta velocidad

utilizan este tipo de transferencia.

Nicolás Quiroz 14

Page 15: USB curso y potencia

Modo de Transferencia Interrupt

Modo utilizado para transmisiones de pequeños paquetes,

rápidos, orientados a percepciones humanas (ratón,

punteros). Este tipo de transferencia son para dispositivos

que deben recibir atención periódicamente y lo utilizan los

dispositivos de baja velocidad. Este tipo de transmisión

garantiza la transferencia de pequeñas cantidades de datos.

El tiempo de respuesta no puede ser inferior al valor

especificado por la interfaz. El ratón o cualquier otro

dispositivo apuntador es una aplicación típica de este modo

de transmisión.

Nicolás Quiroz 15

Page 16: USB curso y potencia

Modo de Transferencia Isócrona

También llamado Flujo en tiempo real, este modo es utilizado

para la transmisión de audio o video comprimido. Este tipo

de transmisión funciona en tiempo real. Este es el modo de

mayor prioridad.

La transmisión de la voz es un ejemplo de esta aplicación. Si

ésta no se transmite correctamente, pueden llegar a oírse

parásitos (glich) y la aplicación puede detectar ciertos errores

de los llamados underruns.

Nicolás Quiroz 16

Page 17: USB curso y potencia

PIC utilizado

PIC18F4550 Vamos a usar un PIC 18F4550 que gestione mediante

software la comunicación USB2.0 con la computadora,

también se puede usar un PIC18F2550,

También hay que configurar dos parámetros 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.

Nicolás Quiroz 17

http://www.pcidatabase.com

Page 18: USB curso y potencia

Nicolás Quiroz 18

USB pipes and endpoints

It consists of a big pipe (12 Mbps) and up to 127 small pipes. Each of the small

pipes connects to a USB device. There are 7 address bits in the USB token

which can address up to 128 devices. However, address 000 0000B, called the

USB default address, is used for all devices when they are first attached. Thus

USB can support up to 127 devices. Each of the small pipes connected to

a USB device can be further divided into smaller pipes.

There can be up to 16 pairs of these tiny pipes from a single small pipe. This is

because there are 4 "endpoint" bits in a USB token and the token can be

identified as IN or OUT tokens.

Page 19: USB curso y potencia

Nicolás Quiroz 19

USB Transfer Types

There are four USB transfer types:

1. Control

2. Isochronous

3. Interrupt

4. Bulk

Page 20: USB curso y potencia

Nicolás Quiroz 20

Control Transfer

Control transfers are bi-directional and intended to support

configuration, command or status communications between

the host and functions.

A control transfer consists of 2 or 3 stages: a setup stage,

data stage (may or may not exist) and status stage. In the

setup stage, the host sends a request to the function. In

the data stage, data transfer occurs in the direction as

indicated in the setup stage, and in the status stage, the

function returns a handshake to the host.

Each USB device is required to implement the endpoint pair

0 as control transfer endpoints. It is used to exchange

information when the device is first attached to the host.

Page 21: USB curso y potencia

Nicolás Quiroz 21

Isochronous Transfer

Isochronous transfer can be uni-directional or bi-directional. It is intended to be used to transfer information that requires a constant rate and can tolerate errors. 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).

Isochronous transfer has the following characteristics:

— guaranteed access to USB with bounded latency, and

— no retrying in case of a delivery failure due to error.

The maximum packet size for isochronous transfer is 1023 bytes per USB frame of 1 ms. This implies that the maximum transfer achievable using isochronous transfer is 8,184 Mbps.

Page 22: USB curso y potencia

Nicolás Quiroz 22

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.

Page 23: USB curso y potencia

Nicolás Quiroz 23

Bulk Transfer

The bulk transfer can be uni- or bi-directional. It is used to

support endpoints that need to communicate large amounts

of data accurately but where the time of delivery is not

critical. The bulk transfer is designed to claim unused

bandwidth of the USB, and therefore the provision of USB

access time to bulk transfers is on a bandwidth available

basis. In case of delivery failure due to errors, the transfer

is retried. A typical usage is a scanner, where a large

amount of data needs to be delivered accurately, but not

immediately.

Page 24: USB curso y potencia

Nicolás Quiroz 24

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.

Page 25: USB curso y potencia

Nicolás Quiroz 25

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.

Page 26: USB curso y potencia

Nicolás Quiroz 26

USB Packet Formats

USB packets fit into one of these types:

• Token

• SOF

• Data

• Handshake

• Special packets.

Page 27: USB curso y potencia

Nicolás Quiroz 27

Token Packets

USB transaction are always initiated by the host and are

started with a token packet in the format shown in figure:

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:

PIDSYNC ADDR ENDP CRC

PID0 PID1 PID2 PID3 PID0 PID1 PID2 PID3

Page 28: USB curso y potencia

Nicolás Quiroz 28

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 OUT 00 01

Token IN 10 01

SOF SOF 01 01

Token SETUP 11 01

Data DATA0 00 11

Data DATA1 10 11

Handshake ACK 00 10

Handshake NAK 10 10

Handshake STALL 11 10

Special PRE 11 00

Page 29: USB curso y potencia

Nicolás Quiroz 29

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.

Page 30: USB curso y potencia

Nicolás Quiroz 30

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.

PIDSYNC Frame Number CRC

Page 31: USB curso y potencia

Nicolás Quiroz 31

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.

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.

PIDSYNC DATA CRC

Page 32: USB curso y potencia

Nicolás Quiroz 32

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.

PIDSYNC

Page 33: USB curso y potencia

Nicolás Quiroz 33

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.

Page 34: USB curso y potencia

USB Protocol by Transfer Types

Page 35: USB curso y potencia

Nicolás Quiroz 35

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.

Page 36: USB curso y potencia

Nicolás Quiroz 36

178 Sync (0000001) SOF(0xA5) Frame#(0x12C)CRC5(0x1F)

Page 37: USB curso y potencia

COMUNICACIÓN USB 2.0

PC <------> PIC

MC Nicolás Quiroz

Nicolás Quiroz 37

Page 38: USB curso y potencia

Ejemplo

Comunicación USB

Realizar una interfaz con la PC a través 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 comunicación USB

Instalar el driver

Nicolás Quiroz 38

Page 39: USB curso y potencia

Nicolás Quiroz 39

Pasos para realizar el

programa en C++

Crear un nuevo proyecto

Basado en un cuadro de dialogo

Copiar los archivos siguientes en el directorio raíz 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 librería usb2550.lib.

• Barra de herramientas: Project -> Setting o se pulsa Alt+F7,

donde saldrá el cuadro de diálogo: Project Settings.

• Ir pestaña Link -> En Object/library modules escribir

―usb2550.lib‖ y oprimir OK.

Con esto ya se tiene enlazado el proyecto con las MFC y la

librería de USB de microchip.

Page 40: USB curso y potencia

Nicolás Quiroz 40

Lo primero es crear un objeto que contenga las propiedades

de las librerías USB. Abrir el archivo PicUSBDlg.h y añadir

las siguientes directivas e instanciación del objeto USB:

#include "usb.h"

#include "usb2550.h"

Y agregar un miembro público a la clase

public:

USB MiUSB;

Page 41: USB curso y potencia

Se muestra el archivo PicUSBDlg.h

Donde se agregaron las directivas, y la declaración del

objeto MiUSB de la clase USB.

Nicolás Quiroz 41

// PicUSBDlg.h: archivo de encabezado//#pragma once#include "afxwin.h"#include "usb.h"#include "usb2550.h"

// Cuadro de diálogo de CPicCalculadoraUSBDlgclass CPicUSBDlg : public CDialog{...............

DECLARE_MESSAGE_MAP()public:USB MiUSB; //Esto es mi objeto USB

}

Page 42: USB curso y potencia

Código para botones

Agregar un 2 botones con caption: ―Led O&N‖ y ―Led O&FF‖

Agregar dos métodos para el evento clic.

Para botón Led ON: OnBtnLedOn() con el siguiente código:

• Utilizar el método miUSB.SendPacket(Arreglo, Tam_bytes)

• Esta función enviará un arreglo Arreglo de bytes de longitud

Tam_bytes, por el puerto USB.

void CPicUSBDlg::OnBtnLedOn() {// TODO: Agregue aquí su código BYTE Datos[1];

Datos[0]=1;MiUSB.SendPacket(Datos,1);

}

• Para el botón Led_OFF sólo

• cambia el dato enviado Datos[0]=0;

Nicolás Quiroz 42

Page 43: USB curso y potencia

Funciones para enviar y recibir datos

Recibir datos desde el PIC

void ReceivePacket(BYTE *ReceiveData, DWORD *ReceiveLength);

ReceiveData – Búfer donde se almacenan los datos recibidos

ReceiveLength- Cuantos datos se reciben

Enviar datos al PIC

void SendPacket(BYTE *SendData, DWORD SendLength);

SendData- Dirección de los datos a enviar

SendLength- cantidad de datos a enviar.

Nicolás Quiroz 43

Page 44: USB curso y potencia

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;

Nicolás Quiroz 44

Page 45: USB curso y potencia

Las librerías 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.

Page 46: USB curso y potencia

Las funciones más importantes

usb_init(): inicializa el hardware USB. Espera en un bucle

infinito hasta que el periférico USB es conectado al bus

(aunque eso no significa que ha sido enumerado por el PC).

Habilita y utiliza la interrupción USB.

usb_task(): Si se utiliza una detección de conexión para la

inicialización, entonces se debe llamar periódicamente a

esta función para controlar el pin de detección de conexión.

Cuando el PIC es conectado o desconectado del bus, esta

función inicializa el periférico USB o resetea el USB stack y

el periférico.

Page 47: USB curso y potencia

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 operación normal y puede enviar y recibir

paquetes de datos.

Existen funciones específicas para CDC, entre ellas:

usb_cdc_putc(c): Es idéntica a put(c) y envía un

carácter. Coloca un carácter en el búfer de transmisión; en

el caso de que esté lleno esperara hasta que pueda

enviarlo.

usb_cdc_getc(c): Es idéntica a get(c) y lee un carácter.

Recibe un carácter del búfer de transmisión; y el caso de

estar vacío esperará hasta que se reciba.

Page 48: USB curso y potencia

Programación

PIC

USB 2.0 Microchip

Page 49: USB curso y potencia

Microchip permite mediante la programación de sus PIC

realizar una comunicación PIC<---->PC de forma sencilla y

eficaz. Utilizando la librería MPUSBAPI, para escribir y leer

en el PIC. La velocidad es de hasta 12Mbit/seg.

Nicolás Quiroz 49

Page 50: USB curso y potencia

Material

1 PIC18F4550

1 cristal de 12 MHz

1 capacitor electrolítico de 47uF/16V

2 capacitores de 15 pF

1 conector USB tipo A macho

1 cable con 4 hilos (1 m)

1 tira de pines (solo 4 pines)

2 resistencias de 330 Ohms

2 Leds (verde y rojo)

Nicolás Quiroz 50

Page 51: USB curso y potencia

Diagrama eléctrico 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)

Nicolás Quiroz 51

Page 52: USB curso y potencia

PIC

Programación del PIC se utiliza el compilador PIC C de la

empresa CCS.

El código principal para crear nuestro USB 2.0 es el

siguiente:

Nicolás Quiroz 52

Page 53: USB curso y potencia

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.

Nicolás Quiroz 53

Page 54: USB curso y potencia

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

Nicolás Quiroz 54

Page 55: USB curso y potencia

usb_put_packet(endpoint, data, len, tgl)

usb_put_packet(1, data, 1, USB_DTS_TOGGLE);

endpoint-> 1, EP1 a la pC

data-> dirección del búfer de datos

len -> cuandos se envian en bytes

tgl -> USB_DTS_TOGGLE

Nicolás Quiroz 55

Page 56: USB curso y potencia

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, //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, puede ser el 0x0011

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

};

Nicolás Quiroz 56

Page 57: USB curso y potencia

Código en el PICvoid main(void) {

int8 datos[3]; //declaramos variables

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

while (TRUE)

{ if(usb_enumerated()) //si el PicUSB está configurado

{

if (usb_kbhit(1)) //si el endpoint contiene datos del host

{

usb_get_packet(1, datos, 1); //obtiene el paquete de tamaño 1 bytes del EP1

//y almacenamos en datos

if (datos[0] == 0)

{ output_low(PIN_B7); // Apaga led

}

if (datos[0] == 1) // Modo_Led

{ output_high(PIN_B7); //// Enciende led

}

}

}

}

}

Nicolás Quiroz 57

Page 58: USB curso y potencia

Elementos de potencia

MC Nicolás Quiroz

Page 59: USB curso y potencia

Circuito para disparar un Relé

Nicolás Quiroz 59

Page 60: USB curso y potencia

SEVEN DARLINGTON ARRAYS

ULN2001A-ULN2002A

ULN2003A-ULN2004A

SEVEN DARLINGTONS PER PACKAGE OUTPUT CURRENT

500mA PER DRIVER (600mA PEAK) .

OUTPUT VOLTAGE 50V

INTEGRATED SUPPRESSION DIODES FOR INDUCTIVE

LOADS

OUTPUTS CAN BE PARALLELED FOR HIGHER CURRENT

TTL/CMOS/PMOS/DTL COMPATIBLE INPUTS

INPUTS PINNED OPPOSITE OUTPUTS TO SIMPLIFY LAYOUT

Nicolás Quiroz 60

Page 61: USB curso y potencia

SEVEN DARLINGTON ARRAYS

ULN2001A-ULN2002A

ULN2003A-ULN2004A

Nicolás Quiroz 61

Page 62: USB curso y potencia

Typical application

Lamp

Nicolás Quiroz 62

Typical application

Motor

Page 63: USB curso y potencia

EIGHT DARLINGTON ARRAYS

ULN2801A, ULN2804A - ULN2805A

ULN2802A - ULN2803A

EIGHTDARLINGTONS WITH COMMON EMITTERS

OUTPUT CURRENT TO 500 mA

OUTPUT VOLTAGE TO 50 V

INTEGRAL SUPPRESSIONDIODES VERSIONS FOR ALL

POPULARLOGIC FAMILIES

OUTPUT CAN BE PARALLELED INPUTS PINNED OPPOSITE

OUTPUTS TO SIMPLIFY BOARD LAYOUT

Nicolás Quiroz 63

Page 64: USB curso y potencia

Puente H

Dirección de motor de DC

Nicolás Quiroz 64

Page 65: USB curso y potencia

Quadruple Half H 4 drivers

L293, L293D, L298(2 amp)

Wide Supply-Voltage Range: 4.5 V to 36 V

Separate Input-Logic Supply

Internal ESD Protection

Thermal Shutdown

Output Current 1 A Per Channel (600 mA for L293D)

Peak Output Current 2 A Per Channel (1.2 A for L293D)

Output Clamp Diodes for Inductive Transient Suppression (L293D)

Nicolás Quiroz 65

Page 66: USB curso y potencia

Manejo de motores L293

Nicolás Quiroz 66

VCC1 Señal TTL (5V) o voltaje de control.

VCC2 Voltaje de alimentación del motor

(5V, 12V, etc.)

Terminales 1 y 9 habilitación de los drivers.

Terminales 2,7,15, y 10 señales de control.

Page 67: USB curso y potencia

Bidirectional DC Motor Control

Nicolás Quiroz 67

Page 68: USB curso y potencia

Motores a pasos

•Motores de reluctancia variable

•Motores de imán permanente - unipolares- bipolares

•Motores multifases

Page 69: USB curso y potencia

Diagrama de las bobinas de un motor a pasos

Nicolás Quiroz 69

Page 70: USB curso y potencia

Unipolar pasos

(wave drive)

Nicolás Quiroz 70

Paso A B C D

1 1 0 0 0

2 0 1 0 0

3 0 0 1 0

4 0 0 0 1

Paso simple:

Esta secuencia de pasos es la mas

simple de todas y consiste en activar

cada bobina una a una y por

separado, con esta secuencia de

encendido de bobinas no se obtiene

mucha fuerza ya que solo es una

bobina cada vez la que arrastra y

sujeta el rotor del eje del motor.

Page 71: USB curso y potencia

Bipolar Stepping-Motor Control

Nicolás Quiroz 71