You are on page 1of 72

UNIVERSIDAD REY JUAN CARLOS

INGENIER IA TECNICA EN INFORMATICA DE SISTEMAS Curso Acad emico 2003/2004

Proyecto n de carrera

Dise no e Implementaci on de controladores Hardware y Software para comunicaciones inal ambricas Bluetooth basado en el chip ROK 101/007 de Ericsson y el Microcontrolador AT89C2051 de Atmel

AUTOR: Gregorio Zamora Merino TUTOR: Juan Antonio Hern andez Tamames FEBRERO 2004

Resumen
En este proyecto se busca obtener una plataforma hardware multiprop osito con capacidades de comunicaci on inal ambricas. Para ello se ha seleccionado el microcontrolador 8051, de amplia difusi on y muy bajo coste, y el sistema de comunicaci on Bluetooth. Con este proyecto se intenta adquirir el conocimiento necesario para el desarrollo de aplicaciones con Bluetooth: para qu e sirve, qu e se puede hacer y, sobre todo, c omo hacerlo. En particular, se ha desarrollado un protocolo de comunicaci on serie, basado en la torre de protocolo de Bluetooth pero no en su totalidad. Se ha implementado el m nimo imprescindible para lograr una comunicaci on, con el n de que no resulte gravosa su implantaci on en equipos como el 8051 donde la memoria utilizada es limitada en el desarrollo de este tipo de aplicaciones.

Indice
1. Introducci on. 1.1. Qu e es Bluetooth? . . . . . . . . . . . . . . . . . . . . . . 1.2. Especicaciones generales de la tecnolog a Bluetooth . . . 1.3. Torre de protocolos. . . . . . . . . . . . . . . . . . . . . . . 1.4. Entorno de desarrollo. . . . . . . . . . . . . . . . . . . . . 1.4.1. Starter kit Bluetooth. . . . . . . . . . . . . . . . . . 1.4.2. Tarjeta Bluetooth. . . . . . . . . . . . . . . . . . . 1.4.3. Tarjeta PCMCIA Bluetooth para port atil. . . . . . 1.4.4. Manual del hardware de la tarjeta madre Bluetooth . . . . . . . . . . . . . . . 1 1 2 4 6 6 7 7 8 9 9 9 14 14 14 14 14 15 18 22 31 32 33

2. Objetivos. 2.1. Objetivo del proyecto . . . . . . . . . . . . . . . . . . . . . . . 2.2. Estudio de alternativas y metodolog a . . . . . . . . . . . . . . 3. Descripci on inform atica. 3.1. Componentes. . . . . . . . . . . . . . 3.1.1. Un ordenador con capacidades 3.1.2. Una tarjeta hija de Bluetooth 3.1.3. Un 8051 . . . . . . . . . . . . 3.2. Especicaci on . . . . . . . . . . . . . 3.2.1. Lado Cliente o lado del PC . 3.2.2. Lado Servidor o lado del 8051 4. Conclusiones. 5. Bibliograf a 6. Ap endices

. . . . . . Bluetooth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

ii

1.
1.1.

Introducci on.
Qu e es Bluetooth?

El concepto de Bluetooth surge de la imperiosa necesidad de las grandes empresas de telecomunicaciones e inform atica, de desarrollar una interfaz abierta, que facilite la comunicaci on entre los diferentes equipos inform aticos y telef onicos, aprovechando la capacidad y la movilidad de los dispositivos inal ambricos, para la total supresi on de los cables de conexi on, adoptando as un u nico est andar de conexi on. Bluetooth se puede denir como una propuesta de especicaci on de radio frecuencia por transmisi on de corto alcance de datos, pudiendo transmitir a trav es de objetos s olidos no met alicos. Su alcance nominal es de 10 cm a 10 m en teor a, pero puede extenderse a 100 m mediante el incremento de transmisi on de energ a. Los ordenadores, tel efonos m oviles, aparatos dom esticos y equipos de ocina, basados en Bluetooth pueden conectarse entre s dentro de areas f sicas reducidas, sin necesidad de utilizar cableado, de forma segura y barata y a altas velocidades de transmisi on. Tambi en se pretende ofrecer acceso a Internet, a trav es de LAN y dar soporte para la sincronizaci on de datos entre dispositivos inform aticos. Una gran ventaja es que en la l nea de comunicaci on pueden existir obst aculos materiales. Las tarjetas Bluetooth son peque nos dispositivos radio de baja potencia, sobre un chip que se comunican con otros productos basados en el est andar. As , podemos eliminar los cables a la hora de conectar dispositivos como ordenadores port atiles, PDAs, tel efonos m oviles, impresoras o m aquinas de fax, entre otros equipos. La conexi on se puede realizar tanto punto a punto como punto-multipunto. Al soportar comunicaciones de voz y datos, Bluetooth puede ser extendido a comunicaciones manos libres para tel efonos inal ambricos en veh culos. La tecnolog a usa la banda ISM (Industrial Scientic Medicine) de los 2.4 GHz que no necesita licencia, est a disponible en casi todo el mundo, aunque debe adaptarse a las interferencias de los peque nos monitores, mandos de garaje, tel efonos sin cables, microondas, que tambi en usan esta frecuencia. Bluetooth es adem as, un m odulo radio de baja potencia, puede integrarse en una amplia variedad de dispositivos. Soporta transmisi on de tres canales de voz, v deo y datos a una velocidad m axima de 1 Mbps, aunque la m axima velocidad real girar a alrededor de los 721 Kbps. El est andar ha sido dise nado para operar en un entorno multiusuario. De hecho, permite conectar hasta ocho usuarios, o dispositivos situados dentro de una peque na red llamada picorred. Diez de estas picorredes pueden coexistir 1

en un mismo espacio de cobertura de radio. Para proporcionar seguridad, cada enlace es codicado y protegido contra interferencias e intrusiones. Para los administradores de redes, las microrredes Bluetooth ofrecen muchas ventajas pero comportan algunos retos. Es cierto, que en una picorred se pueden ofrecer servicios sin requerimientos de seguridad, (las impresoras basadas en Bluetooth de una sala de reuniones, por ejemplo, podr an ser utilizadas sin necesidad de congurarlas), pero tambi en lo es, sin embargo, que si la empresa tiene instalada LAN inal ambricas (IEEE 802.11b) ambas tecnolog as pueden interferir entre s . Para minimizar este problema, los administradores de redes deben situar convenientemente las picorredes Bluetooth y las LAN inal ambricas.

1.2.

Especicaciones generales de la tecnolog a Bluetooth

En la siguiente tabla, se muestran de forma gen erica las especicaciones de la tecnolog a Bluetooth. Algunos elementos, como por ejemplo, las piconets (picorredes) ser an desarrollados con m as detalle en el estudio posterior.

Especicaciones Banda de frecuencia 2.4 GHz Potencia del transmisor 1 mW (0 dBm) Tecnolog a RF Espectro Ensanchado por Secuencia Directa H brida y Saltos en frecuencia (FH-SS) Velocidad de datos 721 Kbps por piconet Rango esperado del sistema 10 metros. Extensi on a 100 metros No m aximo de dispositivos 8 por piconet. 10 piconets en un area de cobertura 1(scatternet) o N m aximo canales de voz 3 por piconet No m aximo canales de datos 7 por piconet Seguridad S , en la capa de enlace Alimentaci on 2.7 Voltios Consumo de potencia: Sleep 30 microamperios Hold 60 microamperios Standby 300 microamperios Transmitiendo 8 - 30 mA Tama no del m odulo 0.5 pulgadas cuadradas (327.68 mm 2 ) Interferencias Bluetooth minimiza la interferencia potencial al emplear saltos r apidos en frecuencia de 1600 veces por segundo. Cuadro 1: Especicaciones generales Bluetooth

1.3.

Torre de protocolos.

La especicaci on de Bluetooth pretende que todas las aplicaciones que sigan esta sean capaces de operar entre s . Para conseguir esta interoperabilidad, las aplicaciones en dispositivos remotos deben ejecutarse sobre una pila de protocolos id enticos. A continuaci on se muestra la pila de protocolos tal y como aparece descrita en la especicaci on:

Figura 1: Pila de protocolos Bluetooth. No todas las aplicaciones hacen uso de todos los protocolos que conforman la pila, y algunas aplicaciones se ejecutan sobre una o m as columnas de la torre. La pila completa se compone tanto de protocolos espec cos de Bluetooth (LMP y L2CAP, por ejemplo) como de protocolos no espec cos de Bluetooth como son OBEX (Objects Exchange Protocol), UDP (User Datagram Protocol), TCP, IP, etc. Debido a que la hora de dise nar la torre de protocolos, el objetivo principal ha sido maximizar el n umero de protocolos existentes que se puedan reutilizar en las capas m as altas para diferentes prop ositos. La reutilizaci on de protocolos es muy importante, para poder hacer que diferentes aplicaciones comerciales ya existentes, utilicen estos protocolos, y puedan interoperar con Bluetooth. Adem as, la especicaci on est a abierta a implementaciones libres (propietarias), o nuevos protocolos de aplicaci on de uso com un. As , se pretende que se puedan desarrollar un gran n umero de aplicaciones, que gocen de las ventajas de la tecnolog a Bluetooth. 4

La torre de protocolos se puede dividir en cuatro capas l ogicas, de acuerdo a su prop osito. La divisi on es la siguiente: Capa de protocolo N ucleo de Bluetooth Sustituci on del cable Control de Telefon a Protocolos adoptados Protocolos de la pila BaseBand, LMP, L2CAP, SDP RFCOMM TCS Binary, AT-Commands PPP, UDP/TCP/IP, OBEX, WAP, VCard, VCal, IRMC, WAE

Cuadro 2: Clasicaci on protocolos Bluetooth.

A parte de todos estos protocolos, la especicaci on dene el HCI (Host Controller Interface), que se encarga de proporcionar una interfaz de comandos al controlador BaseBand, al gestor de enlace, y nos da acceso al estado del hardware y a los registros de control. En la gura de la torre de protocolos aparece, colocado por debajo de L2CAP, pero esta posici on no es obligatoria, ya que, HCI puede estar tambi en por encima de L2CAP. Los protocolos denominados n ucleo de Bluetooth, son aquellos desarrollados espec camente para Bluetooth. Los protocolos n ucleo de Bluetooth (m as Bluetooth radio l ogicamente), deben ser implementados por pr acticamente la mayor a de dispositivos Bluetooth, mientras que el uso de los dem as protocolos est a supeditado a los casos en que estos sean necesarios. Por su parte, las capas l ogicas de sustituci on de cable, de control de telefon a y de protocolos adoptados, agrupan a los protocolos orientados a aplicaci on, permitiendo as a las diferentes aplicaciones existentes o desarrolladas en el futuro poder correr sobre el n ucleo de Bluetooth. Como ya se mencion o antes, la especicaci on es abierta en cuanto a los protocolos que corren encima de los protocolos espec cos de transporte, y as se pueden hacer implementaciones que usen protocolos tan usados como HTTP, FTP, y un largo etc etera. A partir de aqu , vamos a realizar una descripci on de todos los protocolos que emplea Bluetooth, centr andonos un poco m as en aqu ellos protocolos espec cos de Bluetooth y que constituyen la base de su funcionamiento.

1.4.

Entorno de desarrollo.

El material que hemos utilizado, se ha comprado a la compa n a llamada IAR Systems, la cual, es uno de los principales proveedores del mundo en herramientas de desarrollo y de servicios para sistemas embebidos, que se utilizan para productos que contienen microprocesadores, como por ejemplo: tel efonos m oviles, sistemas del GPS, unidades de mando a distancia y juegos para computadora. Adem as, esta compa n a se dedica al desarrollo de software, para sus clientes. IAR Systems igualmente desarrolla y comercializa una gran gama de productos y servicios, para que puedan ser usados en el dise no, desarrollo y pruebas de sistemas. Entre los muchos productos que ofrece dicha empresa, nosotros hemos elegido el Starter kit Bluetooth. Este kit se compone de un conjunto de elementos que a continuaci on explicaremos, ya que son los m as adecuados a la hora de desarrollar nuestro proyecto. 1.4.1. Starter kit Bluetooth.

Figura 2: Starter Kit. El Starter kit Bluetooth de IAR, es una plataforma de evaluaci on y de desarrollo para la tecnolog a Bluetooth. Este producto, incluye el hardware y software necesarios para la comunicaci on sin cables entre dos m aquinas, y con opci on a seguir desarrollando aplicaciones Bluetooth. El software que incluye se puede utilizar para las comunicaciones de datos y/o de voz. Este Kit se compone de un conjunto de elementos que explicaremos a continuaci on. Son los siguientes: 1. Tarjeta Bluetooth.

2. Tarjeta PCMCIA Bluetooth para port atil. 3. Manual del hardware de la tarjeta madre Bluetooth 4. Manual software, el cual contiene un conjunto de APIs, para manejar la tarjeta madre desde un PC. 5. Programa para la tarjeta PCMCIA. 6. Dos programas de ejemplo con c odigo. Uno para puerto serie COM y el otro para puerto serie USB. 7. Suplementos. 1.4.2. Tarjeta Bluetooth.

Figura 3: Starter Kit. La tarjeta est a compuesta por dos m odulos. Uno es el chip ROK y su correspondiente antena, que se encarga de transferir los paquetes de forma inal ambrica, y el otro m odulo est a formado por un conector de puerto serie COM, con su respectiva toma de alimentaci on, y por u ltimo otro conector para puerto serie USB. La uni on de estos dos m odulos es lo que nos permite conectar la tarjeta madre al PC, o bien por COM, o bien por USB, y poder mandar y recibir informaci on. Tambi en es posible utilizar el modulo que se encarga de transferir los paquetes de forma inal ambrica adaptando nosotros sus tensiones a las del equipo que pretendamos que lo controle. 1.4.3. Tarjeta PCMCIA Bluetooth para port atil.

Esta tarjeta s olo se puede utilizar en un port atil. Una vez se conecta a un port atil por primera vez, nos obliga a introducir el Driver. Dicha tarjeta 7

Figura 4: PCMCIA Bluetooth. lo que hace, es emular varios puertos series COM inal ambricos. IAR Systems no nos aporta las APIs necesarias para poder utilizarla, lo u nico que nos aporta es un programa, el cual explicaremos a continuaci on. El programa anteriormente mencionado es lo que nos permite utilizar la tarjeta PCMCIA Bluetooth. 1.4.4. Manual del hardware de la tarjeta madre Bluetooth

