58
UNIVERSIDAD TECNOLOGICA NACIONAL FACULTAD REGIONAL SAN NICOLAS INGENIERIA EN ELECTRONICA PROBLEMA DE INGENIERÍA TECNICAS DIGITALES III ADQUISIDOR GENÉRICO USB Integrantes: Chiodín Sebastián Fernández Torres Walter Docentes: - Profesor: Poblete Felipe - Auxiliar: González Mariano AÑO 2008

UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

  • Upload
    dangque

  • View
    220

  • Download
    1

Embed Size (px)

Citation preview

Page 1: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

UNIVERSIDAD TECNOLOGICA NACIONAL FACULTAD REGIONAL SAN NICOLAS

INGENIERIA EN ELECTRONICA

PROBLEMA DE INGENIERÍA

TECNICAS DIGITALES III

ADQUISIDOR GENÉRICO USB

Integrantes:

Chiodín Sebastián Fernández Torres Walter

Docentes:

- Profesor: Poblete Felipe - Auxiliar: González Mariano

AÑO 2008

Page 2: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

2

INDICE

OBJETIVOS DEL TRABAJO 3 MATERIAS INTEGRADAS......................................................................................................... 3 POSIBLES APLICACIONES........................................................................................................ 3 PROFESORES ENTREVISTADOS..............................................................................................3 BIBLIOGRAFÍA...........................................................................................................................3

DESARROLLO 4 INTRODUCCIÓN.........................................................................................................................4 TEORÍA DE FUNCIONAMIENTO ..............................................................................................9 DIAGRAMA EN BLOQUES ........................................................................................................ 9 INTERFAZ USB..........................................................................................................................11 PROGRAMACIÓN DEL MICROCONTROLADOR................................................................... 12 RESULTADOS DE LAS PRUEBAS ...........................................................................................13 CONCLUSIONES........................................................................................................................13

ANEXOS: 14 LISTADOS DE PROGRAMAS ................................................................................................... 14 CIRCUITO................................................................................................................................... 55 FOTOS DEL PROTOTIPO .......................................................................................................... 56 IMÁGENES DEL PROGRAMADOR..........................................................................................56 FOTOS DE PANTALLA ............................................................................................................. 57

Page 3: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

3

OBJETIVOS DEL TRABAJO Se pretende el diseño de un dispositivo que permita la adquisición de datos en una PC a

través del puerto USB y una precisión de 0.1% (10 bits) para variables analógicas. Estos datos

pueden ser de diversa índole, ya sean digitales o analógicos. La entradas digitales y analógicas que

usaremos serán: 0-5v (ttl) y 0-5v respectivamente. La salida digital será dada por el ttl.

MATERIAS INTEGRADAS

• Medidas Electrónicas II • Instrumentación. • Máquinas eléctricas. • Comunicaciones II

POSIBLES APLICACIONES

Las posibles aplicaciones del proyecto son prácticamente inmediatas, debido a que uno

de los principales roles que juega la Ingeniería Electrónica en la actualidad es principalmente la

adquisición y procesamiento de datos en una gran cantidad de procesos tales como Industriales,

Financieros, Biológicos, Sociales, etc.

PROFESORES ENTREVISTADOS

• Ing. Víctor Culasso (Características del conversor A/D) • Ing. Néstor Chiodin (Aplicación del adquisidor para motores trifásicos). • Ing. Sebastián Shaller (Comparación de USB frente a protocolos de RED).

BIBLIOGRAFÍA

• Apuntes de cátedra. • Apunte 3,”Programación de ensamblador” – Ing. Felipe Poblete

• Sitios de Internet.

• Microsoft MSDN, http://msdn.microsoft.com/es-es/default.aspx • Sitio Oficial Universal Serial Bus (USB), www.usb.org • Sitio Oficial de Microchip, www.microchip.com

• Chris H. Pappas, William H. Murray, “Manual de referencia Visual C++ .NET”, Mc. Graw Hill 2003. • Andrew S. Tanenbaum, “Organización de computadoras, un enfoque estructurado”, Pearson Education 2000.

Page 4: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

4

DESARROLLO

INTRODUCCIÓN

USB es una especificación de las empresas Compaq, Intel, Microsoft y NEC, que describe un canal serie que soporta una gran variedad de periféricos de media y baja velocidad, con soporte integral para transferencias en tiempo real (isócronas) como voz, audio y vídeo comprimido, y que permite mezclar dispositivos y aplicaciones isócronas y asíncronas. Por lo tanto, entre los dispositivos USB más característicos se pueden citar teclados, ratones, joysticks, tabletas gráficas, monitores, módems, impresoras, escáneres, CD-ROMs, dispositivos de audio (como micrófonos o altavoces digitales), cámaras digitales y otros dispositivos multimedia.

Posee las siguientes características:

Un acceso al bus gestionado directamente por el Controlador USB, para permitir transferencias isócronas y eliminar los tiempos de arbitración.

Una velocidad de 12 Mbps (Full Speed o FS) y un subcanal de 1,5 Mbps (Low Speed o LS) para los dispositivos más lentos, como ratones y joysticks.

Una conectividad excepcional, ya que puede manejar hasta 127 dispositivos simultáneamente que se pueden conectar y desconectar en caliente, sin tener que reiniciar el sistema.

Una configuración automática de dispositivos, que elimina la necesidad de realizar configuraciones manuales por medio de puentes o conmutadores.

La coexistencia de dispositivos isócronos y asíncronos. Los dispositivos isócronos se atienden en función del ancho de banda y latencia requeridos, y los asíncronos se atienden durante el tiempo restante no consumido por los dispositivos isócronos.

Una distribución de alimentación desde el Controlador USB, que permite la conexión tanto de dispositivos alimentados desde el bus como autoalimentados.

Una arquitectura fácilmente escalable para permitir la existencia de varios Controladores USB en un sistema. NIVEL FISICO

A nivel físico, USB utiliza un cable de 4 conductores para transmitir una señal diferencial (D+ y D-) y alimentación (VBus = 5V y GND) por medio de conexiones punto a punto. Los dispositivos LS van obligatoriamente equipados con un cable de longitud adecuada (hasta unos 3 m, dependiendo de sus características eléctricas), mientras que los FS pueden ir equipados con un cable o utilizar cables independientes de hasta 5 m (también dependiendo de sus características eléctricas).

Los dispositivos disponen de un transmisor diferencial, receptores diferencial y S/E y resistencias de terminación con los que pueden transmitir y detectar varios estados eléctricos distintos en la línea: Amplio catálogo de modernos periféricos: ratones, teclados, escáneres, cámaras fotográficas, capturadoras TV, monitores, discos duros, otro PC, etc. Posee las siguientes características:

El periférico puede alimentarse de este puerto, por lo que si no gasta mucho, no necesita fuente de alimentación (cuidado, los vatios no son infinitos).

Se necesitan menos componentes, por lo que los periféricos deben ser más baratos.

Page 5: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

5

Facilita la compatibilidad entre Mac y PC. Podemos conectar un gran número de periféricos a un sólo PC (en teoría 127 por puerto) que

por otros medios sería imposible por las limitaciones de IRQs.

TIPOS DE TRANSFERENCIAS DE DATOS USB soporta 4 tipos de transferencias de datos: Transferencias de Control

Se desarrollan en 3 Transacciones: Transacción de Configuración (Setup), en la que se envía al dispositivo un paquete que

especifica la operación a ejecutar. Ocupa 8 bytes. Cero o más Transacciones de Datos, en las que se transfieren los paquetes de datos en el

sentido indicado por la Transacción de Configuración. La información útil por paquete puede ser de 8, 16, 32 ó 64 bytes para endpoints FS, y de 8 bytes para Endpoints LS.

Transacción de Estado, en la que el receptor informa del estado final de la operación. Se procesan por medio de un mecanismo "best effort", según el cual el Controlador USB las

va procesando en función del tiempo disponible en cada Trama. Como mínimo se reserva el 10% del tiempo de Trama, y se puede utilizar tiempo adicional siempre que las necesidades de los tráficos isócrono y de interrupción lo permitan.

Incorporan mecanismos de detección de errores (CRC) y de recuperación/retransmisión de datos.

Transferencias Isócronas

Sólo son utilizables por dispositivos FS. La información útil por paquete puede oscilar entre 1 y 1,023 bytes. En cada Trama se transfiere un paquete por cada conexión isócrona establecida. El sistema puede asignar como máximo el 90% del tiempo de Trama para transferencias

isócronas y de interrupción. Si el sistema ya tiene asignado un tiempo de Trama de forma que no garantiza tiempo suficiente como para manejar una nueva conexión isócrona (transmitir un nuevo paquete por Trama), simplemente no se establece la conexión.

Los posibles errores no se recuperan (la información que no llega a su tiempo, se descarta). Transferencias de Interrupción

Aseguran una transacción (paquete) dentro de un periodo máximo (los dispositivos FS pueden solicitar entre 1 y 255 ms, y los LS entre 10 y 255 ms de periodo máximo de servicio).

Incorpora detección de errores y retransmisión de datos. La información útil por paquete puede oscilar entre 1 y 64 bytes para dispositivos FS y entre

1 y 8 bytes para dispositivos LS. El sistema puede asignar como máximo el 90% del tiempo de Trama para transferencias

isócronas y de interrupción. Si el sistema no puede garantizar tiempo suficiente como para manejar una nueva conexión de interrupción (transmitir un nuevo paquete dentro del periodo máximo requerido), simplemente no se establece la conexión.

Page 6: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

6

Transferencias Bulk

Sólo son utilizables por dispositivos FS. Se procesan por medio de un mecanismo "good effort", en el que el sistema aprovecha

cualquier ancho de banda disponible y en el momento en que esté disponible (en otras palabras, no se garantiza una latencia ni un ancho de banda mínimos). Se puede utilizar el tiempo de Trama reservado y no consumido por transferencias de Control

(10%). Incorporan mecanismos de control de errores para garantizar la entrega de datos. La información útil por paquete puede ser de 8, 16, 32 ó 64 bytes.

DESCRIPTORES

Desde el punto de vista del sistema USB, un dispositivo puede tener varias posibles Configuraciones, en cada una de las cuales el dispositivo puede funcionar de una manera distinta. En cada una de las posibles Configuraciones, el dispositivo queda organizado como un conjunto de Interfaces, donde cada Interfaz especifica qué partes del hardware del dispositivo interactúa con el sistema USB. Cada una de esas partes de hardware se denomina Endpoint. Entonces, de una manera jerárquica, un dispositivo es una colección de posibles Configuraciones, cada Configuración es una colección de Interfaces, y cada Interfaz es una colección de Endpoints. A su vez los Interfaces pueden admitir configuraciones alternativas, con distintas colecciones de Endpoints en cada una de ellas.

Los dispositivos proporcionan toda la información descriptiva al sistema a través de unas estructuras de datos denominados Descriptores. Existen distintos descriptores que proporcionan información a nivel de dispositivo, de configuración, de interfaz y de endpoint.

Las especificaciones de Clase USB definen las configuraciones, interfaces (y sus configuraciones alternativas) y endpoints que los dispositivos pertenecientes a dicha Clase o Subclase deben soportar.

A continuación se detalla el esquema de los descriptores quien emplea el PIC18F4550 en su mapa de memoria.

Page 7: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

7

CLASES, SUBCLASES Y PROTOCOLOS

Los descriptores de dispositivo y de interfaz contienen una serie de campos que permiten al sistema clasificar a los dispositivos. Estos campos son la Clase, la Subclase y el Protocolo.

El Sistema Operativo puede utilizar estos campos para localizar y asociar al dispositivo o interfaz un determinado Driver de Clase, de entre todos los Drivers de esa Clase disponibles en el sistema. También puede seleccionar una determinada configuración del dispositivo, o una determinada configuración alternativa de un interfaz, en función de los protocolos soportados por los distintos Drivers de Clase disponibles en el sistema para esa Clase y Subclase de dispositivo. CAPAS DE USB

Page 8: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

8

La funcionalidad de los dispositivos USB se halla estructurada en un marco de capas. Cada nivel se asocia con un nivel funcional dentro del dispositivo. La capa más alta, excepto el dispositivo, es de configuración. Un dispositivo puede tener múltiples configuraciones. Por ejemplo, un particular dispositivo puede tener múltiples requisitos de alimentación basado en auto alimentación. Para cada configuración, puede haber múltiples interfaces. Cada interfaz podría apoyar un particular de modo de la configuración. Debajo de la interfaz es el Endpoint (s). Los datos son directamente trasladados a este nivel. No puede haber más de 16. El endpoint 0 siempre es un enpoint de control y por defecto, cuando el dispositivo está en el bus, el endpoint 0 debe estar disponibles para configurar el dispositivo. CARACTERÍSTICAS DE DISTINTAS INTERFACES

Puerto serie y puerto paralelo

Uno de los defectos de los puertos serie iníciales era su lentitud en comparación con los puertos paralelos, hablamos de 19.2 kbits por segundo, sin embargo, con el paso del tiempo, están apareciendo multitud de puertos serie de alta velocidad que los hacen muy interesantes ya que utilizan las ventajas del menor cableado y solucionan el problema de la velocidad con un mayor apantallamiento y más barato usando la técnica del par trenzado. Por ello, el puerto RS-232 e incluso multitud de puertos paralelos están siendo reemplazados por nuevos puertos serie como el USB

