Upload
vuongkhanh
View
237
Download
4
Embed Size (px)
Citation preview
INSTITUTO POLITECNICO NACIONAL ESCUELA SUPERIOR DE INGENIERÍA MECÁNICA Y ELÉCTRICA
SECCIÓN DE ESTUDIOS DE POSGRADO E INVESTIGACIÓN
DISEÑO Y CONSTRUCCIÓN DE UN SENSOR DE NIVEL UTILIZANDO FIBRAS ÓPTICAS
TESIS QUE PARA OBTENER EL GRADO DE
MAESTRO EN CIENCIAS EN INGENIERÍA ELECTRÓNICA
OPCIÓN: INSTRUMENTACIÓN
PRESENTA:
FREDDY LÓPEZ VILLAFUERTE
DIRECTOR DE TESIS
Dr. Walter Humberto Fonseca Araujo
MÉXICO, D.F. DICIEMBRE 2002
DEDICATORIAS
A mis padres Luis López Moreno y Evelia López Villafuerte a quienes amo mucho. Les dedico este trabajo por las multiples atenciones y sacrificios que realizaron para que lograra culminar mis estudios y por haberme guiado en el camino del bien. A mis hermanos Tania y Luis con los que comparto mi vivir y me han apoyado en los momentos difíciles con comprensión y cariño.
AGRADECIMIENTOS
Agradezco todas las atenciones recibidas, la paciencia y tolerancia del director de esta Tesis, el Dr. Walter Humberto Fonseca Araujo. Gracias por su amistad y su confianza, le reitero mi admiración y profundo respeto. Al Dr. Argeo Vázquez Martínez quien sin su apoyo no hubiera sido posible la culminación de este trabajo. Gracias por tu amistad y por el tiempo invertido. A mis profesores de la maestría y comisión revisora: Dr. José Manuel de la Rosa Vázquez Dr. Roberto Linares y Miranda Dr. Alexandre Michtchenko M. en C. José Héctor Caltenco Franca M. en C. Raúl Peña Rivero M. en C. Artemio Ramírez Antonio Gracias por su tiempo, consejos y enseñanzas. A mis compañeros de maestría que enriquecieron mi vida: Miguel Ángel Rodríguez Zuno Onofre Alonso Lárraga Tirso Javier Salazar Sandoval Gracias por su amistad y apoyo.
ABSTRACT
ABSTRACT
This Work presents the design and construction of a level sensor with optical fibers. This level sensor is classified as a transmissive, extrinsic and digitally intensity-modulated sensor, it uses the floating force and binary code metallic plate to measure in litres the level of a fluid in a liquid container. The sensor described in this work measures the level of the fluids independently from the physical and/or chemical characteristics of the fluid such as viscosity, density, transparency, etc. The fiber optics light signal is processed by the COP8SGR microcontroller. This electronic device interprets the signal received and it shows the level of the fluid on a Liquid Crystal Display AND491. According to the digital nature and the features of the optical fibers, the sensor can operate in environments with high levels of electromagnetic interference. This is why it is useful for any industrial application.
IX
RESUMEN
RESUMEN En este trabajo se expone el diseño y la construcción de un sensor de nivel de líquidos con fibras ópticas. Este sensor de nivel es de tipo transmisivo, extrínseco y de amplitud modulada digitalmente; utiliza el principio de flotación para determinar el nivel de un líquido en un contenedor. Este sensor puede realizar mediciones independientemente de las características físicas o químicas del fluido en el contenedor, tales como la viscosidad, densidad, transparencia, etc. El procesamiento de la señal lumínica entregada por las fibras ópticas se realiza con el microcontrolador COP8SGR, el cual interpreta la señal recibida y muestra el nivel del liquido del contenedor por medio del exhibidor de cristal líquido AND491. Debido a la naturaleza digital del sensor y a la utilización de las fibras ópticas, es posible que éste opere en ambientes donde existe una alta interferencia electromagnética, lo que lo hace atractivo para muchas aplicaciones industriales.
X
Glosario de términos
GLOSARIO DE TÉRMINOS
VI
Glosario de términos
GLOSARIO DE TÉRMINOS
Arquitectura Harvard Modificada:
Construcción lógica interna del microcontrolador COP8 en donde la memoria de programa y la memoria de datos tienen su propio bus de datos y direcciones respectivamente.
Calibración:
El proceso de ajuste en la respuesta de un instrumento sobre un intervalo lineal de operación.
Código binario:
Representación discreta de dígitos binarios (discretización con los dígitos uno y cero).
Densidad:
Masa por unidad de volumen de una sustancia(Kg/m3).
Exactitud:
Relación entre el valor más cercano de una lectura en un dispositivo de medición y el valor real de la cantidad medida. Usualmente expresada en ± el por ciento de la escala completa de salida o de lectura.
Extrínseco:
Que viene de afuera, que se realiza de forma externa.
Interferencia:
Cualquier energía indeseada que dificulta la recepción de una señal deseada, esta puede ser originada por fenómenos naturales o artificiales.
VII
Glosario de términos
Intervalo de operación:
Esta definido por los limites máximo y mínimo que puede tomar el instrumento, bajo condiciones controladas.
Linealidad:
La linealidad del instrumento se define como el intervalo sobre el cual la variable tiene un comportamiento repetitivo y donde el efecto es proporcional a la causa.
Modulación:
Cambio de amplitud o de frecuencia de una señal portadora.
Régimen turbulento:
Cuando en un fluido las fuerzas de inercia son mucho más significativas que las fuerzas viscosas.
Ruido:
Cualquier perturbación que atenúa o interfiere a la señal deseada.
Sensibilidad:
Cualidad de un instrumento o dispositivo para mostrar su rapidez de respuesta (en el tiempo y/o magnitud) a un estimulo específico.
Sistema digital:
Circuitos electrónicos en los cuales la información es transmitida en forma de trenes de pulsos (información discreta).
Viscosidad:
La resistencia inherente de una sustancia a fluir.
Lux: Unidad de iluminación en el sistema
internacional, 1 lm/m2.
VIII
Glosario de términos
9
Indice
SENSOR DE NIVEL DE LÍQUIDOS UTILIZANDO FIBRAS ÓPTICAS
Contenido: Índice....................................................................................................I Índice de figuras................... .............................................................III Índice de tablas..................................................................................IV Índice de fotografías............................................................................V Índice de programas en ensamblador.................................................V Glosario..............................................................................................VI Abstract...............................................................................................IX Resumen.............................................................................................X Justificación y objetivo........................................................................XI Introducción.......................................................................................XII Antecedentes....................................................................................XIII Capitulo 1. Sistemas de medición de nivel 1 1.1 Introducción. 2 1.2 Características de las fibras ópticas en los sensores. 2 1.3 Sensores de nivel con fibras ópticas. 3 1.3.1 Concepto transmisivo. 4 1.3.2 Concepto reflectivo. 4 1.3.3 Clasificación. 5 1.4 Sensores de nivel transmisivo. 6 1.4.1 Nivel de líquidos bicolor. 6 1.4.2 Sensor de nivel por obstrucción. 7 1.5 Sensor de nivel por fuerza de flotación. 8 1.5.1 Sensor de pistón desplazable 8 1.5.2 Sensor de nivel lector de tarjeta. 9 1.6 Sensores de nivel por presión. 9 1.7 Sensor de superficie reflejante. 10 1.8 Sensor de nivel por cambios de índice de refracción. 11
I
Indice
Capitulo 2. Medición de nivel por lectura de código 13 2.1 Características generales del sensor. 14 2.2 Principio de operación . 15
2.3 Condiciones para realizar la medición de nivel bajo el principio seleccionado. 18
Capitulo 3. Diseño y construcción del sensor
de nivel 21 3.1 Introducción. 22 3.2 Elemento sensor. 22 3.3 Sistema hidráulico. 24 3.4 Sistema óptico del sensor. 26 3.4.1 Fibra óptica. 27 3.4.2 Caracterización de las fibras ópticas de vidrio. 29 3.4.3 Fuente óptica. 32 3.4.4 Receptor óptico. 37 Capitulo 4. Procesamiento de la señal eléctrica e interfase periférica 47 4.1 Introducción. 48 4.2 Procesador de señal. 48 4.3 Periférico de salida. 51 4.4 Interfase periférica. 51 4.5 Programación del microcontrolador COP8SGR7 52 Capitulo 5. Caracterización del sistema y análisis de pérdidas 55 5.1 Introducción. 56 5.2 Sistema general de medición. 56 5.3 Elementos principales que conforman al sistema. 57 5.4 Evaluación del sistema. 58 5.4.1 Desalineación lateral. 60 5.4.2 Desalineación angular. 61
II
Indice
5.4.3 Separación entre terminales. 63 5.4.4 Terminales mal pulidas. 69 5.5 Tolerancia en la lectura del nivel. 69 5.6 Calibración en el sistema de medición. 70 Conclusiones. 71 Recomendaciones y sugerencias 72 Bibliografía. 73 Anexo A Diagramas del sistema 76 Anexo B Especificaciones eléctricas de dispositivos electrónicos 79 Anexo C Programas en lenguaje ensamblador COP8SGR7 99 Anexo D Fotografías del sistema 113
Índice de figuras
1.1 Configuración de sensor reflectivo 5 1.2 Nivel de líquido bicolor 6 1.3 Bosquejo de un sensor de nivel por obstrucción 7 1.4 Interruptor de nivel de líquidos 8 1.5 Sensor de nivel de líquidos con fibra óptica (digital) 9 1.6 Sensor de nivel de líquidos con transductor de presión 10 1.7 Medición de nivel de líquido por superficie reflejante 11 1.8 Sensor de nivel de líquidos con cambio de índice refracción (Refracciométricos) 12 2.1 Bosquejo del código binario en la placa perforada 16 3.1 Bosquejo de la placa ranurada y acanalada 24 3.2 Sistema hidráulico 25 3.3 Elementos generales de un sistema de medición óptico 26 3.4 Partes que integran a una fibra óptica 27 3.5 Cono de aceptación de la fibra óptica dependiente de la apertura numérica 29 3.6 Medición de la apertura numérica de la fibra óptica 30
III
Indice
3.7 Fuente óptica con LED emisor de 850 nm 34 3.8 Circuito para caracterizar a los diodos del emisor 35 3.9 Diagrama del circuito eléctrico del receptor óptico 39 3.10 Curvas características Corriente vs. Voltaje y línea de carga 40 3.11 Circuito equivalente del fotodiodo PIN 41 3.12 Curvas características capacitancia CJ vs. Voltaje inverso 42 3.13 Curvas características Corriente obscuridad vs. Voltaje Inverso 43 3.14 Circuito equivalente del diodo PIN y una etapa de amplificación con sus respectivas fuentes de ruido 43 4.1 Diagrama del circuito integrado COP8SGR7 48 4.2 Diagrama eléctrico de la interfase periférica 52 4.3 Diagrama de flujo del programa principal 53 5.1 Diagrama a bloques del sistema general de medición 56 5.2 Pérdidas de potencia óptica 59 5.3 Desalineamiento entre dos fibras ópticas del mismo radio 60 5.4 Desalineamiento angular entre dos fibras ópticas 62 5.5 Separación existente entre dos fibras ópticas 63 5.6 Eficiencia de acoplamiento 64 5.7 Análisis del ángulo incidente de un haz de luz 66 5.8 Fuente óptica de potencia variable 68 5.9 Bosquejo del código binario en la placa perforada 70
Índice de tablas
Tabla 3.1 Mediciones de la NA para la fibra óptica de 100/140 31 Tabla 3.2 Mediciones de la NA para la fibra óptica de 50/125 31 Tabla 3.3 Mediciones de corriente de LED vs Voltaje de referencia 35 Tabla 3.4 Mediciones de la potencia óptica de LED vs corriente del LED 36 Tabla 5.1 Pérdidas por desalineamiento lateral 61 Tabla 5.2 Pérdidas por desalineamiento angular 63 Tabla 5.3 Medición de las pérdidas en decibeles en la discontinuidad del sistema 66
IV
Indice
Índice de fotografías
Fotografía 1 Sistema completo del sensor de nivel con fibras ópticas 114 Fotografía 2 Vista en planta del receptor óptico y del exhibidor AND491 115 Fotografía 3 Vista en planta del contenedor con el sensor de nivel 116 Fotografía 4 Circuito electrónico del emisor óptico 117 Fotografía 5 Circuito electrónico de la interfase y el receptor óptico 118 Fotografía 6 Detalle de la placa perforada con el código binario 119
Índice de programas en ensamblador
Programa principal del sensor de nivel 100 Programa de la macro “display” para controlar el exhibidor de cristal líquido 109
V
Justificación y Objetivo
JUSTIFICACIÓN
El diseño y construcción de un sensor de nivel donde se emplean los sistemas ópticos en conjunto con la electrónica programable da origen a un sistema robusto y práctico para una amplia variedad de aplicaciones en la industria, en donde se puede llevar a cabo el control de la variable independientemente de las características físicas y químicas de las sustancias que se manejen. Este sensor presenta ventajas en ambientes agresivos y contaminados, tales como los altos índices de interferencia electromagnética y de radiofrecuencia, siendo el sensor inmune a estos ambientes que dificultan la medición que con sistemas eléctricos convencionales, no sería posible implementar.
OBJETIVO Diseño y desarrollo de un sensor de nivel utilizando fibras ópticas bajo el principio de flotación y lectura de una tarjeta perforada. En el trabajo se contemplan las siguientes metas:
a) Análisis de los métodos de medición de nivel con fibras ópticas existentes.
b) Selección del sistema de medición.
c) Selección de materiales para la construcción del sensor.
d) Diseño y construcción del sistema opto-mecánico.
e) Diseño y construcción del sistema opto-electrónico.
f) Procesamiento de las señales entregadas por el sensor.
g) Pruebas finales.
XI
INTRODUCCIÓN
INTRODUCCIÓN
Todos los sistemas de medición electrónicos consisten de tres partes: una entrada derivada de un sensor, un dispositivo electrónico que realiza el procesamiento de la señal de entrada, probablemente en paralelo con las entradas de otras fuentes, y finalmente un dispositivo de salida, típicamente un actuador.
Quizá uno de los retos de la tecnología de los sensores es la
conversión de energía de un tipo a otro para medir un determinado parámetro que representa un fenómeno físico o químico por medio de un transductor; lo cual alude a un arte multidisciplinario, ya que en los sensores están incluidas varias ramas de la ciencia como la electrónica, la ingeniería mecánica, química, física, etc.
La función esencial de un sensor es detectar una variación de energía para procesarla y transformarla a un valor correspondiente en otra forma de energía, empleando en este proceso un transductor. Por ejemplo, los cambios en la presión acústica producen cambios en la corriente eléctrica de un micrófono, cambios en la temperatura produce cambios en el voltaje eléctrico de un termopar, y los cambios en las características espaciales de una escena representan cambios en la corriente eléctrica de una cámara de televisión.
En este trabajo se presenta un sensor de nivel, que muestra en
un exhibidor, el nivel de un líquido cualquiera, que se encuentre en un contenedor determinado, por lo que la variable del nivel del líquido en el contenedor será transformado a información visual en el exhibidor.
El nivel de líquidos es una de las etapas primarias de control de
procesos, especialmente en la industria petroquímica y química. La naturaleza explosiva de muchos de los procesos hacen a los sensores con fibras ópticas una buena opción para estas aplicaciones.
XII
ANTECEDENTES
ANTECEDENTES
Debido a que la medición del nivel de líquidos es un parámetro importante para el control de procesos, en la industria, se han implementado diferentes instrumentos para la medición de esta variable.
Utilizando principios mecánicos, eléctricos o la combinación de
estos se han desarrollado sensores que monitorean el nivel de ciertos líquidos contenidos en un recipiente. Las condiciones en las que se encuentren estos líquidos y las características físicas y/o químicas del mismo, determinaran que elemento sensor es apropiado para la medición de esta variable.
En este trabajo se presenta el desarrollo de un instrumento para
medir el nivel de un líquido en un contenedor, independientemente de las características fisico-químicas del mismo.
Se construirá un sensor óptico que permita la medición del nivel
del líquido en el contenedor, así como el receptor y emisor óptico del sistema.
Se implementará en el sistema un procesador (microcontrolador)
que permita visualizar el estado actual del nivel del líquido en el contenedor así como el hardware respectivo para el correcto funcionamiento del mismo.
Se realizarán las pruebas finales del sistema y se caracterizará
al sistema en general.
XIII
Capitulo 1 Sistemas de medición de nivel
CAPÍTULO 1
SISTEMAS DE MEDICIÓN DE NIVEL
1
Capitulo 1 Sistemas de medición de nivel
1.1 INTRODUCCIÓN
La medición del nivel de un líquido es una parte integral de los parámetros de un proceso de control, que se usa en una amplia variedad de industrias.
La utilización de las fibras ópticas ha revolucionado el campo de
los sensores y representan un avance para la medición de distintas variables utilizadas en un proceso, así como en muchas áreas de la instrumentación han marcado un claro adelanto tecnológico como principio para la medición del nivel tal como a continuación se expone.
1.2 CARACTERÍSTICAS DE LAS FIBRAS ÓPTICAS EN LOS SENSORES
Los sensores con fibras ópticas son esencialmente un medio
donde la luz es guiada dentro de una fibra óptica y puede ser modificada debido a una influencia física, química, biológica, etc.
La luz de una fuente óptica con intensidad constante se
introduce en una fibra óptica por medio de un acoplador y es guiada hasta un punto donde la medición se lleva a cabo.
En este punto la luz puede salir de la fibra y ser modulada en
alguna zona fuera de ella antes de ser nuevamente introducida en la misma fibra o alguna otra diferente (estos sensores son llamados sensores extrínsecos) o la luz puede continuar dentro de la fibra y ser modulada dentro de la misma (sensores intrínsecos) o una combinación de las anteriores (sensores evanescentes) [5].
Los sensores con fibras ópticas representan un recurso
tecnológico que se aplica en una gran variedad de instrumentos. Algunas de las características que hacen atractiva la utilización de las fibras ópticas como sensores son las siguientes:
• Carácter no-eléctrico. • Principio de operación no explosivo.
2
Capitulo 1 Sistemas de medición de nivel
• A menudo no requiere contacto directo con la variable a medir.
• Capacidad de operación remota. • Dimensiones pequeñas y de poco peso. • Opera en áreas de acceso difícil. • Instalación potencialmente sencilla. • Inmune a interferencias de radio frecuencias (RFI) y a la
interferencia electromagnética (EMI). • Alta precisión en las mediciones. • Capacidad de acoplamiento con sistemas de comunicación de
datos. • Transmisión de datos segura. • Potencialmente resistente a la radiación ionizante. • Reducción de costos de protección contra ruido. • Menor mantenimiento. • Reducción de los costos de instalación y reparación.
1.3 SENSORES DE NIVEL CON FIBRAS ÓPTICAS
Todos los sensores de fibras ópticas pueden detectar la variable física por medio de la modulación de intensidad óptica o por la modulación de la fase del haz de luz. Los sensores de nivel regularmente operan con intensidad modulada.
Los sensores de intensidad modulada están asociados
generalmente con el desplazamiento o alguna otra perturbación física que interactúa con la fibra o un transductor mecánico aunado a la fibra. La perturbación causa un cambio en la intensidad de la luz recibida, la cual es función del fenómeno que se está midiendo.
Los conceptos generales asociados con la modulación de
intensidad incluyen al concepto transmisivo y reflectivo, sin embargo, se usan otros mecanismos independiente de o en conjunto con los dos conceptos anteriores, tales como: la absorción, los cambios de densidad, fluorescencia, polarización y rejillas ópticas.
Los sensores de intensidad modulada son analógicos por naturaleza pero tienen un uso importante en aplicaciones digitales para interruptores y contadores.
3
Capitulo 1 Sistemas de medición de nivel
1.3.1 CONCEPTO TRANSMISIVO El concepto de sensor transmisivo normalmente se asocia con la interrupción de un rayo de luz. Por ejemplo si se quiere sensar el desplazamiento axial entre dos fibras ópticas se observará que el acoplamiento de luz sigue la ley de 1/r2 donde r es la distancia entre las sondas.
Otro sensor transmisivo más sensible es el de desplazamiento radial donde el sensor no transmite si las sondas se desplazan una distancia igual un diámetro de la sonda, aproximadamente el primer 20% del desplazamiento da una respuesta lineal en la luz acoplada. 1.3.2 CONCEPTO REFLECTIVO
El concepto reflectivo es atractivo para mucho sensores debido a su precisión, simplicidad y su bajo costo. El sensor está compuesto de dos fibras ópticas (ya sean de núcleos múltiples o de un solo núcleo), por una de ellas se transmite luz a una tarjeta reflejante, mientras la otra atrapará la luz reflejada y la transmitirá al detector, la intensidad de la luz detectada depende de la distancia a la que se encuentre la tarjeta reflejante.
Al graficar la intensidad de la luz reflejada contra la distancia a la
que se encuentra la superficie reflejante muestra que las pendientes iniciales de la curva permiten tener una precisión potencial de millonésimas de pulgada. La precisión también depende del tipo de sonda que se utilice, ya sea hemisférica, coaxial, de par de núcleos o sencilla. Para aplicaciones que requieren de un intervalo dinámico más grande, generalmente se utiliza un sistema de lentes, que expanden el intervalo de medición, desde 5.08 mm (0.2 pulgadas) hasta 13cm (≈5pulgadas) o más.
4
Capitulo 1 Sistemas de medición de nivel
Figura 1.1 Configuración de sensor reflectivo.
1.3.3 CLASIFICACIÓN
Los sensores de nivel pueden dividirse en dos categorías[5]: Sensores de nivel puntual:
Este tipo de sensores se utilizan para marcar un nivel discreto previamente establecido, regularmente funcionan como interruptores de nivel alto y/o nivel bajo; se emplean como alarmas para la condición de sobreflujo o para marcar el estado de nivel bajo o vacío. Sensores de nivel continuo:
Este tipo de sensores proveen un monitoreo completo del nivel del sistema, ya que como su nombre lo indica mide el nivel del fluido en un intervalo determinado. Con ellos se pueden detectar fugas o medir la magnitud actual del nivel del líquido en cuestión.
Los sensores de nivel continuo tienen una salida analógica que
correlaciona directamente el nivel de esta señal con el fluido del contenedor.
En este trabajo se expone un medidor de nivel discreto, ya que
solamente mide niveles discretizados de fluido en el contenedor.
5
Capitulo 1 Sistemas de medición de nivel
1.4 SENSORES DE NIVEL TRANSMISIVO
1.4.1 NIVEL DE LÍQUIDOS BICOLOR
Las calderas generalmente usan cristales de dos colores para detectar el nivel del agua. Se coloca un prisma de tal forma que si en el compartimento se encuentra vapor, se observa una luz roja; pero si el compartimiento se encuentra lleno de agua, la luz roja se refracta y solo la luz verde se transmite.
La interfase entre las fibras y el compartimiento de color debe de estar aislada de la luz ambiental para evitar interferencias del medio externo. Este tipo de sensor es pasivo, sin sistemas mecánicos en movimiento u otros componentes eléctricos (mas que el iluminador ).
Figura 1.2 Nivel de líquido bicolor.
Regularmente estos sensores se encuentran a un lado de la
caldera, pero si se deseara monitorear el proceso se tendría que equipar con fibras ópticas de apertura numérica grande y de núcleos de fibra óptica grandes.
6
Capitulo 1 Sistemas de medición de nivel
1.4.2 SENSOR DE NIVEL POR OBSTRUCCIÓN
Otro sistema transmisivo con fibras ópticas es como el que se muestra en la figura 1.3, en ella se puede apreciar que con el líquido del contenedor, la luz se ve interrumpida en su trayectoria hacia la fibra receptora, de tal forma que al obstruirse el haz, se tiene la información del nivel en el tanque.
El número de fibras ópticas utilizadas es igual al número de
niveles discretos que se requieran en el contenedor; cabe aclarar que este tipo de sensor necesita protecciones para la fibra óptica en la discontinuidad para que no se encuentren en contacto directo con el líquido. Una desventaja de este tipo de sensores es que no puede detectar líquidos que sean transparentes a la longitud de onda de luz empleada.
Figura 1.3 Bosquejo de un sensor de nivel por obstrucción.
7
Capitulo 1 Sistemas de medición de nivel
1.5 SENSOR DE NIVEL POR FUERZA DE FLOTACIÓN Este tipo de sensores detectan el nivel de líquidos empleando flotadores, por medio de ellos y aprovechando la fuerza de flotación es posible seguir el nivel del líquido. 1.5.1 SENSOR DE PISTÓN DESPLAZABLE Este tipo de sensor utiliza un émbolo que es impulsado por un flotador para detectar un nivel alto o bajo en el tanque, tal como lo muestra la figura 1.4.
Se puede apreciar que el sensor puede ser de tipo transmisivo o reflectivo dependiendo si el sensor, por medio del pistón, interrumpe el haz de luz o lo refleja.
Figura 1.4 Interruptor de nivel de líquidos.
8
Capitulo 1 Sistemas de medición de nivel
1.5.2 SENSOR DE NIVEL LECTOR DE TARJETA
Este sensor de nivel utiliza una tarjeta que contiene un código binario (el código puede estar impreso con superficies reflejantes o perforado en la misma placa), por lo que con el uso de n fibras se pueden determinar valores discretos de nivel de líquido.
Figura 1.5 Sensor de nivel de líquidos con fibra óptica (digital).
1.6 SENSORES DE NIVEL POR PRESION (CABEZA HIDROSTÁTICA)
El nivel de líquidos puede determinarse midiendo la presión ejercida sobre una membrana debido al peso de la columna de líquido que ésta ejerce sobre de ella.
La medición se complica cuando por ejemplo se tiene un tanque presurizado, ya que el sistema requiere de dos sensores de presión, uno que mida la presión de la presurización y otro más que mida la
9
Capitulo 1 Sistemas de medición de nivel
presión ejercida por una columna de agua; la diferencia de estas presiones corresponde al nivel de líquidos.
El inconveniente es que este método al tener pequeños errores
en la medición de presión se tendrán errores grandes en el nivel de líquidos.
Figura 1.6 Sensor de nivel de líquidos con transductor de presión.
1.7 SENSOR DE SUPERFICIE REFLEJANTE.
Las técnicas de superficie reflejante usan la reflexión de la luz en la superficie de un determinado líquido, en donde existe una fibra transmisora y varias fibras receptoras.
10
Capitulo 1 Sistemas de medición de nivel
Figura 1.7 Medición de nivel de líquido por superficie reflejante.
Para un intervalo dinámico muy grande (resolución del nivel del líquido) puede parecer muy costoso pero es atractivo para sustancias corrosivas o líquidos a alta temperatura donde el contacto no es posible.
1.8 SENSORES DE NIVEL POR CAMBIOS DE ÍNDICE DE REFRACCIÓN
Los sensores de nivel con cambios en el índice de refracción funcionan al transmitir un haz de luz en un prisma, típicamente un cuarzo (índice de refracción de 1.46).
Cuando el prisma se encuentra en el aire se tiene una reflexión interna total, pero en presencia de un líquido circundante cuyo índice de refracción sea mayor que el del prisma, la luz no se refleja totalmente hacia el interior del prisma ya que el cambio de índice de
11
Capitulo 1 Sistemas de medición de nivel
refracción a su alrededor, hará que parte de la luz se refracte en el líquido. Estos sensores son ideales para monitorear nivel alto o bajo, o para detectar fugas en un sistema.
Figura 1.8 Sensor de nivel de líquidos con cambio de índice de refracción (Refractométricos).
Algunos sensores con fibras ópticas presentados en este capitulo dependen de las cualidades físicas y/o químicas del líquido que se desee medir ( como el índice de refracción del líquido, viscosidad, transparencia, corrosividad, etc.), otros más dependen de las condiciones en que se encuentre el líquido o el contenedor (como la presión interna del tanque, que el líquido se en cuentre en un regimen no turbulento, etc.). El principio elegido para medir el nivel de un líquido fue el de lector de tarjeta, ya que presenta ventajas con respecto a los otros métodos, las características de este principio de medición son analizados en el capitulo 2.
12
Capitulo 2 Medición de nivel por lectura de código
CAPÍTULO 2 MEDICIÓN DE NIVEL POR LECTURA DE CÓDIGO
13
Capitulo 2 Medición de nivel por lectura de código
2.1 CARACTERÍSTICAS GENERALES DEL SENSOR El principio seleccionado para la medición del nivel fue el del sensor de nivel con lector de tarjeta, el elemento principal para este sensor es la tarjeta con código. El sistema fue diseñado para ser modulado en intensidad (presencia o ausencia de luz) y de forma transmisiva (extrínseca).
Una de las ventajas importantes de este medidor es la capacidad de poder trabajar con una variedad de sustancias que puedan fluir en el tanque. Dado que la medición se realiza en base a un principio de flotación, se puede determinar el nivel de diversos líquidos sin importar su densidad, transparencia, agresividad, etc.
El sensor presenta además la cualidad de operar en ambientes
contaminados electromagnéticamente. Las ventajas y características que presenta este principio de operación en el sensor son las siguientes:
• Un número alto de discretización con un mínimo de fibras ópticas.
• Amplio intervalo de medición. • Versatilidad en la instalación. • Elemento sensor de tamaño reducido. • Amplia variedad para los materiales de construcción
(dependiendo del fluido a tratar). • Diversidad en la aplicación de procesos • Construcción simple y duradera. • Flexibilidad en la utilización de sistemas digitales para el
procesamiento de la señal y control de la variable. • Amplia variedad para la conexión de salida (interfaz de
computadora, exhibidores de led´s o de cristal líquido, etc). • Correcta operación en un amplio intervalo de temperatura y
presión (solo dependiente de los materiales de construcción y fibra óptica).
14
Capitulo 2 Medición de nivel por lectura de código
• El principio de operación por lectura de código permite procesarse de modo enteramente digital.
• El diseño del sensor es compacto, seguro y con posibilidades de miniaturizarse por medio de elementos mecánicos.
• La operación del sensor es intrínsecamente seguro en ambientes inflamables y agresivos.
• Facilidad de instalación en lugares poco accesibles • Utilización de fibras ópticas de plástico o de vidrio con diferentes
diámetros y núcleos. • Utilización de fuentes ópticas poco estabilizadas con niveles de
potencia ajustables a un valor fijo. • La fuente óptica no requiere compensación alguna. • El sistema de calibración es práctico y muy sencillo. • El sistema de modulación del haz de luz es sencillo (ausencia o
presencia del haz). • Sistema de procesamiento por microcontrolador COP8 con
capacidad de control de procesos.
2.2 PRINCIPIO DE OPERACIÓN El elemento primario del sensor es la placa con código binario, este código puede incorporarse al sensor en forma reflectiva o transmisiva, dependiendo de si la tarjeta se construye con superficies reflejantes o con perforaciones en la misma que permitan pasar la luz hacia el sistema receptor.
En la realización del proyecto se utilizó el concepto transmisivo al perforar la placa con un código binario de 8 bits, de tal forma que la lectura del código en la placa perforada se realiza con la interrupción o la presencia de luz en el extremo receptor, tal como se muestra en la figura 2.1.
15
Capitulo 2 Medición de nivel por lectura de código
Los niveles discretos (N) detectables en el contenedor con este sistema están en función del número de bits utilizados en la placa perforada, debido a que la placa tiene un código binario de 8 bits entonces los niveles discretos son:
nivelesN n 25622 8 === (1)
El número de fibras emisoras (n) o lectoras del sistema son 8 ya que la placa perforada contiene un código binario de 8 bits.
Figura 2.1 Bosquejo del código binario en la placa perforada.
Cada uno de las 256 combinaciones en la tarjeta perforada indican un nivel de líquido determinado en el tanque.
16
Capitulo 2 Medición de nivel por lectura de código
La lectura de cada combinación en la tarjeta se realiza por medio de las fibras ópticas. El sistema dispone de 8 fibras ópticas emisoras de luz y 8 fibras ópticas receptoras que se encuentran en la parte superior del contenedor.
La placa perforada con el código binario se desplaza entre las
fibras ópticas emisoras y receptoras impulsada por el nivel del líquido contenido en el tanque.
La placa perforada puede desplazarse entre las fibras ópticas
debido a que en la base de la misma se encuentran unos flotadores de plástico que permiten impulsarla conforme el contenedor se llena o se vacía de líquido.
La forma en que se lleva a cabo la lectura del código binario en
la tarjeta perforada por medio de las fibras ópticas es de carácter transmisivo, es decir, las fibras ópticas emisoras transmiten haces de luz hacia las fibras ópticas receptoras, mismas que logran acoplar la potencia lumínica de las primeras dependiendo de la posición de la tarjeta perforada .
Si una de las fibras ópticas emisoras coincide con un hueco de la
tarjeta perforada con el código binario, entonces la fibra óptica receptora podrá acoplar esta radiación ya que la tarjeta permitirá un paso libre y directo entre ambas fibras. Por el contrario, si no hay ranura entre las fibras ópticas entonces la fibra óptica receptora no recibe radiación lumínica, de modo que la ausencia o presencia de luz en las fibras ópticas representan los dígitos binarios de la placa perforada.
Como se tienen 8 fibras ópticas emisoras, entonces se podrá
obtener la lectura de un byte del código de la tarjeta perforada. Esta información se procesa posteriormente y se interpreta como
un determinado nivel del líquido dentro del contenedor.
17
Capitulo 2 Medición de nivel por lectura de código
2.3 CONDICIONES PARA REALIZAR LA MEDICIÓN DE NIVEL BAJO EL PRINCIPIO SELECCIONADO Como se ha mencionado, las características del líquido que se
somete a la medición con este prototipo pueden ser muy variadas. Los fluidos en cuestión pueden tener un alto índice de viscosidad o pueden ser fluidos muy delgados.
Debido a esta cualidad del sensor, los cambios en la densidad y
viscosidad de un fluido (que cambian principalmente por las variaciones de temperatura y presión) no intervienen en la medición del dispositivo, por lo que se hace inmune a los cambios de temperatura y presión dentro del tanque.
La dilatación de ciertos líquidos pueden ser medidos por el
dispositivo, siempre y cuando el nivel de discretización del sensor lo permita.
El sensor puede medir líquidos opacos así como fluidos no
homogéneos; los líquidos a medir pueden no estar limpios o pueden ser una combinación de ellos, ya que el desplazamiento del líquido en el tanque es lo primordial para este principio de operación.
Debido a que los flotadores que desplazan la placa perforada
con el código binario son el único elemento que se encuentra en contacto directo con el fluido, es de especial cuidado elegir el material de los mismos.
El material de los flotadores debe elegirse previamente para
soportar la agresividad del líquido (corrosión, densidad, temperatura del líquido), así como las variaciones de temperatura y presión dentro del contenedor, además debe asegurar su flotabilidad en el líquido.
Para realizar la medición bajo este principio es menester que el
perfil de llenado o de vaciado del líquido dentro del tanque sea lo más plano posible, es decir, que se mantenga una velocidad constante de llenado o vaciado para obtener una lectura estable y bien definida.
18
Capitulo 2 Medición de nivel por lectura de código
En caso de trabajar con líquidos donde el ambiente sea de régimen turbulento, se tendría que establecer factores de corrección en el procesamiento de la señal para obtener una lectura promedio del sistema.
Para este tipo de esquema turbulento, puede ser conveniente
implementar sistemas de rectificación mecánica para reducir las variaciones del perfil del nivel y obtener de esta manera las condiciones de velocidad apropiadas para el sistema.
Para realizar la medición de nivel de un líquido dentro del
contenedor se consideraron los siguientes elementos:
• Una placa perforada con el código binario con las dimensiones adecuadas para su correcto funcionamiento, a fin de aplicar el principio de operación descrito anteriormente.
• Elementos que conforman el sistema óptico (emisor,
receptor, fibras ópticas, etc).
- Diseño electrónico de una fuente óptica de potencia fija ajustable.
- Diseño electrónico de un receptor óptico adecuado
para tratamiento digital.
- Elección de la fibra óptica para el sistema.
- Desarrollo de un método de calibración para el sistema.
• Desarrollo del sistema electrónico para el procesamiento
de las señales entregadas por el sensor.
• Implementación del sistema de salida para obtener la lectura del nivel en el tanque.
19
Capitulo 2 Medición de nivel por lectura de código
• Sistema hidráulico de prueba utilizando ductos de plástico (poliductos PVC o acrílico).
- El líquido de control dentro del tanque es el agua
(Densidad = 1g/cm3, viscosidad absoluta = 1 cP). - Diseño del sistema con tubos de PVC hidráulicos de 1”∅.
20
Capitulo 3 Diseño y construcción del sensor de nivel
CAPÍTULO 3 DISEÑO Y CONSTRUCCIÓN DEL SENSOR DE
NIVEL
21
Capitulo 3 Diseño y construcción del sensor de nivel
3.1 INTRODUCCIÓN La construcción de un sensor con las características descritas, implica la correcta selección de los materiales a utilizar tanto para el diseño opto-mecánico como para el elemento sensor. El diseño debe considerar la sustancia con que se trabajará para reducir al mínimo el mantenimiento del mismo. 3.2 ELEMENTO SENSOR El elemento sensor del sistema está conformado por la placa perforada y los flotadores que se encuentran en su base.
El código binario en la placa fue elegido para tener una conexión semidirecta con la electrónica digital y de esta forma obtener el byte de información correspondiente al nivel del líquido en el contenedor.
El material de la placa perforada debe cubrir los siguientes
requerimientos:
• Debe soportar las condiciones ambientales dentro del contenedor.
• Debe construirse con materiales livianos que permitan la
flotabilidad de las boyas en su base.
• El material debe ser rígido para obtener una buena lectura del código.
Para el prototipo implementado en el laboratorio, se utilizó una
placa de duraluminio de 27.8 cm (10.94 pulgadas) de largo por 6 cm (2.36 pulgadas) de ancho, el grosor de la placa es de 0.76 mm (30 milésimas de pulgada) ( véase el anexo A).
La razón para utilizar duraluminio en el sistema de medición de
nivel fue la de tener una placa ligera y que fuera rígida a la vez, a pesar de tener un grosor pequeño.
22
Capitulo 3 Diseño y construcción del sensor de nivel
La placa con el código binario no debe interactuar químicamente con el agua ni presentar oxidación a largo plazo. Otras alternativas pueden ser placas de magnesio, titanio o algún plástico rígido como el PVC.
Dado que el líquido elegido para las mediciones de prueba es el
agua, los flotadores utilizados para impulsar la placa perforada con el código binario fueron 2 boyas hidráulicas de plástico de 3.5 pulgadas de diámetro.
La placa impulsada por los flotadores se desplaza a través de las
fibras ópticas emisoras y receptoras por medio de unas flechas de aluminio que guían la tarjeta perforada hacia una placa ranurada (también de aluminio) donde descansan las fibras ópticas.
La placa ranurada de aluminio se encuentra en la parte superior
del contenedor. El propósito de esta placa ranurada es el de sostener y alinear las fibras ópticas emisoras y receptoras.
La alineación de las fibras ópticas emisoras y receptoras es tanto
transversal como longitudinal. La alineación longitudinal es necesaria para la lectura de la placa
perforada con el código binario, ya que en la placa perforada cada código está dispuesto en forma horizontal y las 8 fibras ópticas deben mantener la horizontalidad para la lectura correcta de la placa perforada.
La alineación transversal se obtiene con el acanalamiento en “V”
de la placa ranurada, este acanalamiento recorre la placa ranurada de un extremo a otro, tal como lo muestra la figura 3.1.
En los canales descansan las fibras ópticas emisoras y
receptoras, de tal forma que al asentarse en el fondo del canal cada fibra óptica queda alineada con su par en el otro extremo de la ranura; de esta manera se obtiene la mejor alineación transversal y lateral.
23
Capitulo 3 Diseño y construcción del sensor de nivel
Figura 3.1 Bosquejo de la placa ranurada y acanalada.
En la figura 3.1 Se puede apreciar el espacio existente entre fibra
óptica emisora y receptora, esta es la ranura en la placa de aluminio por donde se desplaza la placa perforada con el código binario. En este punto es donde se encuentra la mayor pérdida de potencia óptica entre fibra óptica emisora y receptora. Para mayor detalle referirse al anexo A.
3.3 SISTEMA HIDRÁULICO. El sistema hidráulico utilizado para el sensor de nivel fue el existente en el laboratorio de electrónica. El objeto de utilizar este sistema es el de aprovechar la trayectoria del circuito hidráulico de un contenedor de 50 litros hacia otro de 60 litros (el cual tiene el sensor de nivel de líquidos).
24
Capitulo 3 Diseño y construcción del sensor de nivel
El flujo del líquido es bidireccional, de tal forma que se puedan
hacer pruebas de llenado y vaciado en el tanque que tiene instalado el sensor.
El sistema hidráulico propuesto puede llenar o vaciar el tanque con el sensor de nivel a través de un arreglo de tuberías en conjunto con un juego de válvulas que pueden transportar el líquido de un contenedor a otro y viceversa, tal como se observa en la figura 3.2.
Figura 3.2 Sistema hidráulico.
Debido a las dimensiones del contenedor de 60 litros, a la potencia de la bomba hidráulica, así como al conjunto de tuberías, se logra obtener un perfil de velocidad constante de llenado sin turbulencias excesivas en el contenedor; de tal forma que facilita la medición de la variable.
25
Capitulo 3 Diseño y construcción del sensor de nivel
3.4 SISTEMA ÓPTICO DEL SENSOR Todo sistema óptico está conformado por tres componentes principales: un transmisor, un medio de transmisión óptica (fibras ópticas), la cual sirve como vía o canal de comunicación y un receptor[3]. La fibra óptica, que es un medio dieléctrico, permite guiar a la luz misma que puede contener la información pertinente a la variable física medida (en este caso el nivel de un líquido).
Figura 3.3 Elementos generales de un sistema de medición óptico.
Para cualquier sistema óptico de medición es necesario la
utilización de transductores, que pueden ser de conversión de señales eléctricas (voltaje o corriente) a energía luminosa (transductores emisores) o transductores que conviertan la energía luminosa a señales eléctricas (transductores receptores). El bosquejo de los elementos generales que conforman al sistema óptico del sensor se presenta en la figura 3.3; cada elemento del sistema se trata por separado más adelante.
26
Capitulo 3 Diseño y construcción del sensor de nivel
3.4.1 FIBRA ÓPTICA Las fibras ópticas son filamentos de vidrio o dióxido de silicio largos y flexibles, constan de un núcleo transparente rodeado por un material dieléctrico llamado revestimiento (aunque también existen varios núcleos dentro de un mismo revestimiento) y un recubrimiento que dota de protección al revestimiento[1].
El núcleo es la sección central principal por la que viaja la información en forma de luz. El revestimiento es la capa que rodea al núcleo, su objeto es actuar como pantalla reflejante que atrapa los rayos de luz en el núcleo, su índice de refracción es ligeramente menor al del núcleo.
Figura 3.4 Partes que integran a una fibra óptica.
La transmisión de información en las fibras ópticas se logra aprovechando el fenómeno de la reflexión interna total dentro del núcleo. La selección de las fibras ópticas para el sensor de nivel está limitada por los tipos de fibras ópticas existentes en el laboratorio de electrónica. Las fibras ópticas disponibles en el laboratorio son:
- Fibra óptica de plástico con un diámetro de núcleo de 1000 µm.
- Fibra óptica de vidrio con un diámetro de 50/125 µm.
- Fibra óptica de vidrio con un diámetro de 100/140 µm
27
Capitulo 3 Diseño y construcción del sensor de nivel
Para la elección de alguna de las fibras ópticas anteriores se estudiaron sus características individuales, ventajas e inconvenientes para implementar el sensor.
En primera instancia, se descartó la fibra óptica de plástico de
1000 µm de diámetro debido a que este tipo de fibra óptica tiene una atenuación relativamente elevada a las longitudes de onda localizadas en el infrarrojo, es por esta razón que las fibras ópticas de vidrio tienen más uso, más variedad y una mayor gama de aplicaciones en el mercado de las comunicaciones.
Aunque las fibras ópticas de plástico tienen un núcleo
considerablemente grande y por tanto puede acoplar más luz a la misma, resulta inconveniente para el sensor de nivel, el que esta fibra óptica esté diseñada para ser transparente a las longitudes de onda en el espectro visible, lo cual puede provocar interferencia al sensor debido a la luz ambiental.
La fibra óptica de plástico tiene atenuaciones de hasta más de
1000 dB/Km para longitudes de onda en el infrarrojo, por lo que no son capaces de transmitir luz infrarroja a grandes distancias.
La luz que se propaga en un conductor de fibra óptica de vidrio
experimenta atenuaciones mayores en las longitudes de onda del espectro visible, mientras que en la región del infrarrojo presenta atenuaciones menores.
Para cubrir grandes distancias sin emplear regeneradores
intermedios, es necesario mantener estas pérdidas en el mínimo posible, es por esto, que en este tipo de fibras ópticas conviene emplear luz que se encuentre en longitudes de onda pertenecientes al infrarrojo.
Para la elección de las fibras ópticas de vidrio existentes en el
laboratorio, se caracterizaron ambas fibras ópticas tal como se explica adelante.
28
Capitulo 3 Diseño y construcción del sensor de nivel
3.4.2 CARACTERIZACIÓN DE LAS FIBRAS ÓPTICAS DE VIDRIO
Una característica importante de las fibras ópticas es su habilidad de colectar luz emitida por una fuente. Cuando se acopla una fuente óptica a una fibra óptica, se presentan dos mecanismos de pérdidas, uno de ellos está relacionado al desacoplamiento de área y el otro está relacionado con la apertura numérica.
El desacoplamiento de área se presenta cuando el patrón de radiación de la fuente (cono de la emisión de luz) es más grande que el área transversal del núcleo.
En ocasiones aunque el área iluminada por la fuente sea menor que el área del núcleo, existe otra pérdida asociada con el cono de aceptación de la fibra[4].
El ángulo de aceptación (θa) de luz de la fibra óptica está relacionado con el ángulo crítico, dado que se pretende colectar la mayor cantidad de luz al núcleo de una fibra óptica, entonces es importante conocer este parámetro de las fibras ópticas conocido como apertura numérica (figura 3.5).
Figura 3.5 Cono de aceptación de la fibra óptica dependiente de la apertura
numérica. Para determinar el cono de apertura de las fibras ópticas de vidrio se utilizó un diodo láser como fuente óptica (por su alta capacidad de acoplamiento de potencia óptica a la fibra).
29
Capitulo 3 Diseño y construcción del sensor de nivel
Se inyectó luz por un extremo de la fibra óptica sometida a prueba, y en el otro extremo de la misma se midió la mota de luz conducida por la fibra, observada en una pantalla blanca, tal como se muestra en la figura 3.6.
Figura 3.6 Medición de la apertura numérica de la fibra óptica.
Se determinó la apertura numérica de la fibra óptica por medio de la siguiente expresión[7]:
22
4
2
hd
d
NAsen a
+
==θ (2)
donde d= diámetro de la mota de luz en la pantalla blanca (mm). h= distancia entre la fibra óptica y la pantalla blanca (mm). NA= apertura numérica de la fibra óptica (adimensional). θa = ángulo de apertura (grados). Con la expresión matemática anterior se puede determinar el radio de iluminación de la luz entregada por la fibra óptica a una distancia d.
30
Capitulo 3 Diseño y construcción del sensor de nivel
Para realizar la medición se montó la fibra de 100/140 frente a una pantalla de papel blanco en donde se marcó la imagen del cono de luz proyectado por la fibra. El proceso se realizó a diferentes distancias, para tener más precisión en el cálculo. La fuente óptica fue un apuntador láser comercial al cual se le alteró su lente interna para enfocar el haz hacia la fibra óptica y de esta manera inyectar mayor potencia lumínica a la fibra óptica. Los resultados se presentan en las siguientes tablas: Tabla 3.1 Mediciones de la NA para la fibra óptica de 100/140 µm
h(mm) d(mm) NA(adimensional) 8.43 5.33 0.301 2.59 1.98 0.35
2 1.16 0.27 1.28 0.79 0.29
Promedio 0.302
Tabla 3.2 Mediciones de la NA para la fibra óptica de 50/125 µm h(mm) d(mm) NA(adimensional) 8.43 3.81 0.22 2.6 1 0.192 2 0.81 0.199
1.28 0.6 0.232 Promedio 0.211
En las pruebas que se realizaron a las fibras ópticas de vidrio se puede apreciar que la fibra óptica que tiene una apertura numérica ligeramente mayor es la fibra óptica de 100/140 µm. , por lo que tiene un cono de apertura mayor que la otra fibra óptica. Se eligió la fibra óptica de 100/140 µm dado que tiene un núcleo mayor y por tanto es posible acoplar más potencia lumínica a esta fibra óptica.
31
Capitulo 3 Diseño y construcción del sensor de nivel
3.4.3 FUENTE ÓPTICA
Las fuentes ópticas pueden construirse a base de tres tipos de emisores de luz: Diodos Láser (LD), Diodos Emisores de Luz (LED) o Diodos Súper luminiscentes(SLD)[2]. Los diodos láser son fuentes de luz coherente, producto de la emisión estimulada que tiene lugar en una cavidad resonante, compuesta por una superficie reflejante y otra parcialmente reflejante, en donde se da la retroalimentación óptica. Su ancho espectral es menor a 5nm y tiene un patrón de radiación muy direccional, con lo que se obtiene un acoplamiento de potencia óptica grande. Los diodos emisores de luz son fuentes de luz incoherente debido a que trabajan bajo el principio de emisión espontánea, su fabricación es mucho más sencilla y robusta en comparación con los LD´s, regularmente se modulan en amplitud ya que la potencia luminosa del LED es proporcional a la corriente inyectada en éste; el patrón de radiación de este dispositivo es omnidireccional por lo que el acoplamiento con fibras ópticas es pobre. Los diodos súper luminiscentes (SLD) son similares a los LD´s, su diferencia principal es que en estos dispositivos no se tiene retroalimentación óptica como en los LD´s. La radiación emitida por un SLD es de emisión espontánea amplificada, aunque la emisión no es coherente, su ancho espectral es más reducido que el de un LED, pero más ancha que la de un LD y su patrón de intensidad radiante es más reducido y potente que el de los LED´s. Para seleccionar el tipo de fuente luminosa fue necesario tomar en cuenta las ventajas y los inconvenientes de cada dispositivo, así como los requerimientos del sistema mismo: El diodo Láser, aunque tiene un mayor acoplamiento óptico a la fibra óptica, es críticamente dependiente de la corriente de operación (corriente de umbral de emisión láser) y de la temperatura. Además, este dispositivo es muy delicado en la presencia de transitorios eléctricos y es muy costoso cuando radían en el infrarrojo.
32
Capitulo 3 Diseño y construcción del sensor de nivel
Los diodos súper luminiscentes son de alto costo y requieren de una gran corriente de inyección para producir una ganancia sustancial. Por tanto el dispositivo elegido fue el LED, que tiene mayor estabilidad térmica, mayor tiempo de vida, es menos susceptible a transitorios eléctricos y es económico.
Para los propósitos del sistema es suficiente la utilización de un LED a pesar de su baja eficiencia de acoplamiento de luz a la fibra óptica, ya que sólo se requiere de una fuente óptica relativamente estable.
Las ventanas de operación de la fibra óptica de vidrio preferidas
para telecomunicaciones se encuentran en el espectro infrarrojo, siendo 850, 1300 y 1550 nm las longitudes de onda más empleadas para esa aplicación.
Debido a que se utilizó la fibra óptica multimodo de vidrio de
100/140 µm, se realizaron pruebas con diferentes LED´s que radian en el espectro infrarrojo, siendo el LED OPF371 de OPTEK[11] el que proporcionó el mayor acoplamiento de luz a la fibra óptica elegida.
El LED OPF371 tiene la ventaja de tener integrado al
semiconductor un receptáculo SMA. Este tipo de conectores son los empleados por las fibras ópticas del sistema. Las hojas de especificaciones técnicas del OPF371 se encuentran en el anexo B.
La configuración de la fuente óptica es un circuito electrónico de control de corriente por medio de un transistor y una referencia de voltaje, tal como se puede apreciar en la figura 3.7. La referencia de voltaje de la fuente óptica la proporciona el integrado LM 399[13], esta referencia de voltaje tiene una estabilidad térmica de una millonésima de volt por cada grado centígrado.
33
Capitulo 3 Diseño y construcción del sensor de nivel
Figura 3.7 Fuente óptica con LED emisor de 850 nm.
El integrado LM399 mantiene un voltaje de 6.9 volts entre sus
terminales de cátodo y ánodo, de tal forma que el voltaje de referencia se obtiene por medio del divisor de voltaje entre las resistencias de 1KΩ y 100KΩ tal como sigue:
VoltsVoltsVREF 832.61000100000
1000009.6 =⎥⎦⎤
⎢⎣⎡
Ω+ΩΩ
= (3)
Se puede observar en el diagrama eléctrico que el voltaje de referencia se ve reflejado en el emisor del transistor BD139, lo que provoca una corriente de magnitud semejante en el colector del mismo.
La corriente en el LED se calcula con la siguiente ecuación:
mAohms
VoltsRVII
E
ECE 3.83
82832.6
===≅ (4)
La corriente en el LED se estableció de este valor para obtener la máxima potencia lumínica del diodo pero sin llegar a su corriente límite de operación, en las hojas de especificación del anexo B se puede observar que la corriente límite de este LED es de 100 mA. El capacitor de 22 µF proporciona estabilidad a posibles transitorios por el valor de la constante de tiempo, esta constante está determinada por la resistencia en paralelo y tiene un valor de 2.2 segundos.
34
Capitulo 3 Diseño y construcción del sensor de nivel
Figura 3.8 Circuito para caracterizar a los diodos del emisor.
Con el circuito de la figura 3.8 se caracterizaron los LED´s de cada emisor óptico. Por medio de la resistencia variable de 100 KΩ, se varió el voltaje de referencia de tal forma que se obtuvieron diferentes corrientes en el OPF371, obteniéndose las siguientes mediciones: Tabla 3.3 Mediciones de corriente de LED vs. Voltaje de referencia. Voltaje de referencia VREF (Volts) Corriente en el LED ILED (mA)
1.2 15 1.54 20
2 25 2.41 30 2.78 35 3.14 40 3.56 45 4.03 50 4.47 55 4.89 60 5.23 65 5.7 70
6.05 75 6.48 80 6.87 85 7.25 90 7.69 95 8.2 100
35
Capitulo 3 Diseño y construcción del sensor de nivel
Cabe aclarar que para corrientes que son mayores a 80 mA, las
mediciones se realizaron sin el integrado LM399, esto fue con el fin de caracterizar al diodo emisor en su máxima conducción de corriente.
Se caracterizó la salida óptica del LED OPF371 a partir de las
diferentes corrientes en el dispositivo. La medición de la potencia óptica se realizó con el multímetro óptico Tektroniks Modelo TFC200, obteniéndose las siguientes mediciones.
Corriente en el LED ILED (mA) Potencia óptica PO (µW)
15 26.6 20 38.9 25 48.1 30 59.3 35 61.4 40 80.1 45 87.9 50 99.2 55 106.8 60 113.5 65 123.6 70 132.7 75 139.3 80 146.7 85 153.9 90 160.2 95 165.4
100 171.3 Tabla 4. Mediciones de la potencia óptica de LED vs. corriente del
LED.
De acuerdo con la tabla 3.4, la potencia promedio para una corriente de 80 mA para un lote de 8 LED´s OPF371 fue de 150µW. De los cuales, al acoplarse a la fibra óptica emisora se obtuvo una lectura de potencia promedio de 126µW a la salida de cada fibra óptica.
36
Capitulo 3 Diseño y construcción del sensor de nivel
3.4.4 RECEPTOR ÓPTICO El proceso de conversión de fotones a electrones libres (portadores) es esencial para el sistema óptico. Esta conversión se realiza por medio de fotodetectores que pueden clasificarse como[2]:
a) Elementos fotoemisivos. b) Elementos fotoconductivos.
c) Elementos fotovoltaicos.
A los elementos fotoemisivos se les conoce también como
elementos de efecto fotoeléctrico externo, mientras que los dos restantes se les llama elementos de efecto fotoeléctrico interno.
Los detectores fotoemisivos pueden ser los fotodiodos de vacío y los tubos fotomultiplicadores. El componente principal para este tipo de detectores es el material fotosensitivo en el cátodo.
En este tipo de detectores cuando el cátodo se ilumina por
radiación externa, se desprenden electrones del material sensitivo que viajan por el tubo de vacío donde los electrones se aceleran y colectan por el ánodo, formándose una trayectoria eléctrica completa que fluye hacia un circuito externo. Dado que este tipo de elementos tienen un costo elevado, son poco robustos y además requieren de fuentes de alimentación de alto voltaje (150 – 2000V), se descartó la utilización de los mismos.
Los detectores fotoconductivos son dispositivos de un solo tipo
de material semiconductor; en este tipo de detectores, la conductividad del semiconductor varía linealmente con la incidencia de luz, la cual se traduce en variaciones de corriente o de voltaje para un circuito eléctrico externo. Estos detectores tienen la desventaja de trabajar en un intervalo de longitudes de onda que van de 3µm a 100µm por lo que su utilización fue descartada en el proyecto.
37
Capitulo 3 Diseño y construcción del sensor de nivel
La característica principal de los detectores fotovoltaicos es la presencia de una unión de material semiconductor. La unión puede ser una homounión, una heterounión, una unión semiconductor y metal (como la barrera Schottky), una unión de contacto puntual o una estructura PIN.
Existen básicamente dos tipos de semiconductores
fotodetectores empleados en los receptores ópticos de este tipo; el primero es comúnmente referido como fotodetector PIN, éste genera menos de un de electrón-hueco por fotón absorbido.
El segundo se refiere como fotodetector de avalancha debido al
proceso de ionización de impacto, este proceso produce una ganancia interna, ya que genera más de un par electrón-hueco por fotón absorbido; a esta ganancia se le conoce como ganancia de avalancha.
En algunas aplicaciones, donde se requiere alta sensibilidad, es
ventajoso diseñar los receptores con fotodetectores de avalancha; sin embargo, el proceso de ganancia es estadístico, en donde cada par electrón-hueco primario genera un número aleatorio M de pares electrón-hueco secundarios, con un valor medio N.
Por lo aleatorio del proceso de multiplicación de ionización de impacto se introduce ruido, que puede en algunas circunstancias ser un factor dominante en la sensibilidad del receptor.
Por los argumentos anteriores, se prefirió el diodo PIN OPF471
para la construcción del receptor óptico, ya que además resulta atractivo por las siguientes características: 1.- Alta sensibilidad a la longitud de onda de operación (850 nm). 2.- Contribución mínima al ruido total del receptor.
3.- Tiempo de respuesta mínimo a los cambios de potencia lumínica.
4.- Dimensiones físicas compatibles con la fibra óptica. 5.- Receptáculo SMA integrado al LED.
38
Capitulo 3 Diseño y construcción del sensor de nivel
6.- Baja corriente de obscuridad. 7.- Amplio intervalo de operación térmica.
En la figura 3.9 se muestra el diagrama eléctrico del receptor óptico con el OPF471, en ella se puede apreciar que para polarizar al diodo PIN (en forma inversa) se utilizó una resistencia de 10 KΩ.
Figura 3.9 Diagrama del circuito eléctrico del receptor óptico.
Las curvas características de un diodo PIN se muestran en la figura 3.10, en ellas se puede observar que conforme incide más luz en el diodo PIN OPF471, la curva característica del diodo PIN se desplaza en el eje negativo de iD, por lo que la corriente inversa en el OPF471 se incrementa conforme aumenta la luz incidente sobre el mismo [14].
39
Capitulo 3 Diseño y construcción del sensor de nivel
Figura 3.10 Curvas características de corriente vs. Voltaje y línea de carga
El voltaje de polarización inversa se eligió de 5 volts, por lo que los valores críticos para la recta de carga son:
VDiD=0 = Vcc-IDR = 5 Volts. (5)
ID vD=0 = (Vcc-VD)/R = 5 Volts/10 KΩ = 500 µA. (6)
El intervalo dinámico debido a la resistencia de 10KΩ, es apropiado para el OPF471, dado que para una incidencia de 104 Lux proporciona una corriente de corto circuito (Isc) de aproximadamente 500 µA. Si se incrementara la resistencia de carga se obtendría un intervalo dinámico de corriente más pequeño, con el riesgo de incrementar el ruido en el sistema debido al ruido térmico que es directamente proporcional a la magnitud del resistor de carga, como se demuestra con la siguiente ecuación:
fkTREt ∆= 4 (7) donde Et = ruido rms térmico
k = constante de Boltzmann (1.38x10-23 W-s/K) T = temperatura de el conductor en grados Kelvin. R = resistor o parte real de la impedancia del conductor ∆f = ancho de banda de ruido (Hz).
40
Capitulo 3 Diseño y construcción del sensor de nivel
Cabe aclarar que el incremento del voltaje inverso aplicado al diodo PIN mejora la rapidez en la respuesta del mismo, ya que existe una capacitancia de unión intrínseca entre las terminales del diodo PIN (como se muestra en el circuito equivalente de la figura 3.11), lo que provoca que se forme una constante de tiempo entre la carga y la capacitancia de unión.
En la figura 3.12 se puede notar que conforme se incrementa el
voltaje inverso aplicado, la capacitancia de unión (CJ) disminuye y por tanto aumenta la rapidez de respuesta del diodo PIN.
Figura 3.11 Circuito equivalente del fotodiodo PIN.
El valor de CJ es proporcional al área activa (A) e inversamente
proporcional a la resistivad del material del sustrato (ρ) y al voltaje inverso aplicado (VR), tal como lo indica la siguiente expresión[13]:
CJ = A[(VR+0.5)ρ]1/3 (8)
41
Capitulo 3 Diseño y construcción del sensor de nivel
Figura 3.12 Curvas características capacitancia CJ vs voltaje inverso. Tomada de [14].
Debido a que la variación del nivel de un líquido es lenta (en el
orden de décimas de segundos), no es necesario reducir el valor de CJ con voltajes inversos grandes, sino por el contrario, en el sistema no es conveniente incrementar el voltaje inverso ya que se incrementaría la corriente de obscuridad (como se aprecia en la figura 3.13).
Por esta razón el circuito se polarizó con 5 volts, aprovechando
de esta manera la fuente de polarización para la etapa receptora.
42
Capitulo 3 Diseño y construcción del sensor de nivel
Figura 3.13 Curvas características corriente de oscuridad vs. voltaje inverso. Tomada de [14]. El circuito equivalente del diodo PIN con una primera etapa de
amplificación se muestra en la figura 3.14.
Figura 3.14 Circuito equivalente del diodo PIN y una etapa de amplificación con sus respectivas fuentes de ruido.
En la figura 3.14 se aprecian los siguientes elementos: IL = Corriente generada por la luz incidente (A) VD= Voltaje a través del diodo, VD = Vcc-VRL ≈ 5V - 0.1V = 4.9V ID = Corriente promedio a través del diodo (≈10µA) CJ = Capacitancia de unión (≈1.5 pF)
43
Capitulo 3 Diseño y construcción del sensor de nivel
ISh = Corriente de ruido de granalla de fotodiodo (A) ISh = BqIdc2 .................................................(9) donde q= 1.602x10-19 coulombs, Idc= Corriente promedio (A) B = ancho de banda de ruido (Hz). Por tanto HzHzAxBqII dcSh /pA8.1)1)(10)(10602.1(22 19 ≈== − µ RSh = Resistencia de fuga (Ω) 107 Ω<RSh<1011Ω. RS = Resistencia en serie (Ω), Rs<10Ω RL = Resistencia de carga (Ω), RL = 10 KΩ. EnRL= Voltaje de ruido térmico de RL.
kTRBEnRL 4= donde k= constante de Boltzman = 1.38 x 10-23 W-s/K. T= temperatura del ambiente en grados Kelvin. R= Resistencia o parte real de la impedancia del conductor (Ω). B= Ancho de banda de ruido (Hz). Por tanto HznVHzKKxkTRBEnRL /13)1)(10)(300)(1038.1(44 23 =Ω== − En = Voltaje de ruido del amplificador operacional. )/18( HznV . In = Corriente de ruido del amplificador operacional. )/pA01.0( Hz Ci = Capacitancia de entrada del amplificador operacional (pF). Ri=Resistencia de entrada del amplificador operacional (≈1012Ω). La señal en corriente proveniente de la excitación del diodo PIN
(proporcional a la potencia óptica incidente en una fibra óptica receptora) se amplifica mediante dos etapas, ambas etapas tienen la configuración de un amplificador no inversor. La expresión matemática de la ganancia (AV) de un amplificador no inversor es:
I
fV R
RA += 1 (10)
Donde Rf = Resistor de retroalimentación y RI = Resistor de entrada. La primera etapa es un preamplificador de señal, la cual acondiciona la señal eléctrica del diodo PIN OPF471; la ganancia de esta etapa es A1=101.
44
Capitulo 3 Diseño y construcción del sensor de nivel
Esta primera etapa amplificadora se construyó con el operacional TL071 debido a que es un amplificador operacional de bajo ruido, por lo que es adecuado para amplificar señales muy pequeñas. Cuando incide la luz infrarroja de una fibra óptica receptora en el diodo PIN OPF471 del receptor óptico, se tienen en promedio una señal eléctrica un poco mayor a 1mV en la resistencia de polarización del diodo PIN (10KΩ). Por lo que después del preamplificador se tiene una señal promedio de 0.1 Volt a la salida. La segunda etapa de amplificación tiene una ganancia A2 = 47. Esta etapa tiene el propósito de asegurar los niveles de voltaje compatibles con la tecnología TTL para procesar dicha información posteriormente. Se seleccionó el amplificador operacional LM399, debido a que es de tecnología de colector abierto, por lo que se tiene voltajes de saturación cercanos a los 5 Volts. Después de esta etapa la señal eléctrica se encuentra en un intervalo de 4.75 a 5 Volts. Para minimizar el ruido en el circuito receptor se sugiere que la primera etapa amplificadora tenga la máxima ganancia, ya que la segunda etapa de amplificación se conecta en cascada. El factor de ruido de un sistema con dos etapas de amplificación está definido por la siguiente expresión[15]:
( )1
2112
1G
FFF −+= (11)
Donde F12 = factor de ruido del sistema con dos etapas de amplificación. F1 = factor de ruido del primer amplificador. F2 = factor de ruido del segundo amplificador G1 = ganancia del primer amplificador.
Se concluye que el factor de ruido de una red en cascada está influenciado principalmente por el ruido de la primera etapa, por lo que la ganancia de está etapa debe de ser lo más grande posible.
45
Capitulo 3 Diseño y construcción del sensor de nivel
La ganancia de la primera etapa amplificadora no fue implementada con un valor alto con respecto a la segunda etapa, porque no se deseaba la saturación en la entrada de la segunda etapa. Después de esta segunda etapa amplificadora se manda la señal a un buffer Schmitt antes de ser procesado por el microcontrolador COP8SGR7, tal como se describe en el siguiente capítulo.
46
Capitulo 4 Procesamiento de la señal eléctrica e interfase periférica
CAPÍTULO 4 PROCESAMIENTO DE LA SEÑAL ELÉCTRICA E
INTERFASE PERIFÉRICA
47
Capitulo 4 Procesamiento de la señal eléctrica e interfase periférica
4.1 INTRODUCCIÓN Después de obtener una señal eléctrica de un sensor es necesario procesar esta señal para poder interpretar correctamente la información contenida en ella. Para una mejor comprensión del fenómeno físico, químico o biológico que se somete a medición, es necesario tener alguna interfase con el procesador ya sea visual o auditiva. 4.2 PROCESADOR DE SEÑAL Para procesar la señal entregada por el sensor óptico, se empleó el microcontrolador COP8SGR7 de National Semiconductors [10] de 40 pines. En la figura 4.1 se observan los pines del microcontrolador y algunas de sus funciones alternas. Se puede apreciar que el microcontrolador empleado fue el de encapsulado DIP (Dual in Line Package).
Figura 4.1 Diagrama del circuito integrado COP8SGR7
48
Capitulo 4 Procesamiento de la señal eléctrica e interfase periférica
El microcontrolador COP8SGR7 fue empleado en el sistema por las siguientes características y ventajas:
• Bajo costo del microcontrolador y de su sistema mínimo de programación.
• Puede operar en ambientes con alta contaminación electromagnética.
• Memoria EEPROM de 32Kbytes integrada. • Opera con niveles de bajo voltaje (2.5 Volts) o niveles TTL. • Puertos programables de entrada / salida de alta corriente
(capaces de manejar LED´s, motores y altavoces pequeños).
• Puede operar con un cristal de hasta 10MHz con alta fiabilidad.
• Basado en arquitectura Harvard Modificada. • Sistema de temporización avanzado y de fácil
programación. • Biblioteca de programación avanzada con macros. • Alta eficiencia en los códigos de programación. • Consumo de muy baja potencia (en modos HALT e IDLE). • Ultrabaja emisión de interferencia electromagnética. • Monitoreo del reloj y sistema de protección anticorrupción
de programa • Protección contra descargas electrostáticas (de más de
2000V). • Reset de encendido por fuente. • Puertos programables de entrada / salida avanzados que
minimizan componentes externos.
El microcontrolador COP8SGR7 tiene diferentes opciones para el oscilador, tales como la utilización de un cristal, un circuito resonador interno, activación por onda cuadrada externa o reloj R-C interno o externo.
Se utilizó el modo de cristal para la activación del reloj, ya que
este modo es más estable y a diferencia de las otras opciones es menos dependiente de la fuente de alimentación del sistema.
49
Capitulo 4 Procesamiento de la señal eléctrica e interfase periférica
El ciclo de máquina o la frecuencia de trabajo interno del microcontrolador depende del valor del cristal (fcristal) con que se trabaje, la expresión para calcular el tiempo del ciclo de máquina es:
10
1cristal
C fT = (12)
Debido a que se tiene un cristal de 4 MHz en operación, el
tiempo de máquina (TC) es:
.5.2
104
1 segMHzTC µ== (13)
El microcontrolador COP8SGR7 tiene una arquitectura Harvard
modificada (el diagrama a bloques de la arquitectura interna se puede apreciar en el anexo B).
La característica principal de este tipo de arquitectura (a
diferencia de la arquitectura Von Neumann) es que la memoria de programa y de datos son independientes. Cada memoria tiene su propio bus de datos y bus de direcciones, por lo que se tiene acceso simultáneo a los datos y al programa.
Debido a esta cualidad, la próxima instrucción puede ser
alimentada desde la memoria del programa mientras que la instrucción actual está siendo ejecutada.
Las instrucciones de este microcontrolador puede realizar más
operaciones lógicas por unidad de instrucción con menos ciclos de máquina.
Cada terminal (PIN) de los puertos del microcontrolador puede
ser programado en forma independiente como entrada / salida. Este microcontrolador no solo procesa la señal recibida de las
fibras ópticas sino que controla el funcionamiento adecuado del exhibidor de cristal líquido AND491[12].
50
Capitulo 4 Procesamiento de la señal eléctrica e interfase periférica
4.3 PERIFÉRICO DE SALIDA Para desplegar los resultados del procesamiento del
microcontrolador COP8SGR7, proveniente de la señal de las fibras ópticas del sistema, se empleó como interfase periférica al exhibidor de cristal líquido AND491.
Por medio de este dispositivo electrónico se puede visualizar la
lectura del nivel de líquidos en litros contenido en el tanque sometido a medición. En él se aprecian los mensajes de llenado o de vaciado del contenedor dependiendo del caso en que se encuentre el tanque.
El exhibidor de cristal líquido AND491 es un dispositivo
electrónico inteligente, compacto (88mm x 36mm x 12mm) de 16 caracteres por 2 líneas en pantalla. Este exhibidor puede mostrar 160 caracteres (números, letras y símbolos).
El formato de cada carácter puede ser programado de 5x7
puntos o de 5x10 puntos, cuenta con 11 comandos de control tal como se aprecia en el anexo C.
El exhibidor trabaja con niveles TTL (5 Volts) y tiene un bus de
direcciones y datos de 8 bits, puede ser programada para ser compatible con CPU´s de 4 bits.
4.4 INTERFASE PERIFÉRICA. La interconexión entre el microcontrolador COP8SGR7 y el
exhibidor de cristal líquido AND491 fue directa por medio del puerto D de alta corriente del microcontrolador y el bus de datos y direcciones del exhibidor.
En la figura 4.2 se puede apreciar que los pines de control del
exhibidor están conectados a los pines L5 y L7 del puerto L del microcontrolador, el resistor variable de 10 KΩ conectado a la terminal 3 del exhibidor permite controlar el contraste de la pantalla del mismo.
51
Capitulo 4 Procesamiento de la señal eléctrica e interfase periférica
En el caso de no contar con una fuente externa de iluminación, se puede activar manualmente la luz que ilumina la pantalla completa del exhibidor por medio de un interruptor normalmente abierto.
Figura 4.2 Diagrama eléctrico de la interfase periférica.
En la figura 4.2 se puede observar que la señal que proviene de
la segunda etapa amplificadora del receptor óptico, pasa a través de un buffer con disparadores Schmitt internos (74LS541).
Aunque los disparadores Schmitt cambian de estado a los 2.4
Volts, es necesaria la segunda etapa amplificadora del receptor óptico para obtener una señal confiable y de esta manera mandar un “1” lógico al puerto del microcontrolador cuando se tiene una señal en el diodo PIN OPF471. Los buffer Schmitt también cumplen con el fin de proteger al puerto “F” del microcontrolador COP8SGR7.
4.5 PROGRAMACIÓN DEL COP8SGR7 El microcontrolador COP8SGR7 se programó para procesar la
señal de las fibras ópticas y controlar el exhibidor de cristal AND491.
52
Capitulo 4 Procesamiento de la señal eléctrica e interfase periférica
Al procesar la señal proveniente de las fibras ópticas se conoce el nivel actual del líquido en el contenedor, esta información se despliega en el exhibidor de cristal líquido.
En la programación se configuraron las terminales de los puertos
D (salida de pull-up), F (entrada de alta impedancia) y L (salida de pull-up) del microcontrolador para enviar los datos al exhibidor, obtener la señal de las fibras ópticas y controlar el exhibidor AND491 respectivamente.
Se utilizó el temporizador interno t0 de corrida libre para
sincronizar la actualización de la lectura del nivel en el exhibidor de cristal líquido con la señal obtenida de las fibras ópticas.
Figura 4.3 Diagrama de flujo del programa principal.
53
Capitulo 4 Procesamiento de la señal eléctrica e interfase periférica
El temporizador t0 se decrementa continuamente a la velocidad del ciclo de máquina y genera una interrupción cada 4096 ciclos. Dado que el tiempo de máquina es de 2.5 µseg entonces genera una interrupción cada 10.24 mseg.
Por medio del temporizador t0, se actualiza la lectura del nivel del
líquido en el contenedor, desplegado en el exhibidor de cristal líquido. La actualización de la lectura del nivel del líquido se realiza cada medio segundo por medio de la lógica del programa. El programa principal en lenguaje ensamblador puede encontrarse en el anexo C.
Dado que el tiempo de actualización de lectura del sistema es
menor a un segundo, podría éste operar en tiempo real. Para mostrar los mensajes en el exhibidor AND491 de llenado o
de vaciado del contenedor, así como la lectura del nivel de líquido en el mismo, se modificó e implemento la macro “display” de las bibliotecas de programación para COP8SAC y COP8SGR de National Semiconductor. El programa en extenso de la macro se muestra en el anexo C.
En la Figura 4.3 se muestra el diagrama de flujo general para el
procesamiento de la señal de las fibras ópticas y la lectura del nivel del líquido en el exhibidor de cristal líquido.
54
Capitulo 5 Caracterización del sistema y análisis de pérdidas
CAPITULO 5 CARACTERIZACIÓN DEL SISTEMA Y ANÁLISIS DE
PÉRDIDAS
55
Capitulo 5 Caracterización del sistema y análisis de pérdidas
5.1 INTRODUCCIÓN Para evaluar un sistema en operación es necesario caracterizar cada etapa del proceso para tener conocimiento de la eficiencia, pérdidas de energía, potencia consumida, etc. El obtener estos parámetros del sistema nos permite comparar el mismo con respecto a otros sistemas del mismo propósito. 5.2 SISTEMA GENERAL DE MEDICIÓN El sensor de nivel con fibras ópticas se construyó en 5 bloques principales (tal como se muestra en la figura 5.1): 1.- Fuente óptica. 2.- Sensor óptico (modulador). 3.- Receptor óptico. 4.- Procesador de señal. 5.- Periférico de salida.
Figura 5.1 Diagrama a bloques del sistema general de medición.
56
Capitulo 5 Caracterización del sistema y análisis de pérdidas
5.3 ELEMENTOS PRINCIPALES QUE CONFORMAN AL SISTEMA
• Sistema óptico.
- Fibras ópticas transmisoras:
Fibra óptica multimodo de vidrio, índice escalonado, 100/140 µm de núcleo, apertura numérica de 0.302, atenuación de 4 dB/Km.
Longitud: 1.5 mts. - Fibras ópticas receptoras:
Fibra óptica multimodo de vidrio, índice escalonado, 100/140 µm de núcleo, apertura numérica de 0.302, atenuación de 4 dB/Km.
Longitud: 1.5 mts.
- Elemento emisor:
Diodo Emisor de Luz (LED) OPF371 infrarrojo GaAlAs, longitud de onda de emisión máxima de 850 nm, ancho de banda espectral de 35 nm, encapsulado con conector SMA, fabricante OPTEK. - Elemento detector:
Fotodiodo PIN OPF471, encapsulado con conector SMA, respuesta a longitud de onda de 850 nm (respuesta pico), Responsividad de 0.55 A/W. Fabricante OPTEK. - Conectores: Conectores SMA, Fabricante FIS.
• Sistema mecánico.
- Placa perforada con código binario de 8 bits de duraluminio, 1.27 mm de centro a centro, 0.127 mm de peralte entre líneas de código.
57
Capitulo 5 Caracterización del sistema y análisis de pérdidas
- Placa soporte acanalada en “V” de aluminio con profundidad de 0.76mm (30 mil), ranura al centro transversalmente con 2mm de separación entre bordes.
- Sujetador para fibras ópticas de aluminio, ranurada al centro con 2mm de separación entre bordes y 16 prisioneros de 1.58mm (1/16´´).
- Guías de Aluminio ranuradas longitudinalmente de 40 cm.
• Procesador e interfase periférica.
- Procesador de señal:
Microcontrolador COP8SGR7 con memoria EEPROM de 32 Kbytes integrada, Fabricante National Semiconductors. - Periférico de salida: Exhibidor de cristal líquido AND491, 16 caracteres en pantalla por 2 líneas. Fabricante AND.
5.4 EVALUACIÓN DEL SISTEMA Las distancias existentes entre la fuente óptica, el sensor (punto de medición), y los receptores ópticos están determinados por las pérdidas de potencia en todo el sistema. En ambientes agresivos (como los existentes en la industria petroquímica, química, etc), es necesario localizar los puntos del procesamiento de la señal y monitoreo de la misma.
Tener una distancia prudente del proceso que se desea monitorear permite realizar la medición sin causar riesgos a los usuarios y un ambiente intrínsecamente más seguro. Es por la razón anterior que cobra importancia la caracterización de las pérdidas totales que se originan en la transmisión y recepción de luz en el sensor de nivel.
58
Capitulo 5 Caracterización del sistema y análisis de pérdidas
El análisis de pérdidas de potencia óptica está centrada en
4 casos principales[8]: a) Desalineación lateral. b) Desalineación angular c) Separación entre terminales d) Terminales mal pulidas.
En la figura 5.2 se puede apreciar gráficamente cada caso.
Figura 5.2 Pérdidas de potencia óptica.
Para estimar las pérdidas de potencia óptica en cada caso se
tomaron las siguientes consideraciones:
1.- La potencia óptica está uniformemente distribuida sobre el núcleo de la fibra óptica. 2.- Se muestra separadamente el análisis de los cuatro casos anteriores.
59
Capitulo 5 Caracterización del sistema y análisis de pérdidas
La potencia óptica acoplada al receptor se determina de acuerdo a la siguiente expresión[2]:
Pfotodetector = Pfuente - Σ Pérdidas. (14)
Donde Pfotodetector = Potencia acoplada al receptor. Pfuente= Potencia óptica de la fuente que se acopla a la fibra transmisora.
Σ Pérdidas = Suma de pérdidas de potencias ópticas. La contribución más grande a las pérdidas de potencia óptica en el sistema, se debe a la discontinuidad existente entre la fibra óptica emisora y receptora, siendo menores las pérdidas en los casos restantes. 5.4.1 DESALINEACIÓN LATERAL Para estimar las pérdidas por desalineación lateral se considera el desplazamiento de dos fibras ópticas (emisora y receptora), en donde sus núcleos están desplazados por una distancia d, como se observa en el esquema de la figura 5.3.
Figura 5.3 Desalineamiento entre dos fibras ópticas del mismo radio.
60
Capitulo 5 Caracterización del sistema y análisis de pérdidas
La eficiencia de acoplamiento η1 es la razón del área de superposición con respecto al área del núcleo. Matemáticamente se determina como sigue[8]:
⎥⎥⎦
⎤
⎢⎢⎣
⎡⎟⎠⎞
⎜⎝⎛−−=
2
1 21
22cos.2
ad
ad
adarc
πη (15)
donde el coseno inverso es calculado en radianes.
La pérdida de potencia en decibeles (L1), correspondiente al desplazamiento d se calcula como sigue:
11 10 η⋅⋅−= LogL (16)
donde L1 es la pérdida de potencia en decibeles y η1 es la eficiencia. Para estimar las pérdidas de potencia debido al desalineamiento lateral, se supuso desplazamientos entre los núcleos de las fibras ópticas menores al 10% del diámetro de las mismas, como se observa en la tabla 5.
Tabla 5.1 Pérdidas por desalineamiento lateral. d (µm) L (dB)
2.5 0.1404 5 0.2855
10 0.5904
5.4.2 DESALINEACIÓN ANGULAR La eficiencia de acoplamiento (η2) debido a un desalineamiento angular para una fibra multimodo de índice escalonado, se determina por la siguiente expresión [8]:
NAn⋅⋅
−=π
θη 02 1 (17)
61
Capitulo 5 Caracterización del sistema y análisis de pérdidas
Donde n0 es el índice de refracción de la sustancia existente entre las dos fibras ópticas, el ángulo θ es el ángulo de desalineación en radianes y NA es la apertura numérica de la fibra óptica. La pérdida de potencia (L2) en dB se determina como sigue:
22 10 η⋅⋅−= LogL (18)
La eficiencia se evalúa calculando la superposición de los conos de transmisión y recepción, tal como se muestra en la figura 5.4.
Figura 5.4 Desalineamiento angular entre dos fibras ópticas.
El cono de transmisión puede determinarse a partir de la
siguiente expresión:
00 α⋅⋅= SennNA (19)
Donde NA es la apertura numérica y α es el ángulo del cono de transmisión. Dado que entre las fibras ópticas se encuentra el aire, entonces n0=1, se considera NA= 0.3 para la fibra óptica de vidrio de 100/140 µm.
62
Capitulo 5 Caracterización del sistema y análisis de pérdidas
A continuación se determinan las pérdidas de potencia en decibeles para un desalineamiento de hasta ±5 grados.
Tabla 5.2 Pérdidas por desalineamiento angular. Angulo de inclinación.
Grados Radianes Eficiencia
(η) Pérdidas
(dB) 2 0.0349 0.9629 0.1642 3 0.0524 0.9444 0.2484 4 0.0698 0.9259 0.3344 5 0.0873 0.9074 0.4220
5.4.3 SEPARACIÓN ENTRE TERMINALES En la discontinuidad que existe entre fibras ópticas emisoras y receptoras, ocurren dos fenómenos diferentes de pérdidas de potencia: 1.- En esta discontinuidad existen dos fronteras entre la fibra óptica y el aire, lo que produce una pérdida por reflexión en la frontera de aproximadamente un 4% (0.177), de tal manera que entre las dos superficies de frontera vidrio-aire, se contribuye a una pérdida total por reflexión de 0.35 dB.
Figura 5.5 Separación existente entre dos fibras ópticas.
2.- Cuando se encuentra un espacio entre dos fibras ópticas tal
como se muestra en la figura 5.5, algunos haces de luz transmitidos no son interceptados por la fibra óptica receptora.
Conforme la separación existente entre ellas aumenta, las
pérdidas se incrementan debido a la divergencia del haz radiado por la fibra óptica emisora.
63
Capitulo 5 Caracterización del sistema y análisis de pérdidas
Las fibras ópticas con aperturas numéricas grandes tendrán más pérdidas por separación dado que la radiación emitida diverge más rápido.
Para determinar las pérdidas por separación, se determina el
área del cono de apertura de los haces de luz en la fibra óptica emisora (dependiente de la apertura numérica de la fibra óptica) y se establece una razón entre el área del núcleo de la fibra óptica receptora superpuesta al área del cono de apertura. De esta forma se puede establecer la siguiente relación:
núcleo
cono
AA
PePs
= (20)
Tomando como referencia la figura 5.6 se puede determinar la
eficiencia de acoplamiento del sistema como sigue:
Figura 5.6 Eficiencia de acoplamiento.
El área del cono de luz depende de la apertura numérica de la fibra óptica emisora, por lo que de la figura 5.6 se desprende que:
NAarcsen ⋅=θ , φ = Diámetro del núcleo de la fibra
x= separación entre fibras = 2 mm
r= Radio del cono de luz a una distancia x.
r= x.tg θ
64
Capitulo 5 Caracterización del sistema y análisis de pérdidas
por tanto r=x.tg[arc.sen (N.A)]. La eficiencia (η3) puede definirse como:
2
2
2
3 22
⎟⎠⎞
⎜⎝⎛=
⋅
⎟⎠⎞
⎜⎝⎛⋅
=rrφ
π
φπη (21)
Las pérdidas (L3) en decibeles se definen como:
2
33 2log10log10 ⎟
⎠⎞
⎜⎝⎛−=⋅−=
rL φη (22)
Por tanto el cálculo teórico de las pérdidas de potencia óptica en la discontinuidad del sistema es: Apertura Numérica (NA)= 0.3; x= 2mm; r= (x) [tg (arc. sen 0.3)] = 0.62897mm ≈ 628 µm η3= 6.5 x 10-3
L3= 21.87 dB. Realizando un análisis en la discontinuidad por medio de la óptica geométrica, se tiene que el ángulo de incidencia de un haz que proviene del núcleo de la fibra óptica emisora hacia el núcleo de la fibra óptica receptora es menor a 1.43° (tal como se aprecia en la figura 5.7), por lo que la incidencia de dichos rayos se consideran normales a la superficie de la fibra óptica receptora. Considerando que los haces de luz que inciden en la fibra óptica receptora son perpendiculares a su superficie, se puede tomar en cuenta las pérdidas por la reflexión de fresnel en las fronteras equivalentes a una pérdida de 0.35 dB (≈ 4%) tal como se mencionó anteriormente.
65
Capitulo 5 Caracterización del sistema y análisis de pérdidas
Por tanto la pérdida total debida a la discontinuidad en el sistema es de 22.22 dB.
Figura 5.7 Análisis del ángulo incidente de un haz de luz. Las mediciones que se efectuaron en la discontinuidad se presentan en la tabla 5.3. Tabla 5.3 Medición de las pérdidas en decibeles en la discontinuidad del sistema.
Fibra óptica Emisor (µW) Receptor (µW) Pérdidas (dB) 0 116.3 1.87 17.94 1 110.2 2.116 17.16 2 120.2 2.016 17.75 3 110.7 1.065 20.17 4 103.9 1.125 19.65 5 122 1.92 18 6 151.1 1.298 20.65 7 161.1 1.206 21.26
En la tabla anterior se tiene en cuenta las pérdidas ocasionadas
de manera intrínseca por las fibras ópticas emisoras (1.5 mts) y receptoras (0.5 mts).
66
Capitulo 5 Caracterización del sistema y análisis de pérdidas
Se sabe que la fibra óptica de vidrio de 100/140 µm de núcleo tiene una pérdida de 4 dB/km por lo que en las fibras ópticas se tienen pérdidas de 0.006 dB(≈0.138% ) y 0.002 dB (≈0.046%) respectivamente. Si se calculan las pérdidas ocasionadas por estos tres mecanismos de pérdidas de potencia óptica, se tiene que las pérdidas totales para los casos críticos son: L(total) = L(discontinuidad) + L(desalineación lateral) + + L(desalineación angular) + L( fibras ópticas) (23) L(total)= 22.22 dB + 0.6 dB + 0.4 dB + 0.008 dB = 23.228 dB En la ecuación (23) se observa que la pérdida de potencia total está concentrada en la discontinuidad del sistema. En la tabla 5.3 se puede apreciar que las perdidas en el sistema se encuentran aproximadamente en 19 dB mientras que el valor calculado fue de 23.228 dB. Esta diferencia se debe principalmente a la consideración de que la potencia óptica está uniformemente distribuida en el espacio, siendo que en realidad el patrón de radiación lumínico se encuentra más concentrado en alrededor del eje axial de la fibra óptica (núcleo de la fibra óptica), esto permite que exista un mejor acoplamiento óptico entre fibra óptica emisora y receptora, de tal forma que las pérdidas sean menores a las estimadas.
67
Capitulo 5 Caracterización del sistema y análisis de pérdidas
Para determinar la sensibilidad del receptor óptico se implementó una fuente óptica de potencia variable, como se muestra en la figura 5.8.
Figura 5.8 Fuente óptica de potencia lumínica variable.
Con el circuito anterior se determinó que la mínima potencia
óptica de salida (entregada por una fibra óptica receptora del sistema) para que el buffer schmitt entregue un “1” lógico al microcontrolador, debería de ser aproximadamente de 200 nW. Si la pérdida de potencia en las fibras ópticas receptoras es de 0.046% por cada 50 cm de fibra óptica, entonces para que la potencia más baja del sistema receptor (1.065µW) disminuya a la potencia mínima requerida para reconocer el haz de luz (200nW), es necesario que se incremente la longitud de la fibra óptica receptora en 883 mts.
Por lo anterior se desprende que el sistema óptico receptor se
puede posicionar a 883 mts del lugar de medición. De manera similar se puede posicionar el emisor óptico a una
distancia de 880 mts del sensor, considerando que la potencia mínima de emisión para que se acople a la salida de las fibras ópticas receptoras 200nW es de 20µW y tomando en cuenta que la potencia de inyección mas baja del sistema es de 103.9µW.
68
Capitulo 5 Caracterización del sistema y análisis de pérdidas
5.4.4 TERMINALES MAL PULIDAS Si los cabos de las fibras ópticas no se encuentran bien pulidas,
es decir, si las terminales de las mismas no son lisas y paralelas, se pueden tener pérdidas bastantes significativas (hasta del 80% de la señal de entrada).
Estas pérdidas pueden reducirse considerablemente, si en el
espacio entre las fibras ópticas se llena de fluido igualador de índice de refracción (matching gel). Esta técnica es utilizada habitualmente para el acoplamiento máximo entre la unión fibra óptica-receptor, logrando acoplar mayor potencia óptica al sistema receptor.
En el caso del espacio existente entre fibras ópticas emisoras y
receptoras del sistema no es posible utilizar el fluido igualador, por lo que las caras de las fibras ópticas deben de estar lo más pulidas posibles y tratar de que permanezcan lo mas alineadas posible una de la otra.
5.5 TOLERANCIA EN LA LECTURA DEL NIVEL
Dado que el sensor de nivel de líquidos trabaja con niveles discretos, es necesario estimar el error intrínseco del mismo entre el cambio de la lectura de un determinado nivel y el siguiente.
La precisión en la medición del nivel se ve afectada por el sistema optomecánico, ya que la distancia existente entre el centro de una línea de código en la placa perforada y el código siguiente es de 50 milésimas de pulgada.
Se tiene un peralte entre códigos de 0.127mm (5 milésimas de pulgada) tal como se muestra en el bosquejo de la figura 5.9.
69
Capitulo 5 Caracterización del sistema y análisis de pérdidas
Figura 5.9 Bosquejo del código binario en la placa perforada. Debido a las dimensiones del tanque y de la placa perforada con
el código binario, se tiene que para cada código se detecta un cambio de 0.188 lts.
Si el código no se encuentra alineado con las fibras ópticas
emisoras y receptoras, se presentan pérdidas por desalineamiento lateral (aunque en este caso sea por oclusión), de tal forma que al desalinearse en 60 µm las pérdidas serán de 4.5 dB y se estará cercano al valor de potencia óptica radiada límite.
Si se considera que al estar desalineado 60 µm se obtiene una
lectura estable límite, entonces se deduce que entre códigos se tiene una tolerancia de ±0.094 lts.
5.6 CALIBRACIÓN DEL SISTEMA DE MEDICIÓN La calibración del sensor de nivel de líquidos se hizo a partir del desplazamiento del código en la tarjeta perforada.
Para su calibración se tomó una lectura estable (centro del código) del nivel del líquido en el contenedor, posteriormente se virtió líquido (previamente cuantificado) dentro del contenedor hasta lograr el cambio de la lectura del nivel siguiente. Debido a que la tarjeta es isométrica en toda la extensión del código, se puede determinar el nivel de líquido máximo y mínimo dentro del tanque. Obteniendo el paso de líquido por código se puede determinar los límites de medición del sensor.
70
Recomendaciones
RECOMENDACIONES Y SUGERENCIAS.
Se puede miniaturizar la tarjeta perforada con el código binario para hacer mediciones más finas en el sistema.
Debido a la potencialidad del microcontrolador COP8 se puede crear el programa adecuado en lenguaje ensamblador para el control de actuadores a partir de las señales obtenidas de las fibras ópticas; logrando de esta manera, el monitoreo de otros parámetros del proceso a muy bajo costo.
Pueden implementarse sistemas mecánicos en el sensor para reducir al mínimo el desplazamiento de la tarjeta perforada con respecto al desplazamiento del líquido en el contenedor. El instrumento puede operar con otros tipos de fibras ópticas, siempre y cuando se ajusten los niveles de potencia óptica en el transmisor y la ganancia en el receptor para proporcionar una señal bien definida. El sistema de calibración puede realizarse en forma automática a partir del desarrollo de un programa en el microcontrolador que determine el paso de líquido por código. Para realizar esto, es necesario obtener las dimensiones del tanque (introducidas por teclado) y de la placa perforada con código binario. Para mejorar la exactitud de las mediciones, se puede implementar por programación factores de corrección en la lectura del nivel del líquido dependiendo del tipo de fluido, temperatura y presión dentro del tanque, variaciones de densidad y viscosidad del fluido, etc. Puede implementarse un sistema mecánico que permita que el llenado o vaciado del contenedor no se encuentre en el régimen turbulento. En su defecto programar con un factor de corrección para este tipo de sistemas.
El sensor puede introducirse en un tubo ranurado para evitar el oleaje excesivo dentro del contenedor.
72
Conclusiones
CONCLUSIONES
El enorme potencial de este dispositivo en aplicaciones de
sistemas industriales donde se manejan sustancias peligrosas lo hacen atractivo para una amplia gama de procesos .
Las fuentes ópticas construidas para el sensor de nivel son
económicas y de fácil construcción, ya que no se requiere mucha estabilidad, ni sistemas de compensación sofisticados debido al principio de operación digital del mismo.
La aplicación puede extenderse no solo a fluidos transparentes,
sino que la medición se realiza con casi cualquier fluido que se encuentre en el contenedor, sin importar su viscosidad, grado de explosividad, densidad, corrosión, etc.
Las bondades de las fibras ópticas hacen que este sensor sea
robusto bajo condiciones inoperantes para los métodos convencionales (electromecánicos generalmente), haciéndolo intrínsecamente seguro en ambientes con alta contaminación electromagnética.
Se puede tener control del nivel del líquido en forma remota, con un alto grado de fiabilidad.
La caracterización del sistema se realizó exclusivamente para el sistema mecánico e hidráulico situado en el laboratorio, sin necesidad de aplicar factores de corrección (por cambios en temperatura, presión, viscosidad, densidad, régimen turbulento, etc.) al sistema debido a las consideraciones ambientales y geométricas del mismo.
71
Bibliografía
BIBLIOGRAFIA
73
Bibliografía
[1] Chomycz, Bob, Instalaciones de Fibra Óptica, Fundamentos técnicas y aplicaciones Mc. Graw Hill (1998) [2] Chen, Chin-Lin, Elements of Optoelectronics and Fiber Optics Times Mirror, First edition (1996) [3] Jardón Aguilar, Hildeberto Linares y Miranda, Roberto, Sistemas de Comunicaciones por Fibras Ópticas Alfaomega (1995) [4] D.A., Krohn, Fiber Optics Sensor, Fundamentals and aplications Instruments society of america (1988) [5] Dakin, John Culshaw, Brian, Optical Fiber Sensor Vol. I y II, Principles and components Artech House (1988) [6] Mahlke, Günther Gössing Peter, Conductores de Fibra Óptica, Conceptos básicos Siemens (1987) [7] Instructor´s guide, Course Opcom-1, Principles of fiber optics communication systems Degem systems, First edition (1985) [8] C. Palais, Joseph, Fiber optic communications Prentice Hall, Inc. (1984) [9] Flow and Level Handbook Omega, Vol 29 [10] Basic Family COP8. National Semiconductor [11] OPTEK technology, inc. Optic product, catalog 1989
74
Bibliografía
[12] AND LED and LCD products Display products catalog 1991 [13] Data Conversion / Acquisition National Semiconductor [14] Photodiodes Hamamatsu catalog [15] Hecht, Eugene, Óptica Addison Wesley, Tercera Edición (1999)
75
Anexo
ANEXO A
DIAGRAMAS DEL SISTEMA
76
Anexo B
ANEXO B
ESPECIFICACIONES ELÉCTRICAS DE DISPOSITIVOS ELECTRÓNICOS
79
COP8SGx7 Family8-Bit CMOS OTP Microcontrollers with 8k or 32kMemory, Two Comparators and USARTGeneral DescriptionNote: COP8SGx7 devices are form-fit-function compat-ible supersets of the COP888xG/CS and COP87L88xGFamily devices, and are replacements for these in newdesigns, and design upgrades with minimum effort.
The COP8SGx7 Family of OTP (One Time Programmable)microcontrollers are highly integrated COP8™ Feature coredevices with 8k or 32k memory and advanced features in-cluding Analog comparators, and zero external components.These single-chip CMOS devices are suited for more com-plex applications requiring a full featured controller withlarger memory, low EMI, two comparators, and a full-duplexUSART. 100% form-fit-function compatible 8k to 32k ROM
versions are available (COP8SGx5 Family). Erasable win-dowed versions are available for use with a range of COP8software and hardware development tools.
Family features include an 8-bit memory mapped architec-ture, 10 MHz CKI with 1µs instruction cycle, three multi-function 16-bit timer/counters with PWM, full duplex USART,MICROWIRE/PLUS™, two analog comparators, two powersaving HALT/IDLE modes, MIWU, idle timer, on-chip R/C os-cillator, high current outputs, user selectable options(WATCHDOG™, 4 clock/oscillator modes, power-on-reset),2.7V to 5.5V operation, program code security, and 28/40/44pin packages.
Devices included in this datasheet are:
Device Memory (bytes) RAM (bytes) I/O Pins Packages Temperature
COP8SGE7 8k OTP EPROM 256 24/36/40 28 DIP/SOIC, 40 DIP, 44PLCC/QFP
-40 to +85˚C
COP8SGR7 32k OTP EPROM 512 24/36/40 28 DIP/SOIC, 40 DIP, 44PLCC/QFP
-40 to +85˚C
COP8SGR7-Q3 32k EPROM 512 24/36/40 28 DIP, 40 DIP, 44 PLCC Room Temp.
Key Featuresn Low cost 8-bit OTP microcontrollern Quiet Design (low radiated emissions)n Multi-Input Wakeup pins with optional interrupts (8 pins)n 8 bytes of user storage space in EPROMn User selectable clock options
— Crystal oscillator— Crystal oscillator with on-chip bias resistor— External oscillator— Internal R/C oscillator
n Internal Power-On-Reset — user selectablen WATCHDOG and Clock Monitor Logic — user selectablen Eight high current outputsn 256 or 512 bytes on-board RAMn 8 or 32 kbytes on-board OTP EPROM with security
feature for COP8SGE7n 4 to 32 kbytes ROM based versions available
CPU Featuresn Versatile easy to use instruction setn 1 µs instruction cycle time
n Fourteen multi-source vectored interrupts servicing— External interrupt / Timers T0 — T3— MICROWIRE/PLUS Serial Interface— Multi-Input Wake Up— Software Trap— USART (2; 1 receive and 1 transmit)— Default VIS (default interrupt)
n 8-bit Stack Pointer SP (stack in RAM)n Two 8-bit Register Indirect Data Memory Pointersn True bit manipulationn Memory mapped I/On BCD arithmetic instructions
Peripheral Featuresn Multi-Input Wakeup Logicn Three 16-bit timers (T1 — T3), each with two 16-bit
registers supporting:— Processor Independent PWM mode— External Event Counter mode— Input Capture mode
n Idle Timer (T0)n MICROWIRE/PLUSSerial Interface (SPI Compatible)n Full Duplex USARTn Two Analog Comparators
TRI-STATE® is a registered trademark of National Semiconductor Corporation.MICROWIRE/PLUS™, COP8™, MICROWIRE™ and WATCHDOG™ are trademarks of National Semiconductor Corporation.iceMASTER™ is a trademark of MetaLink Corporation.
July 1999
CO
P8S
Gx7
Family,8-B
itCM
OS
OTP
Microcontrollers
with
8kor
32kM
emory,Tw
oC
omparators
andU
SA
RT
© 1999 National Semiconductor Corporation DS100155 www.national.com
I/O Featuresn Software selectable I/O options (TRI-STATE®
Output,Push-Pull Output, Weak Pull-Up Input, and HighImpedance Input)
n Schmitt trigger inputs on ports G and Ln Eight high current outputsn Packages: 28 SO with 24 I/O pins, 40 DIP with 36 I/O
pins, 44 PLCC and PQFP with 40 I/O pins
Fully Static CMOS Designn Two power saving modes: HALT and IDLE
Temperature Rangen −40˚C to +85˚C
Development Supportn Windowed packages for DIP and PLCCn Real time emulation and full program debug offered by
MetaLink Development System
Block Diagram
DS100155-44
FIGURE 1. COP8SGx7 Block Diagram
www.national.com 2
1.0 Device Description
1.1 ARCHITECTURE
The COP8 family is based on a modified Harvard architec-ture, which allows data tables to be accessed directly fromprogram memory. This is very important with modernmicrocontroller-based applications, since program memoryis usually ROM or EPROM, while data memory is usuallyRAM. Consequently data tables need to be contained innon-volatile memory, so they are not lost when the microcon-troller is powered down. In a modified Harvard architecture,instruction fetch and memory data transfers can be over-lapped with a two stage pipeline, which allows the next in-struction to be fetched from program memory while the cur-rent instruction is being executed using data memory. This isnot possible with a Von Neumann single-address bus archi-tecture.
The COP8 family supports a software stack scheme that al-lows the user to incorporate many subroutine calls. This ca-pability is important when using High Level Languages. Witha hardware stack, the user is limited to a small fixed numberof stack levels.
1.2 INSTRUCTION SET
In today’s 8-bit microcontroller application arena cost/performance, flexibility and time to market are several of thekey issues that system designers face in attempting to buildwell-engineered products that compete in the marketplace.Many of these issues can be addressed through the mannerin which a microcontroller’s instruction set handles process-ing tasks. And that’s why COP8 family offers a unique andcode-efficient instruction set — one that provides the flexibil-ity, functionality, reduced costs and faster time to market thattoday’s microcontroller based products require.
Code efficiency is important because it enables designers topack more on-chip functionality into less program memoryspace (ROM/OTP). Selecting a microcontroller with less pro-gram memory size translates into lower system costs, andthe added security of knowing that more code can be packedinto the available program memory space.
1.2.1 Key Instruction Set Features
The COP8 family incorporates a unique combination of in-struction set features, which provide designers with optimumcode efficiency and program memory utilization.
Single Byte/Single Cycle Code Execution
The efficiency is due to the fact that the majority of instruc-tions are of the single byte variety, resulting in minimum pro-gram space. Because compact code does not occupy a sub-stantial amount of program memory space, designers canintegrate additional features and functionality into the micro-controller program memory space. Also, the majority instruc-tions executed by the device are single cycle, resulting inminimum program execution time. In fact, 77% of the instruc-tions are single byte single cycle, providing greater code andI/O efficiency, and faster code execution.
1.2.2 Many Single-Byte, Multifunction Instructions
The COP8 instruction set utilizes many single-byte, multi-function instructions. This enables a single instruction to ac-complish multiple functions, such as DRSZ, DCOR, JID, LD(Load) and X (Exchange) instructions with post-incrementingand post-decrementing, to name just a few examples. In
many cases, the instruction set can simultaneously executeas many as three functions with the same single-byte in-struction.
JID: (Jump Indirect); Single byte instruction; decodes exter-nal events and jumps to corresponding service routines(analogous to “DO CASE” statements in higher level lan-guages).
LAID: (Load Accumulator-Indirect); Single byte look up tableinstruction provides efficient data path from the programmemory to the CPU. This instruction can be used for tablelookup and to read the entire program memory for checksumcalculations.
RETSK: (Return Skip); Single byte instruction allows returnfrom subroutine and skips next instruction. Decision tobranch can be made in the subroutine itself, saving code.
AUTOINC/DEC: (Auto-Increment/Auto-Decrement); Theseinstructions use the two memory pointers B and X to effi-ciently process a block of data (analogous to “FOR NEXT” inhigher level languages).
1.2.3 Bit-Level Control
Bit-level control over many of the microcontroller’s I/O portsprovides a flexible means to ease layout concerns and saveboard space. All members of the COP8 family provide theability to set, reset and test any individual bit in the datamemory address space, including memory-mapped I/O portsand associated registers.
1.2.4 Register Set
Three memory-mapped pointers handle register indirect ad-dressing and software stack pointer functions. The memorydata pointers allow the option of post-incrementing or post-decrementing with the data movement instructions (LOAD/EXCHANGE). And 15 memory-maped registers allow de-signers to optimize the precise implementation of certainspecific instructions.
1.3 EMI REDUCTION
The COP8SGx7 family of devices incorporates circuitry thatguards against electromagnetic interference — an increasingproblem in today’s microcontroller board designs. National’spatented EMI reduction technology offers low EMI clock cir-cuitry, gradual turn-on output drivers (GTOs) and internal ICC
smoothing filters, to help circumvent many of the EMI issuesinfluencing embedded control designs. National hasachieved 15 dB–20 dB reduction in EMI transmissions whendesigns have incorporated its patented EMI reducing cir-cuitry.
1.4 PACKAGING/PIN EFFICIENCY
Real estate and board configuration considerations demandmaximum space and pin efficiency, particularly given today’shigh integration and small product form factors. Microcontrol-ler users try to avoid using large packages to get the I/Oneeded. Large packages take valuable board space and in-creases device cost, two trade-offs that microcontroller de-signs can ill afford.
The COP8 family offers a wide range of packages and do notwaste pins: up to 90.9% (or 40 pins in the 44-pin package)are devoted to useful I/O.
www.national.com3
Connection Diagrams
DS100155-4
Note 1: Note: x = E for 8k, and R for 32k
Top ViewOrder Number COP8SGx728M8See NS Package Number M28BOrder Number COP8SGx728N8See NS Package Number N28BOrder Number COP8SGR728Q3See NS Package Number D28JQ DS100155-5
Top ViewOrder Number COP8SGx740N8See NS Package Number N40AOrder Number COP8SGR740Q3
See NS Package Number D40KQ
DS100155-6
Top ViewOrder Number COP8SGx744V8See NS Package Number V44AOrder Number COP8SGR744J3
See NS Package Number EL44C
DS100155-43
Top ViewOrder Number COP8SGx7VEJ8
See NS Package Number VEJ44A
FIGURE 2. Connection Diagrams
www.national.com 4
Connection Diagrams (Continued)
Pinouts for 28 -, 40- and 44-Pin Packages
Port Type Alt. Fun 28-Pin SO 40-Pin DIP 44-Pin PLCC 44-Pin PQFP
L0 I/O MIWU 11 17 17 11
L1 I/O MIWU or CKX 12 18 18 12
L2 I/O MIWU or TDX 13 19 19 13
L3 I/O MIWU or RDX 14 20 20 14
L4 I/O MIWU or T2A 15 21 25 19
L5 I/O MIWU or T2B 16 22 26 20
L6 I/O MIWU or T3A 17 23 27 21
L7 I/O MIWU or T3B 18 24 28 22
G0 I/O INT 25 35 39 33
G1 I/O WDOUT* 26 36 40 34
G2 I/O T1B 27 37 41 35
G3 I/O T1A 28 38 42 36
G4 I/O SO 1 3 3 41
G5 I/O SK 2 4 4 42
G6 I SI 3 5 5 43
G7 I CKO 4 6 6 44
D0 O 19 25 29 23
D1 O 20 26 30 24
D2 O 21 27 31 25
D3 O 22 28 32 26
D4 O 29 33 27
D5 O 30 34 28
D6 O 31 35 29
D7 O 32 36 30
F0 I/O 7 9 9 3
F1 I/O COMP1IN− 8 10 10 4
F2 I/O COMP1IN+ 9 11 11 5
F3 I/O COMP1OUT 10 12 12 6
F4 I/O COMP2IN− 13 13 7
F5 I/O COMP2IN+ 14 14 8
F6 I/O COMP2OUT 15 15 9
F7 I/O 16 16 10
C0 I/O 39 43 37
C1 I/O 40 44 38
C2 I/O 1 1 39
C3 I/O 2 2 40
C4 I/O 21 15
C5 I/O 22 16
C6 I/O 23 17
C7 I/O 24 18
VCC 6 8 8 2
GND 23 33 37 31
CKI I 5 7 7 1
RESET I 24 34 38 32
* G1 operation as WDOUT is controlled by ECON bit 2.
www.national.com5
2.1 Ordering Information
DS100155-8
FIGURE 3. Part Numbering Scheme
www.national.com 6
3.0 Electrical Characteristics
Absolute Maximum Ratings (Note 2)
If Military/Aerospace specified devices are required,please contact the National Semiconductor Sales Office/Distributors for availability and specifications.
Supply Voltage (VCC) 7VVoltage at Any Pin −0.3V to VCC +0.3VTotal Current into VCCPin (Source) 100 mA
Total Current out of GNDPin (Sink) 110 mAStorage TemperatureRange −65˚C to +140˚CESD Protection Level 2kV (Human Body Model)Note 2: Absolute maximum ratings indicate limits beyond which damage tothe device may occur. DC and AC electrical specifications are not ensuredwhen operating the device at absolute maximum ratings.
DC Electrical Characteristics−40˚C ≤ TA ≤ +85˚C unless otherwise specified.
Parameter Conditions Min Typ Max Units
Operating Voltage 2.7 5.5 V
Power Supply Rise Time 10 50 x 106 ns
VCC Start Voltage to Guarantee POR 0 0.25 V
Power Supply Ripple (Note 4) Peak-to-Peak 0.1 Vcc V
Supply Current (Note 5)
CKI = 10 MHz VCC = 5.5V, tC = 1 µs 6.0 mA
CKI = 4 MHz VCC = 4.5V, tC = 2.5 µs 2.1 mA
HALT Current (Note 6) VCC = 5.5V, CKI = 0 MHz <4 10 µA
IDLE Current (Note 5)
CKI = 10 MHz VCC = 5.5V, tC = 1 µs 1.5 mA
CKI = 4 MHz VCC = 4.5V, tC = 2.5 µs 0.8 mA
Input Levels (VIH, VIL)
RESET
Logic High 0.8 Vcc V
Logic Low 0.2 Vcc V
CKI, All Other Inputs
Logic High 0.7 Vcc V
Logic Low 0.2 Vcc V
Internal Bias Resistor for theCrystal/Resonator Oscillator
0.5 1 2 MΩ
CKI Resistance to VCC or GND when R/COscillator is selected
VCC = 5.5V 5 8 11 kΩ
Hi-Z Input Leakage VCC = 5.5V −2 +2 µA
Input Pullup Current VCC = 5.5V, VIN = 0V −40 −250 µA
G and L Port Input Hysteresis VCC = 5.5V 0.25 Vcc V
Output Current LevelsD Outputs
Source VCC = 4.5V, VOH = 3.3V −0.4 mA
VCC = 2.7V, VOH = 1.8V −0.2 mA
Sink VCC = 4.5V, VOL = 1.0V 10 mA
VCC = 2.7V, VOL = 0.4V 2 mA
All Others
Source (Weak Pull-Up Mode) VCC = 4.5V, VOH = 2.7V −10.0 −110 µA
VCC = 2.7V, VOH = 1.8V −2.5 −33 µA
Source (Push-Pull Mode) VCC = 4.5V, VOH = 3.3V −0.4 mA
VCC = 2.7V, VOH = 1.8V −0.2 mA
Sink (Push-Pull Mode) VCC = 4.5V, VOL = 0.4V 1.6 mA
VCC = 2.7V, VOL = 0.4V 0.7 mA
TRI-STATE Leakage VCC = 5.5V −2 +2 µA
www.national.com7
DC Electrical Characteristics (Continued)
−40˚C ≤ TA ≤ +85˚C unless otherwise specified.
Parameter Conditions Min Typ Max Units
Allowable Sink Current per Pin (Note 9)
D Outputs and L0 to L3 15 mA
All Others 3 mA
Maximum Input Current without Latchup(Note 7)
Room Temp. ±200 mA
RAM Retention Voltage, Vr 2.0 V
VCC Rise Time from a VCC ≥ 2.0V (Note 10) 12 µs
Input Capacitance (Note 9) 7 pF
Load Capacitance on D2 (Note 9) 1000 pF
AC Electrical Characteristics−40˚C ≤ TA ≤ +85˚C unless otherwise specified.
Parameter Conditions Min Typ Max Units
Instruction Cycle Time (tC)
Crystal/Resonator, External 4.5V ≤ VCC ≤ 5.5V 1 µs
2.7V ≤ VCC < 4.5V 2 µs
R/C Oscillator (Internal) 4.5V ≤ VCC ≤ 5.5V 2 µs
Frequency Variation (Note 9) 4.5V ≤ VCC ≤ 5.5V ±35 %
External CKI Clock Duty Cycle (Note 9) fr = Max 45 55 %
Rise Time (Note 9) fr = 10 MHz Ext Clock 12 ns
Fall Time (Note 9) fr = 10 MHz Ext Clock 8 ns
Output Propagation Delay (Note 8) RL = 2.2k, CL = 100 pF
tPD1, tPD0
SO, SK 4.5V ≤ VCC ≤ 5.5V 0.7 µs
2.7V ≤ VCC < 4.5V 1.75 µs
All Others 4.5V ≤ VCC ≤ 5.5V 1.0 µs
2.7V ≤ VCC < 4.5V 2.5 µs
MICROWIRE Setup Time (tUWS) (Note11)
20 ns
MICROWIRE Hold Time (tUWH) (Note11)
56 ns
MICROWIRE Output PropagationDelay (tUPD) (Note 11)
220 ns
Input Pulse Width (Note 9)
Interrupt Input High Time 1 tCInterrupt Input Low Time 1 tCTimer 1, 2, 3, Input High Time 1 tCTimer 1 2, 3, Input Low Time 1 tC
Reset Pulse Width 1 µs
Note 3: tC = Instruction cycle time.
Note 4: Maximum rate of voltage change must be < 0.5 V/ms.
Note 5: Supply and IDLE currents are measured with CKI driven with a square wave Oscillator, External Oscillator, inputs connected to VCC and outputs driven lowbut not connected to a load.
Note 6: The HALT mode will stop CKI from oscillating in the R/C and the Crystal configurations. In the R/C configuration, CKI is forced high internally. In the crystalor external configuration, CKI is TRI-STATE. Measurement of IDD HALT is done with device neither sourcing nor sinking current; with L. F, C, G0, and G2–G5 pro-grammed as low outputs and not driving a load; all outputs programmed low and not driving a load; all inputs tied to VCC; clock monitor disabled. Parameter refersto HALT mode entered via setting bit 7 of the G Port data register.
Note 7: Pins G6 and RESET are designed with a high voltage input network. These pins allow input voltages > VCC and the pins will have sink current to VCC whenbiased at voltages > VCC (the pins do not have source current when biased at a voltage below VCC). The effective resistance to VCC is 750Ω (typical). These twopins will not latch up. The voltage at the pins must be limited to < 14V. WARNING: Voltages in excess of 14V will cause damage to the pins. This warning excludesESD transients.
Note 8: The output propagation delay is referenced to the end of the instruction cycle where the output change occurs.
www.national.com 8
AC Electrical Characteristics (Continued)
Note 9: Parameter characterized but not tested.
Note 10: Rise times faster than the minimum specification may trigger an internal power-on-reset.
Note 11: MICROWIRE Setup and Hold Times and Propagation Delays are referenced to the appropriate edge of the MICROWIRE clock. See and the MICROWIREoperation description.
Comparators AC and DC CharacteristicsVCC = 5V, −40˚C ≤ TA ≤ +85˚C.
Parameter Conditions Min Typ Max Units
Input Offset Voltage (Note 12) 0.4V ≤ VIN ≤ VCC − 1.5V ±5 ±15 mV
Input Common Mode Voltage Range 0.4 VCC − 1.5 V
Voltage Gain 100 dB
Low Level Output Current VOL = 0.4V −1.6 mA
High Level Output Current VOH = VCC − 0.4V 1.6 mA
DC Supply Current per Comparator(When Enabled)
150 µA
Response Time (Note 13) 200 mV step input100 mV Overdrive,
200 ns
100 pF Load
Note 12: The comparator inputs are high impedance port inputs and, as such, input current is limited to port input leakage current.
Note 13: Response time is measured from a step input to a valid logic level at the comparator output. software response time is dependent of instruction execution.
DS100155-9
FIGURE 4. MICROWIRE/PLUS Timing
www.national.com9
Typical Performance Characteristics TA = 25˚C (unless otherwise specified)
DS100155-49 DS100155-50
DS100155-51 DS100155-52
www.national.com 10
4.0 Pin DescriptionsThe COP8SGE7/COP8SGR7 I/O structure enables design-ers to reconfigure the microcontroller’s I/O functions with asingle instruction. Each individual I/O pin can be indepen-dently configured as output pin low, output high, input withhigh impedance or input with weak pull-up device. A typicalexample is the use of I/O pins as the keyboard matrix inputlines. The input lines can be programmed with internal weakpull-ups so that the input lines read logic high when the keysare all open. With a key closure, the corresponding input linewill read a logic zero since the weak pull-up can easily beoverdriven. When the key is released, the internal weakpull-up will pull the input line back to logic high. This elimi-nates the need for external pull-up resistors. The high cur-rent options are available for driving LEDs, motors andspeakers. This flexibility helps to ensure a cleaner design,with less external components and lower costs. Below is thegeneral description of all available pins.
VCC and GND are the power supply pins. All VCC and GNDpins must be connected.
CKI is the clock input. This can come from the Internal R/Coscillator, external, or a crystal oscillator (in conjunction withCKO). See Oscillator Description section.
RESET is the master reset input. See Reset description sec-tion.
Each device contains four bidirectional 8-bit I/O ports (C, G,L and F), where each individual bit may be independentlyconfigured as an input (Schmitt trigger inputs on ports L andG), output or TRI-STATE under program control. Three datamemory address locations are allocated for each of theseI/O ports. Each I/O port has two associated 8-bit memorymapped registers, the CONFIGURATION register and theoutput DATA register. A memory mapped address is also re-served for the input pins of each I/O port. (See the memorymap for the various addresses associated with the I/O ports.)Figure 5 shows the I/O port configurations. The DATA andCONFIGURATION registers allow for each port bit to be in-dividually configured under software control as shown below:
CONFIGURATION
Register
DATA
RegisterPort Set-Up
0 0 Hi-Z Input
(TRI-STATE Output)
0 1 Input with Weak Pull-Up
1 0 Push-Pull Zero Output
1 1 Push-Pull One Output
Port L is an 8-bit I/O port. All L-pins have Schmitt triggers onthe inputs.
Port L supports the Multi-Input Wake Up feature on all eightpins. Port L has the following alternate pin functions:
L7 Multi-input Wakeup or T3B (Timer T3B Input)
L6 Multi-input Wakeup or T3A (Timer T3A Input)
L5 Multi-input Wakeup or T2B (Timer T2B Input)
L4 Multi-input Wakeup or T2A (Timer T2A Input)
L3 Multi-input Wakeup and/or RDX (USART Receive)
L2 Multi-input Wakeup or TDX (USART Transmit)
L1 Multi-input Wakeup and/or CKX (USART Clock)
L0 Multi-input Wakeup
Port G is an 8-bit port. Pin G0, G2–G5 are bi-directional I/Oports. Pin G6 is always a general purpose Hi-Z input. All pinshave Schmitt Triggers on their inputs. Pin G1 serves as thededicated WATCHDOG output with weak pullup if
WATCHDOG feature is selected by the ECON register.The pin is a general purpose I/O if WATCHDOG feature isnot selected. If WATCHDOG feature is selected, bit 1 of thePort G configuration and data register does not have any ef-fect on Pin G1 setup. Pin G7 is either input or output depend-ing on the oscillator option selected. With the crystal oscilla-tor option selected, G7 serves as the dedicated output pin forthe CKO clock output. With the internal R/C or the externaloscillator option selected, G7 serves as a general purposeHi-Z input pin and is also used to bring the device out ofHALT mode with a low to high transition on G7.
Since G6 is an input only pin and G7 is the dedicated CKOclock output pin (crystal clock option) or general purpose in-put (R/C or external clock option), the associated bits in thedata and configuration registers for G6 and G7 are used forspecial purpose functions as outlined below. Reading the G6and G7 data bits will return zeroes.
Each device will be placed in the HALT mode by writing a “1”to bit 7 of the Port G Data Register. Similarly the device willbe placed in the IDLE mode by writing a “1” to bit 6 of thePort G Data Register.
Writing a “1” to bit 6 of the Port G Configuration Register en-ables the MICROWIRE/PLUS to operate with the alternatephase of the SK clock. The G7 configuration bit, if set high,enables the clock start up delay after HALT when the R/Cclock configuration is used.
Config. Reg. Data Reg.
G7 CLKDLY HALT
G6 Alternate SK IDLE
Port G has the following alternate features:
G7 CKO Oscillator dedicated output or general purpose in-put
G6 SI (MICROWIRE Serial Data Input)
G5 SK (MICROWIRE Serial Clock)
G4 SO (MICROWIRE Serial Data Output)
G3 T1A (Timer T1 I/O)
G2 T1B (Timer T1 Capture Input)
G1 WDOUT WATCHDOG and/or CLock Monitor if WATCH-DOG enabled, otherwise it is a general purpose I/O
G0 INTR (External Interrupt Input)
Port C is an 8-bit I/O port. The 40-pin device does not havea full complement of Port C pins. The unavailable pins arenot terminated. A read operation on these unterminated pinswill return unpredictable values. The 28 pin device do not of-fer Port C. On this device, the associated Port C Data andConfiguration registers should not be used.
Port F is an 8-bit I/O port. The 28--pin device does not havea full complement of Port F pins. The unavailable pins arenot terminated. A read operation on these unterminated pinswill return unpredictable values.
Port F1–F3 are used for Comparator 1. Port F4–F6 are usedfor Comparator 2.
The Port F has the following alternate features:
F6 COMP2OUT (Comparator 2 Output)
F5 COMP2+IN (Comparator 2 Positive Input)
F4 COMP2-IN (Comparator 2 Negative Input)
F3 COMP1OUT (Comparator 1 Output)
F2 COMP1+IN (Comparator 1 Positive Input)
F1 COMP1-IN (Comparator 1 Negative Input)Note: For compatibility with existing software written for COP888xG devices
and with existing Mask ROM devices, a read of the Port I input pins
www.national.com11
4.0 Pin Descriptions (Continued)
(address xxD7) will return the same data as reading the Port F inputpins (address xx96). It is recommended new applications which will goto production with the COPSGx7 use the Port F addresses. Note thatcompatible ROM devices contains the input only Port I instead of thebi-directional Port F.
Port D is an 8-bit output port that is preset high when RESETgoes low. The user can tie two or more D port outputs (ex-cept D2) together in order to get a higher drive.Note: Care must be exercised with the D2 pin operation. At RESET, the ex-
ternal loads on this pin must ensure that the output voltages stayabove 0.7 VCC to prevent the chip from entering special modes. Alsokeep the external loading on D2 to less than 1000 pF.
5.0 Functional DescriptionThe architecture of the devices are a modified Harvard archi-tecture. With the Harvard architecture, the program memoryEPROM is separated from the data store memory (RAM).Both EPROM and RAM have their own separate addressingspace with separate address buses. The architecture,though based on the Harvard architecture, permits transferof data from EPROM to RAM.
5.1 CPU REGISTERS
The CPU can do an 8-bit addition, subtraction, logical or shiftoperation in one instruction (tC) cycle time.
There are six CPU registers:
A is the 8-bit Accumulator Register
PC is the 15-bit Program Counter Register
PU is the upper 7 bits of the program counter (PC)
PL is the lower 8 bits of the program counter (PC)
B is an 8-bit RAM address pointer, which can be optionallypost auto incremented or decremented.
X is an 8-bit alternate RAM address pointer, which can beoptionally post auto incremented or decremented.
S is the 8-bit Segment Address Register used to extend thelower half of the address range (00 to 7F) into 256 data seg-ments of 128 bytes each.
SP is the 8-bit stack pointer, which points to the subroutine/interrupt stack (in RAM). With reset the SP is initialized toRAM address 02F Hex (devices with 64 bytes of RAM), orinitialized to RAM address 06F Hex (devices with 128 bytesof RAM).
All the CPU registers are memory mapped with the excep-tion of the Accumulator (A) and the Program Counter (PC).
5.2 PROGRAM MEMORY
The program memory consists of 8192 or 32,768 bytes ofEPROM. These bytes may hold program instructions or con-stant data (data tables for the LAID instruction, jump vectorsfor the JID instruction, and interrupt vectors for the VIS in-struction). The program memory is addressed by the 15-bitprogram counter (PC). All interrupts in the device vector toprogram memory location 0FF Hex. The contents of the pro-gram memory read 00 Hex in the erased state. Program ex-ecution starts at location 0 after RESET.
5.3 DATA MEMORY
The data memory address space includes the on-chip RAMand data registers, the I/O registers (Configuration, Data andPin), the control registers, the MICROWIRE/PLUS SIO shiftregister, and the various registers, and counters associatedwith the timers (with the exception of the IDLE timer). Datamemory is addressed directly by the instruction or indirectlyby the B, X and SP pointers.
The data memory consists of 256 or 512 bytes of RAM. Six-teen bytes of RAM are mapped as “registers” at addresses0F0 to 0FE Hex. These registers can be loaded immediately,and also decremented and tested with the DRSZ (decrementregister and skip if zero) instruction. The memory pointerregisters X, SP and B are memory mapped into this space ataddress locations 0FC to 0FE Hex respectively, with theother registers (except 0FF) being available for general us-age.
The instruction set permits any bit in memory to be set, resetor tested. All I/O and registers (except A and PC) are
DS100155-10
FIGURE 5. I/O Port Configurations
DS100155-12
FIGURE 6. I/O Port Configurations — Output Mode
DS100155-11
FIGURE 7. I/O Port Configurations — Input Mode
www.national.com 12
5.0 Functional Description (Continued)
memory mapped; therefore, I/O bits and register bits can bedirectly and individually set, reset and tested. The accumula-tor (A) bits can also be directly and individually tested.Note: RAM contents are undefined upon power-up.
5.4 DATA MEMORY SEGMENT RAM EXTENSION
Data memory address 0FF is used as a memory mapped lo-cation for the Data Segment Address Register (S).
The data store memory is either addressed directly by asingle byte address within the instruction, or indirectly rela-tive to the reference of the B, X, or SP pointers (each con-tains a single-byte address). This single-byte address allowsan addressing range of 256 locations from 00 to FF hex. Theupper bit of this single-byte address divides the data storememory into two separate sections as outlined previously.With the exception of the RAM register memory from ad-dress locations 00F0 to 00FF, all RAM memory is memorymapped with the upper bit of the single-byte address beingequal to zero. This allows the upper bit of the single-byte ad-dress to determine whether or not the base address range(from 0000 to 00FF) is extended. If this upper bit equals one(representing address range 0080 to 00FF), then address
extension does not take place. Alternatively, if this upper bitequals zero, then the data segment extension register S isused to extend the base address range (from 0000 to 007F)from XX00 to XX7F, where XX represents the 8 bits from theS register. Thus the 128-byte data segment extensions arelocated from addresses 0100 to 017F for data segment 1,0200 to 027F for data segment 2, etc., up to FF00 to FF7Ffor data segment 255. The base address range from 0000 to007F represents data segment 0.
Figure 8 illustrates how the S register data memory exten-sion is used in extending the lower half of the base addressrange (00 to 7F hex) into 256 data segments of 128 byteseach, with a total addressing range of 32 kbytes from XX00to XX7F. This organization allows a total of 256 data seg-ments of 128 bytes each with an additional upper base seg-ment of 128 bytes. Furthermore, all addressing modes areavailable for all data segments. The S register must bechanged under program control to move from one data seg-ment (128 bytes) to another. However, the upper base seg-ment (containing the 16 memory registers, I/O registers,control registers, etc.) is always available regardless of thecontents of the S register, since the upper base segment(address range 0080 to 00FF) is independent of data seg-ment extension.
The instructions that utilize the stack pointer (SP) always ref-erence the stack as part of the base segment (Segment 0),regardless of the contents of the S register. The S register isnot changed by these instructions. Consequently, the stack(used with subroutine linkage and interrupts) is always lo-cated in the base segment. The stack pointer will be initial-ized to point at data memory location 006F as a result of re-set.
The 128 bytes of RAM contained in the base segment aresplit between the lower and upper base segments. The first112 bytes of RAM are resident from address 0000 to 006F inthe lower base segment, while the remaining 16 bytes of
RAM represent the 16 data memory registers located at ad-dresses 00F0 to 00FF of the upper base segment. No RAMis located at the upper sixteen addresses (0070 to 007F) ofthe lower base segment.
Additional RAM beyond these initial 128 bytes, however, willalways be memory mapped in groups of 128 bytes (or less)at the data segment address extensions (XX00 to XX7F) ofthe lower base segment. The additional 384 bytes of RAM inthis device are memory mapped at address locations 0100to 017F, 0200 to 027F and 0300 to 037F hex.
DS100155-45
FIGURE 8. RAM Organization
www.national.com13
5.0 Functional Description (Continued)
Memory address ranges 0200 to 027F and 0300 to 037F areunavailable on the COP8SGE7, and if read, will return un-derfined data.
5.5 ECON (EPROM CONFIGURATION) REGISTER
The ECON register is used to configure the user selectableclock, security, power-on reset, WATCHDOG, and HALT op-tions. The register can be programmed and read only inEPROM programming mode. Therefore, the register shouldbe programmed at the same time as the program memory.The contents of the ECON register shipped from the factoryread 00 Hex (windowed device) or 80 Hex (OTP device).
The format of the ECON register is as follows:
Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
X POR SECURITY CKI 2 CKI 1 WATCH F-Port HALT
DOG
Bit 7 = x This is for factory test. The polarity is “Don’tCare.”
Bit 6 = 1 Power-on reset enabled.
= 0 Power-on reset disabled.
Bit 5 = 1 Security enabled. EPROM read and writeare not allowed.
= 0 Security disabled. EPROM read and writeare allowed.
Bits 4, 3 = 0, 0 External CKI option selected. G7 is avail-able as a HALT restart and/or general pur-pose input. CKI is clock input.
= 0, 1 R/C oscillator option selected. G7 is avail-able as a HALT restart and/or general pur-pose input. CKI clock input. Internal R/Ccomponents are supplied for maximum R/Cfrequency.
= 1, 0 Crystal oscillator with on-chip crystal biasresistor disabled. G7 (CKO) is the clockgenerator output to crystal/resonator.
= 1, 1 Crystal oscillator with on-chip crystal biasresistor enabled. G7 (CKO) is the clockgenerator output to crystal/resonator.
Bit 2 = 1 WATCHDOG feature disabled. G1 is a gen-eral purpose I/O.
= 0 WATCHDOG feature enabled. G1 pin isWATCHDOG output with weak pullup.
Bit 1 = 1 Force port I compatibility. Disable port Foutputs and pull-ups. This is intended forcompatibility with existing code and MaskROMMed devices only. This bit should beprogrammed to 0 for all other applications.
= 0 Enable full port F capability.
Bit 0 = 1 HALT mode disabled.
= 0 HALT mode enabled.
5.6 USER STORAGE SPACE IN EPROM
In addition to the ECON register, there are 8 bytes ofEPROM available for “user information”. ECON and these 8bytes are outside of the code area and are not protected bythe security bit of the ECON register. Even when security isset, information in the 8-byte USER area is both read andwrite enabled allowing the user to read from and write intothe area at all times while still protecting the code from unau-thorized access.
Both ECON and USER area, 9 bytes total, are outside of thenormal address range of the EPROM and can not be ac-cessed by the executing software. This allows for the stor-age of non-secured information. Typical uses are for storageof serial numbers, data codes, version numbers, copyrightinformation, lot numbers, etc.
The COP8 assembler defines a special ROM section type,CONF, into which the ECON and USER data may be coded.Both ECON and User Data are programmed automaticallyby programmers that are certified by National.
The following examples illustrate the declaration of ECONand the User information.
Syntax:
[label:] .sect econ, conf.db value ;1 byte,
;configures options.db <user information>
.endsect ; up to 8 bytes
Example: The following sets a value in the ECON registerand User Identification for a COP8SGR728M7. The ECONbit values shown select options: Power-on enabled, Securitydisabled, Crystal oscillator with on-chip bias disabled,WATCHDOG enabled and HALT mode enabled.
.sect econ, conf
.db 0x55 ;por, xtal, wd, halt
.db 'my v1.00' ;user data declaration
.endsect
Note: All programmers certified for programming this family of parts will sup-port programming of the CONFiguration section. Please contact Na-tional or your device programmer supplier for more information.
5.7 OTP SECURITY
These devices have a security feature, when enabled, thatprevents external reading of the OTP program memory. Thesecurity bit in the ECON register determines, whether secu-rity is enabled or disabled. If the security feature is disabled,the contents of the internal EPROM may be read.
If the security feature is enabled, then any attempt to ex-ternally read the contents of the EPROM will result in thevalue FF Hex being read from all program locations. Inaddition, with the security feature enabled, the write opera-tion to the EPROM program memory and ECON register isinhibited. The ECON register is readable regardless of thestate of the security bit.
If security is being used, it is recommended that all other bitsin the ECON register be programmed first. Then the securitybit can be programmed.
5.8 RESET
The devices are initialized when the RESET pin is pulled lowor the On-chip Power-On Reset is enabled.
DS100155-13
FIGURE 9. Reset Logic
www.national.com 14
5.0 Functional Description (Continued)
The following occurs upon initialization:
Port L: TRI-STATE (High Impedance Input)
Port C: TRI-STATE (High Impedance Input)
Port G: TRI-STATE (High Impedance Input)
Port F: TRI-STATE (High Impedance Input)
Port D: HIGH
PC: CLEARED to 0000
PSW, CNTRL and ICNTRL registers: CLEARED
SIOR:
UNAFFECTED after RESET with power already applied
RANDOM after RESET at power-on
T2CNTRL: CLEARED
T3CNTRL: CLEARED
Accumulator, Timer 1, Timer 2 and Timer 3:
RANDOM after RESET with crystal clock option
(power already applied)
UNAFFECTED after RESET with R/C clock option
(power already applied)
RANDOM after RESET at power-on
WKEN, WKEDG: CLEARED
WKPND: RANDOM
SP (Stack Pointer):
Initialized to RAM address 06F Hex
B and X Pointers:
UNAFFECTED after RESET with power already applied
RANDOM after RESET at power-on
S Register: CLEARED
RAM:
UNAFFECTED after RESET with power already applied
RANDOM after RESET at power-on
USART:
PSR, ENU, ENUR, ENUI: Cleared except the TBMT bit
which is set to one.
COMPARATORS:
CMPSL; CLEARED
WATCHDOG (if enabled):
The device comes out of reset with both the WATCH-DOG logic and the Clock Monitor detector armed, with theWATCHDOG service window bits set and the Clock Monitorbit set. The WATCHDOG and Clock Monitor circuits are in-hibited during reset. The WATCHDOG service window bitsbeing initialized high default to the maximum WATCHDOGservice window of 64k tC clock cycles. The Clock Monitor bitbeing initialized high will cause a Clock Monitor error follow-ing reset if the clock has not reached the minimum specifiedfrequency at the termination of reset. A Clock Monitor errorwill cause an active low error output on pin G1. This erroroutput will continue until 16 tC–32 tC clock cycles followingthe clock frequency reaching the minimum specified value,at which time the G1 output will go high.
5.8.1 External Reset
The RESET input when pulled low initializes the device. TheRESET pin must be held low for a minimum of one instruc-tion cycle to guarantee a valid reset. During Power-Up initial-ization, the user must ensure that the RESET pin is held lowuntil the device is within the specified VCC voltage. An R/Ccircuit on the RESET pin with a delay 5 times (5x) greaterthan the power supply rise time or 15 µs whichever isgreater, is recommended. Reset should also be wide enoughto ensure crystal start-up upon Power-Up.
RESET may also be used to cause an exit from the HALTmode.
A recommended reset circuit for this device is shown in Fig-ure 10.
5.8.2 On-Chip Power-On Reset
The on-chip reset circuit is selected by a bit in the ECON reg-ister. When enabled, the device generates an internal resetas VCC rises to a voltage level above 2.0V. The on-chip resetcircuitry is able to detect both fast and slow rise times on VCC
(VCC rise time between 10 ns and 50 ms).To guarantee anon-chip power-on-reset, VCCmust start at a voltage less thanthe start voltage specified in the DC characteristics. Also, ifVCC be lowered to the start voltage before powering back upto the operating range. If this is not possible, it is recom-mended that external reset be used.
Under no circumstances should the RESET pin be allowedto float. If the on-chip Power-On Reset feature is being used,RESET pin should be connected directly to VCC. The outputof the power-on reset detector will always preset the Idletimer to 0FFF(4096 tC). At this time, the internal reset will begenerated.
If the Power-On Reset feature is enabled, the internal resetwill not be turned off until the Idle timer underflows. The inter-nal reset will perform the same functions as external reset.The user is responsible for ensuring that VCC is at the mini-mum level for the operating frequency within the 4096 tC. Af-ter the underflow, the logic is designed such that no addi-tional internal resets occur as long as VCC remains above2.0V.
The contents of data registers and RAM are unknown follow-ing the on-chip reset.
DS100155-14
RC >5x power supply rise time or 15 µs, whichever is greater.
FIGURE 10. Reset Circuit Using External Reset
www.national.com15
5.0 Functional Description (Continued)
5.9 OSCILLATOR CIRCUITS
There are four clock oscillator options available: Crystal Os-cillator with or without on-chip bias resistor, R/C Oscillatorwith on-chip resistor and capacitor, and External Oscillator.The oscillator feature is selected by programming the ECONregister, which is summarized in Table 1.
TABLE 1. Oscillator Option
ECON4 ECON3 Oscillator Option
0 0 External Oscillator
1 0 Crystal Oscillator without Bias Resistor
0 1 R/C Oscillator
1 1 Crystal Oscillator with Bias Resistor
5.9.1 Crystal Oscillator
The crystal Oscillator mode can be selected by programmingECON Bit 4 to 1. CKI is the clock input while G7/CKO is theclock generator output to the crystal. An on-chip bias resistorconnected between CKI and CKO can be enabled by pro-gramming ECON Bit 3 to 1 with the crystal oscillator optionselection. The value of the resistor is in the range of 0.5M to2M (typically 1.0M). Table 2 shows the component values re-quired for various standard crystal values. Resistor R2 isonly used when the on-chip bias resistor is disabled. Figure13 shows the crystal oscillator connection diagram.
TABLE 2. Crystal Oscillator Configuration,TA = 25˚C, VCC = 5V
R1 (kΩ) R2 (MΩ) C1 (pF) C2 (pF)CKI Freq.
(MHz)
0 1 20 20 10
0 1 25 25 4
5.6 1 100 100–156 0.455
5.9.2 External Oscillator
The External Oscillator mode can be selected by program-ming ECON Bit 3 to 0 and ECON Bit 4 to 0. CKI can bedriven by an external clock signal provided it meets thespecified duty cycle, rise and fall times, and input levels. G7/CKO is available as a general purpose input G7 and/or Haltcontrol. Figure 14 shows the external oscillator connectiondiagram.
5.9.3 R/C Oscillator
The R/C Oscillator mode can be selected by programmingECON Bit 3 to 1 and ECON Bit 4 to 0. In R/C oscillationmode, CKI is left floating, while G7/CKO is available as ageneral purpose input G7 and/or HALT control. The R/C con-trolled oscillator has on-chip resistor and capacitor for maxi-mum R/C oscillator frequency operation. The maximum fre-quency is 5 MHz ± 35% for VCC between 4.5V to 5.5V andtemperature range of −40˚C to +85˚C. For max frequencyoperation, the CKI pin should be left floating. For lower fre-quencies, an external capacitor should be connected be-tween CKI and either VCC or GND. Immunity of the R/C os-cillator to external noise can be improved by connecting onehalf the external capacitance to VCC and one half to GND.PC board trace length on the CKI pin should be kept as shortas possible. Table 3 shows the oscillator frequency as afunction of external capacitance on the CKI pin. Figure 15shows the R/C oscillator configuration.
TABLE 3. R/C Oscillator Configuration,−40˚C to +85˚C, VCC = 4.5V to 5.5V,
OSC Freq. Variation of ± 35%
ExternalCapacitor (pF)*
R/C OSC Freq(MHz)
Instr. Cycle(µs)
0 5 2.0
9 4 2.5
52 2 5.0
125 1 10
6100 32 kHz 312.5
* Assumes 3-5 pF board capacitance.
DS100155-15
FIGURE 11. Reset Timing (Power-On Reset Enabled)with V CC Tied to RESET
DS100155-16
FIGURE 12. Reset Circuit Using Power-On Reset
www.national.com 16
5.0 Functional Description (Continued)
With On-Chip Bias Resistor
DS100155-17
Without On-Chip Bias Resistor
DS100155-18
FIGURE 13. Crystal Oscillator
DS100155-19
FIGURE 14. External Oscillator
DS100155-20
For operation at lower than maximum R/C oscillator frequency.
DS100155-21
For operation at maximum R/C oscillator frequency.
FIGURE 15. R/C Oscillator
www.national.com17
5.0 Functional Description (Continued)
5.10 CONTROL REGISTERS
CNTRL Register (Address X'00EE)
T1C3 T1C2 T1C1 T1C0 MSEL IEDG SL1 SL0
Bit 7 Bit 0
The Timer1 (T1) and MICROWIRE/PLUS control registercontains the following bits:
T1C3 Timer T1 mode control bit
T1C2 Timer T1 mode control bit
T1C1 Timer T1 mode control bit
T1C0 Timer T1 Start/Stop control in timer
modes 1 and 2, T1 Underflow InterruptPending Flag in timer mode 3
MSEL Selects G5 and G4 as MICROWIRE/PLUSsignals SK and SO respectively
IEDG External interrupt edge polarity select
(0 = Rising edge, 1 = Falling edge)
SL1 & SL0 Select the MICROWIRE/PLUS clock divideby (00 = 2, 01 = 4, 1x = 8)
PSW Register (Address X'00EF)
HC C T1PNDA T1ENA EXPND BUSY EXEN GIE
Bit 7 Bit 0
The PSW register contains the following select bits:
HC Half Carry Flag
C Carry Flag
T1PNDA Timer T1 Interrupt Pending Flag (AutoreloadRA in mode 1, T1 Underflow in Mode 2, T1Acapture edge in mode 3)
T1ENA Timer T1 Interrupt Enable for Timer Underflowor T1A Input capture edge
EXPND External interrupt pending
BUSY MICROWIRE/PLUS busy shifting flag
EXEN Enable external interrupt
GIE Global interrupt enable (enables interrupts)
The Half-Carry flag is also affected by all the instructions thataffect the Carry flag. The SC (Set Carry) and R/C (ResetCarry) instructions will respectively set or clear both the carryflags. In addition to the SC and R/C instructions, ADC,SUBC, RRC and RLC instructions affect the Carry and HalfCarry flags.
ICNTRL Register (Address X'00E8)
Reserved LPEN T0PND T0EN µWPND µWEN T1PNDB T1ENB
Bit 7 Bit 0
The ICNTRL register contains the following bits:
Reserved This bit is reserved and should to zero
LPEN L Port Interrupt Enable (Multi-Input Wakeup/Interrupt)
T0PND Timer T0 Interrupt pending
T0EN Timer T0 Interrupt Enable (Bit 12 toggle)
µWPND MICROWIRE/PLUS interrupt pending
µWEN Enable MICROWIRE/PLUS interrupt
T1PNDB Timer T1 Interrupt Pending Flag for T1B cap-ture edge
T1ENB Timer T1 Interrupt Enable for T1B Input cap-ture edge
T2CNTRL Register (Address X'00C6)
T2C3 T2C2 T2C1 T2C0 T2PNDA T2ENA T2PNDB T2ENB
Bit 7 Bit 0
The T2CNTRL control register contains the following bits:
T2C3 Timer T2 mode control bit
T2C2 Timer T2 mode control bit
T2C1 Timer T2 mode control bit
T2C0 Timer T2 Start/Stop control in timermodes 1 and 2, T2 Underflow Interrupt Pend-ing Flag in timer mode 3
T2PNDA Timer T2 Interrupt Pending Flag (AutoreloadRA in mode 1, T2 Underflow in mode 2, T2Acapture edge in mode 3)
T2ENA Timer T2 Interrupt Enable for Timer Underflowor T2A Input capture edge
T2PNDB Timer T2 Interrupt Pending Flag for T2B cap-ture edge
T2ENB Timer T2 Interrupt Enable for Timer Underflowor T2B Input capture edge
T3CNTRL Register (Address X'00B6)
T3C3 T3C2 T3C1 T3C0 T3PNDA T3ENA T3PNDB T3ENB
Bit 7 Bit 0
The T3CNTRL control register contains the following bits:
T3C3 Timer T3 mode control bit
T3C2 Timer T3 mode control bit
T3C1 Timer T3 mode control bit
T3C0 Timer T3 Start/Stop control in timermodes 1 and 2, T3 Underflow Interrupt Pend-ing Flag in timer mode 3
T3PNDA Timer T3 Interrupt Pending Flag (AutoreloadRA in mode 1, T3 Underflow in mode 2, T3Acapture edge in mode 3)
T3ENA Timer T3 Interrupt Enable for Timer Underflowor T3A Input capture edge
T3PNDB Timer T3 Interrupt Pending Flag for T3B cap-ture edge
T3ENB Timer T3 Interrupt Enable for Timer Underflowor T3B Input capture edge
6.0 TimersEach device contains a very versatile set of timers (T0, T1,T2 and T3). Timer T1, T2 and T3 and associated autoreload/capture registers power up containing random data.
6.1 TIMER T0 (IDLE TIMER)
Each device supports applications that require maintainingreal time and low power with the IDLE mode. This IDLEmode support is furnished by the IDLE timer T0. The TimerT0 runs continuously at the fixed rate of the instruction cycleclock, tC. The user cannot read or write to the IDLE Timer T0,which is a count down timer.
The Timer T0 supports the following functions:
• Exit out of the Idle Mode (See Idle Mode description)
• WATCHDOG logic (See WATCHDOG description)
• Start up delay out of the HALT mode
www.national.com 18
6.0 Timers (Continued)
• Timing the width of the internal power-on-reset
The IDLE Timer T0 can generate an interrupt when thetwelfth bit toggles. This toggle is latched into the T0PNDpending flag, and will occur every 4.096 ms at the maximumclock frequency (tC = 1 µs). A control flag T0EN allows the in-terrupt from the twelfth bit of Timer T0 to be enabled or dis-abled. Setting T0EN will enable the interrupt, while resettingit will disable the interrupt.
6.2 TIMER T1, TIMER T2 and TIMER T3
Each device have a set of three powerful timer/counterblocks, T1, T2 and T3. Since T1, T2, and T3 are identical, allcomments are equally applicable to any of the three timerblocks which will be referred to as Tx.
Each timer block consists of a 16-bit timer, Tx, and two sup-porting 16-bit autoreload/capture registers, RxA and RxB.Each timer block has two pins associated with it, TxA andTxB. The pin TxA supports I/O required by the timer block,while the pin TxB is an input to the timer block. The timerblock has three operating modes: Processor IndependentPWM mode, External Event Counter mode, and Input Cap-ture mode.
The control bits TxC3, TxC2, and TxC1 allow selection of thedifferent modes of operation.
6.2.1 Mode 1. Processor Independent PWM Mode
One of the timer’s operating modes is the Processor Inde-pendent PWM mode. In this mode, the timer generates a“Processor Independent” PWM signal because once thetimer is setup, no more action is required from the CPUwhich translates to less software overhead and greaterthroughput. The user software services the timer block onlywhen the PWM parameters require updating. This capabilityis provided by the fact that the timer has two separate 16-bitreload registers. One of the reload registers contains the“ON” timer while the other holds the “OFF” time. By contrast,a microcontroller that has only a single reload register re-quires an additional software to update the reload value (al-ternate between the on-time/off-time).
The timer can generate the PWM output with the width andduty cycle controlled by the values stored in the reload reg-isters. The reload registers control the countdown values
and the reload values are automatically written into the timerwhen it counts down through 0, generating interrupt on eachreload. Under software control and with minimal overhead,the PMW outputs are useful in controlling motors, triacs, theintensity of displays, and in providing inputs for data acquisi-tion and sine wave generators.
In this mode, the timer Tx counts down at a fixed rate of tC.Upon every underflow the timer is alternately reloaded withthe contents of supporting registers, RxA and RxB. The veryfirst underflow of the timer causes the timer to reload fromthe register RxA. Subsequent underflows cause the timer tobe reloaded from the registers alternately beginning with theregister RxB.
Figure 16 shows a block diagram of the timer in PWM mode.
The underflows can be programmed to toggle the TxA outputpin. The underflows can also be programmed to generate in-terrupts.
Underflows from the timer are alternately latched into twopending flags, TxPNDA and TxPNDB. The user must resetthese pending flags under software control. Two control en-able flags, TxENA and TxENB, allow the interrupts from thetimer underflow to be enabled or disabled. Setting the timerenable flag TxENA will cause an interrupt when a timer un-derflow causes the RxA register to be reloaded into the timer.Setting the timer enable flag TxENB will cause an interruptwhen a timer underflow causes the RxB register to be re-loaded into the timer. Resetting the timer enable flags willdisable the associated interrupts.
Either or both of the timer underflow interrupts may be en-abled. This gives the user the flexibility of interrupting onceper PWM period on either the rising or falling edge of thePWM output. Alternatively, the user may choose to interrupton both edges of the PWM output.
6.2.2 Mode 2. External Event Counter Mode
This mode is quite similar to the processor independentPWM mode described above. The main difference is that thetimer, Tx, is clocked by the input signal from the TxA pin. TheTx timer control bits, TxC3, TxC2 and TxC1 allow the timer tobe clocked either on a positive or negative edge from theTxA pin. Underflows from the timer are latched into the TxP-NDA pending flag. Setting the TxENA control flag will causean interrupt when the timer underflows.
DS100155-46
FIGURE 16. Timer in PWM Mode
www.national.com19
6.0 Timers (Continued)
In this mode the input pin TxB can be used as an indepen-dent positive edge sensitive interrupt input if the TxENB con-trol flag is set. The occurrence of a positive edge on the TxBinput pin is latched into the TxPNDB flag.
Figure 17 shows a block diagram of the timer in ExternalEvent Counter mode.Note: The PWM output is not available in this mode since the TxA pin is being
used as the counter input clock.
6.2.3 Mode 3. Input Capture Mode
Each device can precisely measure external frequencies ortime external events by placing the timer block, Tx, in the in-put capture mode. In this mode, the reload registers serve asindependent capture registers, capturing the contents of thetimer when an external event occurs (transition on the timerinput pin). The capture registers can be read while maintain-ing count, a feature that lets the user measure elapsed timeand time between events. By saving the timer value when
the external event occurs, the time of the external event isrecorded. Most microcontrollers have a latency time be-cause they cannot determine the timer value when the exter-nal event occurs. The capture register eliminates the latencytime, thereby allowing the applications program to retrievethe timer value stored in the capture register.
In this mode, the timer Tx is constantly running at the fixed tCrate. The two registers, RxA and RxB, act as capture regis-ters. Each register acts in conjunction with a pin. The registerRxA acts in conjunction with the TxA pin and the register RxBacts in conjunction with the TxB pin.
The timer value gets copied over into the register when atrigger event occurs on its corresponding pin. Control bits,TxC3, TxC2 and TxC1, allow the trigger events to be speci-fied either as a positive or a negative edge. The trigger con-dition for each input pin can be specified independently.
The trigger conditions can also be programmed to generateinterrupts. The occurrence of the specified trigger conditionon the TxA and TxB pins will be respectively latched into thepending flags, TxPNDA and TxPNDB. The control flag Tx-ENA allows the interrupt on TxA to be either enabled or dis-abled. Setting the TxENA flag enables interrupts to be gener-ated when the selected trigger condition occurs on the TxApin. Similarly, the flag TxENB controls the interrupts from theTxB pin.
Underflows from the timer can also be programmed to gen-erate interrupts. Underflows are latched into the timer TxC0pending flag (the TxC0 control bit serves as the timer under-flow interrupt pending flag in the Input Capture mode). Con-sequently, the TxC0 control bit should be reset when enter-ing the Input Capture mode. The timer underflow interrupt isenabled with the TxENA control flag. When a TxA interruptoccurs in the Input Capture mode, the user must check boththe TxPNDA and TxC0 pending flags in order to determinewhether a TxA input capture or a timer underflow (or both)caused the interrupt.
Figure 18 shows a block diagram of the timer T1 in InputCapture mode. Timer T2 and T3 are identical to T1.
DS100155-47
FIGURE 17. Timer in External Event Counter Mode
DS100155-48
FIGURE 18. Timer in Input Capture Mode
www.national.com 20
6.0 Timers (Continued)
6.3 TIMER CONTROL FLAGS
The control bits and their functions are summarized below.
TxC3 Timer mode control
TxC2 Timer mode control
TxC1 Timer mode control
TxC0 Timer Start/Stop control in Modes 1 and 2 (Pro-cessor Independent PWM and External EventCounter), where 1 = Start, 0 = StopTimer Underflow Interrupt Pending Flag inMode 3 (Input Capture)
TxPNDA Timer Interrupt Pending Flag
TxENA Timer Interrupt Enable Flag
1 = Timer Interrupt Enabled
0 = Timer Interrupt Disabled
TxPNDB Timer Interrupt Pending Flag
TxENB Timer Interrupt Enable Flag
1 = Timer Interrupt Enabled
0 = Timer Interrupt Disabled
The timer mode control bits (TxC3, TxC2 and TxC1) are detailed below:
Mode TxC3 TxC2 TxC1 DescriptionInterrupt A
SourceInterrupt B
SourceTimer
Counts On
1
1 0 1 PWM: TxA Toggle Autoreload RA Autoreload RB tC1 0 0 PWM: No TxA
ToggleAutoreload RA Autoreload RB
tC
2
0 0 0 External EventCounter
TimerUnderflow
Pos. TxB Edge Pos. TxAEdge
0 0 1 External EventCounter
TimerUnderflow
Pos. TxB Edge Pos. TxAEdge
3
0 1 0 Captures: Pos. TxA Edge Pos. TxB Edge tCTxA Pos. Edge or Timer
TxB Pos. Edge Underflow
1 1 0 Captures: Pos. TxA Neg. TxB tCTxA Pos. Edge Edge or Timer Edge
TxB Neg. Edge Underflow
0 1 1 Captures: Neg. TxA Neg. TxB tCTxA Neg. Edge Edge or Timer Edge
TxB Neg. Edge Underflow
1 1 1 Captures: Neg. TxA Neg. TxB tCTxA Neg. Edge Edge or Timer Edge
TxB Neg. Edge Underflow
www.national.com21
7.0 Power Saving FeaturesToday, the proliferation of battery-operated based applica-tions has placed new demands on designers to drive powerconsumption down. Battery-operated systems are not theonly type of applications demanding low power. The powerbudget constraints are also imposed on those consumer/industrial applications where well regulated and expensivepower supply costs cannot be tolerated. Such applicationsrely on low cost and low power supply voltage derived di-rectly from the “mains” by using voltage rectifier and passivecomponents. Low power is demanded even in automotiveapplications, due to increased vehicle electronics content.This is required to ease the burden from the car battery. Lowpower 8-bit microcontrollers supply the smarts to controlbattery-operated, consumer/industrial, and automotive appli-cations.
Each device offers system designers a variety of low-powerconsumption features that enable them to meet the demand-ing requirements of today’s increasing range of low-powerapplications. These features include low voltage operation,low current drain, and power saving features such as HALT,IDLE, and Multi-Input wakeup (MIWU).
Each device offers the user two power save modes of opera-tion: HALT and IDLE. In the HALT mode, all microcontrolleractivities are stopped. In the IDLE mode, the on-board oscil-lator circuitry and timer T0 are active but all other microcon-troller activities are stopped. In either mode, all on-boardRAM, registers, I/O states, and timers (with the exception ofT0) are unaltered.
Clock Monitor, if enabled, can be active in both modes.
7.1 HALT MODE
Each device can be placed in the HALT mode by writing a “1”to the HALT flag (G7 data bit). All microcontroller activities,including the clock and timers, are stopped. The WATCH-DOG logic on the devices are disabled during the HALTmode. However, the clock monitor circuitry, if enabled, re-mains active and will cause the WATCHDOG output pin(WDOUT) to go low. If the HALT mode is used and the userdoes not want to activate the WDOUT pin, the Clock Monitorshould be disabled after the devices come out of reset (re-setting the Clock Monitor control bit with the first write to theWDSVR register). In the HALT mode, the power require-ments of the devices are minimal and the applied voltage(VCC) may be decreased to Vr (Vr = 2.0V) without altering thestate of the machine.
Each device supports three different ways of exiting theHALT mode. The first method of exiting the HALT mode iswith the Multi-Input Wakeup feature on Port L. The secondmethod is with a low to high transition on the CKO (G7) pin.This method precludes the use of the crystal clock configura-tion (since CKO becomes a dedicated output), and so mayonly be used with an R/C clock configuration. The thirdmethod of exiting the HALT mode is by pulling the RESETpin low.
On wakeup from G7 or Port L, the devices resume executionfrom the HALT point. On wakeup from RESET execution willresume from location PC=0 and all RESET conditions apply.
If a crystal or ceramic resonator may be selected as the os-cillator, the Wakeup signal is not allowed to start the chiprunning immediately since crystal oscillators and ceramicresonators have a delayed start up time to reach full ampli-tude and frequency stability. The IDLE timer is used to gen-erate a fixed delay to ensure that the oscillator has indeedstabilized before allowing instruction execution. In this case,upon detecting a valid Wakeup signal, only the oscillator cir-cuitry is enabled. The IDLE timer is loaded with a value of256 and is clocked with the tC instruction cycle clock. The tCclock is derived by dividing the oscillator clock down by a fac-tor of 9. The Schmitt trigger following the CKI inverter on thechip ensures that the IDLE timer is clocked only when the os-cillator has a sufficiently large amplitude to meet the Schmitttrigger specifications. This Schmitt trigger is not part of theoscillator closed loop. The start-up time-out from the IDLEtimer enables the clock signals to be routed to the rest of thechip.
If an R/C clock option is being used, the fixed delay is intro-duced optionally. A control bit, CLKDLY, mapped as configu-ration bit G7, controls whether the delay is to be introducedor not. The delay is included if CLKDLY is set, and excludedif CLKDLY is reset. The CLKDLY bit is cleared on reset.
Each device has two options associated with the HALTmode. The first option enables the HALT mode feature, whilethe second option disables the HALT mode selected throughbit 0 of the ECON register. With the HALT mode enable op-tion, the device will enter and exit the HALT mode as de-scribed above. With the HALT disable option, the device can-not be placed in the HALT mode (writing a “1” to the HALTflag will have no effect, the HALT flag will remain “0”).
The WATCHDOG detector circuit is inhibited during theHALT mode. However, the clock monitor circuit if enabled re-mains active during HALT mode in order to ensure a clockmonitor error if the device inadvertently enters the HALTmode as a result of a runaway program or power glitch.
If the device is placed in the HALT mode, with the R/C oscil-lator selected, the clock input pin (CKI) is forced to a logichigh internally. With the crystal or external oscillator the CKIpin is TRI-STATE.
It is recommended that the user not halt the device by merelystopping the clock in external oscillator mode. If this methodis used, there is a possibility of greater than specified HALTcurrent.
If the user wishes to stop an external clock, it is recom-mended that the CPU be halted by setting the Halt flag firstand the clock be stopped only after the CPU has halted.
www.national.com 22
7.0 Power Saving Features (Continued)
7.2 IDLE MODE
The device is placed in the IDLE mode by writing a “1” to theIDLE flag (G6 data bit). In this mode, all activities, except theassociated on-board oscillator circuitry and the IDLE TimerT0, are stopped.
As with the HALT mode, the device can be returned to nor-mal operation with a reset, or with a Multi-Input Wakeup fromthe L Port. Alternately, the microcontroller resumes normaloperation from the IDLE mode when the twelfth bit (repre-senting 4.096 ms at internal clock frequency of 10 MHz, tC =1 µs) of the IDLE Timer toggles.
This toggle condition of the twelfth bit of the IDLE Timer T0 islatched into the T0PND pending flag.
The user has the option of being interrupted with a transitionon the twelfth bit of the IDLE Timer T0. The interrupt can beenabled or disabled via the T0EN control bit. Setting theT0EN flag enables the interrupt and vice versa.
The user can enter the IDLE mode with the Timer T0 inter-rupt enabled. In this case, when the T0PND bit gets set, thedevice will first execute the Timer T0 interrupt service routineand then return to the instruction following the “Enter IdleMode” instruction.
Alternatively, the user can enter the IDLE mode with theIDLE Timer T0 interrupt disabled. In this case, the device willresume normal operation with the instruction immediatelyfollowing the “Enter IDLE Mode” instruction.Note: It is necessary to program two NOP instructions following both the set
HALT mode and set IDLE mode instructions. These NOP instructionsare necessary to allow clock resynchronization following the HALT orIDLE modes.
DS100155-25
FIGURE 19. Wakeup from HALT
DS100155-26
FIGURE 20. Wakeup from IDLE
www.national.com23
7.0 Power Saving Features (Continued)
7.3 MULTI-INPUT WAKEUP
The Multi-Input Wakeup feature is used to return (wakeup)the device from either the HALT or IDLE modes. AlternatelyMulti-Input Wakeup/Interrupt feature may also be used togenerate up to 8 edge selectable external interrupts.
Figure 21 shows the Multi-Input Wakeup logic.
The Multi-Input Wakeup feature utilizes the L Port. The userselects which particular L port bit (or combination of L Portbits) will cause the device to exit the HALT or IDLE modes.The selection is done through the register WKEN. The regis-ter WKEN is an 8-bit read/write register, which contains acontrol bit for every L port bit. Setting a particular WKEN bitenables a Wakeup from the associated L port pin.
The user can select whether the trigger condition on the se-lected L Port pin is going to be either a positive edge (low tohigh transition) or a negative edge (high to low transition).This selection is made via the register WKEDG, which is an8-bit control register with a bit assigned to each L Port pin.Setting the control bit will select the trigger condition to be anegative edge on that particular L Port pin. Resetting the bitselects the trigger condition to be a positive edge. Changingan edge select entails several steps in order to avoid aWakeup condition as a result of the edge change. First, theassociated WKEN bit should be reset, followed by the edgeselect change in WKEDG. Next, the associated WKPND bitshould be cleared, followed by the associated WKEN bit be-ing re-enabled.
An example may serve to clarify this procedure. Suppose wewish to change the edge select from positive (low going high)
to negative (high going low) for L Port bit 5, where bit 5 haspreviously been enabled for an input interrupt. The programwould be as follows:
RBIT 5, WKEN ; Disable MIWUSBIT 5, WKEDG ; Change edge polarityRBIT 5, WKPND ; Reset pending flagSBIT 5, WKEN ; Enable MIWU
If the L port bits have been used as outputs and thenchanged to inputs with Multi-Input Wakeup/Interrupt, a safetyprocedure should also be followed to avoid wakeup condi-tions. After the selected L port bits have been changed fromoutput to input but before the associated WKEN bits are en-abled, the associated edge select bits in WKEDG should beset or reset for the desired edge selects, followed by the as-sociated WKPND bits being cleared.
This same procedure should be used following reset, sincethe L port inputs are left floating as a result of reset.
The occurrence of the selected trigger condition for Multi-Input Wakeup is latched into a pending register called WK-PND. The respective bits of the WKPND register will be seton the occurrence of the selected trigger edge on the corre-sponding Port L pin. The user has the responsibility of clear-ing these pending flags. Since WKPND is a pending registerfor the occurrence of selected wakeup conditions, the devicewill not enter the HALT mode if any Wakeup bit is both en-abled and pending. Consequently, the user must clear thepending flags before attempting to enter the HALT mode.
WKEN and WKEDG are all read/write registers, and arecleared at reset. WKPND register contains random value af-ter reset.
DS100155-27
FIGURE 21. Multi-Input Wake Up Logic
www.national.com 24
8.0 USARTEach device contains a full-duplex software programmableUSART. The USART (Figure 22) consists of a transmit shiftregister, a receive shift register and seven addressable reg-isters, as follows: a transmit buffer register (TBUF), a re-ceiver buffer register (RBUF), a USART control and statusregister (ENU), a USART receive control and status register(ENUR), a USART interrupt and clock source register(ENUI), a prescaler select register (PSR) and baud (BAUD)register. The ENU register contains flags for transmit and re-ceive functions; this register also determines the length ofthe data frame (7, 8 or 9 bits), the value of the ninth bit intransmission, and parity selection bits. The ENUR registerflags framing, data overrun and parity errors while the US-ART is receiving.
Other functions of the ENUR register include saving theninth bit received in the data frame, enabling or disabling theUSART’s attention mode of operation and providing addi-tional receiver/transmitter status information via RCVG andXMTG bits. The determination of an internal or external clocksource is done by the ENUI register, as well as selecting thenumber of stop bits and enabling or disabling transmit andreceive interrupts. A control flag in this register can also se-lect the USART mode of operation: asynchronous orsynchronous.
DS100155-39
FIGURE 22. USART Block Diagram
www.national.com25
8.0 USART (Continued)
8.1 USART CONTROL AND STATUS REGISTERS
The operation of the USART is programmed through threeregisters: ENU, ENUR and ENUI.
8.2 DESCRIPTION OF USART REGISTER BITS
ENU-USART Control and Status Register (Address at 0BA)
PEN PSEL1 XBIT9/ CHL1 CHL0 ERR RBFL TBMT
PSEL0
Bit 7 Bit 0
PEN: This bit enables/disables Parity (7- and 8-bit modesonly). Read/Write, cleared on reset.
PEN = 0 Parity disabled.
PEN = 1 Parity enabled.
PSEL1, PSEL0: Parity select bits. Read/Write, cleared onreset.
PSEL1 = 0, PSEL0 = 0 Odd Parity (if Parity enabled)
PSEL1 = 0, PSEL0 = 1 Even Parity (if Parity enabled)
PSEL1 = 1, PSEL0 = 0 Mark(1) (if Parity enabled)
PSEL1 = 1, PSEL0 = 1 Space(0) (if Parity enabled)
XBIT9/PSEL0: Programs the ninth bit for transmission whenthe USART is operating with nine data bits per frame. Forseven or eight data bits per frame, this bit in conjunction withPSEL1 selects parity. Read/Write, cleared on reset.
CHL1, CHL0: These bits select the character frame format.Parity is not included and is generated/verified by hardware.Read/Write, cleared on reset.
CHL1 = 0, CHL0 = 0 The frame contains eight data bits.
CHL1 = 0, CHL0 = 1 The frame contains seven databits.
CHL1 = 1, CHL0 = 0 The frame contains nine data bits.
CHL1 = 1, CHL0 = 1 Loopback Mode selected. Trans-mitter output internally looped backto receiver input. Nine bit framingformat is used.
ERR: This bit is a global USART error flag which gets set ifany or a combination of the errors (DOE, FE, PE) occur.Read only; it cannot be written by software, cleared on reset.
RBFL: This bit is set when the USART has received a com-plete character and has copied it into the RBUF register. It isautomatically reset when software reads the character fromRBUF. Read only; it cannot be written by software, clearedon reset.
TBMT: This bit is set when the USART transfers a byte ofdata from the TBUF register into the TSFT register for trans-mission. It is automatically reset when software writes intothe TBUF register. Read only, bit is set to “one” on reset; itcannot be written by software.
ENUR-USART Receive Control and Status Register
(Address at 0BB)
DOE FE PE Reserved RBIT9 ATTN XMTG RCVG
(Note 14)
Bit 7 Bit 0
Note 14: Bit is reserved for future use. User must set to zero.
DOE: Flags a Data Overrun Error. Read only, cleared onread, cleared on reset.
DOE = 0 Indicates no Data Overrun Error has been de-tected since the last time the ENUR registerwas read.
DOE = 1 Indicates the occurrence of a Data Overrun Er-ror.
FE: Flags a Framing Error. Read only, cleared on read,cleared on reset.
FE = 0 Indicates no Framing Error has been detectedsince the last time the ENUR register was read.
FE = 1 Indicates the occurrence of a Framing Error.
PE: Flags a Parity Error. Read only, cleared on read, clearedon reset.
PE = 0 Indicates no Parity Error has been detected sincethe last time the ENUR register was read.
PE = 1 Indicates the occurrence of a Parity Error.
SPARE: Reserved for future use. Read/Write, cleared on re-set.
RBIT9: Contains the ninth data bit received when the US-ART is operating with nine data bits per frame. Read only,cleared on reset.
ATTN: ATTENTION Mode is enabled while this bit is set.This bit is cleared automatically on receiving a character withdata bit nine set. Read/Write, cleared on reset.
XMTG: This bit is set to indicate that the USART is transmit-ting. It gets reset at the end of the last frame (end of last Stopbit). Read only, cleared on reset.
RCVG: This bit is set high whenever a framing error occursand goes low when RDX goes high. Read only, cleared onreset.
ENUI-USART Interrupt and Clock Source Register
(Address at 0BC)
STP2 STP78 ETDX SSEL XRCLK XTCLK ERI ETI
Bit 7 Bit 0
STP2: This bit programs the number of Stop bits to be trans-mitted. Read/Write, cleared on reset.
STP2 = 0 One Stop bit transmitted.
STP2 = 1 Two Stop bits transmitted.
STP78: This bit is set to program the last Stop bit to be 7/8thof a bit in length. Read/Write, cleared on reset.
ETDX: TDX (USART Transmit Pin) is the alternate functionassigned to Port L pin L2; it is selected by setting ETDX bit.To simulate line break generation, software should resetETDX bit and output logic zero to TDX pin through Port Ldata and configuration registers. Read/Write, cleared on re-set.
SSEL: USART mode select. Read/Write, cleared on reset.
SSEL = 0 Asynchronous Mode.
SSEL = 1 Synchronous Mode.
XRCLK: This bit selects the clock source for the receiversection. Read/Write, cleared on reset.
XRCLK = 0 The clock source is selected through thePSR and BAUD registers.
XRCLK = 1 Signal on CKX (L1) pin is used as the clock.
XTCLK: This bit selects the clock source for the transmittersection. Read/Write, cleared on reset.
XTCLK = 0 The clock source is selected through thePSR and BAUD registers.
XTCLK = 1 Signal on CKX (L1) pin is used as the clock.
ERI: This bit enables/disables interrupt from the receiversection. Read/Write, cleared on reset.
ERI = 0 Interrupt from the receiver is disabled.
ERI = 1 Interrupt from the receiver is enabled.
www.national.com 26
8.0 USART (Continued)
ETI: This bit enables/disables interrupt from the transmittersection. Read/Write, cleared on reset.
ETI = 0 Interrupt from the transmitter is disabled.
ETI = 1 Interrupt from the transmitter is enabled.
8.3 Associated I/O Pins
Data is transmitted on the TDX pin and received on the RDXpin. TDX is the alternate function assigned to Port L pin L2;it is selected by setting ETDX (in the ENUI register) to one.RDX is an inherent function of Port L pin L3, requiring nosetup.
The baud rate clock for the USART can be generated on-chip, or can be taken from an external source. Port L pin L1(CKX) is the external clock I/O pin. The CKX pin can be ei-ther an input or an output, as determined by Port L Configu-ration and Data registers (Bit 1). As an input, it accepts aclock signal which may be selected to drive the transmitterand/or receiver. As an output, it presents the internal BaudRate Generator output.
8.4 USART Operation
The USART has two modes of operation: asynchronousmode and synchronous mode.
8.4.1 ASYNCHRONOUS MODE
This mode is selected by resetting the SSEL (in the ENUIregister) bit to zero. The input frequency to the USART is 16times the baud rate.
The TSFT and TBUF registers double-buffer data for trans-mission. While TSFT is shifting out the current character onthe TDX pin, the TBUF register may be loaded by softwarewith the next byte to be transmitted. When TSFT finishestransmitting the current character the contents of TBUF aretransferred to the TSFT register and the Transmit BufferEmpty Flag (TBMT in the ENU register) is set. The TBMTflag is automatically reset by the USART when softwareloads a new character into the TBUF register. There is alsothe XMTG bit which is set to indicate that the USART istransmitting. This bit gets reset at the end of the last frame(end of last Stop bit). TBUF is a read/write register.
The RSFT and RBUF registers double-buffer data being re-ceived. The USART receiver continually monitors the signalon the RDX pin for a low level to detect the beginning of aStart bit. Upon sensing this low level, it waits for half a bittime and samples again. If the RDX pin is still low, the re-ceiver considers this to be a valid Start bit, and the remainingbits in the character frame are each sampled a single time, atthe mid-bit position. Serial data input on the RDX pin isshifted into the RSFT register. Upon receiving the completecharacter, the contents of the RSFT register are copied intothe RBUF register and the Received Buffer Full Flag (RBFL)is set. RBFL is automatically reset when software reads thecharacter from the RBUF register. RBUF is a read only reg-ister. There is also the RCVG bit which is set high when aframing error occurs and goes low once RDX goes high.TBMT, XMTG, RBFL and RCVG are read only bits.
8.4.2 SYNCHRONOUS MODE
In this mode data is transferred synchronously with theclock. Data is transmitted on the rising edge and received onthe falling edge of the synchronous clock.
This mode is selected by setting SSEL bit in the ENUI regis-ter. The input frequency to the USART is the same as thebaud rate.
When an external clock input is selected at the CKX pin, datatransmit and receive are performed synchronously with thisclock through TDX/RDX pins.
If data transmit and receive are selected with the CKX pin asclock output, the device generates the synchronous clockoutput at the CKX pin. The internal baud rate generator isused to produce the synchronous clock. Data transmit andreceive are performed synchronously with this clock.
8.5 FRAMING FORMATS
The USART supports several serial framing formats (Figure23). The format is selected using control bits in the ENU,ENUR and ENUI registers.
The first format (1, 1a, 1b, 1c) for data transmission (CHL0 =1, CHL1 = 0) consists of Start bit, seven Data bits (excludingparity) and 7/8, one or two Stop bits. In applications usingparity, the parity bit is generated and verified by hardware.
The second format (CHL0 = 0, CHL1 = 0) consists of oneStart bit, eight Data bits (excluding parity) and 7/8, one ortwo Stop bits. Parity bit is generated and verified by hard-ware.
The third format for transmission (CHL0 = 0, CHL1 = 1) con-sists of one Start bit, nine Data bits and 7/8, one or two Stopbits. This format also supports the USART “ATTENTION”feature. When operating in this format, all eight bits of TBUFand RBUF are used for data. The ninth data bit is transmittedand received using two bits in the ENU and ENUR registers,called XBIT9 and RBIT9. RBIT9 is a read only bit. Parity isnot generated or verified in this mode.
For any of the above framing formats, the last Stop bit canbe programmed to be 7/8th of a bit in length. If two Stop bitsare selected and the 7/8th bit is set (selected), the secondStop bit will be 7/8th of a bit in length.
The parity is enabled/disabled by PEN bit located in the ENUregister. Parity is selected for 7- and 8-bit modes only. If par-ity is enabled (PEN = 1), the parity selection is then per-formed by PSEL0 and PSEL1 bits located in the ENU regis-ter.
Note that the XBIT9/PSEL0 bit located in the ENU registerserves two mutually exclusive functions. This bit programsthe ninth bit for transmission when the USART is operatingwith nine data bits per frame. There is no parity selection inthis framing format. For other framing formats XBIT9 is notneeded and the bit is PSEL0 used in conjunction with PSEL1to select parity.
The frame formats for the receiver differ from the transmitterin the number of Stop bits required. The receiver only re-quires one Stop bit in a frame, regardless of the setting of theStop bit selection bits in the control register. Note that an im-plicit assumption is made for full duplex USART operationthat the framing formats are the same for the transmitter andreceiver.
www.national.com27
8.0 USART (Continued)
8.6 USART INTERRUPTS
The USART is capable of generating interrupts. Interruptsare generated on Receive Buffer Full and Transmit BufferEmpty. Both interrupts have individual interrupt vectors. Twobytes of program memory space are reserved for each inter-rupt vector. The two vectors are located at addresses 0xECto 0xEF Hex in the program memory space. The interruptscan be individually enabled or disabled using Enable Trans-mit Interrupt (ETI) and Enable Receive Interrupt (ERI) bits inthe ENUI register.
The interrupt from the Transmitter is set pending, and re-mains pending, as long as both the TBMT and ETI bits areset. To remove this interrupt, software must either clear theETI bit or write to the TBUF register (thus clearing the TBMTbit).
The interrupt from the receiver is set pending, and remainspending, as long as both the RBFL and ERI bits are set. Toremove this interrupt, software must either clear the ERI bitor read from the RBUF register (thus clearing the RBFL bit).
8.7 Baud Clock Generation
The clock inputs to the transmitter and receiver sections ofthe USART can be individually selected to come either froman external source at the CKX pin (port L, pin L1) or from asource selected in the PSR and BAUD registers. Internally,
the basic baud clock is created from the oscillator frequencythrough a two-stage divider chain consisting of a 1–16 (in-crements of 0.5) prescaler and an 11-bit binary counter. (Fig-ure 24). The divide factors are specified through two read/write registers shown in Figure 25. Note that the 11-bit BaudRate Divisor spills over into the Prescaler Select Register(PSR). PSR is cleared upon reset.
As shown in Table 5, a Prescaler Factor of 0 corresponds toNO CLOCK. This condition is the USART power down modewhere the USART clock is turned off for power saving pur-pose. The user must also turn the USART clock off when adifferent baud rate is chosen.
The correspondences between the 5-bit Prescaler Selectand Prescaler factors are shown in Table 5. There are manyways to calculate the two divisor factors, but one particularlyeffective method would be to achieve a 1.8432 MHz fre-quency coming out of the first stage. The 1.8432 MHz pres-caler output is then used to drive the software programmablebaud rate counter to create a 16x clock for the following baudrates: 110, 134.5, 150, 300, 600, 1200, 1800, 2400, 3600,4800, 7200, 9600, 19200 and 38400 (Table 4). Other baudrates may be created by using appropriate divisors. The 16xclock is then divided by 16 to provide the rate for the serialshift registers of the transmitter and receiver.
DS100155-40
FIGURE 23. Framing Formats
www.national.com 28
8.0 USART (Continued)
TABLE 4. Baud Rate Divisors(1.8432 MHz Prescaler Output)
Baud Baud Rate
Rate Divisor − 1(N-1)
110(110.03)
1046
134.5(134.58)
855
150 767
300 383
600 191
1200 95
1800 63
2400 47
3600 31
4800 23
7200 15
9600 11
19200 5
38400 2Note: The entries in Table 5 assume a prescaler output of 1.8432 MHz. In the
asynchronous mode the baud rate could be as high as 625k.
TABLE 5. Prescaler Factors
Prescaler Prescaler
Select Factor
00000 NO CLOCK
00001 1
00010 1.5
00011 2
00100 2.5
00101 3
00110 3.5
00111 4
Prescaler Prescaler
Select Factor
01000 4.5
01001 5
01010 5.5
01011 6
01100 6.5
01101 7
01110 7.5
01111 8
10000 8.5
10001 9
10010 9.5
10011 10
10100 10.5
10101 11
10110 11.5
10111 12
11000 12.5
11001 13
11010 13.5
11011 14
11100 14.5
11101 15
11110 15.5
11111 16
DS100155-41
FIGURE 24. USART BAUD Clock Generation
DS100155-42
FIGURE 25. USART BAUD Clock Divisor Registers
www.national.com29
8.0 USART (Continued)
As an example, considering Asynchronous Mode and a CKIclock of 4.608 MHz, the prescaler factor selected is:
4.608/1.8432 = 2.5
The 2.5 entry is available in Table 5. The 1.8432 MHz pres-caler output is then used with proper Baud Rate Divisor(Table 4) to obtain different baud rates. For a baud rate of19200 e.g., the entry in Table 4 is 5.
N − 1 = 5 (N − 1 is the value from Table 4)
N = 6 (N is the Baud Rate Divisor)
Baud Rate = 1.8432 MHz/(16 x 6) = 19200
The divide by 16 is performed because in the asynchronousmode, the input frequency to the USART is 16 times thebaud rate. The equation to calculate baud rates is given be-low.
The actual Baud Rate may be found from:
BR = Fc/(16 x N x P)
Where:
BR is the Baud Rate
Fc is the CKI frequency
N is the Baud Rate Divisor (Table 4).
P is the Prescaler Divide Factor selected by the value in thePrescaler Select Register (Table 5)Note: In the Synchronous Mode, the divisor 16 is replaced by two.
Example:
Asynchronous Mode:
Crystal Frequency = 5 MHz
Desired baud rate = 9600
Using the above equation N x P can be calculated first.
N x P = (5 x 106)/(16 x 9600) = 32.552
Now 32.552 is divided by each Prescaler Factor (Table 5) toobtain a value closest to an integer. This factor happens tobe 6.5 (P = 6.5).
N = 32.552/6.5 = 5.008 (N = 5)
The programmed value (from Table 4) should be 4 (N − 1).
Using the above values calculated for N and P:
BR = (5 x 106)/(16 x 5 x 6.5) = 9615.384
% error = (9615.385 − 9600)/9600 x 100 = 0.16%
8.8 Effect of HALT/IDLE
The USART logic is reinitialized when either the HALT orIDLE modes are entered. This reinitialization sets the TBMTflag and resets all read only bits in the USART control andstatus registers. Read/Write bits remain unchanged. TheTransmit Buffer (TBUF) is not affected, but the Transmit Shiftregister (TSFT) bits are set to one. The receiver registersRBUF and RSFT are not affected.
The device will exit from the HALT/IDLE modes when theStart bit of a character is detected at the RDX (L3) pin. Thisfeature is obtained by using the Multi-Input Wakeup schemeprovided on the device.
Before entering the HALT or IDLE modes the user programmust select the Wakeup source to be on the RDX pin. Thisselection is done by setting bit 3 of WKEN (Wakeup Enable)register. The Wakeup trigger condition is then selected to behigh to low transition. This is done via the WKEDG register(Bit 3 is one.)
If the device is halted and crystal oscillator is used, theWakeup signal will not start the chip running immediately be-
cause of the finite start up time requirement of the crystal os-cillator. The idle timer (T0) generates a fixed (256 tc) delay toensure that the oscillator has indeed stabilized before allow-ing the device to execute code. The user has to consider thisdelay when data transfer is expected immediately after exit-ing the HALT mode.
8.9 Diagnostic
Bits CHARL0 and CHARL1 in the ENU register provide aloopback feature for diagnostic testing of the USART. Whenthese bits are set to one, the following occur: The receiver in-put pin (RDX) is internally connected to the transmitter out-put pin (TDX); the output of the Transmitter Shift Register is“looped back” into the Receive Shift Register input. In thismode, data that is transmitted is immediately received. Thisfeature allows the processor to verify the transmit and re-ceive data paths of the USART.
Note that the framing format for this mode is the nine bit for-mat; one Start bit, nine data bits, and 7/8, one or two Stopbits. Parity is not generated or verified in this mode.
8.10 Attention Mode
The USART Receiver section supports an alternate mode ofoperation, referred to as ATTENTION Mode. This mode ofoperation is selected by the ATTN bit in the ENUR register.The data format for transmission must also be selected ashaving nine Data bits and either 7/8, one or two Stop bits.
The ATTENTION mode of operation is intended for use innetworking the device with other processors. Typically insuch environments the messages consists of device ad-dresses, indicating which of several destinations should re-ceive them, and the actual data. This Mode supports ascheme in which addresses are flagged by having the ninthbit of the data field set to a 1. If the ninth bit is reset to a zerothe byte is a Data byte.
While in ATTENTION mode, the USART monitors the com-munication flow, but ignores all characters until an addresscharacter is received. Upon receiving an address character,the USART signals that the character is ready by setting theRBFL flag, which in turn interrupts the processor if USARTReceiver interrupts are enabled. The ATTN bit is also clearedautomatically at this point, so that data characters as well asaddress characters are recognized. Software examines thecontents of the RBUF and responds by deciding either to ac-cept the subsequent data stream (by leaving the ATTN bit re-set) or to wait until the next address character is seen (bysetting the ATTN bit again).
Operation of the USART Transmitter is not affected by selec-tion of this Mode. The value of the ninth bit to be transmittedis programmed by setting XBIT9 appropriately. The value ofthe ninth bit received is obtained by reading RBIT9. Sincethis bit is located in ENUR register where the error flags re-side, a bit operation on it will reset the error flags.
www.national.com 30
9.0 ComparatorsThe device contains two differential comparators, each witha pair of inputs (positive and negative) and an output. PortsF1–F3 and F4–F6 are used for the comparators. The follow-ing is the Port F assignment:
F6 Comparator2 output
F5 Comparator2 positive input
F4 Comparator2 negative input
F3 Comparator1 output
F2 Comparator1 positive input
F1 Comparator1 negative input
A Comparator Select Register (CMPSL) is used to enablethe comparators, read the outputs of the comparators inter-nally, and enable the outputs of the comparators to the pins.Two control bits (enable and output enable) and one resultbit are associated with each comparator. The comparator re-sult bits (CMP1RD and CMP2RD) are read only bits whichwill read as zero if the associated comparator is not enabled.The Comparator Select Register is cleared with reset, result-ing in the comparators being disabled. The comparatorsshould also be disabled before entering either the HALT orIDLE modes in order to save power. The configuration of theCMPSL register is as follows:
CMPSL REGISTER (ADDRESS X’00B7)
Reserved CMP20E CMP2RD CMP2EN CMP10E CMP1RD CMP1EN Reserved
Bit 7 Bit 0
The CMPSL register contains the following bits:
Reserved These bits are reserved and should be zero
CMP20E Selects pin I6 as comparator 2 output providedthat CMP2EN is set to enable the comparator
CMP2RD Comparator 2 result (this is a read only bit, whichwill read as 0 if the comparator is not enabled)
CMP2EN Enable comparator 2
CMP10E Selects pin I3 as comparator 1 output providedthat CMPIEN is set to enable the comparator
CMP1RD Comparator 1 result (this is a read only bit, whichwill read as 0 if the comparator is not enabled)
CMP1EN Enable comparator 1
Note that the two unused bits of CMPSL may be used assoftware flags.Note: For compatibility with existing code and with existing Mask ROMMed
devices the bits of the CMPSL register will take precedence over theassociated Port F configuration and data output bits.
10.0 Interrupts
10.1 INTRODUCTION
Each device supports thirteen vectored interrupts. Interruptsources include Timer 0, Timer 1, Timer 2, Timer 3, Port LWakeup, Software Trap, MICROWIRE/PLUS, and ExternalInput.
All interrupts force a branch to location 00FF Hex in programmemory. The VIS instruction may be used to vector to theappropriate service routine from location 00FF Hex.
The Software trap has the highest priority while the defaultVIS has the lowest priority.
Each of the 13 maskable inputs has a fixed arbitration rank-ing and vector.
Figure 26 shows the Interrupt Block Diagram.
DS100155-28
FIGURE 26. Interrupt Block Diagram
www.national.com31
10.0 Interrupts (Continued)
10.2 MASKABLE INTERRUPTS
All interrupts other than the Software Trap are maskable.Each maskable interrupt has an associated enable bit andpending flag bit. The pending bit is set to 1 when the interruptcondition occurs. The state of the interrupt enable bit, com-bined with the GIE bit determines whether an active pendingflag actually triggers an interrupt. All of the maskable inter-rupt pending and enable bits are contained in mapped con-trol registers, and thus can be controlled by the software.
A maskable interrupt condition triggers an interrupt under thefollowing conditions:
1. The enable bit associated with that interrupt is set.
2. The GIE bit is set.
3. The device is not processing a non-maskable interrupt.(If a non-maskable interrupt is being serviced, amaskable interrupt must wait until that service routine iscompleted.)
An interrupt is triggered only when all of these conditions aremet at the beginning of an instruction. If different maskableinterrupts meet these conditions simultaneously, the highestpriority interrupt will be serviced first, and the other pendinginterrupts must wait.
Upon Reset, all pending bits, individual enable bits, and theGIE bit are reset to zero. Thus, a maskable interrupt condi-tion cannot trigger an interrupt until the program enables it bysetting both the GIE bit and the individual enable bit. Whenenabling an interrupt, the user should consider whether ornot a previously activated (set) pending bit should be ac-knowledged. If, at the time an interrupt is enabled, any pre-vious occurrences of the interrupt should be ignored, the as-sociated pending bit must be reset to zero prior to enablingthe interrupt. Otherwise, the interrupt may be simply en-abled; if the pending bit is already set, it will immediately trig-ger an interrupt. A maskable interrupt is active if its associ-ated enable and pending bits are set.
An interrupt is an asychronous event which may occur be-fore, during, or after an instruction cycle. Any interrupt whichoccurs during the execution of an instruction is not acknowl-edged until the start of the next normally executed instructionis to be skipped, the skip is performed before the pending in-terrupt is acknowledged.
At the start of interrupt acknowledgment, the following ac-tions occur:
1. The GIE bit is automatically reset to zero, preventing anysubsequent maskable interrupt from interrupting the cur-rent service routine. This feature prevents one maskableinterrupt from interrupting another one being serviced.
2. The address of the instruction about to be executed ispushed onto the stack.
3. The program counter (PC) is loaded with 00FF Hex,causing a jump to that program memory location.
The device requires seven instruction cycles to perform theactions listed above.
If the user wishes to allow nested interrupts, the interruptsservice routine may set the GIE bit to 1 by writing to the PSWregister, and thus allow other maskable interrupts to interruptthe current service routine. If nested interrupts are allowed,caution must be exercised. The user must write the programin such a way as to prevent stack overflow, loss of savedcontext information, and other unwanted conditions.
The interrupt service routine stored at location 00FF Hexshould use the VIS instruction to determine the cause of the
interrupt, and jump to the interrupt handling routine corre-sponding to the highest priority enabled and active interrupt.Alternately, the user may choose to poll all interrupt pendingand enable bits to determine the source(s) of the interrupt. Ifmore than one interrupt is active, the user’s program mustdecide which interrupt to service.
Within a specific interrupt service routine, the associatedpending bit should be cleared. This is typically done as earlyas possible in the service routine in order to avoid missingthe next occurrence of the same type of interrupt event.Thus, if the same event occurs a second time, even while thefirst occurrence is still being serviced, the second occur-rence will be serviced immediately upon return from the cur-rent interrupt routine.
An interrupt service routine typically ends with an RETI in-struction. This instruction sets the GIE bit back to 1, pops theaddress stored on the stack, and restores that address to theprogram counter. Program execution then proceeds with thenext instruction that would have been executed had therebeen no interrupt. If there are any valid interrupts pending,the highest-priority interrupt is serviced immediately upon re-turn from the previous interrupt.
10.3 VIS INSTRUCTION
The general interrupt service routine, which starts at address00FF Hex, must be capable of handling all types of inter-rupts. The VIS instruction, together with an interrupt vectortable, directs the device to the specific interrupt handling rou-tine based on the cause of the interrupt.
VIS is a single-byte instruction, typically used at the very be-ginning of the general interrupt service routine at address00FF Hex, or shortly after that point, just after the code usedfor context switching. The VIS instruction determines whichenabled and pending interrupt has the highest priority, andcauses an indirect jump to the address corresponding to thatinterrupt source. The jump addresses (vectors) for all pos-sible interrupts sources are stored in a vector table.
The vector table may be as long as 32 bytes (maximum of 16vectors) and resides at the top of the 256-byte block contain-ing the VIS instruction. However, if the VIS instruction is atthe very top of a 256-byte block (such as at 00FF Hex), thevector table resides at the top of the next 256-byte block.Thus, if the VIS instruction is located somewhere between00FF and 01DF Hex (the usual case), the vector table is lo-cated between addresses 01E0 and 01FF Hex. If the VIS in-struction is located between 01FF and 02DF Hex, then thevector table is located between addresses 02E0 and 02FFHex, and so on.
Each vector is 15 bits long and points to the beginning of aspecific interrupt service routine somewhere in the 32 kbytememory space. Each vector occupies two bytes of the vectortable, with the higher-order byte at the lower address. Thevectors are arranged in order of interrupt priority. The vectorof the maskable interrupt with the lowest rank is located to0yE0 (higher-order byte) and 0yE1 (lower-order byte). Thenext priority interrupt is located at 0yE2 and 0yE3, and soforth in increasing rank. The Software Trap has the highestrank and its vector is always located at 0yFE and 0yFF. Thenumber of interrupts which can become active defines thesize of the table.
Table 6 shows the types of interrupts, the interrupt arbitrationranking, and the locations of the corresponding vectors inthe vector table.
The vector table should be filled by the user with the memorylocations of the specific interrupt service routines. For ex-
www.national.com 32
10.0 Interrupts (Continued)
ample, if the Software Trap routine is located at 0310 Hex,then the vector location 0yFE and -0yFF should contain thedata 03 and 10 Hex, respectively. When a Software Trap in-terrupt occurs and the VIS instruction is executed, the pro-gram jumps to the address specified in the vector table.
The interrupt sources in the vector table are listed in order ofrank, from highest to lowest priority. If two or more enabledand pending interrupts are detected at the same time, theone with the highest priority is serviced first. Upon returnfrom the interrupt service routine, the next highest-levelpending interrupt is serviced.
If the VIS instruction is executed, but no interrupts are en-abled and pending, the lowest-priority interrupt vector isused, and a jump is made to the corresponding address inthe vector table. This is an unusual occurrence, and may bethe result of an error. It can legitimately result from a changein the enable bits or pending flags prior to the execution ofthe VIS instruction, such as executing a single cycle instruc-tion which clears an enable flag at the same time that thepending flag is set. It can also result, however, from inadvert-ent execution of the VIS command outside of the context ofan interrupt.
The default VIS interrupt vector can be useful for applica-tions in which time critical interrupts can occur during theservicing of another interrupt. Rather than restoring the pro-
gram context (A, B, X, etc.) and executing the RETI instruc-tion, an interrupt service routine can be terminated by return-ing to the VIS instruction. In this case, interrupts will beserviced in turn until no further interrupts are pending andthe default VIS routine is started. After testing the GIE bit toensure that execution is not erroneous, the routine shouldrestore the program context and execute the RETI to returnto the interrupted program.
This technique can save up to fifty instruction cycles (tc), ormore, (50µs at 10 MHz oscillator) of latency for pending in-terrupts with a penalty of fewer than ten instruction cycles ifno further interrupts are pending.
To ensure reliable operation, the user should always use theVIS instruction to determine the source of an interrupt. Al-though it is possible to poll the pending bits to detect thesource of an interrupt, this practice is not recommended. Theuse of polling allows the standard arbitration ranking to be al-tered, but the reliability of the interrupt system is compro-mised. The polling routine must individually test the enableand pending bits of each maskable interrupt. If a SoftwareTrap interrupt should occur, it will be serviced last, eventhough it should have the highest priority. Under certain con-ditions, a Software Trap could be triggered but not serviced,resulting in an inadvertent “locking out” of all maskable inter-rupts by the Software Trap pending flag. Problems such asthis can be avoided by using VIS instruction.
TABLE 6. Interrupt Vector Table
ArbitrationRanking
Source DescriptionVector Address (Note 15)
(Hi-Low Byte)
(1) Highest Software INTR Instruction 0yFE–0yFF
(2) Reserved 0yFC–0yFD
(3) External G0 0yFA–0yFB
(4) Timer T0 Underflow 0yF8–0yF9
(5) Timer T1 T1A/Underflow 0yF6–0yF7
(6) Timer T1 T1B 0yF4–0yF5
(7) MICROWIRE/PLUS BUSY Low 0yF2–0yF3
(8) Reserved 0yF0–0yF1
(9) UART Receive 0yEE–0yEF
(10) UART Transmit 0yEC–0yED
(11) Timer T2 T2A/Underflow 0yEA–0yEB
(12) Timer T2 T2B 0yE8–0yE9
(13) Timer T3 T2A/Underflow 0yE6–0yE7
(14) Timer T3 T3B 0yE4–0yE5
(15) Port L/Wakeup Port L Edge 0yE2–0yE3
(16) Lowest Default VIS Reserved 0yE0–0yE1
Note 15: y is a variable which represents the VIS block. VIS and the vector table must be located in the same 256-byte block except if VIS is located at the last ad-dress of a block. In this case, the table must be in the next block.
www.national.com33
10.0 Interrupts (Continued)
10.3.1 VIS Execution
When the VIS instruction is executed it activates the arbitra-tion logic. The arbitration logic generates an even numberbetween E0 and FE (E0, E2, E4, E6 etc...) depending onwhich active interrupt has the highest arbitration ranking atthe time of the 1st cycle of VIS is executed. For example, ifthe software trap interrupt is active, FE is generated. If theexternal interrupt is active and the software trap interrupt isnot, then FA is generated and so forth. If the only active inter-rupt is software trap, than E0 is generated. This number re-places the lower byte of the PC. The upper byte of the PC re-
mains unchanged. The new PC is therefore pointing to thevector of the active interrupt with the highest arbitration rank-ing. This vector is read from program memory and placedinto the PC which is now pointed to the 1st instruction of theservice routine of the active interrupt with the highest arbitra-tion ranking.
Figure 27 illustrates the different steps performed by the VISinstruction. Figure 28 shows a flowchart for the VIS instruc-tion.
The non-maskable interrupt pending flag is cleared by theRPND (Reset Non-Maskable Pending Bit) instruction (undercertain conditions) and upon RESET.
DS100155-29
FIGURE 27. VIS Operation
www.national.com 34
10.0 Interrupts (Continued)
DS100155-30
FIGURE 28. VIS Flowchart
www.national.com35
10.0 Interrupts (Continued)
Programming Example: External Interrupt
PSW =00EFCNTRL =00EERBIT 0,PORTGCRBIT 0,PORTGD ; G0 pin configured Hi-ZSBIT IEDG, CNTRL ; Ext interrupt polarity; falling edgeSBIT EXEN, PSW ; Enable the external interruptSBIT GIE, PSW ; Set the GIE bit
WAIT: JP WAIT ; Wait for external interrupt....=0FF ; The interrupt causes aVIS ; branch to address 0FF
; The VIS causes a branch to;interrupt vector table
.
.
.
.=01FA ; Vector table (within 256 byte
.ADDRW SERVICE ; of VIS inst.) containing the ext; interrupt service routine
.
.INT_EXIT:
RETI..
SERVICE: RBIT EXPND, PSW ; Interrupt Service Routine; Reset ext interrupt pend. bit
.
.
.JP INT_EXIT ; Return, set the GIE bit
www.national.com 36
10.0 Interrupts (Continued)
10.4 NON-MASKABLE INTERRUPT
10.4.1 Pending Flag
There is a pending flag bit associated with the non-maskableinterrupt, called STPND. This pending flag is not memory-mapped and cannot be accessed directly by the software.
The pending flag is reset to zero when a device Reset oc-curs. When the non-maskable interrupt occurs, the associ-ated pending bit is set to 1. The interrupt service routineshould contain an RPND instruction to reset the pending flagto zero. The RPND instruction always resets the STPNDflag.
10.4.2 Software Trap
The Software Trap is a special kind of non-maskable inter-rupt which occurs when the INTR instruction (used to ac-knowledge interrupts) is fetched from program memory andplaced in the instruction register. This can happen in a vari-ety of ways, usually because of an error condition. Some ex-amples of causes are listed below.
If the program counter incorrectly points to a memory loca-tion beyond the available program memory space, the non-existent or unused memory location returns zeroes which isinterpreted as the INTR instruction.
If the stack is popped beyond the allowed limit (address 06FHex), a 7FFF will be loaded into the PC, if this last location inprogram memory is unprogrammed or unavailable, a Soft-ware Trap will be triggered.
A Software Trap can be triggered by a temporary hardwarecondition such as a brownout or power supply glitch.
The Software Trap has the highest priority of all interrupts.When a Software Trap occurs, the STPND bit is set. The GIEbit is not affected and the pending bit (not accessible by theuser) is used to inhibit other interrupts and to direct the pro-gram to the ST service routine with the VIS instruction. Noth-ing can interrupt a Software Trap service routine except foranother Software Trap. The STPND can be reset only by theRPND instruction or a chip Reset.
The Software Trap indicates an unusual or unknown errorcondition. Generally, returning to normal execution at thepoint where the Software Trap occurred cannot be done re-liably. Therefore, the Software Trap service routine shouldreinitialize the stack pointer and perform a recovery proce-dure that restarts the software at some known point, similarto a device Reset, but not necessarily performing all thesame functions as a device Reset. The routine must also ex-ecute the RPND instruction to reset the STPND flag. Other-wise, all other interrupts will be locked out. To the extent pos-sible, the interrupt routine should record or indicate thecontext of the device so that the cause of the Software Trapcan be determined.
If the user wishes to return to normal execution from thepoint at which the Software Trap was triggered, the usermust first execute RPND, followed by RETSK rather thanRETI or RET. This is because the return address stored onthe stack is the address of the INTR instruction that triggeredthe interrupt. The program must skip that instruction in orderto proceed with the next one. Otherwise, an infinite loop ofSoftware Traps and returns will occur.
Programming a return to normal execution requires carefulconsideration. If the Software Trap routine is interrupted byanother Software Trap, the RPND instruction in the serviceroutine for the second Software Trap will reset the STPND
flag; upon return to the first Software Trap routine, theSTPND flag will have the wrong state. This will allowmaskable interrupts to be acknowledged during the servicingof the first Software Trap. To avoid problems such as this, theuser program should contain the Software Trap routine toperform a recovery procedure rather than a return to normalexecution.
Under normal conditions, the STPND flag is reset by aRPND instruction in the Software Trap service routine. If aprogramming error or hardware condition (brownout, powersupply glitch, etc.) sets the STPND flag without providing away for it to be cleared, all other interrupts will be locked out.To alleviate this condition, the user can use extra RPND in-structions in the main program and in the WATCHDOG ser-vice routine (if present). There is no harm in executing extraRPND instructions in these parts of the program.
10.5 PORT L INTERRUPTS
Port L provides the user with an additional eight fully select-able, edge sensitive interrupts which are all vectored into thesame service subroutine.
The interrupt from Port L shares logic with the wake up cir-cuitry. The register WKEN allows interrupts from Port L to beindividually enabled or disabled. The register WKEDG speci-fies the trigger condition to be either a positive or a negativeedge. Finally, the register WKPND latches in the pendingtrigger conditions.
The GIE (Global Interrupt Enable) bit enables the interruptfunction.
A control flag, LPEN, functions as a global interrupt enablefor Port L interrupts. Setting the LPEN flag will enable inter-rupts and vice versa. A separate global pending flag is notneeded since the register WKPND is adequate.
Since Port L is also used for waking the device out of theHALT or IDLE modes, the user can elect to exit the HALT orIDLE modes either with or without the interrupt enabled. If heelects to disable the interrupt, then the device will restart ex-ecution from the instruction immediately following the in-struction that placed the microcontroller in the HALT or IDLEmodes. In the other case, the device will first execute the in-terrupt service routine and then revert to normal operation.(See HALT MODE for clock option wakeup information.)
10.6 INTERRUPT SUMMARY
The device uses the following types of interrupts, listed be-low in order of priority:
1. The Software Trap non-maskable interrupt, triggered bythe INTR (00 opcode) instruction. The Software Trap isacknowledged immediately. This interrupt service rou-tine can be interrupted only by another Software Trap.The Software Trap should end with two RPND instruc-tions followed by a restart procedure.
2. Maskable interrupts, triggered by an on-chip peripheralblock or an external device connected to the device. Un-der ordinary conditions, a maskable interrupt will not in-terrupt any other interrupt routine in progress. Amaskable interrupt routine in progress can be inter-rupted by the non-maskable interrupt request. Amaskable interrupt routine should end with an RETI in-struction or, prior to restoring context, should return toexecute the VIS instruction. This is particularly usefulwhen exiting long interrupt service routiness if the timebetween interrupts is short. In this case the RETI instruc-tion would only be executed when the default VIS rou-tine is reached.
www.national.com37
11.0 WATCHDOG/Clock MonitorEach device contains a user selectable WATCHDOG andclock monitor. The following section is applicable only ifWATCHDOG feature has been selected in the ECON regis-ter. The WATCHDOG is designed to detect the user programgetting stuck in infinite loops resulting in loss of program con-trol or “runaway” programs.
The WATCHDOG logic contains two separate service win-dows. While the user programmable upper window selectsthe WATCHDOG service time, the lower window providesprotection against an infinite program loop that contains theWATCHDOG service instruction.
The Clock Monitor is used to detect the absence of a clock ora very slow clock below a specified rate on the CKI pin.
The WATCHDOG consists of two independent logic blocks:WD UPPER and WD LOWER. WD UPPER establishes theupper limit on the service window and WD LOWER definesthe lower limit of the service window.
Servicing the WATCHDOG consists of writing a specificvalue to a WATCHDOG Service Register named WDSVRwhich is memory mapped in the RAM. This value is com-posed of three fields, consisting of a 2-bit Window Select, a5-bit Key Data field, and the 1-bit Clock Monitor Select field.Table 7 shows the WDSVR register.
TABLE 7. WATCHDOG Service Register (WDSVR)
WindowSelect
Key DataClock
Monitor
X X 0 1 1 0 0 Y
7 6 5 4 3 2 1 0
The lower limit of the service window is fixed at 256 instruc-tion cycles. Bits 7 and 6 of the WDSVR register allow theuser to pick an upper limit of the service window.
Table 8 shows the four possible combinations of lower andupper limits for the WATCHDOG service window. This flex-ibility in choosing the WATCHDOG service window preventsany undue burden on the user software.
Bits 5, 4, 3, 2 and 1 of the WDSVR register represent the5-bit Key Data field. The key data is fixed at 01100. Bit 0 ofthe WDSVR Register is the Clock Monitor Select bit.
TABLE 8. WATCHDOG Service Window Select
WDSVR WDSVR Clock Service Window
Bit 7 Bit 6 Monitor (Lower-Upper Limits)
0 0 x 2048–8k tC Cycles
0 1 x 2048–16k tC Cycles
1 0 x 2048–32k tC Cycles
1 1 x 2048–64k tC Cycles
x x 0 Clock Monitor Disabled
x x 1 Clock Monitor Enabled
11.1 CLOCK MONITOR
The Clock Monitor aboard the device can be selected or de-selected under program control. The Clock Monitor is guar-anteed not to reject the clock if the instruction cycle clock (1/tC) is greater or equal to 10 kHz. This equates to a clockinput rate on CKI of greater or equal to 100 kHz.
11.2 WATCHDOG/CLOCK MONITOR OPERATION
The WATCHDOG is enabled by bit 2 of the ECON register.When this ECON bit is 0, the WATCHDOG is enabled andpin G1 becomes the WATCHDOG output with a weak pullup.
The WATCHDOG and Clock Monitor are disabled during re-set. The device comes out of reset with the WATCHDOGarmed, the WATCHDOG Window Select bits (bits 6, 7 of theWDSVR Register) set, and the Clock Monitor bit (bit 0 of theWDSVR Register) enabled. Thus, a Clock Monitor error willoccur after coming out of reset, if the instruction cycle clockfrequency has not reached a minimum specified value, in-cluding the case where the oscillator fails to start.
The WDSVR register can be written to only once after resetand the key data (bits 5 through 1 of the WDSVR Register)must match to be a valid write. This write to the WDSVR reg-ister involves two irrevocable choices: (i) the selection of theWATCHDOG service window (ii) enabling or disabling of theClock Monitor. Hence, the first write to WDSVR Register in-volves selecting or deselecting the Clock Monitor, select theWATCHDOG service window and match the WATCHDOGkey data. Subsequent writes to the WDSVR register willcompare the value being written by the user to the WATCH-DOG service window value and the key data (bits 7 through1) in the WDSVR Register. Table 9 shows the sequence ofevents that can occur.
The user must service the WATCHDOG at least once beforethe upper limit of the service window expires. The WATCH-DOG may not be serviced more than once in every lowerlimit of the service window.
The WATCHDOG has an output pin associated with it. Thisis the WDOUT pin, on pin 1 of the port G. WDOUT is activelow and must be externally connected to the RESET pin or tosome other external logic which handles WATCHDOG event.The WDOUT pin has a weak pullup in the inactive state. Thispull-up is sufficient to serve as the connection to VCC for sys-tems which use the internal Power On Reset. Upon trigger-ing the WATCHDOG, the logic will pull the WDOUT (G1) pinlow for an additional 16 tC–32 tC cycles after the signal levelon WDOUT pin goes below the lower Schmitt trigger thresh-old. After this delay, the device will stop forcing the WDOUToutput low. The WATCHDOG service window will restartwhen the WDOUT pin goes high.
A WATCHDOG service while the WDOUT signal is active willbe ignored. The state of the WDOUT pin is not guaranteedon reset, but if it powers up low then the WATCHDOG willtime out and WDOUT will go high.
The Clock Monitor forces the G1 pin low upon detecting aclock frequency error. The Clock Monitor error will continueuntil the clock frequency has reached the minimum specifiedvalue, after which the G1 output will go high following 16tC–32 tC clock cycles. The Clock Monitor generates a con-tinual Clock Monitor error if the oscillator fails to start, or failsto reach the minimum specified frequency. The specificationfor the Clock Monitor is as follows:
1/tC > 10 kHz — No clock rejection.
1/tC < 10 Hz — Guaranteed clock rejection.
www.national.com 38
11.0 WATCHDOG/Clock Monitor (Continued)
TABLE 9. WATCHDOG Service Actions
Key Window Clock Action
Data Data Monitor
Match Match Match Valid Service: Restart Service Window
Don’t Care Mismatch Don’t Care Error: Generate WATCHDOG Output
Mismatch Don’t Care Don’t Care Error: Generate WATCHDOG Output
Don’t Care Don’t Care Mismatch Error: Generate WATCHDOG Output
11.3 WATCHDOG AND CLOCK MONITOR SUMMARY
The following salient points regarding the WATCHDOG andCLOCK MONITOR should be noted:
• Both the WATCHDOG and CLOCK MONITOR detectorcircuits are inhibited during RESET.
• Following RESET, the WATCHDOG and CLOCK MONI-TOR are both enabled, with the WATCHDOG having themaximum service window selected.
• The WATCHDOG service window and CLOCK MONI-TOR enable/disable option can only be changed once,during the initial WATCHDOG service following RESET.
• The initial WATCHDOG service must match the key datavalue in the WATCHDOG Service register WDSVR in or-der to avoid a WATCHDOG error.
• Subsequent WATCHDOG services must match all threedata fields in WDSVR in order to avoid WATCHDOG er-rors.
• The correct key data value cannot be read from theWATCHDOG Service register WDSVR. Any attempt toread this key data value of 01100 from WDSVR will readas key data value of all 0’s.
• The WATCHDOG detector circuit is inhibited during boththe HALT and IDLE modes.
• The CLOCK MONITOR detector circuit is active duringboth the HALT and IDLE modes. Consequently, the de-vice inadvertently entering the HALT mode will be de-tected as a CLOCK MONITOR error (provided that theCLOCK MONITOR enable option has been selected bythe program).
• With the single-pin R/C oscillator option selected and theCLKDLY bit reset, the WATCHDOG service window willresume following HALT mode from where it left off beforeentering the HALT mode.
• With the crystal oscillator option selected, or with thesingle-pin R/C oscillator option selected and the CLKDLYbit set, the WATCHDOG service window will be set to itsselected value from WDSVR following HALT. Conse-quently, the WATCHDOG should not be serviced for atleast 256 instruction cycles following HALT, but must beserviced within the selected window to avoid a WATCH-DOG error.
• The IDLE timer T0 is not initialized with external RESET.
• The user can sync in to the IDLE counter cycle with anIDLE counter (T0) interrupt or by monitoring the T0PNDflag. The T0PND flag is set whenever the twelfth bit of theIDLE counter toggles (every 4096 instruction cycles). Theuser is responsible for resetting the T0PND flag.
• A hardware WATCHDOG service occurs just as the de-vice exits the IDLE mode. Consequently, the WATCH-DOG should not be serviced for at least 256 instructioncycles following IDLE, but must be serviced within the se-lected window to avoid a WATCHDOG error.
• Following RESET, the initial WATCHDOG service (wherethe service window and the CLOCK MONITOR enable/disable must be selected) may be programmed any-where within the maximum service window (65,536 in-struction cycles) initialized by RESET. Note that this initialWATCHDOG service may be programmed within the ini-tial 256 instruction cycles without causing a WATCHDOGerror.
11.4 DETECTION OF ILLEGAL CONDITIONS
The device can detect various illegal conditions resultingfrom coding errors, transient noise, power supply voltagedrops, runaway programs, etc.
Reading of undefined ROM gets zeroes. The opcode forsoftware interrupt is 00. If the program fetches instructionsfrom undefined ROM, this will force a software interrupt, thussignaling that an illegal condition has occurred.
The subroutine stack grows down for each call (jump to sub-routine), interrupt, or PUSH, and grows up for each return orPOP. The stack pointer is initialized to RAM location 06F Hexduring reset. Consequently, if there are more returns thancalls, the stack pointer will point to addresses 070 and 071Hex (which are undefined RAM). Undefined RAM from ad-dresses 070 to 07F (Segment 0), and all other segments(i.e., Segments 4 … etc.) is read as all 1’s, which in turn willcause the program to return to address 7FFF Hex. It is rec-ommended that the user either leave this location unpro-grammed or place an INTR instruction (all 0’s) in this locationto generate a software interrupt signaling an illegal condition.
Thus, the chip can detect the following illegal conditions:
1. Executing from undefined ROM.
2. Over “POP”ing the stack by having more returns thancalls.
When the software interrupt occurs, the user can re-initializethe stack pointer and do a recovery procedure before restart-ing (this recovery program is probably similar to that follow-ing reset, but might not contain the same program initializa-tion procedures). The recovery program should reset thesoftware interrupt pending bit using the RPND instruction.
www.national.com39
12.0 MICROWIRE/PLUSMICROWIRE/PLUS is a serial SPI compatible synchronouscommunications interface. The MICROWIRE/PLUS capabil-ity enables the device to interface with MICROWIRE/PLUSor SPI peripherals (i.e. A/D converters, display drivers, EE-PROMs etc.) and with other microcontrollers which supportthe MICROWIRE/PLUS or SPI interface. It consists of an8-bit serial shift register (SIO) with serial data input (SI), se-rial data output (SO) and serial shift clock (SK). Figure 29shows a block diagram of the MICROWIRE/PLUS logic.
The shift clock can be selected from either an internal sourceor an external source. Operating the MICROWIRE/PLUS ar-rangement with the internal clock source is called the Mastermode of operation. Similarly, operating the MICROWIRE/PLUS arrangement with an external shift clock is called theSlave mode of operation.
The CNTRL register is used to configure and control theMICROWIRE/PLUS mode. To use the MICROWIRE/PLUS,the MSEL bit in the CNTRL register is set to one. In the mas-ter mode, the SK clock rate is selected by the two bits, SL0and SL1, in the CNTRL register. Table 10 details the differentclock rates that may be selected.
TABLE 10. MICROWIRE/PLUSMaster Mode Clock Select
SL1 SL0 SK Period
0 0 2 x tC0 1 4 x tC1 x 8 x tC
Where tC is the instruction cycle clock
12.1 MICROWIRE/PLUS OPERATION
Setting the BUSY bit in the PSW register causes theMICROWIRE/PLUS to start shifting the data. It gets resetwhen eight data bits have been shifted. The user may resetthe BUSY bit by software to allow less than 8 bits to shift. Ifenabled, an interrupt is generated when eight data bits havebeen shifted. The device may enter the MICROWIRE/PLUSmode either as a Master or as a Slave. Figure 29 shows howtwo microcontroller devices and several peripherals may beinterconnected using the MICROWIRE/PLUS arrangements.
WARNING
The SIO register should only be loaded when the SK clock isin the idle phase. Loading the SIO register while the SK clockis in the active phase, will result in undefined data in the SIOregister.
Setting the BUSY flag when the input SK clock is in the ac-tive phase while in the MICROWIRE/PLUS is in the slavemode may cause the current SK clock for the SIO shift reg-ister to be narrow. For safety, the BUSY flag should only beset when the input SK clock is in the idle phase.
12.1.1 MICROWIRE/PLUS Master Mode Operation
In the MICROWIRE/PLUS Master mode of operation theshift clock (SK) is generated internally. The MICROWIREMaster always initiates all data exchanges. The MSEL bit inthe CNTRL register must be set to enable the SO and SKfunctions onto the G Port. The SO and SK pins must also beselected as outputs by setting appropriate bits in the Port Gconfiguration register. In the slave mode, the shift clockstops after 8 clock pulses. Table 11 summarizes the bit set-tings required for Master mode of operation.
DS100155-32
FIGURE 29. MICROWIRE/PLUS Application
www.national.com 40
12.0 MICROWIRE/PLUS (Continued)
12.1.2 MICROWIRE/PLUS Slave Mode Operation
In the MICROWIRE/PLUS Slave mode of operation the SKclock is generated by an external source. Setting the MSELbit in the CNTRL register enables the SO and SK functionsonto the G Port. The SK pin must be selected as an inputand the SO pin is selected as an output pin by setting and re-setting the appropriate bits in the Port G configuration regis-ter. Table 11 summarizes the settings required to enter theSlave mode of operation.
TABLE 11. MICROWIRE/PLUS Mode SettingsThis table assumes that the control flag MSEL is set.
G4 (SO) G5 (SK) G4 G5 Operation
Config. Bit Config. Bit Fun. Fun.
1 1 SO Int. MICROWIRE/PLUS
SK Master
0 1 TRI- Int. MICROWIRE/PLUS
STATE SK Master
1 0 SO Ext. MICROWIRE/PLUS
SK Slave
0 0 TRI- Ext. MICROWIRE/PLUS
STATE SK Slave
The user must set the BUSY flag immediately upon enteringthe Slave mode. This ensures that all data bits sent by theMaster is shifted properly. After eight clock pulses the BUSYflag is clear, the shift clock is stopped, and the sequencemay be repeated.
12.1.3 Alternate SK Phase Operation and SK IdlePolarity
The device allows either the normal SK clock or an alternatephase SK clock to shift data in and out of the SIO register. Inboth the modes the SK idle polarity can be either high or low.The polarity is selected by bit 5 of Port G data register. In thenormal mode data is shifted in on the rising edge of the SKclock and the data is shifted out on the falling edge of the SKclock. In the alternate SK phase operation, data is shifted inon the falling edge of the SK clock and shifted out on the ris-ing edge of the SK clock. Bit 6 of Port G configuration regis-ter selects the SK edge.
A control flag, SKSEL, allows either the normal SK clock orthe alternate SK clock to be selected. Resetting SKSELcauses the MICROWIRE/PLUS logic to be clocked from thenormal SK signal. Setting the SKSEL flag selects the alter-nate SK clock. The SKSEL is mapped into the G6 configura-tion bit. The SKSEL flag will power up in the reset condition,selecting the normal SK signal.
TABLE 12. MICROWIRE/PLUS Shift Clock Polarity and Sample/Shift Phase
Port G
SK Phase G6 (SKSEL)Config. Bit
G5 DataBit
SO Clocked OutOn:
SI Sampled On: SK IdlePhase
Normal 0 0 SK Falling Edge SK Rising Edge Low
Alternate 1 0 SK Rising Edge SK Falling Edge Low
Alternate 0 1 SK Rising Edge SK Falling Edge High
Normal 1 1 SK Falling Edge SK Rising Edge High
DS100155-33
FIGURE 30. MICROWIRE/PLUS SPI Mode Interface Timing, Normal SK Mode, SK Idle Phase being Low
DS100155-34
FIGURE 31. MICROWIRE/PLUS SPI Mode Interface Timing, Alternate SK Mode, SK Idle Phase being Low
www.national.com41
12.0 MICROWIRE/PLUS (Continued)
DS100155-35
FIGURE 32. MICROWIRE/PLUS SPI Mode Interface Timing, Alternate SK Mode, SK Idle Phase being High
DS100155-31
FIGURE 33. MICROWIRE/PLUS SPI Mode Interface Timing, Normal SK Mode, SK Idle Phase being High
www.national.com 42
13.0 Memory MapAll RAM, ports and registers (except A and PC) are mapped into data memory address space.
Address Contents
S/ADD REG
0000 to 006F On-Chip RAM bytes (112 bytes)
0070 to 007F Unused RAM Address Space (Reads AsAll Ones)
xx80 to xx93 Unused RAM Address Space (ReadsUndefined Data)
xx94 Port F data register, PORTFD
xx95 Port F configuration register, PORTFC
xx96 Port F input pins (read only), PORTFP
xx97 to xxAF Unused address space (ReadsUndefined Data)
xxB0 Timer T3 Lower Byte
xxB1 Timer T3 Upper Byte
xxB2 Timer T3 Autoload Register T3RA LowerByte
xxB3 Timer T3 Autoload Register T3RA UpperByte
xxB4 Timer T3 Autoload Register T3RB LowerByte
xxB5 Timer T3 Autoload Register T3RB UpperByte
xxB6 Timer T3 Control Register
xxB7 Comparator Select Register(Reg:CMPSL)
xxB8 UART Transmit Buffer (Reg:TBUF)
xxB9 UART Receive Buffer (Reg:RBUF)
xxBA UART Control and Status Register(Reg:ENU)
xxBB UART Receive Control and StatusRegister (Reg:ENUR)
xxBC UART Interrupt and Clock SourceRegister (Reg:ENUI)
xxBD UART Baud Register (Reg:BAUD)
xxBE UART Prescale Select Register(Reg:PSR)
xxBF Reserved for UART
xxC0 Timer T2 Lower Byte
xxC1 Timer T2 Upper Byte
xxC2 Timer T2 Autoload Register T2RA LowerByte
xxC3 Timer T2 Autoload Register T2RA UpperByte
xxC4 Timer T2 Autoload Register T2RB LowerByte
xxC5 Timer T2 Autoload Register T2RB UpperByte
xxC6 Timer T2 Control Register
xxC7 WATCHDOG Service Register(Reg:WDSVR)
xxC8 MIWU Edge Select Register(Reg:WKEDG)
Address Contents
S/ADD REG
xxC9 MIWU Enable Register (Reg:WKEN)
xxCA MIWU Pending Register (Reg:WKPND)
xxCB to xxCF Reserved
xxD0 Port L Data Register
xxD1 Port L Configuration Register
xxD2 Port L Input Pins (Read Only)
xxD3 Reserved for Port L
xxD4 Port G Data Register
xxD5 Port G Configuration Register
xxD6 Port G Input Pins (Read Only)
xxD7 Port I Input Pins (Read Only) (Actuallyreads Port F input pins)
xxD8 Port C Data Register
xxD9 Port C Configuration Register
xxDA Port C Input Pins (Read Only)
xxDB Reserved for Port C
xxDC Port D
xxDD to xxDF Reserved for Port D
xxE0 to xxE5 Reserved for EE Control Registers
xxE6 Timer T1 Autoload Register T1RB LowerByte
xxE7 Timer T1 Autoload Register T1RB UpperByte
xxE8 ICNTRL Register
xxE9 MICROWIRE/PLUS Shift Register
xxEA Timer T1 Lower Byte
xxEB Timer T1 Upper Byte
xxEC Timer T1 Autoload Register T1RA LowerByte
xxED Timer T1 Autoload Register T1RA UpperByte
xxEE CNTRL Control Register
xxEF PSW Register
xxF0 to FB On-Chip RAM Mapped as Registers
xxFC X Register
xxFD SP Register
xxFE B Register
xxFF S Register
0100–017F On-Chip 128 RAM Bytes
0200–027F On-Chip 128 RAM Bytes (Reads asundefined data on COP8SGE)
0300–037F On-Chip 128 RAM Bytes (Reads asundefined data on COP8SGE)
Note: Reading memory locations 0070H–007FH (Segment 0) will return allones. Reading unused memory locations 0080H–0093H (Segment 0)will return undefined data. Reading memory locations from other Seg-ments (i.e., Segment 4, Segment 5, … etc.) will return undefined data.
www.national.com43
14.0 Instruction Set
14.1 INTRODUCTION
This section defines the instruction set of the COPSAx7Family members. It contains information about the instruc-tion set features, addressing modes and types.
14.2 INSTRUCTION FEATURES
The strength of the instruction set is based on the followingfeatures:
• Mostly single-byte opcode instructions minimize programsize.
• One instruction cycle for the majority of single-byte in-structions to minimize program execution time.
• Many single-byte, multiple function instructions such asDRSZ.
• Three memory mapped pointers: two for register indirectaddressing, and one for the software stack.
• Sixteen memory mapped registers that allow an opti-mized implementation of certain instructions.
• Ability to set, reset, and test any individual bit in datamemory address space, including the memory-mappedI/O ports and registers.
• Register-Indirect LOAD and EXCHANGE instructionswith optional automatic post-incrementing or decrement-ing of the register pointer. This allows for greater effi-ciency (both in cycle time and program code) in loading,walking across and processing fields in data memory.
• Unique instructions to optimize program size andthroughput efficiency. Some of these instructions areDRSZ, IFBNE, DCOR, RETSK, VIS and RRC.
14.3 ADDRESSING MODES
The instruction set offers a variety of methods for specifyingmemory addresses. Each method is called an addressingmode. These modes are classified into two categories: oper-and addressing modes and transfer-of-control addressingmodes. Operand addressing modes are the various meth-ods of specifying an address for accessing (reading or writ-ing) data. Transfer-of-control addressing modes are used inconjunction with jump instructions to control the executionsequence of the software program.
14.3.1 Operand Addressing Modes
The operand of an instruction specifies what memory loca-tion is to be affected by that instruction. Several different op-erand addressing modes are available, allowing memory lo-cations to be specified in a variety of ways. An instructioncan specify an address directly by supplying the specific ad-dress, or indirectly by specifying a register pointer. The con-tents of the register (or in some cases, two registers) point tothe desired memory location. In the immediate mode, thedata byte to be used is contained in the instruction itself.
Each addressing mode has its own advantages and disad-vantages with respect to flexibility, execution speed, and pro-gram compactness. Not all modes are available with all in-structions. The Load (LD) instruction offers the largestnumber of addressing modes.
The available addressing modes are:
• Direct
• Register B or X Indirect
• Register B or X Indirect with Post-Incrementing/Decrementing
• Immediate
• Immediate Short
• Indirect from Program Memory
The addressing modes are described below. Each descrip-tion includes an example of an assembly language instruc-tion using the described addressing mode.
Direct. The memory address is specified directly as a byte inthe instruction. In assembly language, the direct address iswritten as a numerical value (or a label that has been definedelsewhere in the program as a numerical value).
Example: Load Accumulator Memory Direct
LD A,05
Reg/Data Contents Contents
Memory Before After
Accumulator XX Hex A6 Hex
Memory Location A6 Hex A6 Hex
0005 Hex
Register B or X Indirect. The memory address is specifiedby the contents of the B Register or X register (pointer regis-ter). In assembly language, the notation [B] or [X] specifieswhich register serves as the pointer.
Example: Exchange Memory with Accumulator, B Indirect
X A,[B]
Reg/Data Contents Contents
Memory Before After
Accumulator 01 Hex 87 Hex
Memory Location 87 Hex 01 Hex
0005 Hex
B Pointer 05 Hex 05 Hex
Register B or X Indirect with Post-Incrementing/Decrementing. The relevant memory address is specifiedby the contents of the B Register or X register (pointer regis-ter). The pointer register is automatically incremented ordecremented after execution, allowing easy manipulation ofmemory blocks with software loops. In assembly language,the notation [B+], [B−], [X+], or [X−] specifies which registerserves as the pointer, and whether the pointer is to be incre-mented or decremented.
Example: Exchange Memory with Accumulator, B Indirectwith Post-Increment
X A,[B+]
Reg/Data Contents Contents
Memory Before After
Accumulator 03 Hex 62 Hex
Memory Location 62 Hex 03 Hex
0005 Hex
B Pointer 05 Hex 06 Hex
Intermediate. The data for the operation follows the instruc-tion opcode in program memory. In assembly language, thenumber sign character (#) indicates an immediate operand.
www.national.com 44
14.0 Instruction Set (Continued)
Example: Load Accumulator Immediate
LD A,#05
Reg/Data Contents Contents
Memory Before After
Accumulator XX Hex 05 Hex
Immediate Short. This is a special case of an immediate in-struction. In the “Load B immediate” instruction, the 4-bit im-mediate value in the instruction is loaded into the lowernibble of the B register. The upper nibble of the B register isreset to 0000 binary.
Example: Load B Register Immediate Short
LD B,#7
Reg/Data Contents Contents
Memory Before After
B Pointer 12 Hex 07 Hex
Indirect from Program Memory. This is a special case ofan indirect instruction that allows access to data tablesstored in program memory. In the “Load Accumulator Indi-rect” (LAID) instruction, the upper and lower bytes of the Pro-gram Counter (PCU and PCL) are used temporarily as apointer to program memory. For purposes of accessing pro-gram memory, the contents of the Accumulator and PCL areexchanged. The data pointed to by the Program Counter isloaded into the Accumulator, and simultaneously, the originalcontents of PCL are restored so that the program can re-sume normal execution.
Example: Load Accumulator Indirect
LAID
Reg/Data Contents Contents
Memory Before After
PCU 04 Hex 04 Hex
PCL 35 Hex 36 Hex
Accumulator 1F Hex 25 Hex
Memory Location 25 Hex 25 Hex
041F Hex
14.3.2 Tranfer-of-Control Addressing Modes
Program instructions are usually executed in sequential or-der. However, Jump instructions can be used to change thenormal execution sequence. Several transfer-of-control ad-dressing modes are available to specify jump addresses.
A change in program flow requires a non-incrementalchange in the Program Counter contents. The ProgramCounter consists of two bytes, designated the upper byte(PCU) and lower byte (PCL). The most significant bit of PCUis not used, leaving 15 bits to address the program memory.
Different addressing modes are used to specify the new ad-dress for the Program Counter. The choice of addressingmode depends primarily on the distance of the jump. Fartherjumps sometimes require more instruction bytes in order tocompletely specify the new Program Counter contents.
The available transfer-of-control addressing modes are:
• Jump Relative
• Jump Absolute
• Jump Absolute Long
• Jump Indirect
The transfer-of-control addressing modes are described be-low. Each description includes an example of a Jump in-struction using a particular addressing mode, and the effecton the Program Counter bytes of executing that instruction.
Jump Relative. In this 1-byte instruction, six bits of the in-struction opcode specify the distance of the jump from thecurrent program memory location. The distance of the jumpcan range from −31 to +32. A JP+1 instruction is not allowed.The programmer should use a NOP instead.
Example: Jump Relative
JP 0A
Reg Contents Contents
Before After
PCU 02 Hex 02 Hex
PCL 05 Hex 0F Hex
Jump Absolute. In this 2-byte instruction, 12 bits of the in-struction opcode specify the new contents of the ProgramCounter. The upper three bits of the Program Counter re-main unchanged, restricting the new Program Counter ad-dress to the same 4 kbyte address space as the current in-struction.
(This restriction is relevant only in devices using more thanone 4 kbyte program memory space.)
Example: Jump Absolute
JMP 0125
Reg Contents Contents
Before After
PCU 0C Hex 01 Hex
PCL 77 Hex 25 Hex
Jump Absolute Long. In this 3-byte instruction, 15 bits ofthe instruction opcode specify the new contents of the Pro-gram Counter.
Example: Jump Absolute Long
JMP 03625
Reg/ Contents Contents
Memory Before After
PCU 42 Hex 36 Hex
PCL 36 Hex 25 Hex
www.national.com45
14.0 Instruction Set (Continued)
Jump Indirect. In this 1-byte instruction, the lower byte ofthe jump address is obtained from a table stored in programmemory, with the Accumulator serving as the low order byteof a pointer into program memory. For purposes of access-ing program memory, the contents of the Accumulator arewritten to PCL (temporarily). The data pointed to by the Pro-gram Counter (PCH/PCL) is loaded into PCL, while PCH re-mains unchanged.
Example: Jump Indirect
JID
Reg/ Contents Contents
Memory Before After
PCU 01 Hex 01 Hex
PCL C4 Hex 32 Hex
Accumulator 26 Hex 26 Hex
Memory
Location 32 Hex 32 Hex
0126 Hex
The VIS instruction is a special case of the Indirect Transferof Control addressing mode, where the double-byte vectorassociated with the interrupt is transferred from adjacent ad-dresses in program memory into the Program Counter in or-der to jump to the associated interrupt service routine.
14.4 INSTRUCTION TYPES
The instruction set contains a wide variety of instructions.The available instructions are listed below, organized into re-lated groups.
Some instructions test a condition and skip the next instruc-tion if the condition is not true. Skipped instructions are ex-ecuted as no-operation (NOP) instructions.
14.4.1 Arithmetic Instructions
The arithmetic instructions perform binary arithmetic such asaddition and subtraction, with or without the Carry bit.
Add (ADD)
Add with Carry (ADC)
Subtract (SUB)
Subtract with Carry (SUBC)
Increment (INC)
Decrement (DEC)
Decimal Correct (DCOR)
Clear Accumulator (CLR)
Set Carry (SC)
Reset Carry (RC)
14.4.2 Transfer-of-Control Instructions
The transfer-of-control instructions change the usual se-quential program flow by altering the contents of the Pro-gram Counter. The Jump to Subroutine instructions save theProgram Counter contents on the stack before jumping; theReturn instructions pop the top of the stack back into theProgram Counter.
Jump Relative (JP)
Jump Absolute (JMP)
Jump Absolute Long (JMPL)
Jump Indirect (JID)
Jump to Subroutine (JSR)
Jump to Subroutine Long (JSRL)
Return from Subroutine (RET)
Return from Subroutine and Skip (RETSK)
Return from Interrupt (RETI)
Software Trap Interrupt (INTR)
Vector Interrupt Select (VIS)
14.4.3 Load and Exchange Instructions
The load and exchange instructions write byte values in reg-isters or memory. The addressing mode determines thesource of the data.
Load (LD)
Load Accumulator Indirect (LAID)
Exchange (X)
14.4.4 Logical Instructions
The logical instructions perform the operations AND, OR,and XOR (Exclusive OR). Other logical operations can beperformed by combining these basic operations. For ex-ample, complementing is accomplished by exclusiveORingthe Accumulator with FF Hex.
Logical AND (AND)
Logical OR (OR)
Exclusive OR (XOR)
14.4.5 Accumulator Bit Manipulation Instructions
The Accumulator bit manipulation instructions allow the userto shift the Accumulator bits and to swap its two nibbles.
Rotate Right Through Carry (RRC)
Rotate Left Through Carry (RLC)
Swap Nibbles of Accumulator (SWAP)
14.4.6 Stack Control Instructions
Push Data onto Stack (PUSH)
Pop Data off of Stack (POP)
14.4.7 Memory Bit Manipulation Instructions
The memory bit manipulation instructions allow the user toset and reset individual bits in memory.
Set Bit (SBIT)
Reset Bit (RBIT)
Reset Pending Bit (RPND)
14.4.8 Conditional Instructions
The conditional instruction test a condition. If the condition istrue, the next instruction is executed in the normal manner; ifthe condition is false, the next instruction is skipped.
If Equal (IFEQ)
If Not Equal (IFNE)
If Greater Than (IFGT)
If Carry (IFC)
If Not Carry (IFNC)
If Bit (IFBIT)
If B Pointer Not Equal (IFBNE)
And Skip if Zero (ANDSZ)
Decrement Register and Skip if Zero (DRSZ)
www.national.com 46
14.0 Instruction Set (Continued)
14.4.9 No-Operation Instruction
The no-operation instruction does nothing, except to occupyspace in the program memory and time in execution.
No-Operation (NOP)Note: The VIS is a special case of the Indirect Transfer of Control addressing
mode, where the double byte vector associated with the interrupt istransferred from adjacent addresses in the program memory into theprogram counter (PC) in order to jump to the associated interrupt ser-vice routine.
14.5 REGISTER AND SYMBOL DEFINITION
The following abbreviations represent the nomenclatureused in the instruction description and the COP8cross-assembler.
Registers
A 8-Bit Accumulator Register
B 8-Bit Address Register
X 8-Bit Address Register
SP 8-Bit Stack Pointer Register
PC 15-Bit Program Counter Register
PU Upper 7 Bits of PC
PL Lower 8 Bits of PC
Registers
C 1 Bit of PSW Register for Carry
HC 1 Bit of PSW Register for Half Carry
GIE 1 Bit of PSW Register for Global InterruptEnable
VU Interrupt Vector Upper Byte
VL Interrupt Vector Lower Byte
Symbols
[B] Memory Indirectly Addressed by B Register
[X] Memory Indirectly Addressed by X Register
MD Direct Addressed Memory
Mem Direct Addressed Memory or [B]
Meml Direct Addressed Memory or [B] orImmediate Data
Imm 8-Bit Immediate Data
Reg Register Memory: Addresses F0 to FF(Includes B, X and SP)
Bit Bit Number (0 to 7)
← Loaded with
↔ Exchanged with
14.6 INSTRUCTION SET SUMMARY
ADD A,Meml ADD A←A + Meml
ADC A,Meml ADD with Carry A←A + Meml + C, C←Carry,
HC←Half Carry
SUBC A,Meml Subtract with Carry A←A − MemI + C, C←Carry,
HC←Half Carry
AND A,Meml Logical AND A←A and Meml
ANDSZ A,Imm Logical AND Immed., Skip if Zero Skip next if (A and Imm) = 0
OR A,Meml Logical OR A←A or Meml
XOR A,Meml Logical EXclusive OR A←A xor Meml
IFEQ MD,Imm IF EQual Compare MD and Imm, Do next if MD = Imm
IFEQ A,Meml IF EQual Compare A and Meml, Do next if A = Meml
IFNE A,Meml IF Not Equal Compare A and Meml, Do next if A ≠ Meml
IFGT A,Meml IF Greater Than Compare A and Meml, Do next if A > Meml
IFBNE # If B Not Equal Do next if lower 4 bits of B ≠ Imm
DRSZ Reg Decrement Reg., Skip if Zero Reg←Reg − 1, Skip if Reg = 0
SBIT #,Mem Set BIT 1 to bit, Mem (bit = 0 to 7 immediate)
RBIT #,Mem Reset BIT 0 to bit, Mem
IFBIT #,Mem IF BIT If bit #, A or Mem is true do next instruction
RPND Reset PeNDing Flag Reset Software Interrupt Pending Flag
X A,Mem EXchange A with Memory A↔Mem
X A,[X] EXchange A with Memory [X] A↔[X]
LD A,Meml LoaD A with Memory A←Meml
LD A,[X] LoaD A with Memory [X] A←[X]
LD B,Imm LoaD B with Immed. B←Imm
LD Mem,Imm LoaD Memory Immed. Mem←Imm
LD Reg,Imm LoaD Register Memory Immed. Reg←Imm
X A, [B ±] EXchange A with Memory [B] A↔[B], (B←B ±1)
X A, [X ±] EXchange A with Memory [X] A↔[X], (X←X ±1)
www.national.com47
14.0 Instruction Set (Continued)
LD A, [B±] LoaD A with Memory [B] A←[B], (B←B ±1)
LD A, [X±] LoaD A with Memory [X] A←[X], (X←X±1)
LD [B±],Imm LoaD Memory [B] Immed. [B]←Imm, (B←B±1)
CLR A CLeaR A A←0
INC A INCrement A A←A + 1
DEC A DECrement A A←A − 1
LAID Load A InDirect from ROM A←ROM (PU,A)
DCOR A Decimal CORrect A A←BCD correction of A (follows ADC, SUBC)
RRC A Rotate A Right thru C C→A7→…→A0→C
RLC A Rotate A Left thru C C←A7←…←A0←C, HC←A0
SWAP A SWAP nibbles of A A7…A4↔A3…A0
SC Set C C←1, HC←1
RC Reset C C←0, HC←0
IFC IF C IF C is true, do next instruction
IFNC IF Not C If C is not true, do next instruction
POP A POP the stack into A SP←SP + 1, A←[SP]
PUSH A PUSH A onto the stack [SP]←A, SP←SP − 1
VIS Vector to Interrupt Service Routine PU←[VU], PL←[VL]
JMPL Addr. Jump absolute Long PC←ii (ii = 15 bits, 0 to 32k)
JMP Addr. Jump absolute PC9…0←i (i = 12 bits)
JP Disp. Jump relative short PC←PC + r (r is −31 to +32, except 1)
JSRL Addr. Jump SubRoutine Long [SP]←PL, [SP−1]←PU,SP−2, PC←ii
JSR Addr. Jump SubRoutine [SP]←PL, [SP−1]←PU,SP−2, PC9…0←i
JID Jump InDirect PL←ROM (PU,A)
RET RETurn from subroutine SP + 2, PL←[SP], PU←[SP−1]
RETSK RETurn and SKip SP + 2, PL←[SP],PU←[SP−1],
skip next instruction
RETI RETurn from Interrupt SP + 2, PL ←[SP],PU←[SP−1],GIE←1
INTR Generate an Interrupt [SP]←PL, [SP−1]←PU, SP−2, PC←0FF
NOP No OPeration PC←PC + 1
www.national.com 48
14.0 Instruction Set (Continued)
14.7 INSTRUCTION EXECUTION TIME
Most instructions are single byte (with immediate addressingmode instructions taking two bytes).
Most single byte instructions take one cycle time to execute.
Skipped instructions require x number of cycles to beskipped, where x equals the number of bytes in the skippedinstruction opcode.
See the BYTES and CYCLES per INSTRUCTION table fordetails.
Bytes and Cycles per Instruction
The following table shows the number of bytes and cycles foreach instruction in the format of byte/cycle.
Arithmetic and Logic Instructions
[B] Direct Immed.
ADD 1/1 3/4 2/2
ADC 1/1 3/4 2/2
SUBC 1/1 3/4 2/2
AND 1/1 3/4 2/2
OR 1/1 3/4 2/2
XOR 1/1 3/4 2/2
IFEQ 1/1 3/4 2/2
IFGT 1/1 3/4 2/2
IFBNE 1/1
DRSZ 1/3
SBIT 1/1 3/4
RBIT 1/1 3/4
IFBIT 1/1 3/4
RPND 1/1
Instructions Using A & C
CLRA 1/1
INCA 1/1
DECA 1/1
LAID 1/3
DCORA 1/1
RRCA 1/1
RLCA 1/1
SWAPA 1/1
SC 1/1
RC 1/1
IFC 1/1
IFNC 1/1
PUSHA 1/3
POPA 1/3
ANDSZ 2/2
Transfer of Control Instructions
JMPL 3/4
JMP 2/3
JP 1/3
JSRL 3/5
JSR 2/5
JID 1/3
VIS 1/5
RET 1/5
RETSK 1/5
RETI 1/5
INTR 1/7
NOP 1/1
Memory Transfer InstructionsRegister Direct Immed. Register Indirect
Indirect Auto Incr. & Decr.
[B] [X] [B+, B−] [X+, X−]
X A, (Note 16) 1/1 1/3 2/3 1/2 1/3
LD A, (Note 16) 1/1 1/3 2/3 2/2 1/2 1/3
LD B, Imm 1/1 (If B < 16)
LD B, Imm 2/2 (If B > 15)
LD Mem, Imm 2/2 3/3 2/2
LD Reg, Imm 2/3
IFEQ MD, Imm 3/3
Note 16: = > Memory location addressed by B or X or directly.
www.national.com49
14.0 Instruction Set (Continued)
14.8
OP
CO
DE
TA
BLE
Upp
erN
ibbl
e
FE
DC
BA
98
76
54
32
10
LowerNibble
JP−
15JP
−31
LD0F
0,#i
DR
SZ
0F0
RR
CA
RC
AD
CA
,#i
AD
CA
,[B]
IFB
IT0,
[B]
AN
DS
ZA
,#i
LDB
,#0F
IFB
NE
0JS
Rx0
00–
x0F
FJM
Px0
00–
x0F
FJP
+17
INT
R0
JP−
14JP
−30
LD0F
1,#i
DR
SZ
0F1
*S
CS
UB
CA
,#i
SU
BC
A,[B
]IF
BIT
1,[B
]*
LDB
,#0E
IFB
NE
1JS
Rx1
00–
x1F
FJM
Px1
00–
x1F
FJP
+18
JP+
21
JP−
13JP
−29
LD0F
2,#i
DR
SZ
0F2
XA
,[X+
]X
A,[B
+]
IFE
QA
,#i
IFE
QA
,[B]
IFB
IT2,
[B]
*LD
B,#
0DIF
BN
E2
JSR
x200
–x2
FF
JMP
x200
–x2
FF
JP+
19JP
+3
2
JP−
12JP
−28
LD0F
3,#i
DR
SZ
0F3
XA
,[X−
]X
A,[B
−]
IFG
TA
,#i
IFG
TA
,[B]
IFB
IT3,
[B]
*LD
B,#
0CIF
BN
E3
JSR
x300
–x3
FF
JMP
x300
–x3
FF
JP+
20JP
+4
3
JP−
11JP
−27
LD0F
4,#i
DR
SZ
0F4
VIS
LAID
AD
DA
,#i
AD
DA
,[B]
IFB
IT4,
[B]
CLR
ALD
B,#
0BIF
BN
E4
JSR
x400
–x4
FF
JMP
x400
–x4
FF
JP+
21JP
+5
4
JP−
10JP
−26
LD0F
5,#i
DR
SZ
0F5
RP
ND
JID
AN
DA
,#i
AN
DA
,[B]
IFB
IT5,
[B]
SW
AP
ALD
B,#
0AIF
BN
E5
JSR
x500
–x5
FF
JMP
x500
–x5
FF
JP+
22JP
+6
5
JP−
9JP
−25
LD0F
6,#i
DR
SZ
0F6
XA
,[X]
XA
,[B]
XO
RA
,#i
XO
RA
,[B]
IFB
IT6,
[B]
DC
OR
ALD
B,#
09IF
BN
E6
JSR
x600
–x6
FF
JMP
x600
–x6
FF
JP+
23JP
+7
6
JP−
8JP
−24
LD0F
7,#i
DR
SZ
0F7
**
OR
A,#
iO
RA
,[B]
IFB
IT7,
[B]
PU
SH
ALD
B,#
08IF
BN
E7
JSR
x700
–x7
FF
JMP
x700
–x7
FF
JP+
24JP
+8
7
JP−
7JP
−23
LD0F
8,#i
DR
SZ
0F8
NO
PR
LCA
LDA
,#i
IFC
SB
IT0,
[B]
RB
IT0,
[B]
LDB
,#07
IFB
NE
8JS
Rx8
00–
x8F
FJM
Px8
00–
x8F
FJP
+25
JP+
98
JP−
6JP
−22
LD0F
9,#i
DR
SZ
0F9
IFN
EA
,[B]
IFE
QM
d,#i
IFN
EA
,#i
IFN
CS
BIT
1,[B
]R
BIT
1,[B
]LD
B,#
06IF
BN
E9
JSR
x900
–x9
FF
JMP
x900
–x9
FF
JP+
26JP
+10
9
JP−
5JP
−21
LD0F
A,
#iD
RS
Z0F
ALD
A,[X
+]
LDA
,[B+
]LD
[B+
],#i
INC
AS
BIT
2,[B
]R
BIT
2,[B
]LD
B,#
05IF
BN
E0A
JSR
xA00
–xA
FF
JMP
xA00
–xA
FF
JP+
27JP
+11
A
JP−
4JP
−20
LD0F
B,
#iD
RS
Z0F
BLD
A,[X
−]
LDA
,[B−
]LD
[B−
],#i
DE
CA
SB
IT3,
[B]
RB
IT3,
[B]
LDB
,#04
IFB
NE
0BJS
RxB
00–
xBF
FJM
PxB
00–
xBF
FJP
+28
JP+
12B
JP−
3JP
−19
LD0F
C,
#iD
RS
Z0F
CLD
Md,
#iJM
PL
XA
,Md
PO
PA
SB
IT4,
[B]
RB
IT4,
[B]
LDB
,#03
IFB
NE
0CJS
RxC
00–
xCF
FJM
PxC
00–
xCF
FJP
+29
JP+
13C
JP−
2JP
−18
LD0F
D,
#iD
RS
Z0F
DD
IRJS
RL
LD A,M
dR
ET
SK
SB
IT5,
[B]
RB
IT5,
[B]
LDB
,#02
IFB
NE
0DJS
RxD
00–
xDF
FJM
PxD
00–
xDF
FJP
+30
JP+
14D
JP−
1JP
−17
LD0F
E,
#iD
RS
Z0F
ELD A,[X
]LD A,[B
]LD [B],#
iR
ET
SB
IT6,
[B]
RB
IT6,
[B]
LDB
,#01
IFB
NE
0EJS
RxE
00–
xEF
FJM
PxE
00–
xEF
FJP
+31
JP+
15E
JP−
0JP
−16
LD0F
F,
#iD
RS
Z0F
F*
*LD
B,#
iR
ET
IS
BIT
7,[B
]R
BIT
7,[B
]LD
B,#
00IF
BN
E0F
JSR
xF00
–xF
FF
JMP
xF00
–xF
FF
JP+
32JP
+16
F
Whe
re,
iis
the
imm
edia
teda
taM
dis
adi
rect
lyad
dres
sed
mem
ory
loca
tion
*is
anun
used
opco
deT
heop
code
60H
exis
also
the
opco
defo
rIF
BIT
#i,A
www.national.com 50
15.0 Development Tools Support
15.1 OVERVIEW
National is engaged with an international community of inde-pendent 3rd party vendors who provide hardware and soft-ware development tool support. Through National’s interac-tion and guidance, these tools cooperate to form a choice ofsolutions that fits each developer’s needs.
This section provides a summary of the tool and develop-ment kits currently available. Up-to-date information, selec-tion guides, free tools, demos, updates, and purchase infor-mation can be obtained at our web site at:www.national.com/cop8.
15.2 SUMMARY OF TOOLS
COP8 Evaluation Tools
• COP8–NSEVAL: Free Software Evaluation package forWindows. A fully integrated evaluation environment forCOP8, including versions of WCOP8 IDE (Integrated De-velopment Environment), COP8-NSASM, COP8-MLSIM,COP8C, DriveWay™ COP8, Manuals, and other COP8information.
• COP8–MLSIM: Free Instruction Level Simulator tool forWindows. For testing and debugging software instruc-tions only (No I/O or interrupt support).
• COP8–EPU: Very Low cost COP8 Evaluation & Pro-gramming Unit. Windows based evaluation andhardware-simulation tool, with COP8 device programmerand erasable samples. Includes COP8-NSDEV, Drive-way COP8 Demo, MetaLink Debugger, I/O cables andpower supply.
• COP8–EVAL-HIxx: Low cost target application evalua-tion and development board for COP8Sx Families, fromHilton Inc. Real-time environment with integrated A/D,Temp Sensor, and Peripheral I/O.
• COP8–EVAL-ICUxx: Very Low cost evaluation and de-sign test board for COP8ACC and COP8SGx Families,from ICU. Real-time environment with add-on A/D, D/A,and EEPROM. Includes software routines and referencedesigns.
• Manuals, Applications Notes, Literature: Available freefrom our web site at: www.national.com/cop8.
COP8 Integrated Software/Hardware Design Develop-ment Kits
• COP8-EPU: Very Low cost Evaluation & ProgrammingUnit. Windows based development and hardware-simulation tool for COPSx/xG families, with COP8 deviceprogrammer and samples. Includes COP8-NSDEV,Driveway COP8 Demo, MetaLink Debugger, cables andpower supply.
• COP8-DM: Moderate cost Debug Module from MetaLink.A Windows based, real-time in-circuit emulation tool withCOP8 device programmer. Includes COP8-NSDEV,DriveWay COP8 Demo, MetaLink Debugger, power sup-ply, emulation cables and adapters.
COP8 Development Languages and Environments
• COP8-NSASM: Free COP8 Assembler v5 for Win32.Macro assembler, linker, and librarian for COP8 softwaredevelopment. Supports all COP8 devices. (DOS/Win16v4.10.2 available with limited support). (Compatible withWCOP8 IDE, COP8C, and DriveWay COP8).
• COP8-NSDEV: Very low cost Software DevelopmentPackage for Windows. An integrated development envi-ronment for COP8, including WCOP8 IDE, COP8C (lim-ited version), COP8-NSASM, COP8-MLSIM.
• COP8C: Moderately priced C Cross-Compiler and CodeDevelopment System from Byte Craft (no code limit). In-cludes BCLIDE (Byte Craft Limited Integrated Develop-ment Environment) for Win32, editor, optimizing C Cross-Compiler, macro cross assembler, BC-Linker, andMetaLink tools support. (DOS/SUN versions available;Compiler is installable under WCOP8 IDE; Compatiblewith DriveWay COP8).
• EWCOP8-KS: Very Low cost ANSI C-Compiler and Em-bedded Workbench from IAR (Kickstart version:COP8Sx/Fx only with 2k code limit; No FP). A fully inte-grated Win32 IDE, ANSI C-Compiler, macro assembler,editor, linker, Liberian, C-Spy simulator/debugger, PLUSMetaLink EPU/DM emulator support.
• EWCOP8-AS: Moderately priced COP8 Assembler andEmbedded Workbench from IAR (no code limit). A fully in-tegrated Win32 IDE, macro assembler, editor, linker, li-brarian, and C-Spy high-level simulator/debugger withI/O and interrupts support. (Upgradeable with optionalC-Compiler and/or MetaLink Debugger/Emulator sup-port).
• EWCOP8-BL: Moderately priced ANSI C-Compiler andEmbedded Workbench from IAR (Baseline version: AllCOP8 devices; 4k code limit; no FP). A fully integratedWin32 IDE, ANSI C-Compiler, macro assembler, editor,linker, librarian, and C-Spy high-level simulator/debugger.(Upgradeable; CWCOP8-M MetaLink tools interface sup-port optional).
• EWCOP8: Full featured ANSI C-Compiler and Embed-ded Workbench for Windows from IAR (no code limit). Afully integrated Win32 IDE, ANSI C-Compiler, macro as-sembler, editor, linker, librarian, and C-Spy high-levelsimulator/debugger. (CWCOP8-M MetaLink tools inter-face support optional).
• EWCOP8-M: Full featured ANSI C-Compiler and Embed-ded Workbench for Windows from IAR (no code limit). Afully integrated Win32 IDE, ANSI C-Compiler, macro as-sembler, editor, linker, librarian, C-Spy high-levelsimulator/debugger, PLUS MetaLink debugger/hardwareinterface (CWCOP8-M).
COP8 Productivity Enhancement Tools
• WCOP8 IDE: Very Low cost IDE (Integrated Develop-ment Environment) from KKD. Supports COP8C, COP8-NSASM, COP8-MLSIM, DriveWay COP8, and MetaLinkdebugger under a common Windows Project Manage-ment environment. Code development, debug, and emu-lation tools can be launched from the project windowframework.
• DriveWay-COP8: Low cost COP8 Peripherals CodeGeneration tool from Aisys Corporation. Automaticallygenerates tested and documented C or Assembly sourcecode modules containing I/O drivers and interrupt han-dlers for each on-chip peripheral. Application specificcode can be inserted for customization using the inte-grated editor. (Compatible with COP8-NSASM, COP8C,and WCOP8 IDE.)
• COP8-UTILS: Free set of COP8 assembly code ex-amples, device drivers, and utilities to speed up code de-velopment.
www.national.com51
15.0 Development Tools Support(Continued)
• COP8-MLSIM: Free Instruction Level Simulator tool forWindows. For testing and debugging software instruc-tions only (No I/O or interrupt support).
COP8 Real-Time Emulation Tools
• COP8-DM: MetaLink Debug Module. A moderatelypriced real-time in-circuit emulation tool, with COP8 de-vice programmer. Includes MetaLink Debugger, powersupply, emulation cables and adapters.
• IM-COP8: MetaLink iceMASTER®. A full featured, real-time in-circuit emulator for COP8 devices. Includes
COP8-NSDEV, Driveway COP8 Demo, MetaLink Win-dows Debugger, and power supply. Package-specificprobes and surface mount adaptors are ordered sepa-rately.
COP8 Device Programmer Support
• MetaLink’s EPU and Debug Module include developmentdevice programming capability for COP8 devices.
• Third-party programmers and automatic handling equip-ment cover needs from engineering prototype and pilotproduction, to full production environments.
• Factory programming available for high-volume require-ments.
15.3 TOOLS ORDERING NUMBERS FOR THE COP8SGx FAMILY DEVICES
Note: The following order numbers apply to the COP8 devices in this datasheet only.
Vendor Tools Order Number Cost Notes
National COP8-NSEVAL COP8-NSEVAL Free Web site download
COP8-NSASM COP8-NSASM Free Included in EPU and DM. Web site download
COP8-MLSIM COP8-MLSIM Free Included in EPU and DM. Web site download
COP8-NSDEV COP8-NSDEV VL Included in EPU and DM. Order CD from website
COP8-EPU COP8SG-EPU (-1 or -2) VL -1 = 110V, -2 = 220V; Included p/s, 40 pin DIP targetcable, manuals, software, 16/20/28/40 DIP OTPprogramming socket; add DM target adapter or OTPadapter (if needed)
COP8-DM COP8SG-DM (10 MHz) M Included p/s, 28/40/44 pin DIP/SO/PLCC targetcables, manuals, software, 16/20/28/40 DIP/SO and44 PLCC programming socket; add OTP adapter ortarget adapter (if needed)
DM TargetAdapters
DM-COP8/20D-SO VL 20 pin DIP to SO converter
DM-COP8/20D-16D VL 20 pin DIP to 16 pin DIP converter
DM-COP8/20D VL 20 pin DIP target cable
DM-COP8/28D-28CSP L 28 pin DIP to 28 pin CSP converter
DM-COP8/44P-44Q L 44 pin PLCC to 44 QFP converter
DevelopmentDevices
COP8FGx7 VL 8k or 32k Eraseable or OTP devices
OTPProgrammingAdapters
COP8SA-PGMA L For programming 16/20/28 SOIC and 44 PLCC on theEPU
COP8-PGMA-44QFP L For programming 44 QFP on any programmer
COP8-PGMA-28CSP L For programming 28 CSP on any programmer
COP8-PGMA-28SO VL For programming 16/20/28 SOIC on any programmer
IM-COP8 Call MetaLink
www.national.com 52
15.0 Development Tools Support (Continued)
MetaLink COP8-EPU EPU-COP8SG VL 1 = 110V, 2 = 220V; included p/s, 40 pin DIP targetcable, manuals, software, 16/20/28/40 DIP OTPprogramming socket; add DM target adapter or OTPadapter (if needed)
COP8-DM DM5-COP8-FGx (15MHz) or DM4-COP8-SGx(10 MHz), plus PS-10,plus DM-COP8/xxx (ie.28D)
M Included p/s (PS-10), target cable of choice (DIP orPLCC; i.e. DM-COP8/28D), 16/20/28/40 DIP/SO and44 PLCC programming sockets. Add OTP adapter (ifneeded) and target adapter (if needed)
DM TargetAdapters
MHW-CNVxx (xx = 33, 34etc.)
L DM target converters for16DIP/20SO/28SO/44QFP/28CSP; (i.e. MHW-CNV38for 20 pin DIP to SO package converter)
OTPProgrammingAdapters
MHW-COP8-PGMA-DS L For programming 16/20/28 SOIC and 44 PLCC on theEPU
MHW-COP8-PGMA-44QFP L For programming 44 QFP on any programmer
MHW-COP8-PGMA-28CSP L For programming 28 CSP on any programmer
IM-COP8 IM-COP8-AD-464 (-220)(10 MHz maximum)
H Base unit 10 MHz; -220 = 220V; add probe card(required) and target adapter (if needed); includedsoftware and manuals
IM Probe Card PC-COP8SG44PW-AD-10 M 10 MHz 44 PLCC probe card; 2.5V to 6.0V
PC-COP8SG40DW-AD-10 M 10 MHz 40 DIP probe card; 2.5V to 6.0V
IM Probe TargetAdapters
MHW-SOICxx (xx = 16,20, 28)
L 16 or 20 or 28 pin SOIC adapter for probe card
MHW-CSPxx (xx = 20,28)
L 20 or 28 pin CSP adapter for probe card
MHW-CONV33 L 44 pin QFP adapter for 44 PLCC probe card
ICU orNational
COP8-EVAL-ICUxx ICU-303 L No power supply
COP8-EVAL-ICUSG L No power supply
KKD WCOP8-IDE WCOP8-IDE VL Included in EPU and DM
IAR EWCOP8-xx See summary above L - H Included all software and manuals
ByteCraft
COP8C COP8C M Included all software and manuals
Aisys DriveWay COP8 DriveWay COP8 L Included all software and manuals
OTP Programmers Go to:www.national.com/cop8
L - H A wide variety world-wide
Cost: Free; VL =< $100; L = $100 - $300; M = $300 - $1k; H = $1k - $3k; VH = $3k - $5k
www.national.com53
15.0 Development Tools Support (Continued)
15.4 WHERE TO GET TOOLS
Tools are ordered directly from the following vendors. Please go to the vendor’s web site for current listings of distributors.
Vendor Home Office Electronic Sites Other Main Offices
Aisys U.S.A.: Santa Clara, CA www.aisysinc.com Distributors
1-408-327-8820 [email protected]
fax: 1-408-327-8830
Byte Craft U.S.A. www.bytecraft.com Distributors
1-519-888-6911 [email protected]
fax: 1-519-746-6751
IAR Sweden: Uppsala www.iar.se U.S.A.: San Francisco
+46 18 16 78 00 [email protected] 1-415-765-5500
fax: +46 18 16 78 38 [email protected] fax: 1-415-765-5503
[email protected] U.K.: London
[email protected] +44 171 924 33 34
fax: +44 171 924 53 41
Germany: Munich
+49 89 470 6022
fax: +49 89 470 956
ICU Sweden: Polygonvaegen www.icu.se Switzeland: Hoehe
+46 8 630 11 20 [email protected] +41 34 497 28 20
fax: +46 8 630 11 70 [email protected] fax: +41 34 497 28 21
KKD Denmark: www.kkd.dk
MetaLink U.S.A.: Chandler, AZ www.metaice.com Germany: Kirchseeon
1-800-638-2423 [email protected] 80-91-5696-0
fax: 1-602-926-1198 [email protected] fax: 80-91-2386
bbs: 1-602-962-0013 [email protected]
www.metalink.de Distributors Worldwide
National U.S.A.: Santa Clara, CA www.national.com/cop8 Europe: +49 (0) 180 530 8585
1-800-272-9959 [email protected] fax: +49 (0) 180 530 8586
fax: 1-800-737-7018 [email protected] Distributors Worldwide
The following companies have approved COP8 program-mers in a variety of configurations. Contact your local officeor distributor. You can link to their web sites and get the lat-est listing of approved programmers from National’s COP8OTP Support page at: www.national.com/cop8.
Advantech; Advin; BP Microsystems; Data I/O; Hi-Lo Sys-tems; ICE Technology; Lloyd Research; Logical Devices;MQP; Needhams; Phyton; SMS; Stag Programmers; Sys-tem General; Tribal Microsystems; Xeltek.
15.5 CUSTOMER SUPPORT
Complete product information and technical support is avail-able from National’s customer response centers, and fromour on-line COP8 customer support sites.
www.national.com 54
Physical Dimensions inches (millimeters) unless otherwise noted
28-Lead Hermetic Dual-In-Line Package EPROM (D)Order Number COP8SGR728Q3
NS Package Number D28JQ
www.national.com55
Physical Dimensions inches (millimeters) unless otherwise noted (Continued)
40-Lead Hermetic Dual-In-Line Package EPROM (D)Order Number COP8SGR740Q3
NS Package Number D40KQ
Molded SO Wide Body Package (WM)Order Number COP8SGx728Mx,
NS Package Number M28B
www.national.com 56
Physical Dimensions inches (millimeters) unless otherwise noted (Continued)
Molded Dual-In-Line Package (N)Order Number COP8SGx728Nx
NS Package Number N28A
Molded Dual-In-Line Package (N)Order Number COP8SGx740Nx
NS Package Number N40A
www.national.com57
Physical Dimensions inches (millimeters) unless otherwise noted (Continued)
44-Lead EPROM Leaded Chip Carrier (EL)Order Number COP8SGR744J3
NS Package Number EL44C
www.national.com 58
Physical Dimensions inches (millimeters) unless otherwise noted (Continued)
Molded Dual-In-Line Package (N)Order Number COP8SGx744Vx
NS Package Number V44A
Plastic Quad Flat Package (VEJ)Order Number COP8SGx744VEJx
NS Package Number VEJ44A
www.national.com59
Notes
LIFE SUPPORT POLICY
NATIONAL’S PRODUCTS ARE NOT AUTHORIZED FOR USE AS CRITICAL COMPONENTS IN LIFE SUPPORTDEVICES OR SYSTEMS WITHOUT THE EXPRESS WRITTEN APPROVAL OF THE PRESIDENT AND GENERALCOUNSEL OF NATIONAL SEMICONDUCTOR CORPORATION. As used herein:
1. Life support devices or systems are devices orsystems which, (a) are intended for surgical implantinto the body, or (b) support or sustain life, andwhose failure to perform when properly used inaccordance with instructions for use provided in thelabeling, can be reasonably expected to result in asignificant injury to the user.
2. A critical component is any component of a lifesupport device or system whose failure to performcan be reasonably expected to cause the failure ofthe life support device or system, or to affect itssafety or effectiveness.
National SemiconductorCorporationAmericasTel: 1-800-272-9959Fax: 1-800-737-7018Email: [email protected]
National SemiconductorEurope
Fax: +49 (0) 1 80-530 85 86Email: [email protected]
Deutsch Tel: +49 (0) 1 80-530 85 85English Tel: +49 (0) 1 80-532 78 32Français Tel: +49 (0) 1 80-532 93 58Italiano Tel: +49 (0) 1 80-534 16 80
National SemiconductorAsia Pacific CustomerResponse GroupTel: 65-2544466Fax: 65-2504466Email: [email protected]
National SemiconductorJapan Ltd.Tel: 81-3-5639-7560Fax: 81-3-5639-7507
www.national.com
CO
P8S
Gx7
Fam
ily,8
-Bit
CM
OS
OTP
Mic
roco
ntro
llers
with
8kor
32k
Mem
ory,
Two
Com
para
tors
and
US
AR
T
National does not assume any responsibility for use of any circuitry described, no circuit patent licenses are implied and National reserves the right at any time without notice to change said circuitry and specifications.
Anexo C
ANEXO C
PROGRAMAS EN LENGUAJE ENSAMBLADOR COP8SGR7
99
Anexo C
PROGRAMA PRINCIPAL DEL SENSOR DE NIVEL
100
Anexo C
PROGRAMA DE LA MACRO “DISPLAY” PARA
CONTROLAR EL EXHIBIDOR DE CRISTAL LÍQUIDO
109
Programa principal del sensor de nivel de líquidos
PROGRAMA PRINCIPAL DEL SENSOR DE NIVEL DE LÍQUIDOS. (SENSOR.ASM) ; Descripcion.-PRESENTA EL NIVEL DEL LÍQUIDO EN UN TANQUE .incld regcop8.asm .TITLE PRUEBA 1 .CHIP 8SGR .SECT VARIABLE,RAM BINLO: .DSB 002 ;VARIABLE A SER CONVERTIDA BCDLO: .DSB 003 ;RESULTADO DE CONVERSION A BCD BCDASC: .DSB 005 ;BCD EN CODIGO ASCII VAR1: .DSB 001 ;VARIABLE AUXILIAR APUNTA: .DSB 001 ;APUNTADOR DE TABLA EN ROM VAR2: .DSB 001 ; TABRAM: .DSB 005 CONTMS: .DSB 001 ;VARIABLE PARA CONTAR CADA 4.096MS CRISTAL(4MZ) 10.24MS CRISTAL 4 MHZ LLENO: .DSB 005 LLENUEZ: .DSB 005 VACIO: .DSB 005 VANUEZ: .DSB 005 ADR1: .DSB 001 ;LECTURA DEL PUERTO ;**************************************************************** ; REGISTROS INICIAN EN LA DIRECCION F0 Y TERMINAN EN FB ;**************************************************************** ; .SECT RAM,REG CNTR1: .DSB 001 ; VARIABLE PARA CONTADOR DE TIEMPO CNTR: .DSB 001 ; VARIABLE PARA CONTADOR DE TIEMPO CNTR2: .DSB 001 CNTR3: .DSB 001 CNTR4: .DSB 001 CNTR5: .DSB 001 CNTR6: .DSB 001 CNTR7: .DSB 001 .INCLD COP8MAC.MAC .SECT MAIN,ROM RESET: LD SP,#06F ; LD 0FF,#000 ;SEGMENT EN CERO CLR A X A,CONTMS ;CONTMS = 000 CLR A LD PORTFC,#000 ;TODO EL PUERTO F SON ENTRADAS LD PORTFDS,#000 ;CON ENTRADA Hi-Z. LD PORTLC,#0FF ;TODO EL PUERTO L SON SALIDAS DISPLAY TDISP,TABRAM RBIT #5,ICNTRL ;BANDERA PENDIENTE = 0 SBIT #4,ICNTRL ;HABILITACION DE INTERRUPCION SBIT #0,PSW ;HABILITACION GLOBAL DE INTERRUPCIONES
101
Programa principal del sensor de nivel de líquidos
MAIN: LD A,CONTMS ; IFGT A,#49 JP DOIT ;SI NO ES IGUAL EJECUTA LA SIG. INSTRUCCION JP MAIN DOIT: CLR A X A,CONTMS LD A,PORTFD ;SE LEE EL PUERTO X A,ADR1 ;Y SE GUARDA EN ADR1 JSR DESPLI1 ;SALTA A DESPLIEGA LD A,#0FF IFEQ A,ADR1 JSR FULL LD A,#000 IFEQ A,ADR1 JSR EMPTY JP MAIN TDISP: .DB 000,030 .DB 000,030 .DB 000,030 .DB 000,038 .DB 000,00c ;Display On .DB 000,001 ;Display Clr .DB 000,080 ;Set DDRAM .DB 002,'E' ;1 .DB 002,'L' ;2 .DB 002,' ' ;3 .DB 002,'N' ;4 .DB 002,'I' ;5 .DB 002,'V' ;6 .DB 002,'E' ;7 .DB 002,'L' ;8 .DB 002,' ' ;9 .DB 002,'E' ;10 .DB 002,'S' ;11 .DB 002,' ' ;12 .DB 002,'D' ;13 .DB 002,'E' ;14 .DB 002,':' ;15 .DB 000,0C6 ;DIRECCION POSICIÓN 2a. LÍNEA .DB 002,'L' .DB 002,'I' .DB 002,'T' .DB 002,'R' .DB 002,'O' .DB 002,'S' .DB 0ff ;terminador de tabla .=0FF VIS .=01F8 .ADDRW SERT0 ;VECTOR PARA T0
102
Programa principal del sensor de nivel de líquidos
.=0200 ;DIRECCION INICIAL PARA SERVICIO DE ;INTERRUPCION DE T0 SERT0: RBIT #5,ICNTRL ;LIMPIA BANDERA = 0 PUSH A LD A,B PUSH A LD A,X PUSH A LD A,CONTMS INC A X A,CONTMS POP A X A,X POP A X A,B POP A RETI DESPLI1: LD A,ADR1 ;CARGA EL DATO A SER CONVERTIDO ;PREPARACION PARA MULTIPLICACION X A,BINLO LD A,#D'188 ;CONSTANTE DE CONVERSION X A,BINLO+1 ;COLOCA MULTIPLICADOR JSR MPY88 ;ACOMODAR DATOS PARA CONVERCION A ASCII LD A,BINLO+1 X A,BINLO LD A,BINLO+2 X A,BINLO+1 JSR BINDEC16 ;CONVERSION A ASCII JSR NEXT2 RET .=0250 NEXT2: DISPLAY TABDISP2,BCDASC; RET TABDISP2: .DB 000,0C0 ; DIRECCION POSICION 2NDA LINEA. .DB 001,000 ;17 .DB 001,000 ;18 .DB 002,'.' ;19 .DB 001,000 ;28 .DB 001,000 ;20 .DB 002,' ' ;29 .DB 0ff ;terminador de tabla ;SUBRUTINA DE MULTIPLICACION DE 8BITS POR 8 BITS ;REFERENCIA AN-596 PG.7-33 COP8 MICROCONTROLER DATABOOK ;MULTIPLICANDO Y MULTIPLICADOR EN [0],[1] ;RESULTADO [2],[1] MPY88: LD CNTR,#9 RC LD B,#2 CLR A
103
Programa principal del sensor de nivel de líquidos
M88LUP: RRC A X A,[B-] LD A,[B] RRC A X A,[B-] CLR A IFC LD A,[B] RC LD B,#2 ADC A,[B] DRSZ CNTR JP M88LUP RET ;SUBRUITNA PARA CONVERTIR 16 BITS A ASC BCD. BINDEC16: LD CNTR,#16 RC LD B,#2 BD1: LD [B+],#0 IFBNE #5 JP BD1 BD2: LD B,#0 BD3: LD A,[B] ADC A,[B] X A,[B+] IFBNE #2 JP BD3 BD4: LD A,[B] ADD A,#066 ADC A,[B] DCOR A X A,[B+] IFBNE #5 JP BD4 DRSZ CNTR JP BD2 ;MODIFICACION PARA ASCII LD A,BCDLO AND A,#00F OR A,#030 X A,BCDASC+4 LD A,BCDLO AND A,#0F0 RC RRC A RRC A RRC A RRC A OR A,#030 X A,BCDASC+3
104
Programa principal del sensor de nivel de líquidos
LD A,BCDLO+1 AND A,#00F OR A,#030 X A,BCDASC+2 LD A,BCDLO+1 AND A,#0F0 RC RRC A RRC A RRC A RRC A OR A,#030 X A,BCDASC+1 LD A,BCDLO+2 AND A,#00F OR A,#030 X A,BCDASC RET FULL: JSR DISPDELAY JSR PLELLENO JSR DISPDELAY JSR MENLLENUEZ RET DISPDELAY: LD CNTR6,#002 BUINT2: LD CNTR2,#080 BUEXT: LD CNTR3,#0FF BUINT: DRSZ CNTR3 JMP BUINT DRSZ CNTR2 JMP BUEXT DRSZ CNTR6 JMP BUINT2 RET .=0400 PLELLENO: DISPLAY MENLLE,LLENO RET MENLLE: .DB 000,001 .DB 000,080 .DB 002,' ' ;1 .DB 002,' ' ;2 .DB 002,'E' ;3 .DB 002,'L' ;4 .DB 002,' ' ;5 .DB 002,'T' ;6 .DB 002,'A' ;7 .DB 002,'N' ;8 .DB 002,'Q' ;9 .DB 002,'U' ;10 .DB 002,'E' ;11 .DB 002,' ' ;12 .DB 002,'S' ;13
105
Programa principal del sensor de nivel de líquidos
.DB 002,'E' ;14 .DB 002,' ' ;15 .DB 000,0C0 ;DIRECCION POSICIÓN 2a. LÍNEA .DB 002,'L' .DB 002,'L' .DB 002,'E' .DB 002,'N' .DB 002,'O' .DB 002,' ' .DB 002,'P' .DB 002,'L' .DB 002,'E' .DB 002,'N' .DB 002,'A' .DB 002,'M' .DB 002,'E' .DB 002,'N' .DB 002,'T' .DB 002,'E' .DB 0ff ;terminador de tabla .=0500 MENLLENUEZ: DISPLAY DENUEZ,LLENUEZ RET DENUEZ: .DB 000,001 .DB 000,080 ;Set DDRAM .DB 002,'E' ;1 .DB 002,'L' ;2 .DB 002,' ' ;3 .DB 002,'N' ;4 .DB 002,'I' ;5 .DB 002,'V' ;6 .DB 002,'E' ;7 .DB 002,'L' ;8 .DB 002,' ' ;9 .DB 002,'E' ;10 .DB 002,'S' ;11 .DB 002,' ' ;12 .DB 002,'D' ;13 .DB 002,'E' ;14 .DB 002,':' ;15 .DB 000,0C6 ;DIRECCION POSICIÓN 2a. LÍNEA .DB 002,'L' .DB 002,'I' .DB 002,'T' .DB 002,'R' .DB 002,'O' .DB 002,'S' .DB 002,' ' .DB 002,' ' .DB 002,' ' .DB 002,' ' .DB 0ff ;terminador de tabla .=0600 EMPTY: JSR DISDELAY2
106
Programa principal del sensor de nivel de líquidos
JSR PLEVACIO JSR DISDELAY2 JSR MENVANUEZ RET DISDELAY2: LD CNTR7,#002 INT2: LD CNTR4,#080 EXT: LD CNTR5,#0FF INT: DRSZ CNTR5 JMP INT DRSZ CNTR4 JMP EXT DRSZ CNTR7 JMP INT2 RET .=0700 PLEVACIO: DISPLAY MENVA,VACIO RET MENVA: .DB 000,001 .DB 000,080 .DB 002,' ' ;1 .DB 002,' ' ;2 .DB 002,'E' ;3 .DB 002,'L' ;4 .DB 002,' ' ;5 .DB 002,'T' ;6 .DB 002,'A' ;7 .DB 002,'N' ;8 .DB 002,'Q' ;9 .DB 002,'U' ;10 .DB 002,'E' ;11 .DB 002,' ' ;12 .DB 002,'S' ;13 .DB 002,'E' ;14 .DB 002,' ' ;15 .DB 000,0C0 ;DIRECCION POSICIÓN 2a. LÍNEA .DB 002,'V' .DB 002,'A' .DB 002,'C' .DB 002,'I' .DB 002,'O' .DB 002,' ' .DB 002,'P' .DB 002,'L' .DB 002,'E' .DB 002,'N' .DB 002,'A' .DB 002,'M' .DB 002,'E' .DB 002,'N' .DB 002,'T' .DB 002,'E' .DB 0ff ;terminador de tabla
107
Programa principal del sensor de nivel de líquidos
.=0800 MENVANUEZ: DISPLAY DTNUEZ,VANUEZ RET DTNUEZ: .DB 000,001 .DB 000,080 ;Set DDRAM .DB 002,'E' ;1 .DB 002,'L' ;2 .DB 002,' ' ;3 .DB 002,'N' ;4 .DB 002,'I' ;5 .DB 002,'V' ;6 .DB 002,'E' ;7 .DB 002,'L' ;8 .DB 002,' ' ;9 .DB 002,'E' ;10 .DB 002,'S' ;11 .DB 002,' ' ;12 .DB 002,'D' ;13 .DB 002,'E' ;14 .DB 002,':' ;15 .DB 000,0C6 ;DIRECCION POSICIÓN 2a. LÍNEA .DB 002,'L' .DB 002,'I' .DB 002,'T' .DB 002,'R' .DB 002,'O' .DB 002,'S' .DB 002,' ' .DB 002,' ' .DB 002,' ' .DB 002,' ' .DB 0ff ;terminador de tabla .END RESET
108
Anexo C
PROGRAMA DE LA MACRO PARA EL CONTROL DEL EXHIBIDOR DE CRISTAL LÍQUIDO.
;MACRO DISPLAY .MACRO DISPLAY TABC,TABRAM ; TABLA DE CONTROL Y TABLA DE RAM .MLOC LDISP .MLOC N1 .MLOC N2 .MLOC PRAM .MLOC COMAND .MLOC CONST .MLOC DELAY .MLOC LUP .MLOC DELAY1 .MLOC LOOP1 .MLOC DELAYB .MLOC LOP .MLOC DELY1 .MLOC LOP1 .MLOC FINM .MLOC FINMAC PORTFDS = 094 ; DATOS DEL PUERTO F DE ESCRITURA PORTFC = 095 ; CONFIGURACION DEL PUERTO F PORTFD = 096 ; DATOS DEL PUERTO F DE LECTURA PORTLDS = 0D0 ; DATOS DEL PUERTO L DE SALIDA PORTLC = 0D1 ; CONFIGURACION DEL PUERTO L PORTLDE = 0D2 ; DATOS DEL PUERTO L DE ENTRADA PORTGDD = 0D4 ; DATOS DEL PUERTO G DE ESCRITURA PORTGC = 0D5 ; CONFIGURACION DEL PUERTO G PORTGD = 0D6 ; DATOS DEL PUERTO G DE LECTURA PORTCDD = 0D8 ; DATOS DEL PUERTO C DE ESCRITURA PORTCC = 0D9 ; CONFIGURACION DEL PUERTO C PORTCD = 0DA ; DATOS DEL PUERTO C DE LECTURA PORTDD = 0DC ; DATOS DEL PUERTO D DE ESCRITURA ICNTRL = 0E8 CNTRL = 0EE PSW = 0EF SIOR = 0E9 S = 0ff LD B,#TABRAM ;B =DIRECCION VARIABLE EN RAM LD A,#L(TABC) ;A =PARTE BAJA DE DIRECCION DE TDISP LDISP: INC A X A,APUNTA ;APUNTADOR = TDISP+1 LD A,APUNTA DEC A ;A = TDISP LAID ;A = CONTENIDO DEL 1ER. BYTE DE LA TABLA X A,VAR1 ;VAR1 = 1ER BYTE TABLA ;A=XX ;CONTRA VAR1 SE PREGUNTARA SI ES $FF,$00,$01,OTRO LD A,#0FF ;FF = VA HA PREGUNTAR SI ES FIN DE TABLA IFNE A,VAR1 ; ?A NO= VAR1 (FF NO= 1ER BYTE)
110
Anexo C
JP N1 ;SI SON DIFERENTES SALTA A N1 JP FINMAC ;SALTA A FIN DE MACRO N1: CLR A IFNE A,VAR1 ; ? VAR1=0 JP N2 JP COMAND ;SALTA A PROTOCOLO DE COMANDO DEL LCD. N2: LD A,#001 IFNE A,VAR1 ;? VAR1 = 01 JP CONST ;SALTA A PROTOCOLO DE CONSTANTE PRAM: ;B ENTRA APUNTANDO AL SIGUIENTE BYTE A DESPLEGAR. SBIT 5,PORTLDS ; RS = 1 (CONSTANTE) LD A,[B+] X A,PORTFDS ;ESCRIBE EN EL PUERTO F ;GENERACION DEL ENABLE 0..... A ...1 SBIT 7,PORTLDS JSR DELAY RBIT 7,PORTLDS JP FINM COMAND: RBIT 5,PORTLDS ; RS = 0 (COMANDO) LD A,APUNTA LAID ;A = BYTE PAR DE LA TABLA DE CONTROL X A,PORTFDS ;ESCRIBE EN EL PUERTO F ;GENERACION DEL ENABLE 0..... A ...1 SBIT 7,PORTLDS JSR DELAY RBIT 7,PORTLDS JP FINM CONST: SBIT 5,PORTLDS ; RS = 1 (CONSTANTE) LD A,APUNTA LAID ;A = BYTE PAR DE LA TABLA DE CONTROL X A,PORTFDS ;ESCRIBE EN EL PUERTO F ;GENERACION DEL ENABLE 0..... A ...1 SBIT 7,PORTLDS JSR DELAY RBIT 7,PORTLDS JP FINM DELAY: LD CNTR1,#00B LUP: JSR DELAY1 DRSZ CNTR1 JMP LUP RET DELAY1: LD CNTR,#07F LOOP1: DRSZ CNTR JMP LOOP1 RET ; DELAYB: LD CNTR2,#0FF LOP: JSR DELY1
111
Anexo C
DRSZ CNTR2 JMP LOP RET DELY1: LD CNTR3,#0FF LOP1: DRSZ CNTR3 JMP LOP1 RET FINM: LD A,APUNTA INC A JMP LDISP ;SALTA A CICLO DISPLEY FINMAC: NOP .ENDM
112
Anexo D
ANEXO D
FOTOGRAFÍAS DEL SISTEMA
113
Anexo D
Fotografía 1. Sistema completo del sensor de nivel con fibras ópticas.
114
Anexo D
Fotografía 2. Vista en planta del receptor óptico y el exhibidor AND491
115
Anexo D
Fotografía 3. Vista en planta del contenedor con el sensor de nivel.
116
Anexo D
Fotografía 4. Circuito electrónico del emisor óptico.
117
Anexo D
Fotografía 5. Circuito electrónico de la interfase y el receptor óptico.
118
Anexo D
Fotografía 6. Detalle de la placa con el código binario.
119