En las especicaciones que nos entreg o IAR Systems, hay un chero en formato PDF el cual nos informa de todas las caracter stica t ecnicas de la tarjeta madre Bluetooth y en especial hace una peque na aclaraci on entre lo que es una tarjeta madre y lo que es una tarjeta hija. Como anteriormente he mencionado, la citada madre est a compuesta por dos m odulos, sin embargo, la hija est a formada por uno solo, dicho m odulo es el que antes hemos llamado, m odulo Bluetooth. Dicha tarjeta hija se compone de 20 pines, de los cuales 8 sirven para conectar con el perif erico en s , bien a trav es de puerto COM, o bien a trav es de puerto USB. El estudio de dicho manual ha resultado vital para el desarrollo de este proyecto ya que gran parte de este proyecto ha sido unir la tarjeta hija con el 8051 eliminando la tarjeta madre.

2.
2.1.

Objetivos.
Objetivo del proyecto

El objetivo de este proyecto es implementar una comunicaci on Bluetooth de bajo nivel para el desarrollo de aplicaciones basadas en el microcontrolador 8051 de forma que podamos comunicarnos de forma inal ambrica con cualquier otro dispositivo que disponga del sistema de comunicaci on de Bluetooth.

2.2.

Estudio de alternativas y metodolog a

Una vez estudiadas las mas de 1.000 paginas del Core de protocolo de Bluetooth, ya est abamos listos para tratar de programar por nosotros mismos la Bluetooth. Nada mas ver la magnitud del protocolo de Bluetooth y la anchura de las capas, nos dimos cuenta de que no nos iba a ser posible implementar toda la torre de protocolo de Bluetooth para el 8051, y dado el alt simo coste de esta torre en el mercado empezamos a bucear en ella para tratar de encontrar el l mite m nimo donde pudi eramos acortar y enlazar con nuestro propio protocolo.

Figura 5: Ericsson ROK 101/007. Despu es de varios meses de buscar por Internet, por n encontramos en una pagina la documentaci on t ecnica del chip Bluetooth que monta el Starter Kit, el Ericsson ROK 101/007. Este hallazgo ha sido critico para el desarrollo del proyecto ya que sin el, est abamos perdidos, pues no sab amos a que altura de la torre estaba la comunicaci on serie con el chip, y no solo eso, tambi en nos proporcion o informaci on a cerca de su puerto serie, tensiones y amperajes y las opciones de conguraci on del mismo. Una vez que averiguamos que el chip, por si mismo, implementa la capa de HCI de la torre de protocolos, sus niveles de tensi on y sus opciones de conguraci on de UART nos pusimos manos a la obra para realizar la uni on con el 8051. En un primer intento tratamos de realizar la uni on con el 8051 de que disponemos para las practicas. Este 8051 es uno de muy alto nivel, y ya lo 9

Figura 6: Protocolo implementado por el chip ROK. ten amos preparado para desarrollar aplicaciones, montado en una placa y con 2 puertos serie. Por desgracia este 8051 no nos sirve ya que dispone de un reloj interno que hace imposible que el puerto serie alcance los 57.600 Baudios necesarios para la comunicaci on con el ROK. Tratamos entonces de modicar el valor por defecto de la velocidad del puerto serie del ROK por medio de comandos HCI espec cos, pero esto resultaba muy engorroso ya que el ROK vuelve a los 57.600 cuando pierde alimentaci on. Deb amos enchufar el ROK a un PC de forma que envi abamos el comando y luego desenchufar del PC y enchufar en el 8051. No era pr actico. De esta forma, empezamos a investigar 8051s de otros fabricantes y encontramos uno de Atmel, el AT89C2051. Un peque no 8051 con tan solo 2k de memoria, un puerto serie y 3 puertos de E/S. Este peque no 8051 admite frecuencias de reloj de hasta 24Mhz. Gracias a esto y utilizando un reloj de 22Mhz podemos congurar el puerto serie del 8051 a los 57.600 baudios que necesita el ROK.

Figura 7: Atmel AT89C2051. Una vez encontrada la documentaci on y con este 8051 nos pusimos manos a la obra para realizar el acoplamiento. Dada la dicultad de desarrollar aplicaciones con un microcontrolador por la imposibilidad de realizar un depuraci on con cierta comodidad, nos

10

dedicamos a desarrollar el protocolo de comunicaci on mediante 2 PCs utilizando como lenguaje de desarrollo Delphi. Dada la escasez de documentaci on sobre Bluetooth que hab a al inicio de este proyecto en general y la total ausencia de esta, aun en su nalizaci on, a cerca de la capa HCI en concreto, nos vemos obligados a espiar las comunicaciones que se establec an entre el programa de prueba UART EXAMPLE.EXE y la tarjeta madre de Bluetooth. Gracias al programa DockLight1 esta comunicaci on pudo ser descifrada. El programa DockLight no es m as que una peque na aplicaci on de desarrollo para aplicaciones de puerto serie donde podemos ver lo que se recibe en un puerto serie y enviar bytes. La forma de hacerlo fue la siguiente: 1. Conectaba un cable MODEM-null entre los puertos 1 y 2 del PC 2. Lanzaba el DockLight escuchando en el COM2 3. Lanzaba el UART EXAMPLE diciendole que la Bluetooth estaba en el COM1 4. En DockLight aparecia el codigo enviado por UART EXAMPLE para inicializar la tarjeta y lo apuntaba 5. Desconectaba todo 6. Conectaba el cable que trae el Starter Kit al COM1 y a la Bluetooth 7. Lanzaba el DockLight sobre el COM1 y lanzaba el comando que habia apuntado antes 8. Apuntar la respuesta de la Bluetooth 9. Volver a desconectar todo 10. Conectar otra vez el cable MODEM-null entre los COM 1 y 2 11. Lanzar el DockLight escucando en el COM2 12. Lanzar el UART EXAMPLE diciendole que la Bluetooth estaba en el COM1
1

http://www.docklight.de

11

13. Una vez recibido el comando, en el DockLight enviar la respuesta que me dio la Bluetooth 14. Apuntar el siguiente comando que envia el UART EXAMPLE y repetir desde el punto 5 hasta que se hace visible al programa que viene con la PCMCIA Bluetooth. Todo este proceso habr a sido muy sencillo de disponer de la versi on registrada de DockLight, ya que te permite guardar respuestas para la vez siguiente, pero en la versi on de prueba, tenia que escribir a mano todas y cada una de las respuestas cada vez que lanzaba el programa Una vez obtenida toda la secuencia de inicializaci on por medio de comandos HCI ten amos que ser capaces de reproducirlo por medio de un programa. Aqu nos encontramos con el siguiente problema. Y como se hace para escribir en el puerto serie? Gracias a Internet y al Delphi, encontramos un componente de este llamado JLCSoft que nos introduc a un puerto serie muy sencillo de usar. Este es el principal motivo que nos ha hecho optar por Delphi como lenguaje de desarrollo. Una vez que eramos capaces de escribir en el puerto serie y que sab amos qu e deb amos decirle a la Bluetooth para que funcionase, tambi en podiamos establecer la comunicaci on entre dos tarjetas Bluetooth y desconectar, incluso de detectar dispositivos Bluetooth que hubiese en los alrededores, pero no eramos capaces de enviar datos. La tarjeta PCMCIA Bluetooth era capaz de enviar a la del Starter Kit, pero no al rev es. Incluso, cuando el Starter Kit recib a uno de estos paquetes de datos enviaba, adem as del paquete un mensaje de error codicado bajo un comando HCI propio (que no aparece en el Core de Bluetooth). Dec a error lm data.c. Por supuesto que la PCMCIA se limitaba a cumplir estrictamente la especicaci on Bluetooth y a ignorar dicho paquete. Despu es de mucho investigar y releer el Core de Bluetooth, la soluci on estaba all en el Core, pero no en el apartado de HCI, sino en la capa siguiente, la L2CAP. All en la capa L2CAP dicen: si se intenta enviar algo a trav es de la capa de HCI que no corresponda con un paquete L2CAP perfectamente formado, este podr a ser descartado. El proyecto hace uso la capa L2CAP de la torre de protocolos de Bluetooth. 12

Por supuesto que, este proyecto, no implementa dicha capa, pero debemos apoyarnos en ella, ya que de lo contrario la capa de HCI tira los paquetes. El modo en que se desarrolla la comunicaci on serie que es objeto de este proyecto, utiliza la orden L2CAP ECHO para enviar los datos, ignorando cualquier otro comando de esta capa.

Figura 8: Placa de pruebas.

13

3.
3.1.

Descripci on inform atica.


Componentes.

A partir de aqu ya sabemos lo que queremos hacer, ahora s olo queda elegir los componentes adecuados para conseguir lo que nos proponemos. Los componemos necesarios son: 1. Un ordenador con capacidades Bluetooth. La misi on de este ser a ejecutar el programa que va a realizar la funci on de cliente que se conectar a al 8051. 2. Una tarjeta hija de Bluetooth. Su funci on es la de recibir los datos que son transferidos. 3. Un 8051. Su misi on es la de controlar la tarjeta hija de Bluetooth qued andole capacidad para realizar cualquier otra tarea. 3.1.1. Un ordenador con capacidades Bluetooth

El Ordenador del que estamos haciendo menci on en este punto debe disponer de capacidades Bluetooth, pero no de cualquier tipo de adaptador Bluetooth. Debe ser uno que disponga de comunicaci on con el PC por medio de UART ya que el programa que se ha desarrollado en este proyecto no admite esta forma de comunicaci on. Lo cual no quiere decir que el futuro, otro proyecto, adapte la programaci on del actual y permita dicha opci on para aprovechar los actuales adaptadores de Bluetooth de puerto serie, cada vez mas baratos y ables 3.1.2. Una tarjeta hija de Bluetooth

Esta tarjeta es la tarjeta hija de Bluetooth del Starter Kit, la cual es realmente el modulo que permite la comunicaci on inal ambrica. La tarjeta madre no es mas que un adaptador de tensiones entre el chip ROK y el puerto serie del PC. Tambi en es cierto que dispone de una fuente de alimentaci on regulada y muy estable para la alimentaci on del chip, as como otros chips para digitalizaci on de sonido. Recordemos que Bluetooth es capaz de transmitir tanto datos como audio. 3.1.3. Un 8051

Este es el principal punto del proyecto ya que el 8051 no solo debe ser capaz de establecer la comunicaci on con el PC a trav es de Bluetooth, sino 14

que debe ser capaz de controlar el perif erico que queremos controlar a trav es del PC. En este proyecto tan solo nos encargamos de controlar un perif erico t acito, es decir, simplemente vamos a colocar un par de leds para poder comprobar que la comunicaci on entre PC y 8051 se realiza correctamente. En futuros proyectos tan solo debemos cambiar estos leds por el correspondiente perif erico.

3.2.

Especicaci on

Tenemos 3 tipos de paquetes HCI: los comandos, los eventos (o respuestas del chip Bluetooth) y los paquetes de datos. Comandos: Cabecera OpCode Tama no de los par ametros Par ametros 1 byte 2bytes 1byte x bytes Cuadro 3: Paquete de comando Evento: Cabecera OpCode Tama no de los par ametros Par ametros 1 byte 1 byte 1byte x bytes Cuadro 4: Paquete de evento Datos: Cabecera Connection Handle 1 byte 12 bits PB Flag BC Flag Tama no de los Datos 1 bit 1 bit 2 bytes Datos X bytes

Cuadro 5: Paquete de datos Es importante tener en cuenta que el chip ROK de Bluetooth trabaja con el formato de datos Little Endian por lo tanto a la hora de escribir datos de m as de 1 byte debemos escribir los bytes en orden inverso, es decir, si deseamos escribir el dato 4A2CH debemos escribir 2C4AH. La cabecera es: 1. Comando: 01H 2. Evento: 04H 15

3. Datos: 02H A continuaci on veremos que el OpCode se compone de dos partes, el OCF que consta de 10 bits y el OGF de 6: OpCode OGF OCF Cuadro 6: Paquete de datos Lo m as sencillo ser a hacer un ejemplo con el comando HCI Reset: Seg un el Core de Bluetooth su OCF o c odigo de comando es el 0003H y su OGF o c odigo de grupo es el 03H Si juntamos ambas partes el Opcode resultante es: OGF (6 bits) OCF (10 bits) 03 0003 00 0011 00 0000 0011 0000 1100 0000 0011 0C03 Cuadro 7: Paquete de datos Observando la pagina del manual donde esta el HCI Reset observaremos que este comando no tiene par ametros, por lo tanto, lo que debemos enviar a la Bluetooth para realizar un reset ser a: Cabecera OpCode Tama no de los par ametros Par ametros 01 030C 00 Cuadro 8: Paquete de datos La secuencia a enviar, por tanto ser a 01H,03H,0CH,00H Preste especial atenci on al OpCode. Hace un momento hemos dicho que el OpCode era 0C03H y ahora escribimos 030CH. No es un error, a esto es a lo que me refer a con el formato Little Endian. Continuando con el HCI Reset, observamos que el chip Bluetooth nos responder a con un evento para indicarnos si ha ejecutado correctamente el HCI Reset o si ha tenido alg un problema. Leyendo el manual, descubrimos que la Bluetooth nos va a responder con un HCI Command Complete. 16

El OpCode del HCI Command Complete es 0EH. En el caso de los Eventos no hay grupos y al ser el c odigo de un u nico byte no hay l os de formato. El manual de Bluetooth nos indica que los par ametros que devuelve un HCI Command Complete son los siguientes (el orden es importante): Num HCI Command Packets (1 byte) Command Opcode (2 bytes) Return Parameters (x Bytes, depende del comando que lo gener o) Es importante destacar que el HCI Command Complete no solo se genera despu es de un HCI Reset. Muchos otros comandos de HCI tienen como respuesta un HCI Command Complete. Veamos el aspecto que tendr a la respuesta en este caso concreto: 04H, 0EH, 04H, 08H, 03H, 0CH, 00H Donde: Cabecera: 04H (indica Evento) Opcode: 0EH (HCI Command Complete) Tama no de los par ametros: 04H (quedan 4 bytes de par ametros) Par ametros: 08H 03H 0CH 00H (los par ametros) Y donde los par ametros corresponden a: Num HCI Command Packets: 08H (numero de comandos que le podemos enviar a la Bluetooth sin esperar respuesta) Command Opcode: 030CH (Quien gener o el evento) Return Parameters: 00H (Status del HCI Reset, 00H= todo correcto) Luego si el HCI Reset se complet o con exito, recibiremos desde la Bluetooth la siguiente cadena: 04H, 0EH, 04H, 08H, 03H, 0CH, 00H En este apartado cabe destacar, por supuesto, dos partes. Por un lado destacaremos la especicaci on del lado del PC, o cliente, y por otro el lado del 8051, o de servidor. 17