TCP/IP

La arquitectura de un sistema en TCP/IP tiene una serie de metas:

La independencia de la tecnología usada en la conexión a bajo nivel y la arquitectura del ordenador

Conectividad Universal a través de la red Reconocimientos de extremo a extremo Protocolos estandarizados

Comparándolo con USB destacamos los siguientes aspectos

Tiene Mayor velocidad de transmisión de datos que USB. Más difícil de configurar. Es más caro. Requiere de conocimientos de programación más elevados en cuanto al manejo de las

tramas y capas.

Page 9: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

9

BENEFICIOS DE USB

Interface para muchas aplicaciones Autoconfiguración No requiere suministro propio de energía Conexión y desconexión Plug & Play Alguas configuraciones no necesita drivers particulares, por ejemplo dispositivo HID. Fácil uso Amplio código y espacio de datos para las aplicaciones complejas

TEORÍA DE FUNCIONAMIENTO

El dispositivo opera como HID (Human Interface Device) por lo que no requiere drivers externos, sino que emplea los mismos archivos de sistema de Windows Para realizar la conexión (Pipe) entre la aplicación. La única desventaja que conlleva emplear el dispositivo como HID es la disminución de velocidad de comunicación a un máximo de 512Kb/Seg.

Además una ventaja muy importante en lo que respecta haber elegido este tipo de interface para resolver este problema de ingeniería fue el manejo de la tecnología mediante un lenguaje de programación conocido (visual C++).

DIAGRAMA EN BLOQUES

A continuación se detallan los elementos que componen el adquisidor.

Fig. 1

SISTEMA DE CONTROL

SOFTWARE

SALIDA DIGITAL

SEÑAL ANALÓGICA

ENTRADA DIGITAL

PC

INTERFRAZ USB

Page 10: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

10

Descripción del diagrama en bloques

Señal Analógica: Es la señal de entrada proveniente del mundo real, puede ser tensión

corriente, etc.

Entrada Digital: Dicha fase corresponde al ingreso de señales binarias al adquisidor.

Salida Digital: La presente etapa, indicará a través de una columna de diodos LEDS los

valores enviados desde la PC hacia el dispositivo USB.

Sistema de Control: Es el componente principal del hardware, su función radica en leer la

señal analógica y convertirla a binario, así como censar la entrada digital. De este modo,

envía los datos binarios a la PC a través de la interfaz USB. Así mismo puede exhibir datos

provenientes de la PC en la columna de LEDS. Se empleará el microcontrolador

PIC18F4550, el cual posee conversor Analógico / Digital, así como puertos de conexión

USB, debido a que de otra manera se debería usar otro chip mas para la interfaz USB.

Pudiendo así poder unir estos bloques de control e interfaz y lograr simplicidad en el

proyecto.

Interfaz USB: Corresponde al puente de comunicación entre la PC y el Hardware, se halla

integrada dentro del microcontrolador en el sistema de control.

PC: Constituye uno de los aspectos principales del sistema, es la encargada de comunicarse

con el Hardware ya sea enviando o recibiendo datos.

Software: Como ya mencionamos anteriormente se refiere al programa que permita el

proceso de comunicación entre la PC y el dispositivo USB.

Page 11: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

11

INTERFAZ USB

A continuación se detalla una breve explicación del funcionamiento de la interfaz USB incorporada en el dispositivo PIC18F4550.

La familia de dispositivos PIC18FX455/X550 contiene un motor de interfaz USB (SIE) compatible para conexión en alta velocidad y baja velocidad.

El SIE puede ser conector directamente al conector USB de la PC, utilizando el

transreceptor interno, o puede ser conectado por un transreceptor externo. Un regulador interno de 3.3V está también disponible para alimentar el transreceptor interno.

Algunos rasgos de hardware especiales han sido incluidos para mejorar el funcionamiento.

La memoria de puerto dual ha sido suministrada para compartir el acceso de memoria directo entre el microcontrolador y el SIE. También proporcionan descriptores de los buffer, permitiendo a usuarios programar libremente el uso de memoria para los Endpoints en la RAM destinada al bus USB. Además se ha proporcionado un puerto paralelo para permitir la transferencia ininterrumpida de grandes volúmenes de información, tales como la transferencia isócrona hacia o desde Buffers de memoria Externos.

Page 12: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

12

PROGRAMACIÓN DEL MICROCONTROLADOR

En la programación del presente dispositivo se ha modificado y adaptado el FrameWork provisto por Microchip para el tratamiento de enlace USB a través de la configuración en modo HID (Human Interface Device). Dicho código es freeware y se puede descargar del sitio www.microchip.com

El presente Firmware emplea elementos avanzados de programación y compilación

condicional, por lo cual ha sido uno de los factores de más ardua realización en el desarrollo del Problema de Ingeniería.

El programa principal inicializa la configuración de puertos y demás dispositivos con la función InitializeSystem() (Véase Página 40). El cuerpo principal opera como un bucle que se ejecuta indefinidamente con dos funciones dentro del mismo: USBDeviceTasks() y ProcessIO()(Véase Páginas 39 y 40).

USBDeviceTasks() procesa los pedidos del sistema de interrupciones y transferencias de control entre la PC y el dispositivo USB. ProcessIO() (Véase Páginas 43y 44) es encargada de procesar las entradas y las salidas a través de USB, dicha función ha sido adaptada con una tabla de códigos para realizar el proceso de Hand-Shake entre la PC y el microcontrolador.

Diagrama de Flujo Simplificado del Firmware

Inicio

Configurar PLL interno Configuración Puertos Puerto D Salida Puerto B entrada Configurar Conversor A/D

Código de atención Interrupción conversor

Analógico Digital (Pag. 38, YourLowPriorityISRCode())

Procesamiento de E/S [ProcessIO()] Atención trasferencias de control e

interrupciones USB [USBDeviceTasks()]

Page 13: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

13

RESULTADOS DE LAS PRUEBAS

Los resultados de la pruebas han sido satisfactorios desde todo punto de vista, debido a que el adquisidor opera prácticamente en cualquier sistema operativo Windows sin necesidad de “Driver Particulares” al estar configurado como dispositivo HID.

Sin embargo no fue un proceso de desarrollo directo, sino que hubo que solucionar varios inconvenientes tales como frecuencia de sincronismo del sistema, desarrollo de las tablas de Hand-Shake, entre otros.

CONCLUSIONES

Tras desarrollar, en un lapso de tiempo comprendido desde el mes de Mayo hasta Noviembre del presente año, el “Problema de Ingeniería” referente al “Adquisidor genérico USB”, hemos incorporado un amplio espectro de conocimientos relacionados con el Protocolo USB, Programación de las nuevas familias de Microcontroladores de Microchip, manejo del lenguaje Visual C++ y .NET Framework.

Además se ha hecho hincapié en el trabajo grupal como herramienta integradora, permitiendo así obtener un panorama de las metodologías de trabajo grupal empleadas hoy en día a través de equipos de desarrollo.

Page 14: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

14

ANEXOS:

LISTADOS DE PROGRAMAS

Creación del vínculo de interfaz con el dispositivo

A continuación se detalla la implementación del fragmento de código en Visual C++ para poder inicializar el vínculo con el dispositivo. Para este fin empleamos las funciones de los archivos de sistema “Setupapi.dll”, las llamadas a las funciones se han obtenido del sitio oficial de MSDN. //Aplicación de los DLL //Gives us "PSP_DEVICE_INTERFACE_DATA" which contains the Interface specific GUID (different //from class GUID). We need the interface GUID to get the device path. [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiEnumDeviceInterfaces")] extern "C" WINSETUPAPI BOOL WINAPI SetupDiEnumDeviceInterfacesUM( HDEVINFO DeviceInfoSet, //Input: Give it the HDEVINFO we got from SetupDiGetClassDevs() PSP_DEVINFO_DATA DeviceInfoData, //Input (optional) LPGUID InterfaceClassGuid, //Input DWORD MemberIndex, //Input: "Index" of the device you are interested in getting the path for. PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData);//Output: This function fills in an "SP_DEVICE_INTERFACE_DATA" structure. //SetupDiDestroyDeviceInfoList() frees up memory by destroying a DeviceInfoList [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiDestroyDeviceInfoList")] extern "C" WINSETUPAPI BOOL WINAPI SetupDiDestroyDeviceInfoListUM( HDEVINFO DeviceInfoSet); //Input: Give it a handle to a device info list to deallocate from RAM. //SetupDiEnumDeviceInfo() fills in an "SP_DEVINFO_DATA" structure, which we need for SetupDiGetDeviceRegistryProperty() [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiEnumDeviceInfo")] extern "C" WINSETUPAPI BOOL WINAPI SetupDiEnumDeviceInfoUM( HDEVINFO DeviceInfoSet, DWORD MemberIndex, PSP_DEVINFO_DATA DeviceInfoData); //SetupDiGetDeviceRegistryProperty() gives us the hardware ID, which we use to check to see if it has matching VID/PID [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiGetDeviceRegistryProperty")] extern "C" WINSETUPAPI BOOL WINAPI SetupDiGetDeviceRegistryPropertyUM( HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, DWORD Property, PDWORD PropertyRegDataType, PBYTE PropertyBuffer, DWORD PropertyBufferSize, PDWORD RequiredSize); //SetupDiGetDeviceInterfaceDetail() gives us a device path, which is needed before CreateFile() can be used. [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiGetDeviceInterfaceDetail")]

Page 15: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

15