3.2.1.

Lado Cliente o lado del PC

El lado del cliente el primer paso es buscar dispositivos Bluetooth que admitan conexiones entrantes por medio de la orden HCI inquiry. Una vez que sabemos qu e dispositivos hay en los alrededores, podemos conectarnos por medio de la orden HCI Create Connection y empezar las transacciones de datos. Este lado de PC, no tiene porque estar inicializado para permitir conexiones entrantes, ya que no lo necesita, pero como este proyecto ha sido mas de toma de contacto, tanto para mi, como para quien desee aprender la base de las comunicaciones de Bluetooth, dejaremos esta inicializaci on ya que de este modo, el apartado del servidor podr a ser sustituido con otro PC, de forma que es m as sencillo ver todo el proceso de comunicaci on Bluetooth. Disponemos de las ordenes HCI Inquiry, HCI Create Connection, Envio de datos y HCI Disconect:

HCI Inquiry
Veamos en detalle la forma de ordenar el HCI Inquiry y como obtener las respuestas (supondremos siempre c odigo hexadecimal): HCI Inquiry : 01 |01 |04 |05 |33 |8B |9E |08 |05 Con esta linea de comandos le estamos pidiendo a la Bluetooth que busque dispositivos Bluetooth que acepten conexiones entrantes hasta un m aximo de 5 dispositivos. Una vez recibido este comando, la Bluetooth nos responder a con un evento de HCI Command Status. Esto no quiere decir mas que ha aceptado el comando. Cuando encuentre alg un dispositivo la Bluetooth nos env a un HCI Inquiry Result. Seg un el manual de Bluetooth, los dispositivos est an autorizados a enviar todas las respuestas en un u nico evento, enviando las respuestas con forma de array, pero por suerte el ROK 101/007 y la tarjeta PCMCIA, env an un HCI Inquiry Result por cada dispositivo encontrado. Una vez encontrados los 5 dispositivos que le hemos pedido, o trascurrido el tiempo de TimeOut recibiremos un evento HCI Inquiry Complete El evento HCI Inquiry Result tiene el siguiente aspecto: 04 |02 |0F |01 |2F |6E |0F |E3 |01 |00 |01 |00 |00 |04 |02 |72 |42 |61 De donde (de izquierda a derecha): 18

04H: Cabecera de Evento 02H: OpCode de HCI Inquiry Result 0FH: Longitud de los par ametros 01H: Numero de respuestas (normalmente solo una) 2F6E0FE30100H: Direcci on MAC del dispositivo encontrado 01H: Page Scan Repetition Mode del dispositivo encontrado 00H: Page Scan Period Mode del dispositivo encontrado 00H: Page Scan Mode del dispositivo encontrado 040272H: Tipo de dispositivo encontrado 4261H:Clock OSet del dispositivo encontrado Todos estos datos son necesarios para poder crear la conexi on con HCI Create Conection.

HCI Create Conection


Un ejemplo de HCI Create Conection: 01 |05 |04 |0D |F5 |A2 |C8 |A4 |10 |00 |08 |00 |01 |00 |00 |00 |01 donde: 01H: Cabecera Comando 0504H: OpCode 0DH: Longitud total de par ametros F5A2C8A41000H: MAC del dispositivo 0800H: Tipo de paquetes que se van a enviar (DM1) 01H: Scan rep del inquiry 00H: Scan Mode del inquiry 0000H: Clk Oset del inquiry 01H: swicth role allow 19

En cuanto al tipo de paquetes, decir que hay varios tipos, pero son usados en capas m as altas del stack Bluetooth, por lo tanto a nosotros nos vale con conocer este tipo que es el m as simple. Esta decisi on no inuye en el formato de los paquetes a este nivel del stack. Una vez que la Bluetooth recibe esta orden, inmediatamente nos indica por medio de un evento de HCI Command Status que ha recibido la orden y se pone manos a la obra. Cuando ha sido capaz de establecer la conexi on con el dispositivo solicitado, en ambos extremos de la comunicaci on aparece un evento de HCI Connection Complete. Por ejemplo: 04 |03 |0C |00 |01 |00 |F5 |A2 |C8 |A4 |10 |00|00 |00 Donde: 04H: Cabecera Evento 03H: OpCode 0CH: Longitud total de par ametros 00H: Status (00H = OK) 0100H: Connection handle (identicador de conexi on) F5A2C8A41000H: MAC del dispositivo 00H: Link Type (00H = Datos) 00H: Encriptaci on (00H = deshabilitada) Env o de Datos Una vez que hemos sido capaces de encontrar el dispositivo y establecer la comunicaci on ya solo nos falta enviar los datos. Como vimos antes el formato de los paquetes de datos es el siguiente: Cabecera Connection Handle 1 byte 12 bits PB Flag BC Flag Tama no de los Datos 1 bit 1 bit 2 bytes Datos X bytes

Cuadro 9: Paquete de datos Hay que tener cuidado porque esto no es exactamente as . En los Datos que aparecen deben corresponder con un paquete, perfectamente bien formado, de la capa siguiente, la L2CAP. 20

En esta capa disponemos de comandos para establecer nuevas conexiones de nivel superior, pero como lo que buscamos es simplicidad y tratar de no distorsionar, en la medida de lo posible, otras comunicaciones Bluetooth, elegimos la orden L2CAP ECHO para enviar nuestros datos. De esta forma un paquete de datos quedaria as : 02 |01 |20 |0C |00 |08 |00 |01 |00 |08 |01 |04 |00 |00 |00 |00 |35 Donde: 02H: Cabecera Datos 0120H: Connection handle + (PB ag=1) 0C00H: Tama no de los Datos 0800010008010400H: Paquete L2CAP ECHO 000000H: Datos utilizables 35H: Datos u tiles Es decir, que podemos enviar hasta 4 bytes de datos siguiendo esta implementaci on Este formato de paquete es tanto de ida como de vuelta, me explico, si la otra parte de la conexi on nos env a un paquete de datos, lo recibiremos tal cual, con la u nica diferencia del Connection Handle que podr a ser distinto y coincidir a con el asignado por el HCI Connection Complete.

HCI Disconect
Una vez que hemos enviado los datos, podemos desconectarnos por medio del comando HCI Disconnect de la siguiente forma: Por ejemplo: 01 |06 |04 |03 |01 |00 |1F Donde: 01H: Cabecera Comando 0604H: OpCode 03H: Longitud total de los par ametros 21

0100H: Connection Handle 1FH: Raz on ofrecida a la otra parte de la comunicaci on (1FH = error no especicado) Una vez que el chip Bluetooth recibe este comando, inmediatamente nos env a un evento HCI Command Status, pero no podemos asegurar que la comunicaci on se haya interrumpido hasta que no se recibe el HCI Disconnection Complete, que aparece en ambos extremos de la comunicaci on. 3.2.2. Lado Servidor o lado del 8051

Lo mas importante a destacar del 8051 es su inicializaci on como servidor, es decir, para permitir conexiones entrantes. En la inicializaci on lo que se hace es establecer los par ametros de funcionamiento, pero no solo esto, tambi en le damos a la BT patrones de conducta para que reaccione por si misma sin molestarnos Veamos detenidamente los principales comandos HCI de inicializaci on

Comando HCI Reset() HCI Set Event Filter(00) HCI Write Scan Enable (03) HCI Write Authentication Enable(00) HCI Write Voice Settings(0060) HCI Set Event Filter(02,00,02) HCI Write connection Accept timeout(1FA0) HCI Write page Timeout(2000) HCI Change local name(nombre[248])

Descripci on Soft Reset Limpiar el ltro de eventos Permite inquiry y Page Scan Deshabilita la autenticaci on Especica como ser an las comunicaciones de voz Permitir conexiones desde cualquiera Timeout de conexi on Timeout de escritura Informa a la BT de su nombre

Cuadro 10: Secuencia de inicializaci on Veremos a continuaci on la secuencia hexadecimal a enviar y una breve descripci on de lo que estamos haciendo

22

HCI Reset
Secuencia hexadecimal a enviar: 01 |03 |0C |00 Quiz a el m as importante de todos los comandos ya que no debe faltar. Este comando no tiene par ametros, es tan solo un soft reset para la BT. Vuelve a los valores por defecto al Host Controller, Link Manager y el modulo de radio Una vez nalizado el HCI Reset el Host Controller nos devuelve un Evento de Command Complete para informarnos del estado Prototipo de funci on: Function HCI Reset (): status;

HCI Set Event Filter


Secuencia hexadecimal a enviar: Para el caso del parametro (00): 01 |05 |0C |01 |00 Para el caso del parametro (02,00,02): 01 |05 |0C |03 |02 |00 |02
2

Este comando nos permite indicarle a la BT con que Eventos puede molestarnos con cuales no. En concreto con los Eventos generados cuando otra BT inicia un proceso de Inquiry o de intento de conexion. Este comando nos permite programar la BT para que responda autom aticamente como nosotros queremos. Justo despu es del HCI Reset lo siguiente que debemos hacer es limpiar las condiciones. Esta funci on tiene 3 par ametros de entrada. Prototipo de funci on: Function HCI Set Event Filter (Filter Type, Filter Condition Type, Condition): status Filter Type:

Filter Condition Type Para Filter Type = 0x00 El resto de par ametros se omite y no se env an

23

Valor 0x00 0x01 0x02 0x03 - 0xFF

Descripci on Limpiar todos los ltros. En este caso el resto de par ametros se omiten Inquiry Result Connection Setup Reservado

Cuadro 11: Posibles valores de Filter Type Valor 0x00 0x01 0x02 0x03 - 0xFF Descripci on Responder a cualquier dispositivo nuevo Responder dependiendo del Class of Device Responder dependiendo de la MAC Reservado

Cuadro 12: Signicado de Filter Condition Type si Filter Type vale 01H Para Filter Type = 0x01 (inquiry Result) Para Filter Type = 0x02 (Connection Setup)

Valor 0x00 0x01 0x02 0x03 - 0xFF

Descripci on Permitir conexi on con cualquiera Permitir conexi on dependiendo del Class of Device Permitir Conexi on dependiendo de la MAC Reservado

Cuadro 13: Signicado de Filter Condition Type si Filter Type vale 02H

Condition Este par ametro tiene diferente interpretaci on y tama no dependiendo de los elegidos anteriormente Para Filter Type = 0x01 (inquiry Result) Y Filter Condition Type = 0x00 El par ametro no se usa 24

Para Filter Type = 0x01 (inquiry Result) Y Filter Condition Type = 0x01 El par ametro Condition tiene un tama no de 6 Bytes repartidos en dos partes de 3 Bytes Valor Descripci on 0x000000 Por defecto, Devuelve todos los dispositivos 0xXXXXXX Class of Device determinado Cuadro 14: Class Of Device: 3Bytes

Valor 0xXXXXXX

Descripci on Bit Mask usada para determinar el Class of Device a los que no se les hace caso. 0 indica no importa

Cuadro 15: Bit Mask: 3 Bytes Para Filter Type = 0x01 (inquiry Result) Y Filter Condition Type = 0x02 El par ametro Condition tiene un tama no de 6 bytes e indica la MAC permitida Para Filter Type = 0x02 (Connection Setup) Y Filter Condition Type = 0x00 El par ametro condition tiene un tama no de 1 Byte

Valor 0x01 0x02 0x03 0x04 - 0xFF

Descripci on No aceptar conexiones autom aticamente Aceptar conexiones Aceptar conexi on con el ag switch role activado Reservado Cuadro 16: Condition

25

Para Filter Type = 0x02 (Connection Setup) Y Filter Condition Type = 0x01 El par ametro condition tiene un tama no de 7 Bytes repartidos como sigue Valor Descripci on 0x000000 Por defecto, Devuelve todos los dispositivos 0xXXXXXX Class of Device en concreto Cuadro 17: Class of Device: 3 Bytes

Valor 0xXXXXXX

Descripci on Bit Mask usada para determinar el Class of Device a los que no se les hace caso. 0 indica no importa

Cuadro 18: Class Of Device Mask: 3Bytes

Valor 0x01 0x02 0x03 0x04 - 0xFF

Descripci on No aceptar conexiones autom aticamente Aceptar conexiones Aceptar conexi on con el ag switch role activado Reservado Cuadro 19: Auto Accept Flag: 1 byte

Para Filter Type = 0x02 (Connection Setup) Y Filter Condition Type = 0x02 El par ametro Condition tiene un tama no de 7 bytes e indica la MAC permitida y el Auto Accept Flag

26

Valor 0x01 0x02 0x03 0x04 - 0xFF

Descripci on No aceptar conexiones autom aticamente Aceptar conexiones Aceptar conexi on con el ag switch role activado Reservado Cuadro 20: Auto Accept Flag: 1 byte

Una vez nalizado el HCI Set Event Filter el Host Controller nos devuelve un Evento de Command Complete para informarnos del estado

HCI Write Scan Enable


Secuencia hexadecimal a enviar: 01 |1A |0C |01 |03 Esta funcion nos permite indicarle a la BT el comportamiento que debe tener en caso de recibir un intento externo de inquiry o de conexion. Si el bit correspondiente esta activado la BT responder a al extra no o no Prototipo de funci on Function HCI WriteScanEnable (Scan Enable):Status Valor 0x00 0x01 0x02 0x03 0x04 - 0xFF Descripci on Por Defecto, no se permite Scan Inquiry habilitado Page Scan Deshabilitado Inquiry deshabilitado Page Scan habilitado Inquiry habilitado Page Scan habilitado Reservado

Cuadro 21: Scan Enable: 1 Byte

27

HCI Write Autentication Enable