extern "C" BOOL SetupDiGetDeviceInterfaceDetailUM( HDEVINFO DeviceInfoSet, //Input: Wants HDEVINFO which can be obtained from SetupDiGetClassDevs() PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData, //Input: Pointer to an structure which defines the device interface. PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData, //Output: Pointer to a strucutre, which will contain the device path. DWORD DeviceInterfaceDetailDataSize, //Input: Number of bytes to retrieve. PDWORD RequiredSize, //Output (optional): Te number of bytes needed to hold the entire struct PSP_DEVINFO_DATA DeviceInfoData); //Output Subrutina de Vinculo Con el dispositivo private: System::Void tmrTemp_Tick(System::Object^ sender, System::EventArgs^ e) { //Identificadores Globales Guid. GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, 0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30}; HDEVINFO DeviceInfoTable = INVALID_HANDLE_VALUE; PSP_DEVICE_INTERFACE_DATA InterfaceDataStructure = new SP_DEVICE_INTERFACE_DATA; PSP_DEVICE_INTERFACE_DETAIL_DATA DetailedInterfaceDataStructure = new SP_DEVICE_INTERFACE_DETAIL_DATA; SP_DEVINFO_DATA DevInfoData; DWORD InterfaceIndex = 0; DWORD StatusLastError = 0; DWORD dwRegType; DWORD dwRegSize; DWORD StructureSize = 0; PBYTE PropertyValueBuffer; bool MatchFound = false; DWORD ErrorStatus; String^ DeviceIDToFind = MY_DEVICE_ID; //Obtengo la lista de dispositivos DeviceInfoTable = SetupDiGetClassDevsUM(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); //Examino la lista en busqueda de elementos while(true) { InterfaceDataStructure->cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); SetupDiEnumDeviceInterfacesUM(DeviceInfoTable, NULL, &InterfaceClassGuid, InterfaceIndex, InterfaceDataStructure); ErrorStatus = GetLastError(); if(ERROR_NO_MORE_ITEMS == GetLastError()) //Si llegue al ultimo dispositivo, finalizo { //El dispositivo no está conectado SetupDiDestroyDeviceInfoListUM(DeviceInfoTable); //Limpio la estructura que no nece return; } //Obtengo el Hardware ID para ver si es el del dispositivo que busco //Inicializo estructuras auxiliares DevInfoData.cbSize = sizeof(SP_DEVINFO_DATA); SetupDiEnumDeviceInfoUM(DeviceInfoTable, InterfaceIndex, &DevInfoData);

Page 16: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

16

//Pregunto por el tamano del ID SetupDiGetDeviceRegistryPropertyUM(DeviceInfoTable, &DevInfoData, SPDRP_HARDWAREID, &dwRegType, NULL, 0, &dwRegSize); //Almaceno memoria apropiada PropertyValueBuffer = (BYTE *) malloc (dwRegSize); if(PropertyValueBuffer == NULL) //Si es nulo, no puedo almacenar memoria { //Salgo SetupDiDestroyDeviceInfoListUM(DeviceInfoTable); return; } //Retrieve the hardware IDs for the current device we are looking at. PropertyValueBuffer gets filled with a //REG_MULTI_SZ (array of null terminated strings). To find a device, we only care about the very first string in the //buffer, which will be the "device ID". The device ID is a string which contains the VID and PID, in the example //format "Vid_04d8&Pid_003f". SetupDiGetDeviceRegistryPropertyUM(DeviceInfoTable, &DevInfoData, SPDRP_HARDWAREID, &dwRegType, PropertyValueBuffer, dwRegSize, NULL); //Now check if the first string in the hardware ID matches the device ID of my USB device. #ifdef UNICODE String^ DeviceIDFromRegistry = gcnew String((wchar_t *)PropertyValueBuffer); #else String^ DeviceIDFromRegistry = gcnew String((char *)PropertyValueBuffer); #endif //Convert both strings to lower case. This makes the code more robust/portable accross OS Versions DeviceIDFromRegistry = DeviceIDFromRegistry->ToLowerInvariant(); DeviceIDToFind = DeviceIDToFind->ToLowerInvariant(); //Now check if the hardware ID we are looking at contains the correct VID/PID MatchFound = DeviceIDFromRegistry->Contains(DeviceIDToFind); if(MatchFound == true) { DetailedInterfaceDataStructure->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); //Obtengo la Lista de dispositivos SetupDiGetDeviceInterfaceDetailUM(DeviceInfoTable, InterfaceDataStructure, NULL, NULL, &StructureSize, NULL); DetailedInterfaceDataStructure = (PSP_DEVICE_INTERFACE_DETAIL_DATA)(malloc(StructureSize)); //Almacena memoria if(DetailedInterfaceDataStructure == NULL) //Si es nulo { //Salgo. SetupDiDestroyDeviceInfoListUM(DeviceInfoTable); //Limpio la estructura que no se emplea return; } DetailedInterfaceDataStructure->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); //Llamo nuevamente a la función SetupDiGetDeviceInterfaceDetailUM(DeviceInfoTable, InterfaceDataStructure, DetailedInterfaceDataStructure, StructureSize, NULL, NULL); //Almaceno los Handles en Write Handle y readHandle

Page 17: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

17

WriteHandle = CreateFile((DetailedInterfaceDataStructure->DevicePath), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); ErrorStatus = GetLastError(); if(ErrorStatus == ERROR_SUCCESS) ToggleLED_btn->Enabled = true; ReadHandle = CreateFile((DetailedInterfaceDataStructure->DevicePath), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); ErrorStatus = GetLastError(); if(ErrorStatus == ERROR_SUCCESS) { LblEnt->Enabled=true; groupBox1->Enabled=true; LblPot->Enabled=true; b_Encender->Enabled=true; s_usb(v_salida); TmrEnt->Enabled=true; //Habilito el timer de pedido de datos } SetupDiDestroyDeviceInfoListUM(DeviceInfoTable); //Limpio la Estructura que no se emplea return; } InterfaceIndex++; //Barro el Bucle hasta que se encuentre el dispositivo o finalize la lista }//Fin While } Código Completo del programa en Visual C++ Debido a que se ha empleado el método de programación con las librerías CLR (Common Languaje Resourse) de windows, el código principal del programa se halla inmerso en una librería de extensión .h. El nombre del Archivo es Form1.h #pragma once #include <Windows.h> #include <setupapi.h> #include <string.h> #define MY_DEVICE_ID "Vid_04d8&Pid_003F" namespace AquisidorGenericoUSB { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::Runtime::InteropServices; //Need this to support "unmanaged" code. /* In order to use these unmanaged functions from within the managed .NET environment, we need

Page 18: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

18

to explicitly import the functions which we will be using from other .DLL file(s). Simply including the appropriate header files is not enough. Note: In order to avoid potential name conflicts in the header files (which we still use), I have renamed the functions by adding "UM" (unmanaged) onto the end of them. To find documentation for the functions in MSDN, search for the function name without the extra "UM" attached. Note2: In the header files (such as setupapi.h), normally the function names are remapped, depending upon if UNICODE is defined or not. For example, two versions of the function SetupDiGetDeviceInterfaceDetail() exist. One for UNICODE, and one for ANSI. If the wrong version of the function is called, things won't work correctly. Therefore, in order to make sure the correct one gets called (based on your compiler settings, which may or may not define "UNICODE"), it is useful to explicity specify the CharSet when doing the DLL import. */ #ifdef UNICODE #define Seeifdef Unicode #else #define Seeifdef Ansi #endif //Returns a HDEVINFO type for a device information set (USB HID devices in //our case). We will need the HDEVINFO as in input parameter for calling many of //the other SetupDixxx() functions. [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiGetClassDevs")] extern "C" HDEVINFO SetupDiGetClassDevsUM( LPGUID ClassGuid, //Input: Supply the class GUID here. PCTSTR Enumerator, //Input: Use NULL here, not important for our purposes HWND hwndParent, //Input: Use NULL here, not important for our purposes DWORD Flags); //Input: Flags describing what kind of filtering to use. //Gives us "PSP_DEVICE_INTERFACE_DATA" which contains the Interface specific GUID (different //from class GUID). We need the interface GUID to get the device path. [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiEnumDeviceInterfaces")] extern "C" WINSETUPAPI BOOL WINAPI SetupDiEnumDeviceInterfacesUM( HDEVINFO DeviceInfoSet, //Input: Give it the HDEVINFO we got from SetupDiGetClassDevs() PSP_DEVINFO_DATA DeviceInfoData, //Input (optional) LPGUID InterfaceClassGuid, //Input DWORD MemberIndex, //Input: "Index" of the device you are interested in getting the path for. PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData);//Output: This function fills in an "SP_DEVICE_INTERFACE_DATA" structure. //SetupDiDestroyDeviceInfoList() frees up memory by destroying a DeviceInfoList [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiDestroyDeviceInfoList")] extern "C" WINSETUPAPI BOOL WINAPI SetupDiDestroyDeviceInfoListUM( HDEVINFO DeviceInfoSet); //Input: Give it a handle to a device info list to deallocate from RAM.

Page 19: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

19

//SetupDiEnumDeviceInfo() fills in an "SP_DEVINFO_DATA" structure, which we need for SetupDiGetDeviceRegistryProperty() [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiEnumDeviceInfo")] extern "C" WINSETUPAPI BOOL WINAPI SetupDiEnumDeviceInfoUM( HDEVINFO DeviceInfoSet, DWORD MemberIndex, PSP_DEVINFO_DATA DeviceInfoData); //SetupDiGetDeviceRegistryProperty() gives us the hardware ID, which we use to check to see if it has matching VID/PID [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiGetDeviceRegistryProperty")] extern "C" WINSETUPAPI BOOL WINAPI SetupDiGetDeviceRegistryPropertyUM( HDEVINFO DeviceInfoSet, PSP_DEVINFO_DATA DeviceInfoData, DWORD Property, PDWORD PropertyRegDataType, PBYTE PropertyBuffer, DWORD PropertyBufferSize, PDWORD RequiredSize); //SetupDiGetDeviceInterfaceDetail() gives us a device path, which is needed before CreateFile() can be used. [DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiGetDeviceInterfaceDetail")] extern "C" BOOL SetupDiGetDeviceInterfaceDetailUM( HDEVINFO DeviceInfoSet, //Input: Wants HDEVINFO which can be obtained from SetupDiGetClassDevs() PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData, //Input: Pointer to an structure which defines the device interface. PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData, //Output: Pointer to a strucutre, which will contain the device path. DWORD DeviceInterfaceDetailDataSize, //Input: Number of bytes to retrieve. PDWORD RequiredSize, //Output (optional): Te number of bytes needed to hold the entire struct PSP_DEVINFO_DATA DeviceInfoData); //Output // Variables that need to have wide scope. HANDLE WriteHandle = INVALID_HANDLE_VALUE; //Need to get a write "handle" to our device before we can write to it. HANDLE ReadHandle = INVALID_HANDLE_VALUE; //Need to get a read "handle" to our device before we can read from it. /// <summary> /// Summary for Form1 /// /// WARNING: If you change the name of this class, you will need to change the /// 'Resource File Name' property for the managed resource compiler tool /// associated with all .resx files this class depends on. Otherwise, /// the designers will not be able to interact properly with localized /// resources associated with this form. /// </summary> public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // }

Page 20: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

20

protected: /// <summary> /// Clean up any resources being used. /// </summary> ~Form1() { if (components) { delete components; } } private: System::Windows::Forms::Button^ ToggleLED_btn; private: System::Windows::Forms::Label^ LblEnt; private: System::Windows::Forms::GroupBox^ groupBox1; private: System::Windows::Forms::Button^ button8; private: System::Windows::Forms::Button^ button7; private: System::Windows::Forms::Button^ button6; private: System::Windows::Forms::Button^ button5; private: System::Windows::Forms::Button^ button4; private: System::Windows::Forms::Button^ button3; private: System::Windows::Forms::Button^ button2; private: System::Windows::Forms::Button^ button1; private: System::Windows::Forms::TextBox^ txtnum; private: unsigned char v_salida; //Valor de la salida de los LEDS private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::Timer^ tmrTemp; private: System::Windows::Forms::Button^ b_Encender; private: System::Windows::Forms::ProgressBar^ BPot; private: System::Windows::Forms::Label^ LblPot; private: System::Windows::Forms::Timer^ TmrEnt; private: System::Windows::Forms::GroupBox^ groupBox2; private: System::Windows::Forms::Label^ label8; private: System::Windows::Forms::PictureBox^ pictureBox8; private: System::Windows::Forms::Label^ label7; private: System::Windows::Forms::PictureBox^ pictureBox7; private: System::Windows::Forms::Label^ label6; private: System::Windows::Forms::PictureBox^ pictureBox6; private: System::Windows::Forms::Label^ label5; private: System::Windows::Forms::PictureBox^ pictureBox5; private: System::Windows::Forms::Label^ label4; private: System::Windows::Forms::PictureBox^ pictureBox4; private: System::Windows::Forms::Label^ label3; private: System::Windows::Forms::PictureBox^ pictureBox3; private: System::Windows::Forms::Label^ label2; private: System::Windows::Forms::PictureBox^ pictureBox2; private: System::Windows::Forms::Label^ label9; private: System::Windows::Forms::PictureBox^ pictureBox1; private: System::Windows::Forms::MenuStrip^ menuStrip1; private: System::Windows::Forms::ToolStripMenuItem^ archivoToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ ayudaToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ acercaDeToolStripMenuItem; private: System::Windows::Forms::ToolStripMenuItem^ salirToolStripMenuItem; private: System::ComponentModel::IContainer^ components; private: void s_usb(unsigned char val){ unsigned char num; unsigned char BufferSalida[65];

Page 21: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

21

DWORD BytesWritten = 0; //Variable que emplea la función Write File //Preparo el Buffer Para la Transmisión BufferSalida[0] = 0; //Se debe inicializar en 0 por protocolo USB BufferSalida[1] = 0x0A; //0x0A es el código que indica salida a LEDS //El firmware debe tratar apropiadamente dicho código BufferSalida[2] = val; //Cargo el dato a mostrar WriteFile(WriteHandle, &BufferSalida, 65, &BytesWritten, 0); } protected: protected: private: /// <summary> /// Required designer variable. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid)); this->ToggleLED_btn = (gcnew System::Windows::Forms::Button()); this->LblEnt = (gcnew System::Windows::Forms::Label()); this->groupBox1 = (gcnew System::Windows::Forms::GroupBox()); this->button8 = (gcnew System::Windows::Forms::Button()); this->button7 = (gcnew System::Windows::Forms::Button()); this->button6 = (gcnew System::Windows::Forms::Button()); this->button5 = (gcnew System::Windows::Forms::Button()); this->button4 = (gcnew System::Windows::Forms::Button()); this->button3 = (gcnew System::Windows::Forms::Button()); this->button2 = (gcnew System::Windows::Forms::Button()); this->button1 = (gcnew System::Windows::Forms::Button()); this->txtnum = (gcnew System::Windows::Forms::TextBox()); this->label1 = (gcnew System::Windows::Forms::Label()); this->tmrTemp = (gcnew System::Windows::Forms::Timer(this->components)); this->b_Encender = (gcnew System::Windows::Forms::Button()); this->BPot = (gcnew System::Windows::Forms::ProgressBar()); this->LblPot = (gcnew System::Windows::Forms::Label()); this->TmrEnt = (gcnew System::Windows::Forms::Timer(this->components)); this->groupBox2 = (gcnew System::Windows::Forms::GroupBox()); this->label8 = (gcnew System::Windows::Forms::Label()); this->pictureBox8 = (gcnew System::Windows::Forms::PictureBox()); this->label7 = (gcnew System::Windows::Forms::Label()); this->pictureBox7 = (gcnew System::Windows::Forms::PictureBox()); this->label6 = (gcnew System::Windows::Forms::Label()); this->pictureBox6 = (gcnew System::Windows::Forms::PictureBox()); this->label5 = (gcnew System::Windows::Forms::Label()); this->pictureBox5 = (gcnew System::Windows::Forms::PictureBox()); this->label4 = (gcnew System::Windows::Forms::Label()); this->pictureBox4 = (gcnew System::Windows::Forms::PictureBox());

Page 22: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

22

this->label3 = (gcnew System::Windows::Forms::Label()); this->pictureBox3 = (gcnew System::Windows::Forms::PictureBox()); this->label2 = (gcnew System::Windows::Forms::Label()); this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox()); this->label9 = (gcnew System::Windows::Forms::Label()); this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); this->archivoToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->salirToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->ayudaToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->acercaDeToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->groupBox1->SuspendLayout(); this->groupBox2->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox8))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox7))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox6))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox5))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox4))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox3))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox2))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->BeginInit(); this->menuStrip1->SuspendLayout(); this->SuspendLayout(); // // ToggleLED_btn // this->ToggleLED_btn->Enabled = false; this->ToggleLED_btn->Location = System::Drawing::Point(21, 38); this->ToggleLED_btn->Name = L"ToggleLED_btn"; this->ToggleLED_btn->Size = System::Drawing::Size(150, 38); this->ToggleLED_btn->TabIndex = 1; this->ToggleLED_btn->Text = L"Apagar LEDS"; this->ToggleLED_btn->UseVisualStyleBackColor = true; this->ToggleLED_btn->Click += gcnew System::EventHandler(this, &Form1::ToggleLED_btn_Click); // // LblEnt // this->LblEnt->AutoSize = true; this->LblEnt->Enabled = false; this->LblEnt->Location = System::Drawing::Point(274, 278); this->LblEnt->Name = L"LblEnt"; this->LblEnt->Size = System::Drawing::Size(192, 17); this->LblEnt->TabIndex = 3; this->LblEnt->Text = L"Estado de la Entrada Digital: "; // // groupBox1 // this->groupBox1->Controls->Add(this->button8); this->groupBox1->Controls->Add(this->button7); this->groupBox1->Controls->Add(this->button6); this->groupBox1->Controls->Add(this->button5); this->groupBox1->Controls->Add(this->button4); this->groupBox1->Controls->Add(this->button3); this->groupBox1->Controls->Add(this->button2); this->groupBox1->Controls->Add(this->button1);

Page 23: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

23

this->groupBox1->Enabled = false; this->groupBox1->Location = System::Drawing::Point(120, 94); this->groupBox1->Name = L"groupBox1"; this->groupBox1->Size = System::Drawing::Size(319, 140); this->groupBox1->TabIndex = 6; this->groupBox1->TabStop = false; this->groupBox1->Text = L"Manejo de Salida"; this->groupBox1->Enter += gcnew System::EventHandler(this, &Form1::groupBox1_Enter); // // button8 // this->button8->Location = System::Drawing::Point(240, 37); this->button8->Name = L"button8"; this->button8->Size = System::Drawing::Size(72, 38); this->button8->TabIndex = 13; this->button8->Text = L"LED 4"; this->button8->UseVisualStyleBackColor = true; this->button8->Click += gcnew System::EventHandler(this, &Form1::C_LED); // // button7 // this->button7->Location = System::Drawing::Point(84, 37); this->button7->Name = L"button7"; this->button7->Size = System::Drawing::Size(72, 38); this->button7->TabIndex = 12; this->button7->Text = L"LED 2"; this->button7->UseVisualStyleBackColor = true; this->button7->Click += gcnew System::EventHandler(this, &Form1::C_LED); // // button6 // this->button6->Location = System::Drawing::Point(162, 84); this->button6->Name = L"button6"; this->button6->Size = System::Drawing::Size(72, 38); this->button6->TabIndex = 11; this->button6->Text = L"LED 7"; this->button6->UseVisualStyleBackColor = true; this->button6->Click += gcnew System::EventHandler(this, &Form1::C_LED); // // button5 // this->button5->Location = System::Drawing::Point(84, 84); this->button5->Name = L"button5"; this->button5->Size = System::Drawing::Size(72, 38); this->button5->TabIndex = 10; this->button5->Text = L"LED 6"; this->button5->UseVisualStyleBackColor = true; this->button5->Click += gcnew System::EventHandler(this, &Form1::C_LED); // // button4 // this->button4->Location = System::Drawing::Point(162, 37); this->button4->Name = L"button4"; this->button4->Size = System::Drawing::Size(72, 38); this->button4->TabIndex = 9; this->button4->Text = L"LED 3"; this->button4->UseVisualStyleBackColor = true; this->button4->Click += gcnew System::EventHandler(this, &Form1::C_LED); // // button3 // this->button3->Location = System::Drawing::Point(240, 84);

Page 24: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

24

this->button3->Name = L"button3"; this->button3->Size = System::Drawing::Size(72, 38); this->button3->TabIndex = 8; this->button3->Text = L"LED 8"; this->button3->UseVisualStyleBackColor = true; this->button3->Click += gcnew System::EventHandler(this, &Form1::C_LED); // // button2 // this->button2->Location = System::Drawing::Point(6, 84); this->button2->Name = L"button2"; this->button2->Size = System::Drawing::Size(72, 38); this->button2->TabIndex = 7; this->button2->Text = L"LED 5"; this->button2->UseVisualStyleBackColor = true; this->button2->Click += gcnew System::EventHandler(this, &Form1::C_LED); // // button1 // this->button1->Location = System::Drawing::Point(6, 37); this->button1->Name = L"button1"; this->button1->Size = System::Drawing::Size(72, 38); this->button1->TabIndex = 6; this->button1->Text = L"LED 1"; this->button1->UseVisualStyleBackColor = true; this->button1->Click += gcnew System::EventHandler(this, &Form1::C_LED); // // txtnum // this->txtnum->Enabled = false; this->txtnum->Location = System::Drawing::Point(161, 273); this->txtnum->Name = L"txtnum"; this->txtnum->Size = System::Drawing::Size(61, 22); this->txtnum->TabIndex = 8; // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(32, 273); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(123, 17); this->label1->TabIndex = 9; this->label1->Text = L"Valor de la Salida:"; // // tmrTemp // this->tmrTemp->Interval = 10; this->tmrTemp->Tick += gcnew System::EventHandler(this, &Form1::tmrTemp_Tick); // // b_Encender // this->b_Encender->Enabled = false; this->b_Encender->Location = System::Drawing::Point(385, 38); this->b_Encender->Name = L"b_Encender"; this->b_Encender->Size = System::Drawing::Size(150, 38); this->b_Encender->TabIndex = 10; this->b_Encender->Text = L"Encender LEDS"; this->b_Encender->UseVisualStyleBackColor = true; this->b_Encender->Click += gcnew System::EventHandler(this, &Form1::b_Encender_Click); // // BPot // this->BPot->Location = System::Drawing::Point(161, 337);

Page 25: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

25

this->BPot->Maximum = 255; this->BPot->Name = L"BPot"; this->BPot->Size = System::Drawing::Size(365, 36); this->BPot->TabIndex = 11; this->BPot->Click += gcnew System::EventHandler(this, &Form1::BPot_Click); // // LblPot // this->LblPot->AutoSize = true; this->LblPot->Enabled = false; this->LblPot->Location = System::Drawing::Point(32, 346); this->LblPot->Name = L"LblPot"; this->LblPot->Size = System::Drawing::Size(103, 17); this->LblPot->TabIndex = 12; this->LblPot->Text = L"Potenciometro:"; // // TmrEnt // this->TmrEnt->Interval = 500; this->TmrEnt->Tick += gcnew System::EventHandler(this, &Form1::TmrEnt_Tick); // // groupBox2 // this->groupBox2->Controls->Add(this->label8); this->groupBox2->Controls->Add(this->pictureBox8); this->groupBox2->Controls->Add(this->label7); this->groupBox2->Controls->Add(this->pictureBox7); this->groupBox2->Controls->Add(this->label6); this->groupBox2->Controls->Add(this->pictureBox6); this->groupBox2->Controls->Add(this->label5); this->groupBox2->Controls->Add(this->pictureBox5); this->groupBox2->Controls->Add(this->label4); this->groupBox2->Controls->Add(this->pictureBox4); this->groupBox2->Controls->Add(this->label3); this->groupBox2->Controls->Add(this->pictureBox3); this->groupBox2->Controls->Add(this->label2); this->groupBox2->Controls->Add(this->pictureBox2); this->groupBox2->Controls->Add(this->label9); this->groupBox2->Controls->Add(this->pictureBox1); this->groupBox2->Location = System::Drawing::Point(21, 412); this->groupBox2->Name = L"groupBox2"; this->groupBox2->Size = System::Drawing::Size(517, 172); this->groupBox2->TabIndex = 13; this->groupBox2->TabStop = false; this->groupBox2->Text = L"Estado de la Entrada"; // // label8 // this->label8->AutoSize = true; this->label8->Location = System::Drawing::Point(450, 48); this->label8->Name = L"label8"; this->label8->Size = System::Drawing::Size(36, 17); this->label8->TabIndex = 15; this->label8->Text = L"Bit 0"; // // pictureBox8 // this->pictureBox8->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox8.Image"))); this->pictureBox8->Location = System::Drawing::Point(441, 78); this->pictureBox8->Name = L"pictureBox8"; this->pictureBox8->Size = System::Drawing::Size(54, 44); this->pictureBox8->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox8->TabIndex = 14; this->pictureBox8->TabStop = false;

Page 26: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

26

// // label7 // this->label7->AutoSize = true; this->label7->Location = System::Drawing::Point(390, 48); this->label7->Name = L"label7"; this->label7->Size = System::Drawing::Size(36, 17); this->label7->TabIndex = 13; this->label7->Text = L"Bit 1"; // // pictureBox7 // this->pictureBox7->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox7.Image"))); this->pictureBox7->Location = System::Drawing::Point(381, 78); this->pictureBox7->Name = L"pictureBox7"; this->pictureBox7->Size = System::Drawing::Size(54, 44); this->pictureBox7->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox7->TabIndex = 12; this->pictureBox7->TabStop = false; // // label6 // this->label6->AutoSize = true; this->label6->Location = System::Drawing::Point(330, 48); this->label6->Name = L"label6"; this->label6->Size = System::Drawing::Size(36, 17); this->label6->TabIndex = 11; this->label6->Text = L"Bit 2"; // // pictureBox6 // this->pictureBox6->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox6.Image"))); this->pictureBox6->Location = System::Drawing::Point(321, 78); this->pictureBox6->Name = L"pictureBox6"; this->pictureBox6->Size = System::Drawing::Size(54, 44); this->pictureBox6->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox6->TabIndex = 10; this->pictureBox6->TabStop = false; // // label5 // this->label5->AutoSize = true; this->label5->Location = System::Drawing::Point(270, 48); this->label5->Name = L"label5"; this->label5->Size = System::Drawing::Size(36, 17); this->label5->TabIndex = 9; this->label5->Text = L"Bit 3"; // // pictureBox5 // this->pictureBox5->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox5.Image"))); this->pictureBox5->Location = System::Drawing::Point(261, 78); this->pictureBox5->Name = L"pictureBox5"; this->pictureBox5->Size = System::Drawing::Size(54, 44); this->pictureBox5->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox5->TabIndex = 8; this->pictureBox5->TabStop = false; // // label4 // this->label4->AutoSize = true; this->label4->Location = System::Drawing::Point(210, 48);

Page 27: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

27

this->label4->Name = L"label4"; this->label4->Size = System::Drawing::Size(36, 17); this->label4->TabIndex = 7; this->label4->Text = L"Bit 4"; // // pictureBox4 // this->pictureBox4->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox4.Image"))); this->pictureBox4->Location = System::Drawing::Point(201, 78); this->pictureBox4->Name = L"pictureBox4"; this->pictureBox4->Size = System::Drawing::Size(54, 44); this->pictureBox4->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox4->TabIndex = 6; this->pictureBox4->TabStop = false; // // label3 // this->label3->AutoSize = true; this->label3->Location = System::Drawing::Point(150, 48); this->label3->Name = L"label3"; this->label3->Size = System::Drawing::Size(36, 17); this->label3->TabIndex = 5; this->label3->Text = L"Bit 5"; // // pictureBox3 // this->pictureBox3->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox3.Image"))); this->pictureBox3->Location = System::Drawing::Point(141, 78); this->pictureBox3->Name = L"pictureBox3"; this->pictureBox3->Size = System::Drawing::Size(54, 44); this->pictureBox3->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox3->TabIndex = 4; this->pictureBox3->TabStop = false; // // label2 // this->label2->AutoSize = true; this->label2->Location = System::Drawing::Point(90, 49); this->label2->Name = L"label2"; this->label2->Size = System::Drawing::Size(36, 17); this->label2->TabIndex = 3; this->label2->Text = L"Bit 6"; // // pictureBox2 // this->pictureBox2->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox2.Image"))); this->pictureBox2->Location = System::Drawing::Point(81, 79); this->pictureBox2->Name = L"pictureBox2"; this->pictureBox2->Size = System::Drawing::Size(54, 44); this->pictureBox2->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox2->TabIndex = 2; this->pictureBox2->TabStop = false; // // label9 // this->label9->AutoSize = true; this->label9->Location = System::Drawing::Point(30, 48); this->label9->Name = L"label9"; this->label9->Size = System::Drawing::Size(36, 17); this->label9->TabIndex = 1; this->label9->Text = L"Bit 7"; //

Page 28: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

28