Secuencia hexadecimal a enviar: 01 |20 |0C |01 |00 Indica a la BT si debe o no encriptar las conexiones Prototipo de funci on Function HCI Write Authentication Enable (Autentication Enabled):status Valor 0x00 0x01 0x02 - 0xFF Descripci on Por Defecto, Sin autenticacion Con autenticacion Reservado

Cuadro 22: Authentication Enable: 1 Byte

Una vez nalizado el HCI Write Authentication Enable el Host Controller nos devuelve un Evento de Command Complete para informarnos del estado

HCI Write Voice Settings


Secuencia hexadecimal a enviar: 01 |26 |0C |02 |60 |00 Indica el formato de los paquetes de audio que se enviar an/recibir an Prototipo de funci on: Function HCI Write Voice Settings(Voice settings):status Valor XXXXXXXX10 XXXXXXXX11 00011000XX Descripci on Air Coding Format: A-law Reserved Default Condition, (X means that there is no default value for the corresponding bit. The manufacturer may use any value.

Cuadro 23: Voice settings: 2Bytes (10 bits)

28

HCI Write Connection Accept Timeout


Secuencia hexadecimal a enviar: 01 |16 |0C |02 |A0 |1F Tiempo que esperar a la BT antes de dar una conexion por erronea Prototipo de funci on: Function HCI Write connection Accept timeout (Conn Accept Timeout):status Valor Descripci on N = 0xXXXX Tiempo= N * 0.625 mseg Rango: 0x001 - 0xB540 Tiempo : 0.625 mseg - 29 Segundos Por defecto 0x1FA0 (5seg) Cuadro 24: Conn Accept Timeout: 2Bytes

HCI Write Page Timeout


Secuencia hexadecimal a enviar: 01 |18 |0C |02 |00 |20 Tiempo que esperar a la BT hasta dar un envio de datos por erroneo y desconectar Prototipo de funci on: Function HCI Write page Timeout (Page Timeout):status

29

Valor Descripci on N = 0xXXXX Tiempo= N * 0.625 mseg Rango: 0x001 - 0xB540 Tiempo : 0.625 mseg - 29 Segundos Por defecto 0x1FA0 (5seg) Cuadro 25: Page Timeout: 2Bytes

HCI Change Local Name


Secuencia hexadecimal a enviar: 01 |13 |0C |F8 |Nombre[248]) Nombre amigable con el que se identicar a la BT en caso de que le pregunten por el. Prototipo de funci on: Function HCI Change local name (Name):status Valor Descripci on Si el nombre contiene menos de 248 caracteres hay que rellenar con 0x00 (NULL) Cuadro 26: Name: 248Bytes

30

4.

Conclusiones.

Dada la escas sima documentaci on con la que cont abamos al inicio de este proyecto, u nicamente los White Paper que ofrece Bluetooth.org en su pagina Web, el desarrollo de este proyecto ha sido, pr acticamente en su totalidad, mediante ingenier a inversa, es decir, espiando la comunicaci on que se establece entre la tarjeta madre de Bluetooth y el programa de ejemplo que nos ofrec a el starter kit. El principal logro que cabe destacar de este proyecto es, que si a penas documentaci on hemos sido capaces de desarrollar una base de comunicaci on inal ambrica que puede ser aplicada a cualquier dispositivo basado en 8051 u nicamente a nadiendo un chip ROK 101/007 de Ericsson.

Conunicaci on serie

La utilidad de este proyecto est a justicada pues a partir de el, dada su generalidad, se puede construir la interface hardware para comunicaci on inal ambrica mediante bluetooth de cualquier dispositivo considerado perif erico que realice operaciones de E/S de datos. En particular, ya se est a desarrollando, en otro proyecto, un transmisor inal ambrico de electrocardiogramas en tiempo real para PDAs, PCs y tel efonos m oviles

31

5.

Bibliograf a
* Bluetooth V1.1 Core Specications: www.bluetooth.org * Juego de instrucciones del microcontrolador 8051: www.8052.com * LaTeX A document preparation system: www.latex-project.org

32

6.

Ap endices
Documentaci on t ecnica del Atmel AT89C2051 Documentaci on t ecnica del Ericsson ROK 101/007

33

Features
Compatible with MCS-51 Products 2K Bytes of Reprogrammable Flash Memory
Endurance: 1,000 Write/Erase Cycles 2.7V to 6V Operating Range Fully Static Operation: 0 Hz to 24 MHz Two-level Program Memory Lock 128 x 8-bit Internal RAM 15 Programmable I/O Lines Two 16-bit Timer/Counters Six Interrupt Sources Programmable Serial UART Channel Direct LED Drive Outputs On-chip Analog Comparator Low-power Idle and Power-down Modes

Description
The AT89C2051 is a low-voltage, high-performance CMOS 8-bit microcomputer with 2K bytes of Flash programmable and erasable read only memory (PEROM). The device is manufactured using Atmels high-density nonvolatile memory technology and is compatible with the industry-standard MCS-51 instruction set. By combining a versatile 8-bit CPU with Flash on a monolithic chip, the Atmel AT89C2051 is a powerful microcomputer which provides a highly-flexible and cost-effective solution to many embedded control applications. The AT89C2051 provides the following standard features: 2K bytes of Flash, 128 bytes of RAM, 15 I/O lines, two 16-bit timer/counters, a five vector two-level interrupt architecture, a full duplex serial port, a precision analog comparator, on-chip oscillator and clock circuitry. In addition, the AT89C2051 is designed with static logic for operation down to zero frequency and supports two software selectable power saving modes. The Idle Mode stops the CPU while allowing the RAM, timer/counters, serial port and interrupt system to continue functioning. The power-down mode saves the RAM contents but freezes the oscillator disabling all other chip functions until the next hardware reset.

8-bit Microcontroller with 2K Bytes Flash AT89C2051

Pin Configuration
PDIP/SOIC
RST/VPP (RXD) P3.0 (TXD) P3.1 XTAL2 XTAL1 (INT0) P3.2 (INT1) P3.3 (TO) P3.4 (T1) P3.5 GND 1 2 3 4 5 6 7 8 9 10 20 19 18 17 16 15 14 13 12 11 VCC P1.7 P1.6 P1.5 P1.4 P1.3 P1.2 P1.1 (AIN1) P1.0 (AIN0) P3.7

Rev. 0368E02/00

Block Diagram

AT89C2051

AT89C2051
Pin Description
VCC Supply voltage. GND Ground. Port 1 Port 1 is an 8-bit bi-irectional I/O port. Port pins P1.2 to P1.7 provide internal pullups. P1.0 and P1.1 require external pullups. P1.0 and P1.1 also serve as the positive input (AIN0) and the negative input (AIN1), respectively, of the on-chip precision analog comparator. The Port 1 output buffers can sink 20 mA and can drive LED displays directly. When 1s are written to Port 1 pins, they can be used as inputs. When pins P1.2 to P1.7 are used as inputs and are externally pulled low, they will source current (IIL) because of the internal pullups. Port 1 also receives code data during Flash programming and verification. Port 3 Port 3 pins P3.0 to P3.5, P3.7 are seven bi-irectional I/O pins with internal pullups. P3.6 is hard-wired as an input to the output of the on-chip comparator and is not accessible as a general purpose I/O pin. The Port 3 output buffers can sink 20 mA. When 1s are written to Port 3 pins they are pulled high by the internal pullups and can be used as inputs. As inputs, Port 3 pins that are externally being pulled low will source current (IIL) because of the pullups. Port 3 also serves the functions of various special features of the AT89C2051 as listed below:
Port Pin P3.0 P3.1 P3.2 P3.3 P3.4 P3.5 Alternate Functions RXD (serial input port) TXD (serial output port) INT0 (external interrupt 0) INT1 (external interrupt 1) T0 (timer 0 external input) T1 (timer 1 external input) Note: C1, C2 = 30 pF 10 pF for Crystals = 40 pF 10 pF for Ceramic Resonators

Each machine cycle takes 12 oscillator or clock cycles. XTAL1 Input to the inverting oscillator amplifier and input to the internal clock operating circuit. XTAL2 Output from the inverting oscillator amplifier.

Oscillator Characteristics
XTAL1 and XTAL2 are the input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator, as shown in Figure 1. Either a quartz crystal or ceramic resonator may be used. To drive the device from an external clock source, XTAL2 should be left unconnected while XTAL1 is driven as shown in Figure 2. There are no requirements on the duty cycle of the external clock signal, since the input to the internal clocking circuitry is through a divide-by-two flip-flop, but minimum and maximum voltage high and low time specifications must be observed. Figure 1. Oscillator Connections

Figure 2. External Clock Drive Configuration

Port 3 also receives some control signals for Flash programming and verification. RST Reset input. All I/O pins are reset to 1s as soon as RST goes high. Holding the RST pin high for two machine cycles while the oscillator is running resets the device. 3

Special Function Registers


A map of the on-chip memory area called the Special Function Register (SFR) space is shown in the table below. Note that not all of the addresses are occupied, and unoccupied addresses may not be implemented on the chip. Read accesses to these addresses will in general return Table 1. AT89C2051 SFR Map and Reset Values
0F8H 0F0H 0E8H 0E0H 0D8H 0D0H 0C8H 0C0H 0B8H 0B0H 0A8H 0A0H 98H 90H 88H 80H SCON 00000000 P1 11111111 TCON 00000000 TMOD 00000000 SP 00000111 TL0 00000000 DPL 00000000 TL1 00000000 DPH 00000000 TH0 00000000 TH1 00000000 PCON 0XXX0000 SBUF XXXXXXXX IP XXX00000 P3 11111111 IE 0XX00000 PSW 00000000 ACC 00000000 B 00000000 0FFH 0F7H 0EFH 0E7H 0DFH 0D7H 0CFH 0C7H 0BFH 0B7H 0AFH 0A7H 9FH 97H 8FH 87H

random data, and write accesses will have an indeterminate effect. User software should not write 1s to these unlisted locations, since they may be used in future products to invoke new features. In that case, the reset or inactive values of the new bits will always be 0.

AT89C2051

AT89C2051
Restrictions on Certain Instructions
The AT89C2051 and is an economical and cost-effective member of Atmels growing family of microcontrollers. It contains 2K bytes of flash program memory. It is fully compati bl e with the MCS-51 arc hitec tur e, and c an be programmed using the MCS-51 instruction set. However, there are a few considerations one must keep in mind when utilizing certain instructions to program this device. All the instructions related to jumping or branching should be restricted such that the destination address falls within the physical program memory space of the device, which is 2K for the AT89C2051. This should be the responsibility of the software programmer. For example, LJMP 7E0H would be a valid instruction for the AT89C2051 (with 2K of memory), whereas LJMP 900H would not. 1. Branching instructions: LCALL, LJMP, ACALL, AJMP, SJMP, JMP @A+DPTR These unconditional branching instructions will execute correctly as long as the programmer keeps in mind that the destination branching address must fall within the physical boundaries of the program memory size (locations 00H to 7FFH for the 89C2051). Violating the physical space limits may cause unknown program behavior. CJNE [...], DJNZ [...], JB, JNB, JC, JNC, JBC, JZ, JNZ With these conditional branching instructions the same rule above applies. Again, violating the memory boundaries may cause erratic execution. For applications involving interrupts the normal interrupt service routine address locations of the 80C51 family architecture have been preserved. 2. MOVX-related instructions, Data Memory: The AT89C2051 contains 128 bytes of internal data memory. Thus, in the AT89C2051 the stack depth is limited to 128 bytes, the amount of available RAM. External DATA memory access is not supported in this device, nor is external PROGRAM memory execution. Therefore, no MOVX [...] instructions should be included in the program. A typical 80C51 assembler will still assemble instructions, even if they are written in violation of the restrictions mentioned above. It is the responsibility of the controller user to know the physical features and limitations of the device being used and adjust the instructions used correspondingly.

Program Memory Lock Bits


On the chip are two lock bits which can be left unprogrammed (U) or can be programmed (P) to obtain the additional features listed in the table below:

Lock Bit Protection Modes(1)


Program Lock Bits LB1 1 2 3 Note: U P P LB2 U U P Protection Type No program lock features. Further programming of the Flash is disabled. Same as mode 2, also verify is disabled.

1. The Lock Bits can only be erased with the Chip Erase operation.

Idle Mode
In idle mode, the CPU puts itself to sleep while all the onchip peripherals remain active. The mode is invoked by software. The content of the on-chip RAM and all the special functions registers remain unchanged during this mode. The idle mode can be terminated by any enabled interrupt or by a hardware reset. P1.0 and P1.1 should be set to 0 if no external pullups are used, or set to 1 if external pullups are used. It should be noted that when idle is terminated by a hardware reset, the device normally resumes program execution, from where it left off, up to two machine cycles before the internal reset algorithm takes control. On-chip hardware inhibits access to internal RAM in this event, but access to the port pins is not inhibited. To eliminate the possibility of an unexpected write to a port pin when Idle is terminated by reset, the instruction following the one that invokes Idle should not be one that writes to a port pin or to external memory.

Power-down Mode
In the power down mode the oscillator is stopped, and the instruction that invokes power down is the last instruction executed. The on-chip RAM and Special Function Registers retain their values until the power down mode is terminated. The only exit from power down is a hardware reset. Reset redefines the SFRs but does not change the on-chip RAM. The reset should not be activated before VCC is restored to its normal operating level and must be held active long enough to allow the oscillator to restart and stabilize. P1.0 and P1.1 should be set to 0 if no external pullups are used, or set to 1 if external pullups are used. 5

Programming The Flash


The AT89C2051 is shipped with the 2K bytes of on-chip PEROM code memory array in the erased state (i.e., contents = FFH) and ready to be programmed. The code memory array is programmed one byte at a time. Once the array is programmed, to re-program any non-blank byte, the entire memory array needs to be erased electrically. Internal Address Counter: The AT89C2051 contains an internal PEROM address counter which is always reset to 000H on the rising edge of RST and is advanced by applying a positive going pulse to pin XTAL1. Programming Algorithm: To program the AT89C2051, the following sequence is recommended. 1. Power-up sequence: Apply power between VCC and GND pins Set RST and XTAL1 to GND 2. Set pin RST to H Set pin P3.2 to H 3. Apply the appropriate combination of H or L logic levels to pins P3.3, P3.4, P3.5, P3.7 to select one of the programming operations shown in the PEROM Programming Modes table. To Program and Verify the Array: 4. Apply data for Code byte at location 000H to P1.0 to P1.7. 5. Raise RST to 12V to enable programming. 6. Pulse P3.2 once to program a byte in the PEROM array or the lock bits. The byte-write cycle is self-timed and typically takes 1.2 ms. 7. To verify the programmed data, lower RST from 12V to logic H level and set pins P3.3 to P3.7 to the appropiate levels. Output data can be read at the port P1 pins. 8. To program a byte at the next address location, pulse XTAL1 pin once to advance the internal address counter. Apply new data to the port P1 pins. 9. Repeat steps 5 through 8, changing data and advancing the address counter for the entire 2K bytes array or until the end of the object file is reached. 10.Power-off sequence: set XTAL1 to L set RST to L Turn VCC power off Data Polling: The AT89C2051 features Data Polling to indicate the end of a write cycle. During a write cycle, an attempted read of the last byte written will result in the complement of the written data on P1.7. Once the write cycle has been completed, true data is valid on all outputs, and

the next cycle may begin. Data Polling may begin any time after a write cycle has been initiated. Ready/Busy: The Progress of byte programming can also be monitored by the RDY/BSY output signal. Pin P3.1 is pulled low after P3.2 goes High during programming to indicate BUSY. P3.1 is pulled High again when programming is done to indicate READY. Program Verify: If lock bits LB1 and LB2 have not been programmed code data can be read back via the data lines for verification: 1. Reset the internal address counter to 000H by bringing RST from L to H. 2. Apply the appropriate control signals for Read Code data and read the output data at the port P1 pins. 3. Pulse pin XTAL1 once to advance the internal address counter. 4. Read the next code data byte at the port P1 pins. 5. Repeat steps 3 and 4 until the entire array is read. The lock bits cannot be verified directly. Verification of the lock bits is achieved by observing that their features are enabled. Chip Erase: The entire PEROM array (2K bytes) and the two Lock Bits are erased electrically by using the proper combination of control signals and by holding P3.2 low for 10 ms. The code array is written with all 1s in the Chip Erase operation and must be executed before any nonblank memory byte can be re-programmed. Reading the Signature Bytes: The signature bytes are read by the same procedure as a normal verification of locations 000H, 001H, and 002H, except that P3.5 and P3.7 must be pulled to a logic low. The values returned are as follows. (000H) = 1EH indicates manufactured by Atmel (001H) = 21H indicates 89C2051

Programming Interface
Every code byte in the Flash array can be written and the entire array can be erased by using the appropriate combination of control signals. The write operation cycle is selftimed and once initiated, will automatically time itself to completion. All major programming vendors offer worldwide support for the Atmel microcontroller series. Please contact your local programming vendor for the appropriate software revision.

AT89C2051

AT89C2051
Flash Programming Modes
Mode Write Code Data(1)(3) RST/VPP 12V P3.2/PROG P3.3 L P3.4 H P3.5 H P3.7 H

Read Code Data(1) Write Lock Bit - 1

H 12V

L H

L H

H H

H H

Bit - 2

12V

Chip Erase

12V

(2)

Read Signature Byte Notes:

1. The internal PEROM address counter is reset to 000H on the rising edge of RST and is advanced by a positive pulse at XTAL 1 pin. 2. Chip Erase requires a 10 ms PROG pulse. 3. P3.1 is pulled Low during programming to indicate RDY/BSY.

Figure 3. Programming the Flash Memory

Figure 4. Verifying the Flash Memory

PP

Flash Programming and Verification Characteristics


TA = 0C to 70C, VCC = 5.0 10%
Symbol VPP IPP tDVGL tGHDX tEHSH tSHGL tGHSL tGLGH tELQV tEHQZ tGHBL tWC tBHIH tIHIL Note: 1. Parameter Programming Enable Voltage Programming Enable Current Data Setup to PROG Low Data Hold after PROG P3.4 (ENABLE) High to VPP VPP Setup to PROG Low VPP Hold after PROG PROG Width ENABLE Low to Data Valid Data Float after ENABLE PROG High to BUSY Low Byte Write Cycle Time RDY/BSY\ to Increment Clock Delay Increment Clock High Only used in 12-volt programming mode. 1.0 200 0 1.0 1.0 1.0 10 10 1 110 1.0 1.0 50 2.0 Min 11.5 Max 12.5 250 Units V A s s s s s s s s ns ms s ns

Flash Programming and Verification Waveforms

AT89C2051

AT89C2051
Absolute Maximum Ratings*
Operating Temperature ................................. -55C to +125C Storage Temperature ..................................... -65C to +150C Voltage on Any Pin with Respect to Ground .....................................-1.0V to +7.0V Maximum Operating Voltage ............................................ 6.6V DC Output Current...................................................... 25.0 mA *NOTICE: Stresses beyond those listed under Absolute Maximum Ratings may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or any other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability.

DC Characteristics
TA = -40C to 85C, VCC = 2.0V to 6.0V (unless otherwise noted)
Symbol VIL VIH VIH1 VOL VOH Parameter Input Low-voltage Input High-voltage Input High-voltage Output Low-voltage (Ports 1, 3)
(1)

Condition

Min -0.5

Max 0.2 VCC - 0.1 VCC + 0.5 VCC + 0.5 0.5

Units V V V V V V V

(Except XTAL1, RST) (XTAL1, RST) IOL = 20 mA, VCC = 5V IOL = 10 mA, VCC = 2.7V IOH = -80 A, VCC = 5V 10% IOH = -30 A IOH = -12 A

0.2 VCC + 0.9 0.7 VCC

Output High-voltage (Ports 1, 3)

2.4 0.75 VCC 0.9 VCC -50 -750 10 20 0 50 VCC 300 10 15/5.5 5/1 100

IIL ITL ILI VOS VCM RRST CIO ICC

Logical 0 Input Current (Ports 1, 3) Logical 1 to 0 Transition Current (Ports 1, 3) Input Leakage Current (Port P1.0, P1.1) Comparator Input Offset Voltage Comparator Input Common Mode Voltage Reset Pull-down Resistor Pin Capacitance Power Supply Current

VIN = 0.45V VIN = 2V, VCC = 5V 10% 0 < VIN < VCC VCC = 5V

A A A mV V K pF mA mA A

Test Freq. = 1 MHz, TA = 25C Active Mode, 12 MHz, VCC = 6V/3V Idle Mode, 12 MHz, VCC = 6V/3V P1.0 & P1.1 = 0V or VCC

Power-down Mode(2) Notes:

VCC = 6V P1.0 & P1.1 = 0V or VCC

VCC = 3V P1.0 & P1.1 = 0V or VCC 20 A 1. Under steady state (non-transient) conditions, IOL must be externally limited as follows: Maximum IOL per port pin: 20 mA Maximum total IOL for all output pins: 80 mA If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test conditions. 2. Minimum VCC for Power-down is 2V.

External Clock Drive Waveforms

External Clock Drive


VCC = 2.7V to 6.0V Symbol 1/tCLCL tCLCL tCHCX tCLCX tCLCH tCHCL Parameter Oscillator Frequency Clock Period High Time Low Time Rise Time Fall Time Min 0 83.3 30 30 20 20 Max 12 VCC = 4.0V to 6.0V Min 0 41.6 15 15 20 20 Max 24 Units MHz ns ns ns ns ns

10

AT89C2051

AT89C2051
()

Serial Port Timing: Shift Register Mode Test Conditions


VCC = 5.0V 20%; Load Capacitance = 80 pF
12 MHz Osc Symbol tXLXL tQVXH tXHQX tXHDX tXHDV Parameter Serial Port Clock Cycle Time Output Data Setup to Clock Rising Edge Output Data Hold after Clock Rising Edge Input Data Hold after Clock Rising Edge Clock Rising Edge to Input Data Valid Min 1.0 700 50 0 700 Max Variable Oscillator Min 12tCLCL 10tCLCL-133 2tCLCL-117 0 10tCLCL-133 Max Units s ns ns ns ns

Shift Register Mode Timing Waveforms

AC Testing Input/Output Waveforms(1)

Float Waveforms(1)

Note:

1. AC Inputs during testing are driven at VCC - 0.5V for a logic 1 and 0.45V for a logic 0. Timing measurements are made at VIH min. for a logic 1 and VIL max. for a logic 0.

Note:

1. For timing purposes, a port pin is no longer floating when a 100 mV change from load voltage occurs. A port pin begins to float when 100 mV change frothe loaded VOH/VOL level occurs.

11

AT89C2051
TYPICAL ICC - ACTIVE (85C)
20 Vcc=6.0V

I 15 C C 10 m A
5

Vcc=5.0V Vcc=3.0V

0 0 6 12 18 24

FREQUENCY (MHz)

AT89C2051
TYPICAL ICC - IDLE (85C)
3 Vcc=6.0V

I C 2 C m 1 A

Vcc=5.0V

Vcc=3.0V 0 0 3 6 9 12

FREQUENCY (MHz)

AT89C2051
TYPICAL ICC vs. VOLTAGE- POWER DOWN (85C)
20

I 15 C C 10 A
5

0 3.0V

4.0V

5.0V

6.0V

Vcc VOLTAGE

Notes:

1. XTAL1 tied to GND for ICC (power-down) 2. P.1.0 and P1.1 = VCC or GND 3. Lock bits programmed

12

AT89C2051

AT89C2051
Ordering Information
Speed (MHz) 12 Power Supply 2.7V to 6.0V Ordering Code AT89C2051-12PC AT89C2051-12SC AT89C2051-12PI AT89C2051-12SI 24 4.0V to 6.0V AT89C2051-24PC AT89C2051-24SC AT89C2051-24PI AT89C2051-24SI Package 20P3 20S 20P3 20S 20P3 20S 20P3 20S Operation Range Commercial (0C to 70C) Industrial (-40C to 85C) Commercial (0C to 70C) Industrial (-40C to 85C)

Package Type 20P3 20S 20-lead, 0.300 Wide, Plastic Dual In-line Package (PDIP) 20-lead, 0.300 Wide, Plastic Gull Wing Small Outline (SOIC)

13

Packaging Information
20P3, 20-lead, 0.300" Wide, Plastic Dual Inline Package (PDIP) Dimensions in Inches and (Millimeters)
JEDEC STANDARD MS-001 AD
1.060(26.9) .980(24.9)

20S, 20-lead, 0.300" Wide, Plastic Gull WIng Small Outline (SOIC) Dimensions in Inches and (Millimeters)

PIN 1

0.020 (0.508) 0.013 (0.330)

.280(7.11) .240(6.10)
PIN 1

0.299 (7.60) 0.420 (10.7) 0.291 (7.39) 0.393 (9.98)

.900(22.86) REF .210(5.33) MAX SEATING PLANE .150(3.81) .115(2.92) .110(2.79) .090(2.29) .070(1.78) .045(1.13) .325(8.26) .300(7.62) .014(.356) .008(.203) 0 REF 15

.090(2.29) MAX
.050 (1.27) BSC

.005(.127) MIN

.015(.381) MIN .022(.559) .014(.356)

0.513 (13.0) 0.497 (12.6)

0.105 (2.67) 0.092 (2.34)

0.012 (0.305) 0.003 (0.076)

0 REF 8

0.013 (0.330) 0.009 (0.229)

.430(10.92) MAX

0.035 (0.889) 0.015 (0.381)

14

AT89C2051

Atmel Headquarters
Corporate Headquarters
2325 Orchard Parkway San Jose, CA 95131 TEL (408) 441-0311 FAX (408) 487-2600

Atmel Operations
Atmel Colorado Springs
1150 E. Cheyenne Mtn. Blvd. Colorado Springs, CO 80906 TEL (719) 576-3300 FAX (719) 540-1759

Europe
Atmel U.K., Ltd. Coliseum Business Centre Riverside Way Camberley, Surrey GU15 3YL England TEL (44) 1276-686-677 FAX (44) 1276-686-697

Atmel Rousset
Zone Industrielle 13106 Rousset Cedex France TEL (33) 4-4253-6000 FAX (33) 4-4253-6001

Asia
Atmel Asia, Ltd. Room 1219 Chinachem Golden Plaza 77 Mody Road Tsimhatsui East Kowloon Hong Kong TEL (852) 2721-9778 FAX (852) 2722-1369

Japan
Atmel Japan K.K. 9F, Tonetsu Shinkawa Bldg. 1-24-8 Shinkawa Chuo-ku, Tokyo 104-0033 Japan TEL (81) 3-3523-3551 FAX (81) 3-3523-7581

Fax-on-Demand
North America: 1-(800) 292-8635 International: 1-(408) 441-0732

e-mail
literature@atmel.com

Web Site
http://www.atmel.com

BBS
1-(408) 436-4309
Atmel Corporation 2000. Atmel Corporation makes no warranty for the use of its products, other than those expressly contained in the Company s standard warranty which is detailed in Atmel s Terms and Conditions located on the Company s web site. The Company assumes no responsibility for any errors which may appear in this document, reserves the right to change devices or specifications detailed herein at any time without notice, and does not make any commitment to update the information contained herein. No licenses to patents or other intellectual property of Atmel are granted by the Company in connection with the sale of Atmel products, expressly or by implication. Atmel s products are not authorized for use as critical components in life suppor t devices or systems. Marks bearing

and/or

are registered trademarks and trademarks of Atmel Corporation. Printed on recycled paper.
0368E02/00/xM

Terms and product names in this document may be trademarks of others.

ROK 101 007

ROK 101 007 Bluetooth Module

Key Features
Pre-qualified Bluetooth 1.0B Module RF output power class 2 FCC and ETSI approved 460 kb/s max data rate over UART Multiple interface for different applications -UART for data -PCM for voice -USB for voice and data I2C interface Internal crystal oscillator HCI firmware included Multi Point Operation Built-in shielding

Suggested Applications
Computers and peripherals Handheld devices and accessories Access points

Description
ROK 101 007 is a short-range module for implementing Bluetooth functionality into various electronic devices. The module consists of three major parts; a baseband controller, a flash memory, and a radio that operates in the globally available 2.42.5 GHz free ISM band. Both data and voice transmission is supported by the module. Communication between the module and the host controller is carried out using a highspeed USB interface compliant with USB Specifications 1.1 or an UART/ PCM interface. When using the USB interface, the module appears as a USB slave device and therefore requires no PC resources. ROK 101 007, which is compliant with Bluetooth version 1.0B, is a Class 2 Bluetooth Module (0 dBm) and is type-approved. The module supports all Bluetooth profiles.