// pictureBox1 // this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox1.Image"))); this->pictureBox1->Location = System::Drawing::Point(21, 78); this->pictureBox1->Name = L"pictureBox1"; this->pictureBox1->Size = System::Drawing::Size(54, 44); this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox1->TabIndex = 0; this->pictureBox1->TabStop = false; // // menuStrip1 // this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) {this->archivoToolStripMenuItem, this->ayudaToolStripMenuItem}); this->menuStrip1->Location = System::Drawing::Point(0, 0); this->menuStrip1->Name = L"menuStrip1"; this->menuStrip1->RenderMode = System::Windows::Forms::ToolStripRenderMode::System; this->menuStrip1->Size = System::Drawing::Size(559, 25); this->menuStrip1->TabIndex = 14; this->menuStrip1->Text = L"menuStrip1"; // // archivoToolStripMenuItem // this->archivoToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) {this->salirToolStripMenuItem}); this->archivoToolStripMenuItem->Name = L"archivoToolStripMenuItem"; this->archivoToolStripMenuItem->Size = System::Drawing::Size(66, 21); this->archivoToolStripMenuItem->Text = L"&Archivo"; // // salirToolStripMenuItem // this->salirToolStripMenuItem->Name = L"salirToolStripMenuItem"; this->salirToolStripMenuItem->Size = System::Drawing::Size(114, 22); this->salirToolStripMenuItem->Text = L"&Salir"; this->salirToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::salirToolStripMenuItem_Click); // // ayudaToolStripMenuItem // this->ayudaToolStripMenuItem->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(1) {this->acercaDeToolStripMenuItem}); this->ayudaToolStripMenuItem->Name = L"ayudaToolStripMenuItem"; this->ayudaToolStripMenuItem->Size = System::Drawing::Size(59, 21); this->ayudaToolStripMenuItem->Text = L"Ay&uda"; this->ayudaToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::ayudaToolStripMenuItem_Click); // // acercaDeToolStripMenuItem // this->acercaDeToolStripMenuItem->Name = L"acercaDeToolStripMenuItem"; this->acercaDeToolStripMenuItem->Size = System::Drawing::Size(152, 22); this->acercaDeToolStripMenuItem->Text = L"&Acerca De"; this->acercaDeToolStripMenuItem->Click += gcnew System::EventHandler(this, &Form1::acercaDeToolStripMenuItem_Click); // // Form1 // this->AutoScaleDimensions = System::Drawing::SizeF(8, 16); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(559, 607); this->Controls->Add(this->groupBox2); this->Controls->Add(this->LblPot);

Page 29: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

29

this->Controls->Add(this->BPot); this->Controls->Add(this->b_Encender); this->Controls->Add(this->label1); this->Controls->Add(this->txtnum); this->Controls->Add(this->groupBox1); this->Controls->Add(this->LblEnt); this->Controls->Add(this->ToggleLED_btn); this->Controls->Add(this->menuStrip1); this->Icon = (cli::safe_cast<System::Drawing::Icon^ >(resources->GetObject(L"$this.Icon"))); this->MainMenuStrip = this->menuStrip1; this->Name = L"Form1"; this->Text = L"Adquisidor Génerico USB"; this->FormClosed += gcnew System::Windows::Forms::FormClosedEventHandler(this, &Form1::Form1_FormClosed); this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load); this->groupBox1->ResumeLayout(false); this->groupBox2->ResumeLayout(false); this->groupBox2->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox8))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox7))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox6))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox5))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox4))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox3))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox2))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->EndInit(); this->menuStrip1->ResumeLayout(false); this->menuStrip1->PerformLayout(); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e) { //Inicializo el valor de la salida de los led v_salida= 0; txtnum->Text =v_salida.ToString(); tmrTemp->Enabled=true; //HAbilito el temporizador } private: System::Void ToggleLED_btn_Click(System::Object^ sender, System::EventArgs^ e) { v_salida = 0; txtnum->Text =v_salida.ToString(); s_usb(v_salida); } private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { } //Funcion que maneja la salida de los numeros private: System::Void C_LED(System::Object^ sender, System::EventArgs^ e) { int v_exp,i; //Valor que almacena el exponente del numero unsigned char num;

Page 30: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

30

String^ sebas, ^cadena; sebas = sender->ToString(); cadena = sebas->Substring(38); v_exp=Convert::ToInt32(cadena); v_exp--; num = (Math::Pow(2,v_exp)); //Reviso si el bit está en estado alto, si esta lo bajo y viceversa. if( (num&v_salida) == num) v_salida= v_salida ^ num; else v_salida= v_salida| num; txtnum->Text =v_salida.ToString(); //Preparo el Buffer Para la Transmisión s_usb(v_salida); } private: System::Void tmrTemp_Tick(System::Object^ sender, System::EventArgs^ e) { //Identificadores Globales Guid. GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, 0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30}; HDEVINFO DeviceInfoTable = INVALID_HANDLE_VALUE; PSP_DEVICE_INTERFACE_DATA InterfaceDataStructure = new SP_DEVICE_INTERFACE_DATA; PSP_DEVICE_INTERFACE_DETAIL_DATA DetailedInterfaceDataStructure = new SP_DEVICE_INTERFACE_DETAIL_DATA; SP_DEVINFO_DATA DevInfoData; DWORD InterfaceIndex = 0; DWORD StatusLastError = 0; DWORD dwRegType; DWORD dwRegSize; DWORD StructureSize = 0; PBYTE PropertyValueBuffer; bool MatchFound = false; DWORD ErrorStatus; String^ DeviceIDToFind = MY_DEVICE_ID; //Obtengo la lista de dispositivos DeviceInfoTable = SetupDiGetClassDevsUM(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE); //Examino la lista en busqueda de elementos while(true) { InterfaceDataStructure->cbSize = sizeof(SP_DEVICE_INTERFACE_DATA); SetupDiEnumDeviceInterfacesUM(DeviceInfoTable, NULL, &InterfaceClassGuid, InterfaceIndex, InterfaceDataStructure); ErrorStatus = GetLastError(); if(ERROR_NO_MORE_ITEMS == GetLastError()) //Si llegue al ultimo dispositivo, finalizo { //El dispositivo no está conectado SetupDiDestroyDeviceInfoListUM(DeviceInfoTable); //Limpio la estructura que no nece return; } //Obtengo el Hardware ID para ver si es el del dispositivo que busco //Inicializo estructuras auxiliares DevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

Page 31: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

31

SetupDiEnumDeviceInfoUM(DeviceInfoTable, InterfaceIndex, &DevInfoData); //Pregunto por el tamano del ID SetupDiGetDeviceRegistryPropertyUM(DeviceInfoTable, &DevInfoData, SPDRP_HARDWAREID, &dwRegType, NULL, 0, &dwRegSize); //Almaceno memoria apropiada PropertyValueBuffer = (BYTE *) malloc (dwRegSize); if(PropertyValueBuffer == NULL) //Si es nulo, no puedo almacenar memoria { //Salgo SetupDiDestroyDeviceInfoListUM(DeviceInfoTable); return; } //Retrieve the hardware IDs for the current device we are looking at. PropertyValueBuffer gets filled with a //REG_MULTI_SZ (array of null terminated strings). To find a device, we only care about the very first string in the //buffer, which will be the "device ID". The device ID is a string which contains the VID and PID, in the example //format "Vid_04d8&Pid_003f". SetupDiGetDeviceRegistryPropertyUM(DeviceInfoTable, &DevInfoData, SPDRP_HARDWAREID, &dwRegType, PropertyValueBuffer, dwRegSize, NULL); //Now check if the first string in the hardware ID matches the device ID of my USB device. #ifdef UNICODE String^ DeviceIDFromRegistry = gcnew String((wchar_t *)PropertyValueBuffer); #else String^ DeviceIDFromRegistry = gcnew String((char *)PropertyValueBuffer); #endif //Convert both strings to lower case. This makes the code more robust/portable accross OS Versions DeviceIDFromRegistry = DeviceIDFromRegistry->ToLowerInvariant(); DeviceIDToFind = DeviceIDToFind->ToLowerInvariant(); //Now check if the hardware ID we are looking at contains the correct VID/PID MatchFound = DeviceIDFromRegistry->Contains(DeviceIDToFind); if(MatchFound == true) { DetailedInterfaceDataStructure->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); //Obtengo la Lista de dispositivos SetupDiGetDeviceInterfaceDetailUM(DeviceInfoTable, InterfaceDataStructure, NULL, NULL, &StructureSize, NULL); DetailedInterfaceDataStructure = (PSP_DEVICE_INTERFACE_DETAIL_DATA)(malloc(StructureSize)); //Almacena memoria if(DetailedInterfaceDataStructure == NULL) //Si es nulo { //Salgo. SetupDiDestroyDeviceInfoListUM(DeviceInfoTable); //Limpio la estructura que no se emplea return; } DetailedInterfaceDataStructure->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); //Llamo nuevamente a la función SetupDiGetDeviceInterfaceDetailUM(DeviceInfoTable, InterfaceDataStructure, DetailedInterfaceDataStructure, StructureSize, NULL, NULL);

Page 32: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

32

//Almaceno los Handles en Write Handle y readHandle WriteHandle = CreateFile((DetailedInterfaceDataStructure->DevicePath), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); ErrorStatus = GetLastError(); if(ErrorStatus == ERROR_SUCCESS) ToggleLED_btn->Enabled = true; ReadHandle = CreateFile((DetailedInterfaceDataStructure->DevicePath), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); ErrorStatus = GetLastError(); if(ErrorStatus == ERROR_SUCCESS) { LblEnt->Enabled=true; groupBox1->Enabled=true; LblPot->Enabled=true; b_Encender->Enabled=true; s_usb(v_salida); TmrEnt->Enabled=true; //Habilito el timer de pedido de datos } SetupDiDestroyDeviceInfoListUM(DeviceInfoTable); //Limpio la Estructura que no se emplea return; } InterfaceIndex++; //Barro el Bucle hasta que se encuentre el dispositivo o finalize la lista }//Fin While } private: System::Void b_Encender_Click(System::Object^ sender, System::EventArgs^ e) { v_salida = 0xFF; txtnum->Text=v_salida.ToString(); s_usb(v_salida); } private: System::Void groupBox1_Enter(System::Object^ sender, System::EventArgs^ e) { } private: System::Void BPot_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void TmrEnt_Tick(System::Object^ sender, System::EventArgs^ e) { DWORD BytesWritten = 0; DWORD BytesRead = 0; unsigned char OutputPacketBuffer[65]; unsigned char InputPacketBuffer[65]; InputPacketBuffer[0] = 0; OutputPacketBuffer[0] = 0; OutputPacketBuffer[1] = 0x81; //El codigo 0x81 pide estado de la entrada análogia y estado de los LEDS WriteFile(WriteHandle, &OutputPacketBuffer, 65, &BytesWritten, 0); //Obtengo la respuesta del Hardware ReadFile(ReadHandle, &InputPacketBuffer, 65, &BytesRead, 0); //Exhibo los datos BPot->Value=InputPacketBuffer[3]; Indicar_bits(InputPacketBuffer[4]); //Exhibo los Bits de entrada en la columna de la pantalla LblEnt->Text= "Estado de la Entrada Digital: " + InputPacketBuffer[4].ToString(); }

Page 33: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

33

private: System::Void Form1_FormClosed(System::Object^ sender, System::Windows::Forms::FormClosedEventArgs^ e) { unsigned char num; unsigned char BufferSalida[65]; DWORD BytesWritten = 0; //Variable que emplea la función Write File //Preparo el Buffer Para la Transmisión BufferSalida[0] = 0; //Se debe inicializar en 0 por protocolo USB BufferSalida[1] = 0xBA; //0x0A es el código que resetea el dispositivo //El firmware debe tratar apropiadamente dicho código WriteFile(WriteHandle, &BufferSalida, 65, &BytesWritten, 0); } void Indicar_bits(int entr) { int i=0,j; String ^ apagado="..\\LED_OFF.jpg"; String ^ prendido="..\\LED_ON.jpg"; String ^ cadena; cadena=""; //convierto el valor a una cadena binaria while(entr > 0){ if((entr%2)==1) cadena="1"+ cadena; else cadena="0" + cadena; entr =int(entr/2); i++; }; //Completo con ceros el Byte for(j=1;j<=(8-i);j++) cadena="0" + cadena; //Verifico valor por valor de la cadena y cambio el color de fondo de las imagenes //según corresponda for(j=0;j<8;j++){ if(cadena[j]=='1') safe_cast<PictureBox^>(groupBox2->Controls[(15-(j*2))])->Image= Image::FromFile(prendido); else safe_cast<PictureBox^>(groupBox2->Controls[(15-(j*2))])->Image= Image::FromFile(apagado); } return ; } private: System::Void ayudaToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void acercaDeToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) {

Page 34: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

34

MessageBox::Show("Adquisidor Genérico USB Versión 1.0\n Técnicas Digitales III\n F.R.S.N U.T.N. 2008","Acerca De",MessageBoxButtons::OK, MessageBoxIcon::Information); } private: System::Void salirToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) { this->Close(); } }; } Archivo Cpp El presente archivo crea en la memoria la Clase referente a la ventana declarada en Form1.h // Aquisidor Generico USB.cpp : main project file. #include "stdafx.h" #include "Form1.h" using namespace AquisidorGenericoUSB; [STAThreadAttribute] int main(array<System::String ^> ^args) { // Enabling Windows XP visual effects before any controls are created Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); // Create the main window and run it Application::Run(gcnew Form1()); return 0; } Programación del Microcontrolador

Se describe parte del código de inicialización del sistema. Para modificar la configuración

de los puertos y conversores A/D, se emplean las funciones UserInit() y se altera el código de la librería HardwareProfile.H

#ifndef USBMOUSE_C #define USBMOUSE_C /** INCLUDES *******************************************************/ #include "GenericTypeDefs.h" #include "Compiler.h" #include "usb_config.h" #include "./USB/usb_device.h" #include "./USB/usb.h" #include "HardwareProfile.h" #include "./USB/usb_function_hid.h" /** CONFIGURATION **************************************************/ #if defined(PICDEM_FS_USB) // Configuration bits for PICDEM FS USB Demo Board (based on PIC18F4550) #pragma config PLLDIV = 5 // (20 MHz crystal on PICDEM FS USB board) #pragma config CPUDIV = OSC1_PLL2 #pragma config USBDIV = 2 // Clock source from 96MHz PLL/2