ROK 101 007

Preliminary

I2C_DATA I2C_CLK TXD RXD RTS CTS DETACH WAKE_UP D+ DPCM_IN PCM_OUT PCM_SYNC PCM_CLK

T6 C3 B5 A5 A6 B6 C1 B4 B1 B2 A1 A2 A3 A4

C4 Baseband C6 UART Voltage Regulation C2

VCC_IO VCC ON

ADDR USB DATA FLASH Memory PCM CTRL B3 R1 R2 T1 T3 GND GND GND GND GND

POR

Radio Module Loop Filter Radio ASIC VCO Tank TXBalun RXBalun Switch Antenna Filter T2 ANT R4 R5 R6 T4 T5 C5 NC NC NC NC NC NC

PBA 313 01/2


13MHz Crystal

R3

RESET#

Figure 1. Block Diagram

Audio

HCI Link Manager

0 1 2 3 cm

Baseband Radio

Figure 2. Actual size of the Ericsson Bluetooth Module, and also showing the HW and FW stack.

Preliminary
Absolute Maximum Ratings
Parameter Symbol Min Typ

ROK 101 007

Max

Unit

Temperature Storage temperature Operating temperature Power Supply VCC VCC_IO Digital Inputs Input low voltage Input high voltage

TStg TAmb VCC VCC_IO VIL VIH

-30 0 -0.3 -0.8 -0.5

+85 +75 +5.25 +3.6

C C V V V V

VCC_IO +0.3

Recommended Operating Conditions


Temperature Ambient temperature, Test Power Supply Positive Supply Voltage I/O Ports Supply Voltage Tamb VCC VCC_IO +23 +3.3 +3.3 C V V

Electrical Characteristics
DC Specifications Unless otherwise noted, the specification applies for TAmb = 0 to +75C, 3.175 < VCC < 5.25V
Parameter Condition Symbol Min Typ Max Unit

Power Supply Supply Voltage I/O Ports Supply Voltage Digital Inputs Logical Input High Logical Input Low Logical Input High Logical Input Low Digital Outputs Logical Output High Logical Output Low

See note 10 Except ON signal Except ON signal ON signal only ON signal only

VCC VCC_IO VIH1 VIL2 VIH2 VIL2 VOH VOL

3.175 2.7 0.7 x VCC_IO 0 2.0 0 0.9 x VCC_IO 0

3.3 3.3

5.25 3.6 VCC_IO 0.3 x VCC_IO VCC 0.4 VCC_IO 0.1 x VCC_IO

V V V V V V V V

ROK 101 007

Preliminary

5Parameter

Condition

Symbol

Min

Typ

Max

Unit

Average Current Consumption Standby Shutdown - SW Shutdown HW Page Scan Mode R0

Average ICC + ICC_IO ISTA ISSW ISHW IPSM1 5.95 2.35 1 50 mA mA A mA

Page Scan Mode R1

Page Scan Mode R2

Inquiry Scan
with Page Scan Mode R0.

Inquiry Scan
with Page Scan Mode R1.

Inquiry Scan
with Page Scan Mode R2.

Connect State VCC_IO Current

See note 1 Page Scan Enable Page scan window: continuous Page scan interval : n/a (0s) Page Scan Enable Page scan window: 11.25ms Page scan interval : 1.28s Page Scan Enable Page scan window: 11.25ms Page scan interval : 2.56s Inquiry Scan Enable Page Scan Window : 2.56s 11.25ms Page Scan Interval : 2.56s Inquiry Scan Window : 11.25ms Inquiry Scan Interval : 2.56s Inquiry Scan Enable Page Scan Window : 11.25ms Page Scan Interval : 1.28s Inquiry Scan Window : 11.25ms Inquiry Scan Interval : 2.56s Inquiry Scan Enable Page Scan Window : 11.25ms Page Scan Interval : 2.56s Inquiry Scan Window : 11.25ms Inquiry Scan Interval : 2.56s Established connection with data transfer Only ICC_IO , VCC_IO=TBD

IPSM2

6.35

mA

IPSM3

6.15

mA

IISM1

50

mA

IISM2

6.55

mA

IISM3

6.35

mA

ICS ICC_IO

26 TBD

mA mA

Preliminary
RF Specifications
Parameter Condition Symbol Min Typ

ROK 101 007

Max

Unit

General Frequency Range Double Sided IF Bandwidth Antenna load VSWR VSWR Receive Performance Sensitivity level Max input level C/I co-channel C/I 1MHz C/I 2MHz C/I 3MHz Blocking, C/IDC-5GHz Out-of-band blocking

2.402 1 50 3:1 3:1

2.480

GHz MHz

RX mode TX mode, see note 2 PIN: -70dBm, 75kHz offset (max), PIN: -20dBm, 75kHz offset (max), C: -60 dBm C: -60 dBm C: -60 dBm C: -67 dBm See figure 6 30-1910 MHz 1910-2000 MHz 2000-2399 MHz 2484-3000 MHz 3.00-12.75 GHz 30 MHz to 1 GHz 1 GHz to 12.75 GHz see notes 3,4 and figure 3 see note 5 fMod

0.1% 0.1% 14 +4 -30 -40 +4 -10 -27 -27 -10 -57 -47 140 175 +48 4 25 40 40 1.000 -36 -30 -47 -47 3,2 -250 13.0000 -20 150 15 3 25 11 +20 +250

BER BER dB dB dB dB dBm dBm dBm dBm dBm dBm dBm kHz kHz dBm kHz kHz kHz MHz dBm dBm dBm dBm kHz ppm MHz ppm s n/a n/a

Spurious Emissions Spurious Emissions Transmitter Performance Frequency deviation Initial frequency error TX power TX carrier drift in 1 slot (366 s) TX carrier drift in 3 slots (1598 s) TX carrier drift in 5 slots (2862 s) 20 dB bandwidth

-48 -2 fDrift1 -25 fDrift2 -40 see figure 4 fDrift3 -40 Measured with RBW: 10 kHz and peak detector

1.5

Spurious Emissions 30 MHz 1GHz Spurious Emissions 1 GHz 12.75 GHz Spurious Emissions 1.8 Hz 1.9 GHz Spurious Emissions 5.15 GHz 5.3 GHz Timing performance LPO_CLK frequency Trimmed, see note 6 fLPO_CLK Tolerance of LPO_CLK see note 6 System clock frequency fSYS_CLK Tolerance of system clock see note 5 Channel switching time see figure 5 Received Signal Strength Indicator RSSI Input power = -40 dBm RSSI Input power = -60 dBm

ROK 101 007


RF Specifications continued...

Preliminary

TX_DATA: See note 4

64 logic 'Low' & 64 logic 'High'

Figure 3. Frequency Deviation


SYNT_ON TX_ON Df

PHD_OFF
PHD_OFF +f dev TX carrier dri ft TX_DATA: High

-f dev

TX_DATA: Low

TX_DATA: High

t=214 s

t=580 s

t=1598 s

t=2862 s

Figure 4. Frequency drift.

Old ch.

SYNT_ON

TX_ON

New ch. Channel switching time

50 kHz

Figure 5. Channel switching time 6

Preliminary
RF Specifications continued...
C/I Blocking The blocking characteristics can be basically split into two regions: Inband and Out-of-band. Blocking is performed both on the chip and on the module level.
dB(RX path)
0

ROK 101 007

m1

-10

-20

-30

In-band Filtering on chip C/I @ 2MHz: -30 dB -> 0.1%BER C/I 3MHz: -40 dB -> 0.1%BER Out-of-band Antenna filter, DC to 1.9 GHz and 3:rd harmonic. Switch, low freq. and 2:nd harmonic. RX-balun, low freq. and 2:nd harmonic. On-chip IF filter

m4
-40

m3
-50

-60

-70

m2

-80

-90

-100 0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

m1
freq=2.450GHz dB( RX path)=-3.529

GH z

m3
freq=1.800GHz dB(RX path) = -47.426

Figure 6 shows the combination blocking effect of the antenna switch, antenna filter and RX balun. In addition to the blocking characteristics shown in figure 6, there is antenna isolation and filtering on the chip. Marker 1 shows the region where the Bluetooth band is located. Markers 2 - 4 show the blocking at the telecom frequency bands. An example of the total blocking characteristics can be seen in figure 7.

m2
freq=900.0MHz dB(RX path) = -74.580

m4
freq=1.900GHz dB(RX path ) = -36.537

Figure 6. Typical blocking characteristics excluding antenna isolation and on chip filtering.

Example 1
Interference of +33 dBm at 2015 MHz.

Example 2
Interference of +33 dBm at 1910 MHz.

Antenna isolation Antenna filter, Antenna switch, RX-balun

15 dB 27 dB

Antenna isolation Antenna filter, Antenna switch, RX-balun

25 dB 36 dB

Interference level before IF filter +33-15-27= -9 dBm

Interference level before IF filter +33-25-36= -28 dBm

0.1% BER requires a C/I of more than -40 dB at the IF filter. 0.1% BER carrier level -40 + (-9)= 0.1% BER carrier level -40 + (-28)= -68 dBm

-49 dBm

Figure 7. Blocking examples.

ROK 101 007

Preliminary

Pin Description
Pin Pin Name Type Direction Description

A1 A2 A3 A4 A5 A6 B1 B2 B3 B4 B5 B6 C1 C2 C3 C4 C5 C6 R1 R2 R3 R4 R5 R6 T1 T2 T3 T4 T5 T6

PCM_IN PCM_OUT PCM_SYNC PCM_CLK RXD RTS D+ DGND WAKE_UP TXD CTS DETACH ON I2C_CLK VCC_IO NC VCC GND GND RESET# NC NC NC GND ANT GND NC NC I2C_DATA

CMOS CMOS CMOS CMOS CMOS CMOS CMOS CMOS Power CMOS CMOS CMOS CMOS Power CMOS Power Power Power Power CMOS Power RF Power Power CMOS

In Out In/Out In/Out Input Input In/Out In/Out Power Output Output Output Input Input Output Power Power Power Power Input Power In/Out Power Power In/Out

PCM data, see notes 7,9 PCM data, see notes 7,9 Sets the PCM data sampling rate, see notes 7,9 PCM clock that sets the PCM data rate, see notes 7,9 RX data to the UART, see note 9 Flow control signal, Request To Send data from UART, see notes 7,9 USB data pin, see notes 9,10 USB data pin, see notes 9,10 Signal ground Indicates that the module wants to be attached to the USB, Active High. See notes 9,10 TX data from the UART, see note 9 Flow control signal, Clear To Send data from UART, see note 9 Indicates that the USB host wants to detach the module, Active High. See notes 7,9 When tied to VCC, the module is enabled. I2C clock signal, see note 9 External supply rail to the Input / Output ports Do not connect Supply Voltage Signal ground Signal ground Active low reset, see notes 8,9 Do not connect Do not connect Do not connect Signal Ground 50 Antenna connection Signal Ground Test point, internal voltage regulator - Do not connect Do not connect I2C data signal, see note 9

Notes 1. Current consumption is based upon when the module is when ON is low and VCC_IO is grounded. 2. During the TX mode, the VSWR specification states the limits that are acceptable before any other RF parameters are strongly effected, i.e. frequency deviation and initial frequency error. 3. Frequency deviation measurements are now recorded differentially, (f Mod1 - f Mod0 ) / 2. 4. Provided that the TX INV register (bit 0) has been set in the enable register at startup. 5. Tolerance for the system clock takes into account both the complete temperature range and aging of the crystal. 6. LPO_CLK frequency is pre-trimmed within a tolerance of 250ppm. 7. 100k pull-up resistors to VCC_IO are used on the module. PCM signals direction is programmable 8. RESET# signal must be fed from an open drain output. 9. CMOS buffers are low voltage TTL compatible signals. 10. To be compliant with the USB specification, VCC_IO 3.11V

Preliminary

ROK 101 007

Mechanical Specification

32.8

0.2

1.6 5.05 7.85

0.2 0.2 0.2

1.6

0.2
0.2

7.85

0.2
16.8 2.75 max without solder balls

14.1 15.7

0.2 0.2

14.1

0.2

Detail A

approx 0.2 mm

Detail A
0.54 0.2

Co-planarity 0.1 mm

3.12 4.39 5.66 6.93 8.2 9.47

TR

6 5 4 3 2 1

CBA

Pad size: 35 mil = 0.889 mm Tolerance on placement: 0.02 mm

Figure 8. Mechanical dimensions.

22.22 23.5 24.76

5.72 6.98

ROK 101 007


Application Block Schematics
USB Application

Preliminary

VCC

VCC_IO

ON

VCC

USB Host

D+

D-

Bluetooth Module

Wake_up

Control

Detach GND

GND

Figure 9. A typical USB configuration. UART and PCM Application

VCC ON VCC_IO RS232 4 RS 232


transceiver
VCC_IO ON VCC

UART

Bluetooth Module

4
GND

Codec

PCM

GND
Figure 10. A typical UART or PCM configuration.

10

Preliminary

ROK 101 007

Functional Description
The ROK 101 007 is a complete Bluetooth module that has been specified and designed according to the Bluetooth System v1.0B. Its implementation is based on a highperformance integrated radio transceiver (PBA 313 01 /2) working with a baseband controller, a flash memory and surrounding secondary components features low energy consumption for use in battery operated devices. Block Diagram ROK 101 007 has five major operational blocks. Figure 11 illustrates the interaction of the various blocks. The functionality of each block is as follows: 1. Radio functionality is achieved by using the Bluetooth Radio, PBA 313 01/ 2. Six operational blocks are shown for the radio section and their operation is as follows: 1a) VCO-tank is a part of the phase locked loop. The modulation is performed directly on the VCO. To ensure high performance the VCO-tank is laser trimmed.

1b) Loop filter, filters the tuning voltage of the VCO-tank. 1c) RX-balun handles transformation from unbalanced to balanced transmission. 1d) TX-balun handles biasing of the output amplifier stage and transformation from balanced to unbalanced transmission. 1e) Antenna switch directs the power either from the antenna filter to the receive ports or from the ASIC output ports to the antenna filter. 1f) Antenna filter band-pass filters the radio signal. 2. The baseband controller is an ARM7-Thumb based chip that controls the operation of the radio transceiver via one of the interface methods; USB or UART. Additionally, the baseband controller has a PCM Voice interface and I2C interface. A Flash memory is used together with the baseband controller. Please, refer also to the Firmware section.

4.

The power management block regulates and filters the supply voltage. VCC is typically 3.3V and two regulated voltages are produced, 2.8V and 2.2VNOM. An internal clock is mounted on the module. The clock frequency is 13MHz and is generated from a crystal oscillator that guarantees a timing accuracy within 20ppm.

5.

Bluetooth Module stack


The Host Controller Interface (HCI) handles the communication by the transport layer through the UART or USB interface with the host. The Baseband and radio provides a secure and reliable radio link for higher layers. The following sections describe the Bluetooth module stack in more detail. It is implemented in accordance with and complies with the Specification of the Bluetooth System v1.0B.

3.

2
I2C Interface (2) USB Interface (4) Baseband DATA PCM Voice Interface (4) Voltage Regulation ADDR

POWER (3)

UART Interface (4)

3
FLASH Memory

Audio

HCI Link Manager Baseband

CTRL

1
Loop Filter Radio ASIC VCO Tank TXBalun RXBalun Switch

Radio Module

Antenna Filter

Radio
ANT

PBA 313 01/2 RESET 13MHz Crystal

Figure 11. Simplified Block Diagram

Figure 12. HW/FW parts included in the Ericsson Buetooth module. 11

ROK 101 007

Preliminary

Bluetooth Radio Interface The Bluetooth module is a class 2 device with 4dBm maximum output power with no power control needed. Nominal range of the module with a typical antenna is up to a range of 10 m (at 0 dBm). It is compliant with FCC and ETSI regulations in the ISM band. Baseband Bluetooth uses an ad-hoc net structure with a maximum of eight active units in a single piconet. By default the first unit setting up a connection is the master of the point to point link. The master transmits in the even timeslots and the slave transmits in the odd timeslots. For full duplex transmission, a TimeDivision Duplex (TDD) scheme is used. Packets are sent over the air in timeslots, with a nominal length of 625 s. A packet can be extended to a maximum of 5 timeslots (DM5 and

DH5 packets) and is then sent by using the same RF channel for the entire packet. Two types of connections are provided - Asynchronous Connectionless Link (ACL) for data and the Synchronous Connection Oriented Link (SCO) for voice. Three 64 kb/s voice channels can be supported simultaneously. Furthermore, there are also packages used for link control purposes. A variety of different packet types with error correction schemes and data rates can be used over the air interface. Also asymmetric communication is available for high speed communication in one direction. The Baseband provides the linksetup and control routines for the layers above. Furthermore, the Baseband also provides Bluetooth

security like encryption, authentication and key management. Please refer to the Specification of the Bluetooth System v1.0B part B for in-depth information regarding the Baseband.

Firmware (FW)
The module includes firmware for the host controller interface, HCI, and the link manager, LM. The FW resides in the Flash and is available in object code format. Link Manager (LM) The Link Manager in each Bluetooth module can communicate with another Link Manager by using the Link Manager Protocol (LMP) which is a peer to peer protocol. The LMP messages have the highest priority and are used for link-setup, security, control and power saving modes. The receiving Link Manager

Type ID NULL POLL FHS

User Payload (bytes) na na na 18

FEC na na na 2/3

CRC na na na yes

Symetric Max. rate na na na na

Asymetric Max.rate na na na na

LM LC RF

LMP

LM LC RF

Physical layer

Link control packets

Figure 13. Link manager


Payload Header (bytes) 1 1 2 2 2 2 1 User Payload (bytes) 0-17 0-27 0-121 0-183 0-224 0-339 0-29 Symetric Max. rate (kb/s) 108.8 172.8 258.1 390.4 286.7 433.9 185.6 Asymetric Max rate (kb/s) Forward 108.8 172.8 387.2 585.6 477.8 723.2 185.6 Reverse 108.8 172.8 54.4 86.4 36.3 57.6 185.6

Type DM1 DH1 DM3 DH3 DM5 DH5 AUX1

FEC 2/3 no 2/3 no 2/3 no no

CRC yes yes yes yes yes yes no

filter-out the message and does not need to acknowledge the message to the transmitting LM due to the reliable link provided by the Baseband and radio. LM to LM communication can take place without actions taken by the host. Discovery of features at other Bluetooth enabled devices nearby can be found and saved for later use by the host. Please refer to the Specification of the Bluetooth System v1.0B part C for in-depth information regarding the LMP.

ACL packets
Payload header (bytes) na na na 1D User Payload (bytes) 10 20 30 10+(0-9) D Symetric Max. rate (kb/s) 64.0 64.0 64.0 64.0+57.6 D

Type HV1 HV2 HV3 DV

FEC 1/3 2/3 no 2/3 D

CRC no no no Yes D

SCO packets

Table 1: Link Control Packets Table, ACL Packets Table, SCO packets

12

Preliminary

ROK 101 007

Host Control Interface (HCI) The HCI provides a uniform command I/F to the Baseband and Link Manager and also to HW status registers. There are three different types of HCI packets: HCI command packets from host to Bluetooth module HCI. HCI event packets from Bluetooth module HCI to host. HCI data packets going both ways.

Please refer to the Specification of the Bluetooth System v1.0B part H:4 regarding the HCI and UART transport layers. PCM Voice Interface The standard PCM interface has a sample rate of 8 kHz (PCM_SYNC). The PCM clock is variable between 200 kHz and 2.0MHz. The PCM data can be linear PCM (13-16bit), -Law (8bit) or A-Law (8bit). The PCM I/F can be either master or slave providing or receiving the PCM_SYNC. Redirection of PCM_OUT and PCM_IN can be accomplished as well. Over the air the encoding is programmable to be CVSD, A-Law or -Law. Preferably the robust CVSD encoding should be used. USB Interface The module is a USB high-speed class device (12Mbps) that has the

full functionality of a USB slave and is compliant to the USB 1.1 specification. Data transfer occurs on the bi-directional ports, D+ & D-. Additionally, there are two side band signals for a notebook application. Two side band signals Wake_up and Detach are used to control the state from which the notebook resumes. When the host is in a power down mode, Wake_up wakes the host up when the Bluetooth system receives an incoming connection. The host indicates that it is in Suspend mode by using the Detach signal. I2C Interface A master I2C I/F is available on the module. The control of the I2C pins are performed by Ericsson specific HCI commands available in the FW implementation see Appendix C.

It is not necessary to make use of all different commands and events for an application. If the application is aimed at a pre-specified profile, the capabilities of such a profile is necessary to adjust to see Specification of the Bluetooth System v1.0B Profiles. a) With the HCI UART Transport Layer on top of HCI, the module will communicate with a host through the UART I/F. The PCM I/ F is also available for communicating voice. b) With the HCI USB Transport Layer on top of the HCI, the module will communicate with a host through the USB. Detach and Wake_up signals are also available for notebook implementations. Please refer to the Specification of the Bluetooth System v1.0B part H:14 for in-depth information regarding the HCI and different transport layers

PCM_CLK t PSS

PCM_SYNC

tPSH tDSL

tDSH

PCM_X in

MSB

MSB-1 t PDLP

MSB-2

MSB-3

PCM_X out

MSB

MSB-1

MSB-2

Figure 14. PCM timing

Module HW Interfaces
UART Interface The UART implemented on the module is an industry standard 16C450 and supports the following baud rates: 300, 600, 900, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400 and 460800 bits/s. 128 byte FIFOs are associated with the UART. Four signals will be provided for the UART interface. TxD & RxD are used for data flow, and RTS & CTS is used for flow control.
Name
fpcmClk fpcmSync tCCH tCCL tPSS tPSH tDSL tDSH tPDLP

Description
PCM data-transfer clock frequency 1 PCM sample rate sync. frequency PCM_CLK high period PCM_CLK low period PCM_SYNC (setup) to PCM CLK (fall) PCM_SYNC pulse length PCM_X in (setup) to PCM_CLK (fall) PCM_X in (hold) from PCM_CLK (fall) PCM_X out valid from PCM_CLK (rise)

Min Typ
128 8 200 200 100 200 100 100 150

Max
2000

Unit
kHz kHz ns ns ns ns ns ns ns

Table 2. PCM parameters

13

ROK 101 007

Preliminary

Antenna The ANT pin should be connected to a 50-antenna interface, thereby supporting the best signal strength performance. Ericsson Microelectronics can recommend application specific antennas see Appendix C. Power-up Sequence There is no need for a power up sequence if VCC, ON and VCC_IO are tied together. A power up sequence, if used, shall be applied accordingly: Connection of the supply rails, GND and then VCC; then the ON signal should be applied in order to initiate the internal regulators; and finally, the VCC_IO supply rail can be activated. The power-down sequence is similar to the power-up procedure but in the reverse format. Therefore, the disconnection of the signals shall be as follows: VCC_IO, ON,VCC and finally GND. RESET# The assignment of the RESET# input is to generate a reset signal to the complete Bluetooth module. During power-up the reset signal is set low automatically so that power supply glitches are avoided. Therefore no reset input should be required after power-up. When implementing an external RESET#, the signal should be fed from an open drain output. Power There are three inputs to the Voltage Management section (VCC, VCC_IO, ON). VCC is the supply voltage that is typically 3.3V. A separate power supply rail (VCC_IO) is provided for the I/O ports, UART, PCM and USB. To be compliant with the USB 1.1 specification, VCC_IO > 3.11V. VCC_IO can either be connected to VCC or to a dedicated supply rail, which is the same as the logical interface of the host.

Shielding / EMC Requirements The module has its own RF shielding and is approved according to the standards by FCC and ETSI. If the approval number is not visible on the outside when the module is utilized in the final product, an exterior label must state that there is a transmitter module inside the product. Ground Ground should be distributed with very low impedance as a ground plane. Connect all GND pins to the ground plane.

eutectic solder paste. A preferred solder paste height is 150m. Soldering Profile It must be noted that the module should not be allowed to be hanging upside down in the re-flow operation. This means that the module has to be assembled on the side of the PCB that is soldered last. The re-flow process should be a regular surface mount soldering profile (full convection strongly preferred); the ramp-up should not be higher than 2oC/s and with a peak temperature of 210-235oC during 2060 seconds. Pad Size It is recommended that the pads on the PCB should have a diameter of 0.7-0.9 mm. The surface finish on the PCB pads should be Nickel/Gold or a flat Tin/Lead surface or OSP (Organic Surface Protection).

Assembly Guidelines
Solder Paste The ROK 101 007 module is made for surface mounting and the SSP connection pads have been formed after printing eutectic Tin/Lead solder paste. The solder paste to use is not critical as long as this is a normal
tr VCC

td_on td

td_off

ON
tr_on t td_VCC_IO_o VCC_IO
ff

tf_on td_VCC_IO_o

Figure 15. Power up sequence

Parameter
tr tr_on tf_on td_on td_off tdvcc_io_on tdvcc_io_off

Min

Nom

Max
1 60 60

Unit
ms s s s s

tr

td_on td_off

s s

Table 3. Power up parameters

14

Preliminary

ROK 101 007

Placement The placement machine should be able to recognize odd BGA combinations (all ball recognition preferred) and be able to pick the component asymmetrical. The module contains a flat pick-area of 10mm diameter minimum. The weight of the module is typically 2.8gr. Storage Keep the component in its dry pack when not yet using the reel. After removal from the dry pack ensure that the modules are soldered onto the PCB within 48 hours.

Packaging
All devices will be delivered in a package protecting them from electrostatic discharges and mechanical shock. The package will be marked with the following information: a) Delivery address. b) Purchase order-number c) Type of goods and component designation. d) Ericssons name and logotype. e) Date of manufacture and batch number. f) Number of components in the package.

Abbreviations
ASIC - Application Specific Integrated Circuit BER - Bit Error Rate CMOS - Complementary Metal Oxide Semiconductor C/I - Carrier to Interference Ratio DCE - Data Circuit terminating Equipment GP - Gold Print HCI - Host Controller Interface ISM - Industrial Scientific and Medical PCB - Printed Circuit Board PCM - Pulse Code Modulation PDA - Personal Digital Assistant PtP - Point to Point Rx - Receive SIG - Special Interest Group SSP - Screen Solder Print Tx - Transmit UART - Universal Asynchronous Receiver Transmitter USB - Universal Serial Bus VCO - Voltage Controlled Oscillator

Marking
Every module is marked with the following information on the: a) Component designation: ROK 101 007. b) Ericssons name and logotype. c) Manufacturing code (place, year, week) and batch number. d) CE logotype e) Type approval RTA no. See manual

Ordering Information
Package 30 GP 30 SSP Part No. ROK 101 007/1 ROK 101 007/2

Information given in this data sheet is believed to be accurate and reliable. However no responsibility is assumed for the consequences of its use nor for any infringement of patents or other rights of third parties which may result from its use. No license is granted by implication or otherwise under any patent or patent rights of Ericsson Microelectronics. These products are sold only according to Ericsson Microelectronics' general conditions of sale, unless otherwise confirmed in writing.

Specifications subject to change without notice.

Microelectronics Ericsson Microelectronics AB SE-164 81 Kista-Stockholm, Sweden Telephone: +46 8 757 50 00 www.ericsson.com/microe

1522-ROK 101 007 Rev. PA5 Ericsson Microelectronics AB, April 2000
15

ROK 101 007

Preliminary

APPENDIX A
Getting Started
The ROK 101 007 Bluetooth module is easy to use when designing a Bluetooth application. However, there is a need for know-how in the Bluetooth System specification v1.0B as well as the Profile specification v1.0B when designing and endcustomer product. Bluetooth module Know-how in Bluetooth specification regarding HCI commands Test board with UART/PCM or USB I/F Visual C++ for PC SW design Preferably HCIdriver, L2CAP, RFCOMM and SDP from Ericsson The list above show some parts that would make designing convenient. All information needed, regarding how to drive the HCI over UART is specified in part H4 of the Bluetooth System v1.0B further more part H1 and also Appendix IX with message charts is relevant. Below follow an example of how to set up an ACL link between to Bluetooth modules by using the UART I/F and also a schematic of how to interface the module and control it by a host, normally a PC or microcontroller.