Page 35: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

35

#pragma config FOSC = HSPLL_HS #pragma config FCMEN = OFF #pragma config IESO = OFF #pragma config PWRT = OFF #pragma config BOR = ON #pragma config BORV = 3 #pragma config VREGEN = ON //USB Voltage Regulator #pragma config WDT = OFF #pragma config WDTPS = 32768 #pragma config MCLRE = ON #pragma config LPT1OSC = OFF #pragma config PBADEN = OFF // #pragma config CCP2MX = ON #pragma config STVREN = ON #pragma config LVP = OFF // #pragma config ICPRT = OFF // Dedicated In-Circuit Debug/Programming #pragma config XINST = OFF // Extended Instruction Set #pragma config CP0 = OFF #pragma config CP1 = OFF // #pragma config CP2 = OFF // #pragma config CP3 = OFF #pragma config CPB = OFF // #pragma config CPD = OFF #pragma config WRT0 = OFF #pragma config WRT1 = OFF // #pragma config WRT2 = OFF // #pragma config WRT3 = OFF #pragma config WRTB = OFF // Boot Block Write Protection #pragma config WRTC = OFF // #pragma config WRTD = OFF #pragma config EBTR0 = OFF #pragma config EBTR1 = OFF // #pragma config EBTR2 = OFF // #pragma config EBTR3 = OFF #pragma config EBTRB = OFF #elif defined(PIC18F87J50_PIM) // Configuration bits for PIC18F87J50 FS USB Plug-In Module board #pragma config XINST = OFF // Extended instruction set #pragma config STVREN = ON // Stack overflow reset #pragma config PLLDIV = 3 // (12 MHz crystal used on this board) #pragma config WDTEN = OFF // Watch Dog Timer (WDT) #pragma config CP0 = OFF // Code protect #pragma config CPUDIV = OSC1 // OSC1 = divide by 1 mode #pragma config IESO = OFF // Internal External (clock) Switchover #pragma config FCMEN = OFF // Fail Safe Clock Monitor #pragma config FOSC = HSPLL // Firmware must also set OSCTUNE<PLLEN> to start PLL! #pragma config WDTPS = 32768 // #pragma config WAIT = OFF // Commented choices are // #pragma config BW = 16 // only available on the // #pragma config MODE = MM // 80 pin devices in the // #pragma config EASHFT = OFF // family. #pragma config MSSPMSK = MSK5 // #pragma config PMPMX = DEFAULT // #pragma config ECCPMX = DEFAULT #pragma config CCP2MX = DEFAULT #elif defined(LOW_PIN_COUNT_USB_DEVELOPMENT_KIT) #pragma config CPU_DIV = NoClkDiv, USB_LSCLK = OFF // CONFIG1L #pragma config FOSC = HS, PLL_EN=ON, FCMEN = OFF, IESO = OFF // CONFIG1H #pragma config PWRT = OFF, BOREN = OFF, BORV = 30, VREGEN = ON // CONFIG2L #pragma config WDTEN = OFF, WDTPS = 32768 // CONFIG2H

Page 36: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

36

#pragma config MCLRE = OFF, HFOFST = OFF // CONFIG3H #pragma config STVREN = ON, LVP = OFF, XINST = OFF, BBSIZ=OFF // CONFIG4L #pragma config CP0 = OFF, CP1 = OFF // CONFIG5L #pragma config CPB = OFF // CONFIG5H #pragma config WRT0 = OFF, WRT1 = OFF // CONFIG6L //#pragma config WRTB = ON, WRTC = OFF // CONFIG6H // Disabled WRTB for debugging. Reenable for real. #pragma config WRTB = OFF, WRTC = OFF // CONFIG6H #pragma config EBTR0 = OFF, EBTR1 = OFF // CONFIG7L #pragma config EBTRB = OFF // CONFIG7H #ifdef __DEBUG #pragma config BKBUG = ON #endif #ifndef __DEBUG #pragma config BKBUG = OFF #endif #elif defined(EXPLORER_16) #ifdef __PIC24FJ256GB110__ //Defined by MPLAB when using 24FJ256GB110 device _CONFIG1( JTAGEN_OFF & GCP_OFF & GWRP_OFF & COE_OFF & FWDTEN_OFF & ICS_PGx2) _CONFIG2( 0xF7FF & IESO_OFF & FCKSM_CSDCMD & OSCIOFNC_OFF & POSCMOD_HS & FNOSC_PRIPLL & PLLDIV_DIV2 & IOL1WAY_ON) #else #error No hardware board defined, see "HardwareProfile.h" and __FILE__ #endif #else #error No hardware board defined, see "HardwareProfile.h" and __FILE__ #endif /** VARIABLES ******************************************************/ #pragma udata BYTE old_sw2,old_sw3; BOOL emulate_mode; BYTE movement_length; BYTE vector = 0; BOOL fin_conv = FALSE; BOOL proc_ad = FALSE; /* Fin_conv se habilita despues de leer el conversor A/D indica a proccess_io que envie los datos del conversor que estan actualizados proc_ad se habilita para indicar al sistema que procesa salidas a la PC; */ #pragma udata USB_VARS unsigned char ReceivedDataBuffer[64]; unsigned char ToSendDataBuffer[64]; #pragma udata USB_HANDLE USBOutHandle = 0; USB_HANDLE USBInHandle = 0; BOOL blinkStatusValid = TRUE; /** PRIVATE PROTOTYPES *********************************************/ void BlinkUSBStatus(void); BOOL Switch2IsPressed(void); BOOL Switch3IsPressed(void);

Page 37: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

37

void Emulate_Mouse(void); static void InitializeSystem(void); void ProcessIO(void); void UserInit(void); void YourHighPriorityISRCode(); void YourLowPriorityISRCode(); /** VECTOR REMAPPING ***********************************************/ #if defined(__18CXX) //On PIC18 devices, addresses 0x00, 0x08, and 0x18 are used for //the reset, high priority interrupt, and low priority interrupt //vectors. However, the current Microchip USB bootloader //examples are intended to occupy addresses 0x00-0x7FF or //0x00-0xFFF depending on which bootloader is used. Therefore, //the bootloader code remaps these vectors to new locations //as indicated below. This remapping is only necessary if you //wish to program the hex file generated from this project with //the USB bootloader. If no bootloader is used, edit the //usb_config.h file and comment out the following defines: //#define PROGRAMMABLE_WITH_USB_HID_BOOTLOADER //#define PROGRAMMABLE_WITH_USB_LEGACY_CUSTOM_CLASS_BOOTLOADER #if defined(PROGRAMMABLE_WITH_USB_HID_BOOTLOADER) #define REMAPPED_RESET_VECTOR_ADDRESS 0x1000 #define REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS 0x1008 #define REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS 0x1018 #elif defined(PROGRAMMABLE_WITH_USB_MCHPUSB_BOOTLOADER) #define REMAPPED_RESET_VECTOR_ADDRESS 0x800 #define REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS 0x808 #define REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS 0x818 #else #define REMAPPED_RESET_VECTOR_ADDRESS 0x00 #define REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS 0x08 #define REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS 0x18 #endif #if defined(PROGRAMMABLE_WITH_USB_HID_BOOTLOADER)||defined(PROGRAMMABLE_WITH_USB_MCHPUSB_BOOTLOADER) extern void _startup (void); // See c018i.c in your C18 compiler dir #pragma code REMAPPED_RESET_VECTOR = REMAPPED_RESET_VECTOR_ADDRESS void _reset (void) { _asm goto _startup _endasm } #endif #pragma code REMAPPED_HIGH_INTERRUPT_VECTOR = REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS void Remapped_High_ISR (void) { _asm goto YourHighPriorityISRCode _endasm } #pragma code REMAPPED_LOW_INTERRUPT_VECTOR = REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS void Remapped_Low_ISR (void) { _asm goto YourLowPriorityISRCode _endasm } #if defined(PROGRAMMABLE_WITH_USB_HID_BOOTLOADER)||defined(PROGRAMMABLE_WITH_USB_MCHPUSB_BOOTLOADER) //Note: If this project is built while one of the bootloaders has //been defined, but then the output hex file is not programmed with //the bootloader, addresses 0x08 and 0x18 would end up programmed with 0xFFFF. //As a result, if an actual interrupt was enabled and occured, the PC would jump //to 0x08 (or 0x18) and would begin executing "0xFFFF" (unprogrammed space). This

Page 38: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

38

//executes as nop instructions, but the PC would eventually reach the REMAPPED_RESET_VECTOR_ADDRESS //(0x1000 or 0x800, depending upon bootloader), and would execute the "goto _startup". This //would effective reset the application. //To fix this situation, we should always deliberately place a //"goto REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS" at address 0x08, and a //"goto REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS" at address 0x18. When the output //hex file of this project is programmed with the bootloader, these sections do not //get bootloaded (as they overlap the bootloader space). If the output hex file is not //programmed using the bootloader, then the below goto instructions do get programmed, //and the hex file still works like normal. The below section is only required to fix this //scenario. #pragma code HIGH_INTERRUPT_VECTOR = 0x08 void High_ISR (void) { _asm goto REMAPPED_HIGH_INTERRUPT_VECTOR_ADDRESS _endasm } #pragma code LOW_INTERRUPT_VECTOR = 0x18 void Low_ISR (void) { _asm goto REMAPPED_LOW_INTERRUPT_VECTOR_ADDRESS _endasm } #endif //end of "#if defined(PROGRAMMABLE_WITH_USB_HID_BOOTLOADER)||defined(PROGRAMMABLE_WITH_USB_LEGACY_CUSTOM_CLASS_BOOTLOADER)" #pragma code //These are your actual interrupt handling routines. #pragma interrupt YourHighPriorityISRCode void YourHighPriorityISRCode() { //Check which interrupt flag caused the interrupt. //Service the interrupt //Clear the interrupt flag //Etc. } //This return will be a "retfie fast", since this is in a #pragma interrupt section #pragma interruptlow YourLowPriorityISRCode void YourLowPriorityISRCode() { //Interrupción del conversor A/D PIR1bits.ADIF=0; //Limpio el flag de interrupción proc_ad = FALSE; //INdico que termine de procesar ToSendDataBuffer[1] = 0x81; //Indico con el código 0x81 que envío a la PC //datos del conversor y de los pulsadores ToSendDataBuffer[2] = ADRESH; ToSendDataBuffer[3] = PORTB; fin_conv=TRUE; } //This return will be a "retfie", since this is in a #pragma interruptlow section #elif defined(__C30__) #if defined(PROGRAMMABLE_WITH_USB_HID_BOOTLOADER)

Page 39: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

39