Principle schematic for UART inter- connect


The inter-connection to the levelshifter when designing a test-board could be according to the schematic below. (Figure A1.) The Bluetooth module can be connected as a DCE/DTE and a modem/nullmodem cable could therefor be used in-between the testboard and the PC.

Setting up a Bluetooth point-to-point connection


The Host Controller Interface (HCI) in the module is a command I/F. The host presents commands to the HCI and receives events back from the HCI of the module. The module Link Manager provides link set up capability to the HCI.

The capacitor values are chosen for a VCC from 3.2 to 3.6 V
V CC 100nF 1 3
VCC VCC_IO ON

VCC

RS-232 VCC + CX V+
16 2 100nF 100nF 4

100nF

BLUETOOTH MODULE ROK 101 007


TXD B5 CTS B6 RXD A5 RTS A6

+ CX 5 -

VGND

6 15 7 14 8 13

100nF

Host_B Bluetooth module is set in paging scan mode listening for a Bluetooth device asking for a new connection

10 11 9 12

2 RXD 8 CTS 3 TXD 7 RTS

Host_A Bluetooth module is set in paging mode asking for a connection to Host_B

MAX3232E

9-pin D-sub

Figure A1. Bluetooth module connected as a DCE through level shifter

This is accomplished by first setting up the connection between the Host and the module and thereafter creating the connection between the modules using HCI commands.

Figure A2. Bluetooth host to host communication 16

Preliminary

ROK 101 007

Host set-up via UART:


There are 4 different types of HCIpackets accepted on the UART I/F.
HCI packet type HCI command packet HCI ACL data packet HCI SCO data packet HCI event packet HCI packet indicator 0x01 0x02 0x03 0x04

Read_Buffer_Size: Providing the host with information on buffer size for ACL and SCO data packets for the module returned with a Command_Complete_Event packet. The host shall use this information for controlling the transmission

Inquiry The HCI command Inquiry with the parameters LAP, Inquiry_Length, and Num_Responses can also be used for collecting BD_ADDR of remote Bluetooth units.

Creating a Point-to-point connection


Page Scan mode
Command OCF HCI_Write_Scan_Enable 0x0005 Command parameters Scan_Enable Return parameters Status

Table A1. HCI packets The HCI packet indicator shall be sent immediately before the HCI packet. When the entire HCI packet has been received a new indicator should be expected. The default speed setting is 57.6 kb/s and can be changed by sending a specified bit stream to the I/F - see Appendix C on how to change the speed setting of the UART. When the speed set-up for the UART is made for both Host_ A & B, the Command Packets can be sent and Event Packets received by the hosts. See HCI over UART in part H:4 of the Bluetooth System v1.0B for detailed information regarding parameters and protocol. Soft Reset First HCI command packet to send should be the RESET packet. A Command_Complete_Event with a status parameter should be returned to the host. Buffer information Buffer information should be exchanged between the module and respective host by using HCI commands.

Host_Buffer_Size: Providing the module with information on buffer size for ACL and SCO packets to the host.

Table A2. HCI Write Scan Enable OCF code To set a Bluetooth module in the mode for being able to connect to (Host_B), page scan mode, there are some settings that should be performed. The Write_Scan_Enable command with correct parameter (Scan_Enable=0x001A) will set the module in Page scan mode if the Command_Complete_Event is successful. Furthermore the setting of authentication and encryption should be disabled (default) by using the: Write_Authentication_Enable Write_Encryption_Mode

It is the host that manages the data buffers of the Host Controller on the module. Timers It could be necessary to set important timers used by the module for time out handling. The timers are all set by writing to registers using HCI commands. The default values can be checked in Specification of the Bluetooth System v1.0B part H:1 or by using Read_xxx_xxx commands. Bluetooth Address The hosts, using the HCI command Read_BD_ADDR will find the Bluetooth address of the module by the Command_Complete_Event with the BD_ADDR as a parameter. By Remote_Name_Request, the BD_ADDR of the remote module can also be found.

The basic settings for getting into scan mode could be according to the below suggested script list. Read Buffer Size Set Event Filter Write Scan Enable: (Scan Enable: 0x03) Write Voice Setting: (Voice Channel Setting: 0x0060) Write Authentication Enable: (Authentication Enable: 0x00)

17

ROK 101 007

Preliminary

Set Event Filter: (Connection Setup Filter: Connections from All Devices, Auto Accept: 0x02)

Write Connection Accept


Command parameters BD_ADDR Packet_Type Packet_Scan_Repetition_Mode Packet_Scan_Mode Clock_Offset

Command OCF HCI_Create_Connection 0x0005

Return parameters

Table A3. HCI Create Connection OCF code Timeout: (Connection Accept Timeout: 0x2000) Write Page Timeout: (Page Timeout: 0x3000) Page mode The Create_Connection command is used to set-up a link to another Bluetooth device. Create_Connection: BD_ADDR: 0xYYYYYYYYYYYY, Packet Type: 0x0007, Page Scan Repetition Mode: 0x01, Page Scan Mode: 0x00, Clock Offset: 0x0000 This command will cause the Link Manager to try to create a connection to the Bluetooth module with the appropriate BD_ADDR. The local Bluetooth module (Host_A) starts the paging process to set up a link to the page-scanning remote device (Host_B). By LMP the negotiation between the two Bluetooth modules Link Managers (LM) the link set-up can be completed.

ACL link up and running Host_A is the master of the point-topoint piconet and Host_B is slave. The unit starting the paging process is by definition the master. The link set-up is completed when the event Connection_Complete_Event is returned to both Host_A and Host_B with the connection handle as one of the parameters and the status parameter 0x00 (success). When Bluetooth link is up and running the HCI data packets can be sent from host to host. The host must take care of generating the packages going from Host to Host Controller in the module over the UART I/F, in the same way the Host must arrange the packages received from the Host Controller. Both sides need information on what kind of data is received, to be able to interpret the bit flow correctly. For extensive information on setting up a Bluetooth link please refer to Bluetooth System v1.0B Appendix IX Message Sequence Charts Adding an SCO link When creating a voice connection using the PCM I/F, an ACL link must be up and running between the two devices, an SCO link can thereafter be added. The control of the PCM I/F (FS, PCM_IN/OUT and PCM_CLK) is handled by Ericsson specific HCI command see Appendix C.

Driving SW
HCI- API The Bluetooth module includes all HCI command capabilities according to Bluetooth System v1.0B. Furthermore, there is some Ericsson specific commands available for accessing HW registers and HW control see Appendix C. SW for driving the module should be developed for the HCI interface. There is source code SW available with Ericsson Bluetooth Developers Kit (EBDK), see Appendix B, which can be used for driving the module. This SW comes with the EBDK and has an HCI-API for application development on the HCI I/F. Higher layer-API Software (HCIdriver, L2CAP, RFCOMM and SDP) are available in a generic, source code format, i.e. to be adapted to various operating systems. HCIdriver implements the HCI command driver used by the host L2CAP handles protocol multiplexing, segmentation and re-assembly of packets RFCOMM provides a serial port emulation over the L2CAP protocol SDP Service Discovery Protocol provides information on the services available on a Bluetooth device Additional SW for the application shall be developed for the actual application on top of the RFCOMM API. If the application is according to a SIG predefined profile, it should be implemented accordingly. New applications can be the driver of the specification of new profiles decided by the SIG see Specification of the Bluetooth System v1.0B Profiles.

4 8 Connection handle

12 16 PB BC Flag Flag

20 24 Data total length

32

Data
Table A4. ACL data packet

18

Preliminary

ROK 101 007

APPENDIX B
Development tools
Ericsson Bluetooth Development Kit (EBDK) The easiest way of getting started is to use the Ericsson Bluetooth Developers Kit. It provides all parts necessary for developing applications for the Bluetooth module. Available are: PC plug&play Demos using radio/baseband Macro capability C++ v5.0 Source code for use in applications HCIdriver, L2CAP, SDP and RFCOMM for applications using UART communication Pins for electrical measurements Antennas
Memory
JTAG Radio Board (0dBm) Radio Board (20dBm)

optional external antenna

Ericsson Radio Module

Ericsson Radio Module

EBDK

USB

A udio

LEDS

USB9602 Radio Board

MS7540

Ericsson Radio Module


Monitoring pins

GLUE LOGIC (XLI NX)

Memor y

Ericsson BaseBand
Base Band Board

Development can easily take place on the EBDK platform and thereafter the implementation of the full Bluetooth capability can be setup by developed SW/HW and the Bluetooth module. Software (HCIdriver, L2CAP, RFCOMM and SDP) will be available in source code for PC. HCIdriver implements the HCI command driver used by the host L2CAP handles protocol multiplexing, segmentation and re-assembly of packets RFCOMM provides a serial port emulation over the L2CAP protocol SDP Service Discovery Protocol provides information on the services available on a Bluetooth device Technical support is available from the EBDK distributor. Please contact Ericsson Microelectronics for ordering and information regarding the

Address / Data / Control

Application Board RS-232 RS-232 RS-232 I2C

Figure B1. Ericsson Bluetooth Development Kit (EBDK)

EBSK
Ericsson Bluetooth Module ROK 101 007/1

Levelshift

Codec

DC/DC

RS-232

USB

Audio

Power

Figure B2. Ericsson Bluetooth Starter Kit (EBSK) EBDK and regarding extra daughter board with ROK 101 007 as add-on to the EBDK. Ericsson Bluetooth Starter Kit (EBSK) A very small convenient kit, which preferably is used in point-tomultipoint configuration designs, based on the Bluetooth module ROK 101 007. Please contact Ericsson Microelectronics for ordering and information regarding the Ericsson Bluetooth Starter Kit.

19

ROK 101 007

Preliminary

APPENDIX C
Bluetooth Information
This part will be updated and new information will be added continuously. Radio Fast Frequency hopping (1600channel hop/s) with 79(23) channels available (2.402 to 2.480 GHz) and a symbol rate of 1Ms/s over the air exploits the maximum channel bandwidth in the unlicensed ISM band. To sustain a high transfer rate in busy radio environment, the frequency hopping together with advanced coding techniques maximizes the throughput. During Page and Inquiry the hopping frequency is risen to 3200 hops/s to enhance the time needed for connection set-up. Modulation technique is a binary Gaussian Frequency Shift Keying GFSK, with a BT product of 0.5. The channel bandwidth is 1 MHz and the frequency deviation from the carrier frequency of the RF channel is between +/-140 to +/-175 kHz for representing a 1/0.

Country Europe & USA Japan Spain France

Frequency range 2400-2483.5 MHz 2471-2497 MHz 2445-2475 MHz 2446.5-2483.5 MHz

RF channels f = 2402 + k MHz f = 2473 + k MHz f = 2449 + k MHz f = 2454 + k MHz

k = 0....78 k = 0....22 k = 0....22 k = 0....22

Table C1. Frequency ranges used. A rapid process is ongoing to harmonise Spanish, French and Japanese frequency ranges with the rest of the world. Data and parameter formats There are exceptions in the Bluetooth system for data and parameter formats general rules below. All values are in Binary and Hexadecimal little Endian formats Negative values must use 2s complement format Array parameter notation is parameterA[i], parameterB[i], All parameter values are sent/received in little Endian format. The least significant byte is sent first unless noted otherwise. HCI Opcodes The Opcodes have been changed during the ongoing standardisation work. Below is the description on how to send opcodes to the module. Below is the general HCI command
Little Endian

8
OpCode

12

16

20

24

28

31

lsb

OCF

msb lsb

OGF

Parameter Total length


msb

OpCode Command Field 10 bits

OpCode Group Field 6 bits

Amount of parameters in bytes

OGFRange (6 bits): 0x00-0x3F

0x3E: Bluetooth logo testing 0x3F: Vendor specific debug commands OCFRange (10 bits): 0x0000-0x03FF

HCI_Inquiry_Cancel (Example):
LINK CONTROL COMMAND

OGF: 0x01 bin: 0000 0001


msb lsb

OCF: 0x0002 bin: 0000 0000 0000 0010


msb lsb

Real code bin: 0000 01 | 00 0000 0010


msb lsb

0x0402 Sent to module in hex: 02 04 00


Zero parameters

Reverse byte order

Figure C1. Byte order sent to module

20

Preliminary

ROK 101 007

packet format depicted as well as a byte order description. UART speed setting The baud rate is changed with an Ericsson specific HCI command. HCI_Ericsson_Set_Uart_Baud_Rate The command has one parameter, baud rate - one byte long according to the table below . The op-code for the command is 0xfc07 - the last figure is due to a possible change. Sending the command should be performed accordingly: 07 fc 01 yz , where yz is the chosen baud rate from the table. The op-code is sent in reverse byte order. 01 is the parameter length, in this case one byte. Remember to add the HCI packet indicator. Observe - When changing the baud rate for the module the host also has to change the baud rate. Observe - Removing power to the module the baud rate will be reset to 57.6 kbps. Observe -Two zeros are not printed in the beginning of the binary parameters below. The length of the parameter is 1 byte. Ericsson specific HCI commands By using the Ericsson specific HCI command there are a number of features available for the application design.

UART speed Parameter to send


460.8 kbps 230.4 kbps 115.2 kbps 57.6 kbps 28.8 kbps 14.4 kbps 7200 bps 3600 bps 1800 bps 900 bps 153.6 kbps 76.8 kbps 38.4 kbps 19.2 kbps 9600 bps 4800 bps 2400 bps 1200 bps 600 bps 300 bps 00000 00001 00010 00011 00100 00101 00110 00111 01000 01001 10000 10001 10010 10011 10100 10101 10110 10111 11000 11001

Table C2. UART speed setting parameter

Contact Ericsson Microelectronics for a command reference list. Antennas Antenna design is not specified and standardised in the Bluetooth System v1.0B. Many different types of antennas can and will be used. Application specific antennas suitable for production are expected to be a new market for antenna designs. Ericsson Microelectronics have antennas for the EBDK and other

development kits. Contact Ericsson Microelectronics for information on antennas. Contacting Ericsson Microelectronics For further information regarding Bluetooth technology, components and development tools, please contact Ericsson Microelectronics: Telephone: Scandinavia: Europe: North America: Rest of World:

+46 8 757 47 00 +44 1793 488 300 +1 877 374 26 42 +46 8 757 47 00

www.ericsson.se/microe

21

You might also like