/* * ISR JUMP TABLE * * It is necessary to define jump table as a function because C30 will * not store 24-bit wide values in program memory as variables. * * This function should be stored at an address where the goto instructions * line up with the remapped vectors from the bootloader's linker script. * * For more information about how to remap the interrupt vectors, * please refer to AN1157. An example is provided below for the T2 * interrupt with a bootloader ending at address 0x1400 */ void __attribute__ ((address(0x1404))) ISRTable(){ asm("reset"); //reset instruction to prevent runaway code asm("goto %0"::"i"(&_T2Interrupt)); //T2Interrupt's address } #endif #endif //of "#if defined(__18CXX)" /** DECLARATIONS ***************************************************/ #pragma code /******************************************************************** * Function: void main(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: Main program entry point. * * Note: None *******************************************************************/ #if defined(__18CXX) void main(void) #else int main(void) #endif { // //This can be used for user entry into the bootloader // #if defined(__C30__) // mInitSwitch2(); // if(sw2 == 0) // { // EnterBootloader(); // } // #endif InitializeSystem(); while(1) { // Check bus status and service USB interrupts. USBDeviceTasks(); // Interrupt or polling method. If using polling, must call // this function periodically. This function will take care // of processing and responding to SETUP transactions // (such as during the enumeration process when you first

Page 40: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

40

// plug in). USB hosts require that USB devices should accept // and process SETUP packets in a timely fashion. Therefore, // when using polling, this function should be called // frequently (such as once about every 100 microseconds) at any // time that a SETUP packet might reasonably be expected to // be sent by the host to your device. In most cases, the // USBDeviceTasks() function does not take very long to // execute (~50 instruction cycles) before it returns. // Application-specific tasks. // Application related code may be added here, or in the ProcessIO() function. ProcessIO(); }//end while }//end main /******************************************************************** * Function: static void InitializeSystem(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: InitializeSystem is a centralize initialization * routine. All required USB initialization routines * are called from here. * * User application initialization routine should * also be called from here. * * Note: None *******************************************************************/ static void InitializeSystem(void) { #if (defined(__18CXX) & !defined(PIC18F87J50_PIM)) ADCON1 |= 0x0F; // Default all pins to digital #elif defined(__C30__) AD1PCFGL = 0xFFFF; #endif #if defined(PIC18F87J50_PIM) //On the PIC18F87J50 Family of USB microcontrollers, the PLL will not power up and be enabled //by default, even if a PLL enabled oscillator configuration is selected (such as HS+PLL). //This allows the device to power up at a lower initial operating frequency, which can be //advantageous when powered from a source which is not gauranteed to be adequate for 48MHz //operation. On these devices, user firmware needs to manually set the OSCTUNE<PLLEN> bit to //power up the PLL. { unsigned int pll_startup_counter = 600; OSCTUNEbits.PLLEN = 1; //Enable the PLL and wait 2+ms until the PLL locks before enabling USB module

Page 41: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

41

while(pll_startup_counter--); } //Device switches over automatically to PLL output after PLL is locked and ready. //Configure all I/O pins to use digital input buffers. The PIC18F87J50 Family devices //use the ANCONx registers to control this, which is different from other devices which //use the ADCON1 register for this purpose. WDTCONbits.ADSHR = 1; // Select alternate SFR location to access ANCONx registers ANCON0 = 0xFF; // Default all pins to digital ANCON1 = 0xFF; // Default all pins to digital WDTCONbits.ADSHR = 0; // Select normal SFR locations #endif // The USB specifications require that USB peripheral devices must never source // current onto the Vbus pin. Additionally, USB peripherals should not source // current on D+ or D- when the host/hub is not actively powering the Vbus line. // When designing a self powered (as opposed to bus powered) USB peripheral // device, the firmware should make sure not to turn on the USB module and D+ // or D- pull up resistor unless Vbus is actively powered. Therefore, the // firmware needs some means to detect when Vbus is being powered by the host. // A 5V tolerant I/O pin can be connected to Vbus (through a resistor), and // can be used to detect when Vbus is high (host actively powering), or low // (host is shut down or otherwise not supplying power). The USB firmware // can then periodically poll this I/O pin to know when it is okay to turn on // the USB module/D+/D- pull up resistor. When designing a purely bus powered // peripheral device, it is not possible to source current on D+ or D- when the // host is not actively providing power on Vbus. Therefore, implementing this // bus sense feature is optional. This firmware can be made to use this bus // sense feature by making sure "USE_USB_BUS_SENSE_IO" has been defined in the // HardwareProfile.h file. #if defined(USE_USB_BUS_SENSE_IO) tris_usb_bus_sense = INPUT_PIN; // See HardwareProfile.h #endif // If the host PC sends a GetStatus (device) request, the firmware must respond // and let the host know if the USB peripheral device is currently bus powered // or self powered. See chapter 9 in the official USB specifications for details // regarding this request. If the peripheral device is capable of being both // self and bus powered, it should not return a hard coded value for this request. // Instead, firmware should check if it is currently self or bus powered, and // respond accordingly. If the hardware has been configured like demonstrated // on the PICDEM FS USB Demo Board, an I/O pin can be polled to determine the // currently selected power source. On the PICDEM FS USB Demo Board, "RA2" // is used for this purpose. If using this feature, make sure "USE_SELF_POWER_SENSE_IO" // has been defined in HardwareProfile.h, and that an appropriate I/O pin has been mapped // to it in HardwareProfile.h. #if defined(USE_SELF_POWER_SENSE_IO) tris_self_power = INPUT_PIN; // See HardwareProfile.h #endif USBDeviceInit(); //usb_device.c. Initializes USB module SFRs and firmware //variables to known states. UserInit(); }//end InitializeSystem /****************************************************************************** * Function: void UserInit(void) * * PreCondition: None *

Page 42: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

42

* Input: None * * Output: None * * Side Effects: None * * Overview: This routine should take care of all of the demo code * initialization that is required. * * Note: * *****************************************************************************/ void UserInit(void) { //Initialize all of the LED pins mInitAllLEDs(); //Inicializo el conversor A/D y configuro las interrupciones //------------------------------------------------------------------ RCONbits.IPEN=1; INTCONbits.GIEH = 1; INTCONbits.GIEL = 1; PIE1bits.ADIE=1; //Habilito la interrupción del conversor A/D IPR1bits.ADIP=0; //Configuro la interrupción como de baja prioridad //Configuro el conversor A/D ADCON1 = 0x0E; //Habilito el PIN AN0 ADCON0 = 0x01; //Selecciono el PIN AN0 para el conversor y lo enciendo ADCON2 = 0x11; //Configuro el tiempo de adquisición interno //y lo justifico a izquierda //para exhibir los datos en un solo puerto //para justificado derecha, emplear ADCON2 = 0xB1 //------------------------------------------------------------------- //Initialize all of the push buttons mInitAllSwitches(); old_sw2 = sw2; old_sw3 = sw3; //initialize the variable holding the handle for the last // transmission USBOutHandle = 0; USBInHandle = 0; blinkStatusValid = TRUE; }//end UserInit /******************************************************************** * Function: void ProcessIO(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: This function is a place holder for other user * routines. It is a mixture of both USB and * non-USB tasks. * * Note: None

Page 43: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

43

*******************************************************************/ void ProcessIO(void) { //Blink the LEDs according to the USB device status if(blinkStatusValid) { BlinkUSBStatus(); } // User Application USB tasks if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return; if(fin_conv==TRUE){ if(!HIDTxHandleBusy(USBInHandle)) { USBInHandle = HIDTxPacket(HID_EP,(BYTE*)&ToSendDataBuffer,64); fin_conv = FALSE; } } if(!HIDRxHandleBusy(USBOutHandle)) { blinkStatusValid = FALSE; switch(ReceivedDataBuffer[0]) { case 0x80: //Toggle LEDs if(mLED_1 == mLED_2) { mLED_1_Toggle(); mLED_2_Toggle(); } else { mLED_1 = mLED_2; } break; case 0x81: //Recibo la señal para enviar los datos del conversor y //el estado de los pulsadores if(fin_conv == FALSE && proc_ad==FALSE) { ADCON0bits.GO_DONE = 1; //Habilito la lectura del conversor A/D proc_ad= TRUE; //Indico que proceso la salida } break; //Atención para salida a LEDS case 0x0A: LATD = ReceivedDataBuffer[1]; break; //Codigo de Reset del dispositivo case 0xBA: Reset(); break; } //Re-arm the OUT endpoint for the next packet

Page 44: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

44

USBOutHandle = HIDRxPacket(HID_EP,(BYTE*)&ReceivedDataBuffer,64); } }//end ProcessIO /****************************************************************************** * Function: BOOL Switch2IsPressed(void) * * PreCondition: None * * Input: None * * Output: TRUE - pressed, FALSE - not pressed * * Side Effects: None * * Overview: Indicates if the switch is pressed. * * Note: * *****************************************************************************/ BOOL Switch2IsPressed(void) { if(sw2 != old_sw2) { old_sw2 = sw2; // Save new value if(sw2 == 0) // If pressed return TRUE; // Was pressed }//end if return FALSE; // Was not pressed }//end Switch2IsPressed /****************************************************************************** * Function: BOOL Switch3IsPressed(void) * * PreCondition: None * * Input: None * * Output: TRUE - pressed, FALSE - not pressed * * Side Effects: None * * Overview: Indicates if the switch is pressed. * * Note: * *****************************************************************************/ BOOL Switch3IsPressed(void) { if(sw3 != old_sw3) { old_sw3 = sw3; // Save new value if(sw3 == 0) // If pressed return TRUE; // Was pressed }//end if return FALSE; // Was not pressed }//end Switch3IsPressed /******************************************************************** * Function: void BlinkUSBStatus(void) * * PreCondition: None * * Input: None *

Page 45: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

45

* Output: None * * Side Effects: None * * Overview: BlinkUSBStatus turns on and off LEDs * corresponding to the USB device state. * * Note: mLED macros can be found in HardwareProfile.h * USBDeviceState is declared and updated in * usb_device.c. *******************************************************************/ void BlinkUSBStatus(void) { static WORD led_count=0; if(led_count == 0)led_count = 10000U; led_count--; #define mLED_Both_Off() {mLED_1_Off();mLED_2_Off();} #define mLED_Both_On() {mLED_1_On();mLED_2_On();} #define mLED_Only_1_On() {mLED_1_On();mLED_2_Off();} #define mLED_Only_2_On() {mLED_1_Off();mLED_2_On();} if(USBSuspendControl == 1) { if(led_count==0) { mLED_1_Toggle(); mLED_2 = mLED_1; // Both blink at the same time }//end if } else { if(USBDeviceState == DETACHED_STATE) { mLED_Both_Off(); } else if(USBDeviceState == ATTACHED_STATE) { mLED_Both_On(); } else if(USBDeviceState == POWERED_STATE) { mLED_Only_1_On(); } else if(USBDeviceState == DEFAULT_STATE) { mLED_Only_2_On(); } else if(USBDeviceState == ADDRESS_STATE) { if(led_count == 0) { mLED_1_Toggle(); mLED_2_Off(); }//end if } else if(USBDeviceState == CONFIGURED_STATE) { if(led_count==0) { mLED_1_Toggle(); mLED_2 = !mLED_1; // Alternate blink }//end if }//end if(...) }//end if(UCONbits.SUSPND...) }//end BlinkUSBStatus

Page 46: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

46

// ****************************************************************************************************** // ************** USB Callback Functions **************************************************************** // ****************************************************************************************************** // The USB firmware stack will call the callback functions USBCBxxx() in response to certain USB related // events. For example, if the host PC is powering down, it will stop sending out Start of Frame (SOF) // packets to your device. In response to this, all USB devices are supposed to decrease their power // consumption from the USB Vbus to <2.5mA each. The USB module detects this condition (which according // to the USB specifications is 3+ms of no bus activity/SOF packets) and then calls the USBCBSuspend() // function. You should modify these callback functions to take appropriate actions for each of these // conditions. For example, in the USBCBSuspend(), you may wish to add code that will decrease power // consumption from Vbus to <2.5mA (such as by clock switching, turning off LEDs, putting the // microcontroller to sleep, etc.). Then, in the USBCBWakeFromSuspend() function, you may then wish to // add code that undoes the power saving things done in the USBCBSuspend() function. // The USBCBSendResume() function is special, in that the USB stack will not automatically call this // function. This function is meant to be called from the application firmware instead. See the // additional comments near the function. /****************************************************************************** * Function: void USBCBSuspend(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: Call back that is invoked when a USB suspend is detected * * Note: None *****************************************************************************/ void USBCBSuspend(void) { //Example power saving code. Insert appropriate code here for the desired //application behavior. If the microcontroller will be put to sleep, a //process similar to that shown below may be used: //ConfigureIOPinsForLowPower(); //SaveStateOfAllInterruptEnableBits(); //DisableAllInterruptEnableBits(); //EnableOnlyTheInterruptsWhichWillBeUsedToWakeTheMicro(); //should enable at least USBActivityIF as a wake source //Sleep(); //RestoreStateOfAllPreviouslySavedInterruptEnableBits(); //Preferrably, this should be done in the USBCBWakeFromSuspend() function instead.

Page 47: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

47

//RestoreIOPinsToNormal(); //Preferrably, this should be done in the USBCBWakeFromSuspend() function instead. //IMPORTANT NOTE: Do not clear the USBActivityIF (ACTVIF) bit here. This bit is //cleared inside the usb_device.c file. Clearing USBActivityIF here will cause //things to not work as intended. #if defined(__C30__) #if 0 U1EIR = 0xFFFF; U1IR = 0xFFFF; U1OTGIR = 0xFFFF; IFS5bits.USB1IF = 0; IEC5bits.USB1IE = 1; U1OTGIEbits.ACTVIE = 1; U1OTGIRbits.ACTVIF = 1; TRISA &= 0xFF3F; LATAbits.LATA6 = 1; Sleep(); LATAbits.LATA6 = 0; #endif #endif } /****************************************************************************** * Function: void _USB1Interrupt(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: This function is called when the USB interrupt bit is set * In this example the interrupt is only used when the device * goes to sleep when it receives a USB suspend command * * Note: None *****************************************************************************/ #if 0 void __attribute__ ((interrupt)) _USB1Interrupt(void) { #if !defined(self_powered) if(U1OTGIRbits.ACTVIF) { LATAbits.LATA7 = 1; IEC5bits.USB1IE = 0; U1OTGIEbits.ACTVIE = 0; IFS5bits.USB1IF = 0; //USBClearInterruptFlag(USBActivityIFReg,USBActivityIFBitNum); USBClearInterruptFlag(USBIdleIFReg,USBIdleIFBitNum); //USBSuspendControl = 0; LATAbits.LATA7 = 0; } #endif } #endif /****************************************************************************** * Function: void USBCBWakeFromSuspend(void) *

Page 48: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

48

* PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: The host may put USB peripheral devices in low power * suspend mode (by "sending" 3+ms of idle). Once in suspend * mode, the host may wake the device back up by sending non- * idle state signalling. * * This call back is invoked when a wakeup from USB suspend * is detected. * * Note: None *****************************************************************************/ void USBCBWakeFromSuspend(void) { // If clock switching or other power savings measures were taken when // executing the USBCBSuspend() function, now would be a good time to // switch back to normal full power run mode conditions. The host allows // a few milliseconds of wakeup time, after which the device must be // fully back to normal, and capable of receiving and processing USB // packets. In order to do this, the USB module must receive proper // clocking (IE: 48MHz clock must be available to SIE for full speed USB // operation). } /******************************************************************** * Function: void USBCB_SOF_Handler(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: The USB host sends out a SOF packet to full-speed * devices every 1 ms. This interrupt may be useful * for isochronous pipes. End designers should * implement callback routine as necessary. * * Note: None *******************************************************************/ void USBCB_SOF_Handler(void) { // No need to clear UIRbits.SOFIF to 0 here. // Callback caller is already doing that. } /******************************************************************* * Function: void USBCBErrorHandler(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: The purpose of this callback is mainly for

Page 49: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

49

* debugging during development. Check UEIR to see * which error causes the interrupt. * * Note: None *******************************************************************/ void USBCBErrorHandler(void) { // No need to clear UEIR to 0 here. // Callback caller is already doing that. // Typically, user firmware does not need to do anything special // if a USB error occurs. For example, if the host sends an OUT // packet to your device, but the packet gets corrupted (ex: // because of a bad connection, or the user unplugs the // USB cable during the transmission) this will typically set // one or more USB error interrupt flags. Nothing specific // needs to be done however, since the SIE will automatically // send a "NAK" packet to the host. In response to this, the // host will normally retry to send the packet again, and no // data loss occurs. The system will typically recover // automatically, without the need for application firmware // intervention. // Nevertheless, this callback function is provided, such as // for debugging purposes. } /******************************************************************* * Function: void USBCBCheckOtherReq(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: When SETUP packets arrive from the host, some * firmware must process the request and respond * appropriately to fulfill the request. Some of * the SETUP packets will be for standard * USB "chapter 9" (as in, fulfilling chapter 9 of * the official USB specifications) requests, while * others may be specific to the USB device class * that is being implemented. For example, a HID * class device needs to be able to respond to * "GET REPORT" type of requests. This * is not a standard USB chapter 9 request, and * therefore not handled by usb_device.c. Instead * this request should be handled by class specific * firmware, such as that contained in usb_function_hid.c. * * Note: None *******************************************************************/ void USBCBCheckOtherReq(void) { USBCheckHIDRequest(); }//end /******************************************************************* * Function: void USBCBStdSetDscHandler(void) * * PreCondition: None * * Input: None

Page 50: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

50

* * Output: None * * Side Effects: None * * Overview: The USBCBStdSetDscHandler() callback function is * called when a SETUP, bRequest: SET_DESCRIPTOR request * arrives. Typically SET_DESCRIPTOR requests are * not used in most applications, and it is * optional to support this type of request. * * Note: None *******************************************************************/ void USBCBStdSetDscHandler(void) { // Must claim session ownership if supporting this request }//end /******************************************************************* * Function: void USBCBInitEP(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: This function is called when the device becomes * initialized, which occurs after the host sends a * SET_CONFIGURATION (wValue not = 0) request. This * callback function should initialize the endpoints * for the device's usage according to the current * configuration. * * Note: None *******************************************************************/ void USBCBInitEP(void) { //enable the HID endpoint USBEnableEndpoint(HID_EP,USB_IN_ENABLED|USB_OUT_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP); //Re-arm the OUT endpoint for the next packet USBOutHandle = HIDRxPacket(HID_EP,(BYTE*)&ReceivedDataBuffer,64); } /******************************************************************** * Function: void USBCBSendResume(void) * * PreCondition: None * * Input: None * * Output: None * * Side Effects: None * * Overview: The USB specifications allow some types of USB * peripheral devices to wake up a host PC (such * as if it is in a low power suspend to RAM state). * This can be a very useful feature in some * USB applications, such as an Infrared remote * control receiver. If a user presses the "power" * button on a remote control, it is nice that the * IR receiver can detect this signalling, and then

Page 51: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

51

* send a USB "command" to the PC to wake up. * * The USBCBSendResume() "callback" function is used * to send this special USB signalling which wakes * up the PC. This function may be called by * application firmware to wake up the PC. This * function should only be called when: * * 1. The USB driver used on the host PC supports * the remote wakeup capability. * 2. The USB configuration descriptor indicates * the device is remote wakeup capable in the * bmAttributes field. * 3. The USB host PC is currently sleeping, * and has previously sent your device a SET * FEATURE setup packet which "armed" the * remote wakeup capability. * * This callback should send a RESUME signal that * has the period of 1-15ms. * * Note: Interrupt vs. Polling * -Primary clock * -Secondary clock ***** MAKE NOTES ABOUT THIS ******* * > Can switch to primary first by calling USBCBWakeFromSuspend() * The modifiable section in this routine should be changed * to meet the application needs. Current implementation * temporary blocks other functions from executing for a * period of 1-13 ms depending on the core frequency. * * According to USB 2.0 specification section 7.1.7.7, * "The remote wakeup device must hold the resume signaling * for at lest 1 ms but for no more than 15 ms." * The idea here is to use a delay counter loop, using a * common value that would work over a wide range of core * frequencies. * That value selected is 1800. See table below: * ========================================================== * Core Freq(MHz) MIP RESUME Signal Period (ms) * ========================================================== * 48 12 1.05 * 4 1 12.6 * ========================================================== * * These timing could be incorrect when using code * optimization or extended instruction mode, * or when having other interrupts enabled. * Make sure to verify using the MPLAB SIM's Stopwatch * and verify the actual signal on an oscilloscope. *******************************************************************/ void USBCBSendResume(void) { static WORD delay_count; USBResumeControl = 1; // Start RESUME signaling delay_count = 1800U; // Set RESUME line for 1-13 ms do { delay_count--; }while(delay_count); USBResumeControl = 0; } /** EOF main.c *************************************************/ #endif

Page 52: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

52

Fragmento de HardwareProfile.h /** LED ************************************************************/ //Configuro el puerto D integramente como salida #define mInitAllLEDs() LATD &= 0x00; TRISD &= 0x00; #define mLED_1 LATDbits.LATD0 #define mLED_2 LATDbits.LATD1 #define mLED_3 LATDbits.LATD2 #define mLED_4 LATDbits.LATD3 #define mLED_1_On() mLED_1 = 1; #define mLED_2_On() mLED_2 = 1; #define mLED_3_On() mLED_3 = 1; #define mLED_4_On() mLED_4 = 1; #define mLED_1_Off() mLED_1 = 0; #define mLED_2_Off() mLED_2 = 0; #define mLED_3_Off() mLED_3 = 0; #define mLED_4_Off() mLED_4 = 0; #define mLED_1_Toggle() mLED_1 = !mLED_1; #define mLED_2_Toggle() mLED_2 = !mLED_2; #define mLED_3_Toggle() mLED_3 = !mLED_3; #define mLED_4_Toggle() mLED_4 = !mLED_4; /** SWITCH *********************************************************/ #define mInitAllSwitches() TRISBbits.TRISB4=1;TRISBbits.TRISB5=1; #define mInitSwitch2() TRISBbits.TRISB4=1; #define mInitSwitch3() TRISBbits.TRISB5=1; #define sw2 PORTBbits.RB4 #define sw3 PORTBbits.RB5 Configuración del descriptor

Como habíamos mencionado anteriormente el descriptor es un sector de memoria accesible simultáneamente por el microcontrolador y el sistema operativo, que indica a la PC la configuración del dispositivo, así como características de los Endpoints, intervalo de acceso entre otros. En la librería usb_descriptor.h se detalla la estructura de memoria del descriptor. /********************************************************************* * Descriptor specific type definitions are defined in: * usb_device.h * * Configuration options are defined in: * usb_config.h ********************************************************************/ #ifndef __USB_DESCRIPTORS_C #define __USB_DESCRIPTORS_C /** INCLUDES *******************************************************/ #include "GenericTypeDefs.h" #include "Compiler.h" #include "usb_config.h" #include "./USB/usb_device.h" #include "./USB/usb_function_hid.h"

Page 53: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

53

/** CONSTANTS ******************************************************/ #if defined(__18CXX) #pragma romdata #endif /* Device Descriptor */ ROM USB_DEVICE_DESCRIPTOR device_dsc= { 0x12, // Size of this descriptor in bytes USB_DESCRIPTOR_DEVICE, // DEVICE descriptor type 0x0200, // USB Spec Release Number in BCD format 0x00, // Class Code 0x00, // Subclass code 0x00, // Protocol code USB_EP0_BUFF_SIZE, // Max packet size for EP0, see usb_config.h 0x04D8, // Vendor ID 0x003F, // Product ID: Mouse in a circle fw demo 0x0002, // Device release number in BCD format 0x01, // Manufacturer string index 0x02, // Product string index 0x00, // Device serial number string index 0x01 // Number of possible configurations }; /* Configuration 1 Descriptor */ ROM BYTE configDescriptor1[]={ /* Configuration Descriptor */ 0x09,//sizeof(USB_CFG_DSC), // Size of this descriptor in bytes USB_DESCRIPTOR_CONFIGURATION, // CONFIGURATION descriptor type 0x29,0x00, // Total length of data for this cfg 1, // Number of interfaces in this cfg 1, // Index value of this configuration 0, // Configuration string index _DEFAULT | _SELF, // Attributes, see usb_device.h 50, // Max power consumption (2X mA) /* Interface Descriptor */ 0x09,//sizeof(USB_INTF_DSC), // Size of this descriptor in bytes USB_DESCRIPTOR_INTERFACE, // INTERFACE descriptor type 0, // Interface Number 0, // Alternate Setting Number 2, // Number of endpoints in this intf HID_INTF, // Class code 0, // Subclass code 0, // Protocol code 0, // Interface string index /* HID Class-Specific Descriptor */ 0x09,//sizeof(USB_HID_DSC)+3, // Size of this descriptor in bytes RRoj hack DSC_HID, // HID descriptor type 0x11,0x01, // HID Spec Release Number in BCD format (1.11) 0x00, // Country Code (0x00 for Not supported) HID_NUM_OF_DSC, // Number of class descriptors, see usbcfg.h DSC_RPT, // Report descriptor type HID_RPT01_SIZE,0x00,//sizeof(hid_rpt01), // Size of the report descriptor /* Endpoint Descriptor */ 0x07,/*sizeof(USB_EP_DSC)*/ USB_DESCRIPTOR_ENDPOINT, //Endpoint Descriptor HID_EP | _EP_IN, //EndpointAddress _INT, //Attributes 0x40,0x00, //size 0x01, //Interval /* Endpoint Descriptor */ 0x07,/*sizeof(USB_EP_DSC)*/ USB_DESCRIPTOR_ENDPOINT, //Endpoint Descriptor HID_EP | _EP_OUT, //EndpointAddress

Page 54: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

54

_INT, //Attributes 0x40,0x00, //size 0x01 //Interval }; //Language code string descriptor ROM struct{BYTE bLength;BYTE bDscType;WORD string[1];}sd000={ sizeof(sd000),USB_DESCRIPTOR_STRING,{0x0409 }}; //Manufacturer string descriptor ROM struct{BYTE bLength;BYTE bDscType;WORD string[21];}sd001={ sizeof(sd001),USB_DESCRIPTOR_STRING, {'S','e','b','a','s','t','i','a','n',' ', 'C','h','i','o','d','i','n',' ','T','M','. ' }}; //Product string descriptor ROM struct{BYTE bLength;BYTE bDscType;WORD string[19];}sd002={ sizeof(sd002),USB_DESCRIPTOR_STRING, {'A','d','q','u','i','s','i ','d','o','r',' ', 'G','e','n','e','r','i','c ','o' }}; //Class specific descriptor - HID ROM struct{BYTE report[HID_RPT01_SIZE];}hid_rpt01={ { 0x06, 0x00, 0xFF, // Usage Page = 0xFFFF (Vendor Defined) 0x09, 0x01, // Usage 0xA1, 0x01, // Collection (Application, probably not important because vendor defined usage) 0x19, 0x01, // Usage Minimum (Vendor Usage = 0) (minimum bytes the device should send is 0) 0x29, 0x40, // Usage Maximum (Vendor Usage = 64) (maximum bytes the device should send is 64) 0x15, 0x00, // Logical Minimum (Vendor Usage = 0) 0x26, 0xFF, 0x00, // Logical Maximum (Vendor Usage = 255) 0x75, 0x08, // Report Size 8 bits (one full byte) for each report. 0x95, 0x40, // Report Count 64 bytes in a full report. 0x81, 0x02, // Input (Data, Var, Abs) 0x19, 0x01, // Usage Minimum (Vendor Usage = 0) 0x29, 0x40, // Usage Maximum (Vendor Usage = 64) 0x91, 0x02, // Output (Data, Var, Ads) 0xC0} }; // End Collection //Array of configuration descriptors ROM BYTE *ROM USB_CD_Ptr[]= { (ROM BYTE *ROM)&configDescriptor1 }; //Array of string descriptors ROM BYTE *ROM USB_SD_Ptr[]= { (ROM BYTE *ROM)&sd000, (ROM BYTE *ROM)&sd001, (ROM BYTE *ROM)&sd002 }; /** EOF usb_descriptors.c ***************************************************/ #endif

Page 55: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

55

CIRCUITO

Page 56: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

56

FOTOS DEL PROTOTIPO

IMÁGENES DEL PROGRAMADOR

Page 57: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

57

FOTOS DE PANTALLA

Page 58: UNIVERSIDAD TECNOLOGICA NACIONAL … generico USB.pdf · universidad tecnologica nacional facultad regional san nicolas ingenieria en electronica problema de ingenierÍa tecnicas

Técnicas Digitales III – Problema de ingeniería

58