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 NIVEL UTIL UTIL IZANDO FIBRAS FIBRA S ÓPTICAS ÓPTICAS TESIS QUE PARA OBTENER EL GRADO DE MAESTRO EN CIENCIAS EN INGENIERÍA ELECTRÓNI EL ECTRÓNICA CA
OPCIÓN: INSTRUMENTACIÓN PRESENTA: FREDDY LÓPEZ VILLAFUERTE
DIRECTOR DE TESIS
Dr. Walter Humberto Fonseca Araujo
MÉXICO, D.F.
DICIEMBRE DICIEMB RE 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 A GRADECIMIENTOS
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. 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 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.
de
volumen
de
una
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 internacional, 1 lm/m 2.
en
el
sistema
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 Introducción. 1.2 Características de las fibras ópticas en los sensores. 1.3 Sensores de nivel con fibras ópticas. 1.3.1 Concepto transmisivo. 1.3.2 Concepto reflectivo. 1.3.3 Clasificación. 1.4 Sensores de nivel transmisivo. 1.4.1 Nivel de líquidos bicolor. 1.4.2 Sensor de nivel por obstrucción. 1.5 Sensor de nivel por fuerza de flotación. 1.5.1 Sensor de pistón desplazable 1.5.2 Sensor de nivel lector de tarjeta. 1.6 Sensores de nivel por presión. 1.7 Sensor de superficie reflejante. 1.8 Sensor de nivel por cambios de índice de refracción.
1 2 2 3 4 4 5 6 6 7 8 8 9 9 10 11
I
Indice
Capitulo 2. Medición de nivel por lectura de código 2.1 2.2 2.3
Características generales del sensor. Principio de operación . Condiciones para realizar la medición de nivel bajo el principio seleccionado.
13 14 15 18
Capitulo 3. Diseño y construcción del sensor de nivel
21
3.1 Introducción. 3.2 Elemento sensor. 3.3 Sistema hidráulico. 3.4 Sistema óptico del sensor. 3.4.1 Fibra óptica. 3.4.2 Caracterización de las fibras ópticas de vidrio. 3.4.3 Fuente óptica. 3.4.4 Receptor óptico.
22 22 24 26 27 29 32 37
Capitulo 4. Procesamiento de la señal eléctrica e interfase periférica
47
4.1 4.2 4.3 4.4 4.5
Introducción. Procesador de señal. Periférico de salida. Interfase periférica. Programación del microcontrolador COP8SGR7
48 48 51 51 52
Capitulo 5. Caracterización del sistema y análisis de pérdidas
55
5.1 Introducción. 5.2 Sistema general de medición. 5.3 Elementos principales que conforman al sistema. 5.4 Evaluación del sistema. 5.4.1 Desalineación lateral. 5.4.2 Desalineación angular.
56 56 57 58 60 61 II
Indice
5.4.3 Separación entre terminales. 5.4.4 Terminales mal pulidas. 5.5 Tolerancia en la lectura del nivel. 5.6 Calibración en el sistema de medición.
63 69 69 70
Conclusiones. Recomendaciones y sugerencias Bibliografía. Anexo A
71 72 73
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 1.2 1.3 1.4 1.5 1.6 1.7 1.8 2.1 3.1 3.2 3.3 3.4 3.5 3.6
Configuración de sensor reflectivo Nivel de líquido bicolor Bosquejo de un sensor de nivel por obstrucción Interruptor de nivel de líquidos Sensor de nivel de líquidos con fibra óptica (digital) Sensor de nivel de líquidos con transductor de presión Medición de nivel de líquido por superficie reflejante Sensor de nivel de líquidos con cambio de índice refracción (Refracciométricos) Bosquejo del código binario en la placa perforada Bosquejo de la placa ranurada y acanalada Sistema hidráulico Elementos generales de un sistema de medición óptico Partes que integran a una fibra óptica Cono de aceptación de la fibra óptica dependiente de la apertura numérica Medición de la apertura numérica de la fibra óptica
5 6 7 8 9 10 11 12 16 24 25 26 27 29 30 III
Indice
3.7 Fuente óptica con LED emisor de 850 nm 3.8 Circuito para caracterizar a los diodos del emisor 3.9 Diagrama del circuito eléctrico del receptor óptico 3.10 Curvas características Corriente vs. Voltaje y línea de carga 3.11 Circuito equivalente del fotodiodo PIN 3.12 Curvas características capacitancia C J vs. Voltaje inverso 3.13 Curvas características Corriente obscuridad vs. Voltaje Inverso 3.14 Circuito equivalente del diodo PIN y una etapa de amplificación con sus respectivas fuentes de ruido 4.1 Diagrama del circuito integrado COP8SGR7 4.2 Diagrama eléctrico de la interfase periférica 4.3 Diagrama de flujo del programa principal 5.1 Diagrama a bloques del sistema general de medición 5.2 Pérdidas de potencia óptica 5.3 Desalineamiento entre dos fibras ópticas del mismo radio 5.4 Desalineamiento angular entre dos fibras ópticas 5.5 Separación existente entre dos fibras ópticas 5.6 Eficiencia de acoplamiento 5.7 Análisis del ángulo incidente de un haz de luz 5.8 Fuente óptica de potencia variable 5.9 Bosquejo del código binario en la placa perforada
34 35 39 40 41 42 43 43 48 52 53 56 59 60 62 63 64 66 68 70
Índice de tablas Tabla 3.1 Mediciones de la NA para la fibra óptica de 100/140 Tabla 3.2 Mediciones de la NA para la fibra óptica de 50/125 Tabla 3.3 Mediciones de corriente de LED vs Voltaje de referencia Tabla 3.4 Mediciones de la potencia óptica de LED vs corriente del LED Tabla 5.1 Pérdidas por desalineamiento lateral Tabla 5.2 Pérdidas por desalineamiento angular Tabla 5.3 Medición de las pérdidas en decibeles en la discontinuidad del sistema
31 31 35 36 61 63 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 Programa de la macro “display” para controlar el exhibidor de cristal líquido
100 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/r 2 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: N = 2 = 2 = 256niveles n
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 SISTEMA HIDRÁULICO. HIDRÁUL ICO. 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 ÓPTICAS DE VIDRIO
DE
LAS
FIBRAS
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]: d senθ a
= NA =
2 2
d
4
(2)
+ h2
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: V REF
100000Ω ⎤ = 6.832Volts = 6.9Volts ⎡⎢ ⎣100000Ω + 1000Ω ⎥⎦
(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: I E
≅ I C =
V E R E
=
6.832Volts 82ohms
= 83.3mA
(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 I LED (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 i D, 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: VD⏐iD=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 10 4 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: E t
=
4kTR∆ f
(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 (C J) 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 C J 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, V D = 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 = 2qI dc B .................................................(9) donde q= 1.602x10-19 coulombs, Idc= Corriente promedio (A) B = ancho de banda de ruido (Hz). Por tanto I Sh = 2qI dc B = 2(1.602 x10−19 )(10 µ A)(1 Hz ) ≈ 1.8 pA / Hz RSh = Resistencia de fuga ( Ω) 107 Ω
=
4kTRB
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 E nRL = 4kTRB = 4(1.38 x10−23 )(300 K )(10 K Ω)(1 Hz ) = 13nV / Hz En = Voltaje de ruido del amplificador operacional. (18nV / Hz ) . In = Corriente de ruido del amplificador operacional. (0.01 pA / 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: AV
= 1+
R f R I
(10)
Donde Rf = Resistor de retroalimentación y R I = 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 A 2 = 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]: F 12
= F 1 +
(F 2 − 1) G1
(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 (f cristal) con que se trabaje, la expresión para calcular el tiempo del ciclo de máquina es: T C =
1
f cristal
(12)
10
Debido a que se tiene un cristal de 4 MHz en operación, el tiempo de máquina (TC) es: T C =
1 4 MHz
=
2.5µ seg.
(13)
10
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 pullup) 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 t 0 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.2.3.4.5.-
Fuente óptica. Sensor óptico (modulador). Receptor óptico. Procesador de señal. 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 de núcleo, apertura numérica de 0.302, atenuación de 4 dB/Km. Longitud: 1.5 mts.
µm
- Fibras ópticas receptoras: Fibra óptica multimodo de vidrio, índice escalonado, 100/140 de núcleo, apertura numérica de 0.302, atenuación de 4 dB/Km. Longitud: 1.5 mts.
µm
- 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⎡
d
d
η 1 = ⎢arc. cos − π ⎢ 2 a 2a ⎣
⎛ d ⎞ 1− ⎜ ⎟ ⎝ 2a ⎠
2
⎤ ⎥ ⎥⎦
(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: L1
= −10 ⋅ Log ⋅ η 1
(16)
donde L1 es la pérdida de potencia en decibeles y eficiencia.
η1 es la
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. L (dB) d (µm) 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]: η 2
= 1−
n0 ⋅ θ
π ⋅ NA
(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: L2
= −10 ⋅ Log ⋅ η 2
(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: NA = n0 ⋅ Sen ⋅ α 0
Donde NA es la apertura numérica y transmisión.
(19)
α es el ángulo del cono de
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. Eficiencia Pérdidas (dB) Grados Radianes (η) 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: Ps Pe
=
Acono Anúcleo
(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: θ = arcsen ⋅ NA ,
φ = 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 = π ⋅ r 2 ⎝ 2r ⎠
(21)
Las pérdidas (L3) en decibeles se definen como: 2
L3
= −10 log⋅ η 3
φ ⎞ = −10 log⎛ ⎜ ⎟ ⎝ 2r ⎠
(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 0 1 2 3 4 5 6 7
Emisor (µW) 116.3 110.2 120.2 110.7 103.9 122 151.1 161.1
Receptor ( µW) 1.87 2.116 2.016 1.065 1.125 1.92 1.298 1.206
Pérdidas (dB) 17.94 17.16 17.75 20.17 19.65 18 20.65 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
July 1999
COP8SGx7 Family 8-Bit CMOS OTP Microcontrollers with 8k or 32k Memory, Two Comparators and USART General Description Note: COP8SGx7 devices are form-fit-function compatible supersets of the COP888xG/CS and COP87L88xG Family devices, and are replacements for these in new designs, and design upgrades with minimum effort. The COP8SGx7 Family of OTP (One Time Programmable) microcontrollers are highly integrated COP8 ™ Feature core devices with 8k or 32k memory and advanced features including Analog comparators, and zero external components. These single-chip CMOS devices are suited for more complex applications requiring a full featured controller with larger memory, low EMI, two comparators, and a full-duplex USART. 100% form-fit-function compatible 8k to 32k ROM
Devices included in this datasheet are:
Memory (bytes)
RAM (bytes)
I/O Pins
Packages
Temperature
COP8SGE7
8k OTP EPROM
256
24/36/40
28 DIP/SOIC, 40 DIP, 44 PLCC/QFP
-40 to +85˚C
COP8SGR7
32k OTP EPROM
512
24/36/40
28 DIP/SOIC, 40 DIP, 44 PLCC/QFP
-40 to +85˚C
32k EPROM
512
24/36/40
28 DIP, 40 DIP, 44 PLCC
Room Temp.
Key Features
Fourteen multi-source vectored interrupts servicing — External interrupt / Timers T0 — T3 — MICRO WIRE/PLUS Serial Interface — Multi -Input Wake Up — Soft ware Trap — USA RT (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 Pointers n True bit manipulation n Memory mapped I/O n BCD arithmetic instructions n
Low cost 8-bit OTP microcontroller Quiet Design (low radiated emissions) n Multi-Input Wakeup pins with optional interrupts (8 pins) n 8 bytes of user storage space in EPROM n 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 selectable n WATCHDOG and Clock Monitor Logic — user selectable n Eight high current outputs n 256 or 512 bytes on-board RAM n 8 or 32 kbytes on-board OTP EPROM with security feature for COP8SGE7 n 4 to 32 kbytes ROM based versions available n n
CPU Features n
Family features include an 8-bit memory mapped architecture, 10 MHz CKI with 1µs instruction cycle, three multifunction 16-bit timer/counters with PWM, full duplex USART, MICROWIRE/PLUS ™, two analog comparators, two power saving HALT/IDLE modes, MIWU, idle timer, on-chip R/C oscillator, 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/44 pin packages.
Device
COP8SGR7-Q3
n
versions are available (COP8SGx5 Family). Erasable windowed versions are available for use with a range of COP8 software and hardware development tools.
Versatile easy to use instruction set 1 µs instruction cycle time
Peripheral Features Multi-Input Wakeup Logic 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 USART n Two Analog Comparators n n
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.
© 1999 National Semiconductor Corporation
DS100155
www.national.com
a C n O d P U 8 S S A G R x T 7 F a m i l y , 8 - B i t C M O S O T P M i c r o c o n t r o l l e r s w i t h 8 k o r 3 2 k M e m o r y , T w o C o m p a r a t o r s
I/O Features
Fully Static CMOS Design
Software selectable I/O options (TRI-STATE ® Output,Push-Pull Output, Weak Pull-Up Input, and High Impedance Input) n Schmitt trigger inputs on ports G and L n Eight high current outputs n Packages: 28 SO with 24 I/O pins, 40 DIP with 36 I/O pins, 44 PLCC and PQFP with 40 I/O pins
n
n
Two power saving modes: HALT and IDLE
Temperature Range n
−40˚C to +85˚C
Development Support n n
Windowed packages for DIP and PLCC 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
many cases, the instruction set can simultaneously execute as many as three functions with the same single-byte instruction.
1.1 ARCHITECTURE
JID: (Jump Indirect); Single byte instruction; decodes external events and jumps to corresponding service routines (analogous to “DO CASE” statements in higher level languages).
The COP8 family is based on a modified Harvard architecture, which allows data tables to be accessed directly from program memory. This is very important with modern microcontroller-based applications, since program memory is usually ROM or EPROM, while data memory is usually RAM. Consequently data tables need to be contained in non-volatile memory, so they are not lost when the microcontroller is powered down. In a modified Harvard architecture, instruction fetch and memory data transfers can be overlapped with a two stage pipeline, which allows the next instruction to be fetched from program memory while the current instruction is being executed using data memory. This is not possible with a Von Neumann single-address bus architecture.
LAID: (Load Accumulator-Indirect); Single byte look up table instruction provides efficient data path from the program memory to the CPU. This instruction can be used for table lookup and to read the entire program memory for checksum calculations. RETSK: (Return Skip); Single byte instruction allows return from subroutine and skips next instruction. Decision to branch can be made in the subroutine itself, saving code. AUTOINC/DEC: (Auto-Increment/Auto-Decrement); These instructions use the two memory pointers B and X to efficiently process a block of data (analogous to “FOR NEXT” in higher level languages).
The COP8 family supports a software stack scheme that allows the user to incorporate many subroutine calls. This capability is important when using High Level Languages. With a hardware stack, the user is limited to a small fixed number of stack levels.
1.2.3 Bit-Level Control Bit-level control over many of the microcontroller’s I/O ports provides a flexible means to ease layout concerns and save board space. All members of the COP8 family provide the ability to set, reset and test any individual bit in the data memory address space, including memory-mapped I/O ports and associated registers.
1.2 INSTRUCTION SET In today’s 8-bit microcontroller application arena cost/ performance, flexibility and time to market are several of the key issues that system designers face in attempting to build well-engineered products that compete in the marketplace. Many of these issues can be addressed through the manner in which a microcontroller’s instruction set handles processing tasks. And that’s why COP8 family offers a unique and code-efficient instruction set— one that provides the flexibility, functionality, reduced costs and faster time to market that today’s microcontroller based products require.
1.2.4 Register Set Three memory-mapped pointers handle register indirect addressing and software stack pointer functions. The memory data pointers allow the option of post-incrementing or postdecrementing with the data movement instructions (LOAD/ EXCHANGE). And 15 memory-maped registers allow designers to optimize the precise implementation of certain specific instructions.
Code efficiency is important because it enables designers to pack more on-chip functionality into less program memory space (ROM/OTP). Selecting a microcontroller with less program memory size translates into lower system costs, and the added security of knowing that more code can be packed into the available program memory space.
1.3 EMI REDUCTION The COP8SGx7 family of devices incorporates circuitry that guards against electromagnetic interference — an increasing problem in today’s microcontroller board designs. National’s patented EMI reduction technology offers low EMI clock circuitry, gradual turn-on output drivers (GTOs) and internal I CC smoothing filters, to help circumvent many of the EMI issues influencing embedded control designs. National has achieved 15 dB–20 dB reduction in EMI transmissions when designs have incorporated its patented EMI reducing circuitry.
1.2.1 Key Instruction Set Features The COP8 family incorporates a unique combination of instruction set features, which provide designers with optimum code efficiency and program memory utilization. Single Byte/Single Cycle Code Execution The efficiency is due to the fact that the majority of instructions are of the single byte variety, resulting in minimum program space. Because compact code does not occupy a substantial amount of program memory space, designers can integrate additional features and functionality into the microcontroller program memory space. Also, the majority instructions executed by the device are single cycle, resulting in minimum program execution time. In fact, 77 % of the instructions are single byte single cycle, providing greater code and I/O efficiency, and faster code execution.
1.4 PACKAGING/PIN EFFICIENCY Real estate and board configuration considerations demand maximum space and pin efficiency, particularly given today’s high integration and small product form factors. Microcontroller users try to avoid using large packages to get the I/O needed. Large packages take valuable board space and increases device cost, two trade-offs that microcontroller designs can ill afford.
1.2.2 Many Single-Byte, Multifunction Instructions
The COP8 family offers a wide range of packages and do not waste pins: up to 90.9% (or 40 pins in the 44-pin package) are devoted to useful I/O.
The COP8 instruction set utilizes many single-byte, multifunction instructions. This enables a single instruction to accomplish multiple functions, such as DRSZ, DCOR, JID, LD (Load) and X (Exchange) instructions with post-incrementing and post-decrementing, to name just a few examples. In
3
www.national.com
Connection Diagrams
DS100155-4
Note 1: Note: x = E for 8k, and R for 32k
Top View Order Number COP8SGx728M8 See NS Package Number M28B Order Number COP8SGx728N8 See NS Package Number N28B Order Number COP8SGR728Q3 See NS Package Number D28JQ
DS100155-5
Top View Order Number COP8SGx740N8 See NS Package Number N40A Order Number COP8SGR740Q3 See NS Package Number D40KQ
DS100155-6
DS100155-43
Top View Order Number COP8SGx744V8 See NS Package Number V44A Order Number COP8SGR744J3 See NS Package Number EL44C
Top View Order 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 28-Pin SO
40-Pin DIP
44-Pin PLCC
44-Pin PQFP
L0
Port
I/O
Type
MIWU
Alt. Fun
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.
5
www.national.com
2.1 Ordering Information
DS100155-8
FIGURE 3. Part Numbering Scheme
www.national.com
6
3.0 Electrical Characteristics
Total Current out of GND Pin (Sink) Storage Temperature Range ESD Protection Level
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 (V CC) Voltage at Any Pin Total Current into VCC Pin (Source)
110 mA −65˚C to +140˚C 2kV (Human Body Model)
Note 2: Absolute maximum ratings indicate limits beyond which damage to the device may occur. DC and AC electrical specifications are not ensured when operating the device at absolute maximum ratings.
7V −0.3V to VCC +0.3V 100 mA
DC Electrical Characteristics −40˚C ≤ T A ≤ +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 10 6
ns
VCC Start Voltage to Guarantee POR
0
0.25
V
0.1 Vcc
V
6.0
mA
2.1
mA
10
µA
Power Supply Ripple (Note 4)
Peak-to-Peak
Supply Current (Note 5) CKI = 10 MHz CKI = 4 MHz HALT Current (Note 6)
VCC = 5.5V, tC = 1 µs VCC = 4.5V, tC = 2.5 µs
<4
VCC = 5.5V, CKI = 0 MHz
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 (V IH, VIL) RESET Logic High
0.8 Vcc
V
Logic Low
0.2 Vcc
V
CKI, All Other Inputs Logic High
0.7 V cc
V
Logic Low Internal Bias Resistor for the Crystal/Resonator Oscillator
0.2 Vcc
V
0.5
1
2
MΩ
5
8
11
kΩ
CKI Resistance to VCC or GND when R/C Oscillator is selected
VCC = 5.5V
Hi-Z Input Leakage
V CC = 5.5V
−2
+2
µA
Input Pullup Current
VCC = 5.5V, VIN = 0V
−40
−250
µA
G and L Port Input Hysteresis
V CC = 5.5V
0.25 Vcc
V
VCC = 4.5V, VOH = 3.3V
−0.4
mA
VCC = 2.7V, VOH = 1.8V
−0.2
mA
Output Current Levels D Outputs Source Sink
VCC = 4.5V, VOL = 1.0V
10
mA
VCC = 2.7V, VOL = 0.4V
2
mA
V CC = 4.5V, VOH = 2.7V
−10.0
−110
VCC = 2.7V, VOH = 1.8V
−2.5
−33
Source (Push-Pull Mode)
V CC = 4.5V, VOH = 3.3V
−0.4
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
VCC = 5.5V
−2
All Others Source (Weak Pull-Up Mode)
TRI-STATE Leakage
7
µA µA mA
+2
µA
www.national.com
DC Electrical Characteristics (Continued) −40˚C ≤ T A ≤ +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
3
mA
All Others Maximum Input Current without Latchup (Note 7)
Room Temp.
±200
RAM Retention Voltage, Vr VCC Rise Time from a V CC
mA
2.0 ≥
2.0V
(Note 10)
V
12
µs
Input Capacitance
(Note 9)
7
pF
Load Capacitance on D2
(Note 9)
1000
pF
AC Electrical Characteristics −40˚C ≤ T A ≤ +85˚C unless otherwise specified. Parameter
Conditions
Min
Typ
Max
Units
Instruction Cycle Time (tC) Crystal/Resonator, External R/C Oscillator (Internal) Frequency Vari at ion (N ot e 9)
4.5V ≤ V CC ≤ 5.5V
1
2.7V ≤ V CC < 4.5V
2
µs µs
4.5V ≤ V CC ≤ 5.5V
2
µs
4. 5V ≤ V CC ≤ 5.5V
±35
% 55
%
Rise Time (Note 9)
fr = 10 MHz Ext Clock
12
ns
Fall Time (Note 9)
fr = 10 MHz Ext Clock
8
ns
4.5V ≤ V CC ≤ 5.5V
0.7
µs
2.7V ≤ V CC < 4.5V
1.75
µs
4.5V ≤ V CC ≤ 5.5V
1.0
µs
External CKI Clock Duty Cycle (Note 9)
Output Propagation Delay (Note 8)
fr = Max
45
R L = 2.2k, CL = 100 pF
tPD1, tPD0 SO, SK All Others
2.7V ≤ V CC < 4.5V
2.5
µs
MICROWIRE Setup Time (tUWS) (Note 11)
20
ns
MICROWIRE Hold Time (tUWH) (Note 11)
56
ns
MICROWIRE Output Propagation Delay (tUPD) (Note 11)
220
ns
Input Pulse Width (Note 9) Interrupt Input High Time
1
tC
Interrupt Input Low Time
1
tC
Timer 1, 2, 3, Input High Time
1
tC
Timer 1 2, 3, Input Low Time
1
tC
1
µs
Reset Pulse Width 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 low but 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 crystal or 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 programmed as low outputs and not driving a load; all outputs programmed low and not driving a load; all inputs tied to V CC; clock monitor disabled. Parameter refers to 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 > V CC and the pins will have sink current to VCC when biased at voltages > V CC (the pins do not have source current when biased at a voltage below VCC). The effective resistance to VCC is 750Ω (typical). These two pins 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 excludes ESD 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 MICROWIRE operation description.
Comparators AC and DC Characteristics VCC = 5V, −40˚C ≤ T A ≤ +85˚C. Parameter Input Offset V ol tage (Note 12)
Conditions
Min
±5
0.4V ≤ V IN ≤ V CC − 1.5V
Input Common Mode Voltage Range
Typ
0.4
Voltage Gain
Max
Units
±15
mV
V CC − 1.5 100
V 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) Response Time (Note 13)
200 mV step input 100 mV Overdrive,
150
µA
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
9
www.national.com
Typical Performance Characteristics
www.national.com
TA = 25˚C (unless otherwise specified)
DS100155-49
DS100155-50
DS100155-51
DS100155-52
10
4.0 Pin Descriptions
WATCHDOG feature is selected by the ECON register. The pin is a general purpose I/O if WATCHDOG feature is not selected. If WATCHDOG feature is selected, bit 1 of the Port G configuration and data register does not have any effect on Pin G1 setup. Pin G7 is either input or output depending on the oscillator option selected. With the crystal oscillator option selected, G7 serves as the dedicated output pin for the CKO clock output. With the internal R/C or the external oscillator option selected, G7 serves as a general purpose Hi-Z input pin and is also used to bring the device out of HALT mode with a low to high transition on G7.
The COP8SGE7/COP8SGR7 I/O structure enables designers to reconfigure the microcontroller’s I/O functions with a single instruction. Each individual I/O pin can be independently configured as output pin low, output high, input with high impedance or input with weak pull-up device. A typical example is the use of I/O pins as the keyboard matrix input lines. The input lines can be programmed with internal weak pull-ups so that the input lines read logic high when the keys are all open. With a key closure, the corresponding input line will read a logic zero since the weak pull-up can easily be overdriven. When the key is released, the internal weak pull-up will pull the input line back to logic high. This eliminates the need for external pull-up resistors. The high current options are available for driving LEDs, motors and speakers. This flexibility helps to ensure a cleaner design, with less external components and lower costs. Below is the general description of all available pins.
Since G6 is an input only pin and G7 is the dedicated CKO clock output pin (crystal clock option) or general purpose input (R/C or external clock option), the associated bits in the data and configuration registers for G6 and G7 are used for special purpose functions as outlined below. Reading the G6 and 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 will be placed in the IDLE mode by writing a “1” to bit 6 of the Port G Data Register.
VCC and GND are the power supply pins. All V CC and GND pins must be connected. CKI is the clock input. This can come from the Internal R/C oscillator, external, or a crystal oscillator (in conjunction with CKO). See Oscillator Description section.
Writing a “1” to bit 6 of the Port G Configuration Register enables the MICROWIRE/PLUS to operate with the alternate phase of the SK clock. The G7 configuration bit, if set high, enables the clock start up delay after HALT when the R/C clock configuration is used.
RESET is the master reset input. See Reset description section. Each device contains four bidirectional 8-bit I/O ports (C, G, L and F), where each individual bit may be independently configured as an input (Schmitt trigger inputs on ports L and G), output or TRI-STATE under program control. Three data memory address locations are allocated for each of these I/O ports. Each I/O port has two associated 8-bit memory mapped registers, the CONFIGURATION register and the output DATA register. A memory mapped address is also reserved for the input pins of each I/O port. (See the memory map for the various addresses associated with the I/O ports.) Figure 5 shows the I/O port configurations. The DATA and CONFIGURATION registers allow for each port bit to be individually configured under software control as shown below: CONFIGURATION
DATA
Register
Register
0
0
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 input 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)
Port Set-Up
G1 WDOUT WATCHDOG and/or CLock Monitor if WATCHDOG enabled, otherwise it is a general purpose I/O
Hi-Z Input
G0 INTR (External Interrupt Input)
(TRI-STATE Output) 0
1
Input with Weak Pull-Up
1
0
Push-Pull Zero Output
1
1
Push-Pull One Output
Port C is an 8-bit I/O port. The 40-pin device does not have a full complement of Port C pins. The unavailable pins are not terminated. A read operation on these unterminated pins will return unpredictable values. The 28 pin device do not offer Port C. On this device, the associated Port C Data and Configuration registers should not be used.
Port L is an 8-bit I/O port. All L-pins have Schmitt triggers on the inputs.
Port F is an 8-bit I/O port. The 28--pin device does not have a full complement of Port F pins. The unavailable pins are not terminated. A read operation on these unterminated pins will return unpredictable values.
Port L supports the Multi-Input Wake Up feature on all eight pins. 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)
Port F1–F3 are used for Comparator 1. Port F4–F6 are used for Comparator 2.
L5 Multi-input Wakeup or T2B (Timer T2B Input) L4 Multi-input Wakeup or T2A (Timer T2A Input)
The Port F has the following alternate features:
L3 Multi-input Wakeup and/or RDX (USART Receive)
F6 COMP2OUT (Comparator 2 Output)
L2 Multi-input Wakeup or TDX (USART Transmit)
F5 COMP2+IN (Comparator 2 Positive Input)
L1 Multi-input Wakeup and/or CKX (USART Clock)
F4 COMP2-IN (Comparator 2 Negative Input)
L0 Multi-input Wakeup
F3 COMP1OUT (Comparator 1 Output)
Port G is an 8-bit port. Pin G0, G2–G5 are bi-directional I/O ports. Pin G6 is always a general purpose Hi-Z input. All pins have Schmitt Triggers on their inputs. Pin G1 serves as the dedicated WATCHDOG output with weak pullup if
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
11
www.national.com
4.0 Pin Descriptions (Continued)
5.0 Functional Description The architecture of the devices are a modified Harvard architecture. With the Harvard architecture, the program memory EPROM is separated from the data store memory (RAM). Both EPROM and RAM have their own separate addressing space with separate address buses. The architecture, though based on the Harvard architecture, permits transfer of data from EPROM to RAM.
(address xxD7) will return the same data as reading the Port F input pins (address xx96). It is recommended new applications which will go to production with the COPSGx7 use the Port F addresses. Note that compatible ROM devices contains the input only Port I instead of the bi-directional Port F.
Port D is an 8-bit output port that is preset high when RESET goes low. The user can tie two or more D port outputs (except D2) together in order to get a higher drive. Note: Care must be exercised with the D2 pin operation. At RESET, the external loads on this pin must ensure that the output voltages stay above 0.7 VCC to prevent the chip from entering special modes. Also keep the external loading on D2 to less than 1000 pF.
5.1 CPU REGISTERS The CPU can do an 8-bit addition, subtraction, logical or shift operation in one instruction (t C) 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 optionally post auto incremented or decremented. X is an 8-bit alternate RAM address pointer, which can be optionally post auto incremented or decremented. S is the 8-bit Segment Address Register used to extend the lower half of the address range (00 to 7F) into 256 data segments 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 to RAM address 02F Hex (devices with 64 bytes of RAM), or initialized to RAM address 06F Hex (devices with 128 bytes of RAM).
DS100155-10
FIGURE 5. I/O Port Configurations
All the CPU registers are memory mapped with the exception of the Accumulator (A) and the Program Counter (PC). 5.2 PROGRAM MEMORY The program memory consists of 8192 or 32,768 bytes of EPROM. These bytes may hold program instructions or constant data (data tables for the LAID instruction, jump vectors for the JID instruction, and interrupt vectors for the VIS instruction). The program memory is addressed by the 15-bit program counter (PC). All interrupts in the device vector to program memory location 0FF Hex. The contents of the program memory read 00 Hex in the erased state. Program execution starts at location 0 after RESET. DS100155-12
5.3 DATA MEMORY
FIGURE 6. I/O Port Configurations — Output Mode
The data memory address space includes the on-chip RAM and data registers, the I/O registers (Configuration, Data and Pin), the control registers, the MICROWIRE/PLUS SIO shift register, and the various registers, and counters associated with the timers (with the exception of the IDLE timer). Data memory is addressed directly by the instruction or indirectly by the B, X and SP pointers. The data memory consists of 256 or 512 bytes of RAM. Sixteen bytes of RAM are mapped as “registers” at addresses 0F0 to 0FE Hex. These registers can be loaded immediately, and also decremented and tested with the DRSZ (decrement register and skip if zero) instruction. The memory pointer registers X, SP and B are memory mapped into this space at address locations 0FC to 0FE Hex respectively, with the other registers (except 0FF) being available for general usage. The instruction set permits any bit in memory to be set, reset or tested. All I/O and registers (except A and PC) are
DS100155-11
FIGURE 7. I/O Port Configurations — Input Mode www.national.com
12
5.0 Functional Description (Continued)
extension does not take place. Alternatively, if this upper bit equals zero, then the data segment extension register S is used to extend the base address range (from 0000 to 007F) from XX00 to XX7F, where XX represents the 8 bits from the S register. Thus the 128-byte data segment extensions are located from addresses 0100 to 017F for data segment 1, 0200 to 027F for data segment 2, etc., up to FF00 to FF7F for data segment 255. The base address range from 0000 to 007F represents data segment 0.
memory mapped; therefore, I/O bits and register bits can be directly and individually set, reset and tested. The accumulator (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 location for the Data Segment Address Register (S).
Figure 8 illustrates how the S register data memory extension is used in extending the lower half of the base address range (00 to 7F hex) into 256 data segments of 128 bytes each, with a total addressing range of 32 kbytes from XX00 to XX7F. This organization allows a total of 256 data segments of 128 bytes each with an additional upper base segment of 128 bytes. Furthermore, all addressing modes are available for all data segments. The S register must be changed under program control to move from one data segment (128 bytes) to another. However, the upper base segment (containing the 16 memory registers, I/O registers, control registers, etc.) is always available regardless of the contents of the S register, since the upper base segment (address range 0080 to 00FF) is independent of data segment extension.
The data store memory is either addressed directly by a single byte address within the instruction, or indirectly relative to the reference of the B, X, or SP pointers (each contains a single-byte address). This single-byte address allows an addressing range of 256 locations from 00 to FF hex. The upper bit of this single-byte address divides the data store memory into two separate sections as outlined previously. With the exception of the RAM register memory from address locations 00F0 to 00FF, all RAM memory is memory mapped with the upper bit of the single-byte address being equal to zero. This allows the upper bit of the single-byte address 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
DS100155-45
FIGURE 8. RAM Organization RAM represent the 16 data memory registers located at addresses 00F0 to 00FF of the upper base segment. No RAM is located at the upper sixteen addresses (0070 to 007F) of the lower base segment.
The instructions that utilize the stack pointer (SP) always reference the stack as part of the base segment (Segment 0), regardless of the contents of the S register. The S register is not changed by these instructions. Consequently, the stack (used with subroutine linkage and interrupts) is always located in the base segment. The stack pointer will be initialized to point at data memory location 006F as a result of reset.
Additional RAM beyond these initial 128 bytes, however, will always be memory mapped in groups of 128 bytes (or less) at the data segment address extensions (XX00 to XX7F) of the lower base segment. The additional 384 bytes of RAM in this device are memory mapped at address locations 0100 to 017F, 0200 to 027F and 0300 to 037F hex.
The 128 bytes of RAM contained in the base segment are split between the lower and upper base segments. The first 112 bytes of RAM are resident from address 0000 to 006F in the lower base segment, while the remaining 16 bytes of
13
www.national.com
5.0 Functional Description (Continued)
Both ECON and USER area, 9 bytes total, are outside of the normal address range of the EPROM and can not be accessed by the executing software. This allows for the storage of non-secured information. Typical uses are for storage of serial numbers, data codes, version numbers, copyright information, lot numbers, etc.
Memory address ranges 0200 to 027F and 0300 to 037F are unavailable on the COP8SGE7, and if read, will return underfined data. 5.5 ECON (EPROM CONFIGURATION) REGISTER
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 automatically by programmers that are certified by National.
The ECON register is used to configure the user selectable clock, security, power-on reset, WATCHDOG, and HALT options. The register can be programmed and read only in EPROM programming mode. Therefore, the register should be programmed at the same time as the program memory. The contents of the ECON register shipped from the factory read 00 Hex (windowed device) or 80 Hex (OTP device).
The following examples illustrate the declaration of ECON and the User information. Syntax: [label:] .sect .db
The format of the ECON register is as follows: Bit 7
Bit 6
Bit 5
Bit 4
Bit 3
X
POR
SECURITY
CKI 2
CKI 1
Bit 2 W ATCH
Bit 1
Bit 0
F-Por t
HALT
Bit 6 Bit 5
=x
.endsect
=1
Power-on reset enabled. Power-on reset disabled.
=1
Security enabled. EPROM read and write are not allowed.
=0
Security disabled. EPROM read and write are allowed.
These devices have a security feature, when enabled, that prevents external reading of the OTP program memory. The security bit in the ECON register determines, whether security 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 externally read the contents of the EPROM will result in the value FF Hex being read from all program locations. In addition, with the security feature enabled, the write operation to the EPROM program memory and ECON register is inhibited. The ECON register is readable regardless of the state of the security bit.
= 1, 1 Crystal oscillator with on-chip crystal bias resistor enabled. G7 (CKO) is the clock generator output to crystal/resonator.
Bit 1
Bit 0
=0
WATCHDOG feature enabled. G1 pin is WATCHDOG output with weak pullup.
=1
Force port I compatibility. Disable port F outputs and pull-ups. This is intended for compatibility with existing code and Mask ROMMed devices only. This bit should be programmed to 0 for all other applications.
=0
Enable full port F capability.
=1
HALT mode disabled.
=0
HALT mode enabled.
0x55 ;por, xtal, wd, halt 'my v1.00' ;user data declaration
5.7 OTP SECURITY
= 1, 0 Crystal oscillator with on-chip crystal bias resistor disabled. G7 (CKO) is the clock generator output to crystal/resonator.
WATCHDOG feature disabled. G1 is a general purpose I/O.
econ, conf
.db .db
Note: All programmers certified for programming this family of parts will support programming of the CONFiguration section. Please contact National or your device programmer supplier for more information.
= 0, 1 R/C oscillator option selected. G7 is available as a HALT restart and/or general purpose input. CKI clock input. Internal R/C components are supplied for maximum R/C frequency.
= 1
.sect
.endsect
Bits 4, 3 = 0, 0 External CKI option selected. G7 is available as a HALT restart and/or general purpose input. CKI is clock input.
Bit 2
; up to 8 bytes
Example: The following sets a value in the ECON register and User Identification for a COP8SGR728M7. The ECON bit values shown select options: Power-on enabled, Security disabled, Crystal oscillator with on-chip bias disabled, WATCHDOG enabled and HALT mode enabled.
This is for factory test. The polarity is “Don’t Care.”
=0
;configures options
.db
DOG
Bit 7
econ, conf value ;1 byte,
If security is being used, it is recommended that all other bits in the ECON register be programmed first. Then the security bit can be programmed. 5.8 RESET The devices are initialized when the RESET pin is pulled low or the On-chip Power-On Reset is enabled.
5.6 USER STORAGE SPACE IN EPROM In addition to the ECON register, there are 8 bytes of EPROM available for “user information”. ECON and these 8 bytes are outside of the code area and are not protected by the security bit of the ECON register. Even when security is set, information in the 8-byte USER area is both read and write enabled allowing the user to read from and write into the area at all times while still protecting the code from unauthorized access.
www.national.com
DS100155-13
FIGURE 9. Reset Logic
14
5.0 Functional Description (Continued)
5.8.1 External Reset The RESET input when pulled low initializes the device. The RESET pin must be held low for a minimum of one instruction cycle to guarantee a valid reset. During Power-Up initialization, the user must ensure that the RESET pin is held low until the device is within the specified V CC voltage. An R/C circuit on the RESET pin with a delay 5 times (5x) greater than the power supply rise time or 15 µs whichever is greater, is recommended. Reset should also be wide enough to ensure crystal start-up upon Power-Up.
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
RESET may also be used to cause an exit from the HALT mode.
PSW, CNTRL and ICNTRL registers: CLEARED SIOR:
A recommended reset circuit for this device is shown in Fig- ure 10 .
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
DS100155-14
RC > 5x power supply rise time or 15 µs, whichever is greater.
WKEN, WKEDG: CLEARED WKPND: RANDOM
FIGURE 10. Reset Circuit Using External Reset
SP (Stack Pointer): Initialized to RAM address 06F Hex
5.8.2 On-Chip Power-On Reset
B and X Pointers:
The on-chip reset circuit is selected by a bit in the ECON register. When enabled, the device generates an internal reset as V CC rises to a voltage level above 2.0V. The on-chip reset circuitry is able to detect both fast and slow rise times on V CC (VCC rise time between 10 ns and 50 ms).To guarantee an on-chip power-on-reset, V CCmust start at a voltage less than the start voltage specified in the DC characteristics. Also, if VCC be lowered to the start voltage before powering back up to the operating range. If this is not possible, it is recommended that external reset be used.
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
Under no circumstances should the RESET pin be allowed to float. If the on-chip Power-On Reset feature is being used, RESET pin should be connected directly to V CC. The output of the power-on reset detector will always preset the Idle timer to 0FFF(4096 t C). At this time, the internal reset will be generated.
which is set to one. COMPARATORS: CMPSL; CLEARED WATCHDOG (if enabled): The device comes out of reset with both the WATCHDOG logic and the Clock Monitor detector armed, with the WATCHDOG service window bits set and the Clock Monitor bit set. The WATCHDOG and Clock Monitor circuits are inhibited during reset. The WATCHDOG service window bits being initialized high default to the maximum WATCHDOG service window of 64k t C clock cycles. The Clock Monitor bit being initialized high will cause a Clock Monitor error following reset if the clock has not reached the minimum specified frequency at the termination of reset. A Clock Monitor error will cause an active low error output on pin G1. This error output will continue until 16 t C –32 tC clock cycles following the clock frequency reaching the minimum specified value, at which time the G1 output will go high.
If the Power-On Reset feature is enabled, the internal reset will not be turned off until the Idle timer underflows. The internal reset will perform the same functions as external reset. The user is responsible for ensuring that V CC is at the minimum level for the operating frequency within the 4096 t C. After the underflow, the logic is designed such that no additional internal resets occur as long as V CC remains above 2.0V. The contents of data registers and RAM are unknown following the on-chip reset.
15
www.national.com
5.0 Functional Description (Continued)
5.9.1 Crystal Oscillator The crystal Oscillator mode can be selected by programming ECON Bit 4 to 1. CKI is the clock input while G7/CKO is the clock generator output to the crystal. An on-chip bias resistor connected between CKI and CKO can be enabled by programming ECON Bit 3 to 1 with the crystal oscillator option selection. The value of the resistor is in the range of 0.5M to 2M (typically 1.0M). Table 2 shows the component values required for various standard crystal values. Resistor R2 is only used when the on-chip bias resistor is disabled. Figure 13 shows the crystal oscillator connection diagram. TABLE 2. Crystal Oscillator Configuration, TA = 25˚C, V CC = 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 programming ECON Bit 3 to 0 and ECON Bit 4 to 0. CKI can be driven by an external clock signal provided it meets the specified duty cycle, rise and fall times, and input levels. G7/ CKO is available as a general purpose input G7 and/or Halt control. Figure 14 shows the external oscillator connection diagram. 5.9.3 R/C Oscillator
DS100155-15
FIGURE 11. Reset Timing (Power-On Reset Enabled) with VCC Tied to RESET
The R/C Oscillator mode can be selected by programming ECON Bit 3 to 1 and ECON Bit 4 to 0. In R/C oscillation mode, CKI is left floating, while G7/CKO is available as a general purpose input G7 and/or HALT control. The R/C controlled oscillator has on-chip resistor and capacitor for maximum R/C oscillator frequency operation. The maximum frequency is 5 MHz ± 35% for VCC between 4.5V to 5.5V and temperature range of −40˚C to +85˚C. For max frequency operation, the CKI pin should be left floating. For lower frequencies, an external capacitor should be connected between CKI and either VCC or GND. Immunity of the R/C oscillator to external noise can be improved by connecting one half the external capacitance to V CC and one half to GND. PC board trace length on the CKI pin should be kept as short as possible. Table 3 shows the oscillator frequency as a function of external capacitance on the CKI pin. Figure 15 shows the R/C oscillator configuration.
DS100155-16
FIGURE 12. Reset Circuit Using Power-On Reset 5.9 OSCILLATOR CIRCUITS There are four clock oscillator options available: Crystal Oscillator with or without on-chip bias resistor, R/C Oscillator with on-chip resistor and capacitor, and External Oscillator. The oscillator feature is selected by programming the ECON register, which is summarized in Table 1.
TABLE 3. R/C Oscillator Configuration, −40˚C to +85˚C, VCC = 4.5V to 5.5V, OSC Freq. Variation of ± 35%
TABLE 1. Oscillator Option ECON4 ECON3
Oscillator Option
External Capacitor (pF)*
R/C OSC Freq (MHz)
Instr. Cycle (µs) 2.0
0
0
External Oscillator
0
5
1
0
Crystal Oscillator without Bias Resistor
9
4
2.5
0
1
R/C Oscillator
52
2
5.0
1
1
Crystal Oscillator with Bias Resistor
125
1
10
6100
32 kHz
312.5
* Assumes 3-5 pF board capacitance.
www.national.com
16
5.0 Functional Description (Continued) With On-Chip Bias Resistor
Without On-Chip Bias Resistor
DS100155-17
DS100155-18
FIGURE 13. Crystal Oscillator
DS100155-19
FIGURE 14. External Oscillator
DS100155-21
DS100155-20
For operation at lower than maximum R/C oscillator frequency.
For operation at maximum R/C oscillator frequency.
FIGURE 15. R/C Oscillator
17
www.national.com
5.0 Functional Description (Continued)
T1ENB
Timer T1 Interrupt Enable for T1B Input capture edge
5.10 CONTROL REGISTERS T2CNTRL Register (Address X'00C6) CNTRL Register (Address X'00EE) T1C3
T1C2
T1C1
T1C0
MSEL
T2 C3
IEDG
SL1
Bit 7
SL0
T2 C2
T 2C 1
T 2C 0
T2 PN DA
T2 EN A
T 2P ND B
T 2EN B
Bit 7
Bit 0
Bit 0
The T2CNTRL control register contains the following bits:
The Timer1 (T1) and MICROWIRE/PLUS control register contains the following bits:
T2C3
Timer T2 mode control bit
T2C2
Timer T2 mode control bit
T1C3
Timer T1 mode control bit
T2C1
Timer T2 mode control bit
T1C2
Timer T1 mode control bit
T2C0
T1C1
Timer T1 mode control bit
Timer T2 S tart/S top cont rol in t imer modes 1 and 2, T2 Underflow Interrupt Pending Flag in timer mode 3
T2PNDA
Timer T2 Interrupt Pending Flag (Autoreload RA in mode 1, T2 Underflow in mode 2, T2A capture edge in mode 3)
T2ENA
Timer T2 Interrupt Enable for Timer Underflow or T2A Input capture edge
(0 = Rising edge, 1 = Falling edge)
T2PNDB
Select the MICROWIRE/PLUS clock divide by (00 = 2, 01 = 4, 1x = 8)
Timer T2 Interrupt Pending Flag for T2B capture edge
T2ENB
Timer T2 Interrupt Enable for Timer Underflow or T2B Input capture edge
T1C0
Timer T1 Start/Stop control in timer modes 1 and 2, T1 Underflow Interrupt Pending Flag in timer mode 3
MSEL
Selects G5 and G4 as MICROWIRE/PLUS signals SK and SO respectively
IEDG
External interrupt edge polarity select
SL1 & SL0
PSW Register (Address X'00EF) HC
C
T1PNDA
T1ENA
T3CNTRL Register (Address X'00B6)
EXPND
BUSY
EXEN
GIE
Bit 7
T3 C3
Bit 0
The PSW register contains the following select bits: HC
Half Carr y Flag
C
Carry Flag
T1ENA
Timer T1 Interrupt Enable for Timer Underflow or 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 that affect the Carry flag. The SC (Set Carry) and R/C (Reset Carry) instructions will respectively set or clear both the carry flags. In addition to the SC and R/C instructions, ADC, SUBC, RRC and RLC instructions affect the Carry and Half Carry flags.
T0PND
T0EN
µWPND
µWEN
T1PNDB
T 3C 0
T3 PN DA
T3 EN A
T 3P ND B
T 3EN B Bit 0
Timer T3 mode control bit
T3C2
Timer T3 mode control bit
T3C1
Timer T3 mode control bit
T3C0
Timer T3 S tart/S top cont rol in t imer modes 1 and 2, T3 Underflow Interrupt Pending Flag in timer mode 3
T3PNDA
Timer T3 Interrupt Pending Flag (Autoreload RA in mode 1, T3 Underflow in mode 2, T3A capture edge in mode 3)
T3ENA
Timer T3 Interrupt Enable for Timer Underflow or T3A Input capture edge
T3PNDB
Timer T3 Interrupt Pending Flag for T3B capture edge
T3ENB
Timer T3 Interrupt Enable for Timer Underflow or T3B Input capture edge
Each 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.
T1ENB
Bit 7
T3C3
6.0 Timers
ICNTRL Register (Address X'00E8) LPEN
T 3C 1
The T3CNTRL control register contains the following bits:
T1PNDA Timer T1 Interrupt Pending Flag (Autoreload RA in mode 1, T1 Underflow in Mode 2, T1A capture edge in mode 3)
Reserved
T3 C2
Bit 7
Bit 0
The ICNTRL register contains the following bits:
6.1 TIMER T0 (IDLE TIMER)
Reserved This bit is reserved and should to zero
T0PND
Timer T0 Interrupt pending
T0EN
Timer T0 Interrupt Enable (Bit 12 toggle)
Each device supports applications that require maintaining real time and low power with the IDLE mode. This IDLE mode support is furnished by the IDLE timer T0. The Timer T0 runs continuously at the fixed rate of the instruction cycle clock, tC. The user cannot read or write to the IDLE TimerT0, which is a count down timer.
µWPND
MICROWIRE/PLUS interrupt pending
The Timer T0 supports the following functions:
µWEN
Enable MICROWIRE/PLUS interrupt
T1PNDB
Timer T1 Interrupt Pending Flag for T1B capture edge
• • •
LPEN
www.national.com
L Port Interrupt Enable (Multi-Input Wakeup/ Interrupt)
18
Exit out of the Idle Mode (See Idle Mode description) WATCHDOG logic (See WATCHDOG description) Start up delay out of the HALT mode
6.0 Timers (Continued) •
and the reload values are automatically written into the timer when it counts down through 0, generating interrupt on each reload. Under software control and with minimal overhead, the PMW outputs are useful in controlling motors, triacs, the intensity of displays, and in providing inputs for data acquisition and sine wave generators.
Timing the width of the internal power-on-reset
The IDLE Timer T0 can generate an interrupt when the twelfth bit toggles. This toggle is latched into the T0PND pending flag, and will occur every 4.096 ms at the maximum clock frequency (t C = 1 µs). A control flag T0EN allows the interrupt from the twelfth bit of Timer T0 to be enabled or disabled. Setting T0EN will enable the interrupt, while resetting it will disable the interrupt.
In this mode, the timer Tx counts down at a fixed rate of t C. Upon every underflow the timer is alternately reloaded with the contents of supporting registers, RxA and RxB. The very first underflow of the timer causes the timer to reload from the register RxA. Subsequent underflows cause the timer to be reloaded from the registers alternately beginning with the register RxB.
6.2 TIMER T1, TIMER T2 and TIMER T3 Each device have a set of three powerful timer/counter blocks, T1, T2 and T3. Since T1, T2, and T3 are identical, all comments are equally applicable to any of the three timer blocks which will be referred to as Tx.
Figure 16 shows a block diagram of the timer in PWM mode.
The underflows can be programmed to toggle the TxA output pin. The underflows can also be programmed to generate interrupts.
Each timer block consists of a 16-bit timer, Tx, and two supporting 16-bit autoreload/capture registers, RxA and RxB. Each timer block has two pins associated with it, TxA and TxB. The pin TxA supports I/O required by the timer block, while the pin TxB is an input to the timer block. The timer block has three operating modes: Processor Independent PWM mode, External Event Counter mode, and Input Capture mode.
Underflows from the timer are alternately latched into two pending flags, TxPNDA and TxPNDB. The user must reset these pending flags under software control. Two control enable flags, TxENA and TxENB, allow the interrupts from the timer underflow to be enabled or disabled. Setting the timer enable flag TxENA will cause an interrupt when a timer underflow causes the RxA register to be reloaded into the timer. Setting the timer enable flag TxENB will cause an interrupt when a timer underflow causes the RxB register to be reloaded into the timer. Resetting the timer enable flags will disable the associated interrupts.
The control bits TxC3, TxC2, and TxC1 allow selection of the different modes of operation. 6.2.1 Mode 1. Processor Independent PWM Mode One of the timer’s operating modes is the Processor Independent PWM mode. In this mode, the timer generates a “Processor Independent” PWM signal because once the timer is setup, no more action is required from the CPU which translates to less software overhead and greater throughput. The user software services the timer block only when the PWM parameters require updating. This capability is provided by the fact that the timer has two separate 16-bit reload 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 requires an additional software to update the reload value (alternate between the on-time/off-time).
Either or both of the timer underflow interrupts may be enabled. This gives the user the flexibility of interrupting once per PWM period on either the rising or falling edge of the PWM output. Alternatively, the user may choose to interrupt on both edges of the PWM output. 6.2.2 Mode 2. External Event Counter Mode This mode is quite similar to the processor independent PWM mode described above. The main difference is that the timer, Tx, is clocked by the input signal from the TxA pin. The Tx timer control bits, TxC3, TxC2 andTxC1 allow the timer to be clocked either on a positive or negative edge from the TxA pin. Underflows from the timer are latched into the TxPNDA pending flag. Setting the TxENA control flag will cause an interrupt when the timer underflows.
The timer can generate the PWM output with the width and duty cycle controlled by the values stored in the reload registers. The reload registers control the countdown values
DS100155-46
FIGURE 16. Timer in PWM Mode
19
www.national.com
6.0 Timers (Continued)
the external event occurs, the time of the external event is recorded. Most microcontrollers have a latency time because they cannot determine the timer value when the external event occurs. The capture register eliminates the latency time, thereby allowing the applications program to retrieve the timer value stored in the capture register.
In this mode the input pin TxB can be used as an independent positive edge sensitive interrupt input if the TxENB control flag is set. The occurrence of a positive edge on the TxB input pin is latched into the TxPNDB flag. Figure 17 shows a block diagram of the timer in External Event Counter mode.
In this mode, the timer Tx is constantly running at the fixed t C rate. The two registers, RxA and RxB, act as capture registers. Each register acts in conjunction with a pin. The register RxA acts in conjunction with the TxA pin and the register RxB acts in conjunction with the TxB pin.
Note: The PWM output is not available in this mode since the TxApin is being used as the counter input clock.
The timer value gets copied over into the register when a trigger event occurs on its corresponding pin. Control bits, TxC3, TxC2 and TxC1, allow the trigger events to be specified either as a positive or a negative edge. The trigger condition for each input pin can be specified independently. The trigger conditions can also be programmed to generate interrupts. The occurrence of the specified trigger condition on the TxA and TxB pins will be respectively latched into the pending flags, TxPNDA and TxPNDB. The control flag TxENA allows the interrupt on TxA to be either enabled or disabled. Setting the TxENA flag enables interrupts to be generated when the selected trigger condition occurs on the TxA pin. Similarly, the flag TxENB controls the interrupts from the TxB pin.
DS100155-47
Underflows from the timer can also be programmed to generate interrupts. Underflows are latched into the timer TxC0 pending flag (the TxC0 control bit serves as the timer underflow interrupt pending flag in the Input Capture mode). Consequently, the TxC0 control bit should be reset when entering the Input Capture mode. The timer underflow interrupt is enabled with the TxENA control flag. When a TxA interrupt occurs in the Input Capture mode, the user must check both the TxPNDA and TxC0 pending flags in order to determine whether a TxA input capture or a timer underflow (or both) caused the interrupt.
FIGURE 17. Timer in External Event Counter Mode 6.2.3 Mode 3. Input Capture Mode Each device can precisely measure external frequencies or time external events by placing the timer block, Tx, in the input capture mode. In this mode, the reload registers serve as independent capture registers, capturing the contents of the timer when an external event occurs (transition on the timer input pin). The capture registers can be read while maintaining count, a feature that lets the user measure elapsed time and time between events. By saving the timer value when
Figure 18 shows a block diagram of the timer T1 in Input Capture mode. Timer T2 and T3 are identical to T1.
DS100155-48
FIGURE 18. Timer in Input Capture Mode
www.national.com
20
6.0 Timers (Continued)
TxPNDA Timer Interrupt Pending Flag TxENA
6.3 TIMER CONTROL FLAGS
1 = Timer Interrupt Enabled
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 (Processor Independent PWM and External Event Counter), where 1 = Start, 0 = Stop Timer Underflow Interrupt Pending Flag in Mode 3 (Input Capture)
Timer Interrupt Enable Flag 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
1
2
Interrupt B Source
PWM: TxA Toggle
Autoreload RA
Autoreload RB
PWM: No TxA Toggle
Autoreload RA
Autoreload RB
0
External Event Counter
Timer Underflow
Pos. TxB Edge
Pos. TxA Edge
0
1
External Event Counter
Timer Underflow
Pos. TxB Edge
Pos. TxA Edge
1
0
Captures:
Pos. TxA Edge
Pos. TxB Edge
tC
TxA Pos. Edge
or Timer tC
TxC2
TxC1
1
0
1
1
0
0
0
0
0 0
1
3
Interrupt A Source
TxC3
0
1
1
1
1
0
1
1
Description
T xB Pos. Edge
Underf low
Captures:
Pos. TxA
Neg. TxB
TxA Pos. Edge
Edge or Timer
Edge
TxB Neg. Edge
Underflow
Captures:
Neg. TxA
Neg. TxB
TxA Neg. Edge
Edge or Timer
Edge
TxB Neg. Edge
Underflow
Captures:
Neg. TxA
Neg. TxB
TxA Neg. Edge
Edge or Timer
Edge
TxB Neg. Edge
Underflow
21
Timer Counts On tC tC
tC
tC
www.national.com
7.0 Power Saving Features
On wakeup from G7 or Port L, the devices resume execution from the HALT point. On wakeup from RESET execution will resume from location PC=0 and all RESET conditions apply.
Today, the proliferation of battery-operated based applications has placed new demands on designers to drive power consumption down. Battery-operated systems are not the only type of applications demanding low power. The power budget constraints are also imposed on those consumer/ industrial applications where well regulated and expensive power supply costs cannot be tolerated. Such applications rely on low cost and low power supply voltage derived directly from the “mains” by using voltage rectifier and passive components. Low power is demanded even in automotive applications, due to increased vehicle electronics content. This is required to ease the burden from the car battery. Low power 8-bit microcontrollers supply the smarts to control battery-operated, consumer/industrial, and automotive applications.
If a crystal or ceramic resonator may be selected as the oscillator, the Wakeup signal is not allowed to start the chip running immediately since crystal oscillators and ceramic resonators have a delayed start up time to reach full amplitude and frequency stability. The IDLE timer is used to generate a fixed delay to ensure that the oscillator has indeed stabilized before allowing instruction execution. In this case, upon detecting a valid Wakeup signal, only the oscillator circuitry is enabled. The IDLE timer is loaded with a value of 256 and is clocked with the t C instruction cycle clock. The t C clock is derived by dividing the oscillator clock down by a factor of 9. The Schmitt trigger following the CKI inverter on the chip ensures that the IDLE timer is clocked only when the oscillator has a sufficiently large amplitude to meet the Schmitt trigger specifications. This Schmitt trigger is not part of the oscillator closed loop. The start-up time-out from the IDLE timer enables the clock signals to be routed to the rest of the chip.
Each device offers system designers a variety of low-power consumption features that enable them to meet the demanding requirements of today’s increasing range of low-power applications. These features include low voltage operation, low current drain, and power saving features such as HALT, IDLE, and Multi-Input wakeup (MIWU).
If an R/C clock option is being used, the fixed delay is introduced optionally. A control bit, CLKDLY, mapped as configuration bit G7, controls whether the delay is to be introduced or not. The delay is included if CLKDLY is set, and excluded if CLKDLY is reset. The CLKDLY bit is cleared on reset.
Each device offers the user two power save modes of operation: HALT and IDLE. In the HALT mode, all microcontroller activities are stopped. In the IDLE mode, the on-board oscillator circuitry and timer T0 are active but all other microcontroller activities are stopped. In either mode, all on-board RAM, registers, I/O states, and timers (with the exception of T0) are unaltered.
Each device has two options associated with the HALT mode. The first option enables the HALT mode feature, while the second option disables the HALT mode selected through bit 0 of the ECON register. With the HALT mode enable option, the device will enter and exit the HALT mode as described above. With the HALT disable option, the device cannot be placed in the HALT mode (writing a “1” to the HALT flag will have no effect, the HALT flag will remain “0”).
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 WATCHDOG logic on the devices are disabled during the HALT mode. However, the clock monitor circuitry, if enabled, remains active and will cause the WATCHDOG output pin (WDOUT) to go low. If the HALT mode is used and the user does not want to activate the WDOUT pin, the Clock Monitor should be disabled after the devices come out of reset (resetting the Clock Monitor control bit with the first write to the WDSVR register). In the HALT mode, the power requirements of the devices are minimal and the applied voltage (VCC) may be decreased to V r (Vr = 2.0V) without altering the state of the machine.
The WATCHDOG detector circuit is inhibited during the HALT mode. However, the clock monitor circuit if enabled remains active during HALT mode in order to ensure a clock monitor error if the device inadvertently enters the HALT mode as a result of a runaway program or power glitch. If the device is placed in the HALT mode, with the R/C oscillator selected, the clock input pin (CKI) is forced to a logic high internally. With the crystal or external oscillator the CKI pin is TRI-STATE. It is recommended that the user not halt the device by merely stopping the clock in external oscillator mode. If this method is used, there is a possibility of greater than specified HALT current.
Each device supports three different ways of exiting the HALT mode. The first method of exiting the HALT mode is with the Multi-Input Wakeup feature on Port L. The second method is with a low to high transition on the CKO (G7) pin. This method precludes the use of the crystal clock configuration (since CKO becomes a dedicated output), and so may only be used with an R/C clock configuration. The third method of exiting the HALT mode is by pulling the RESET pin low.
www.national.com
If the user wishes to stop an external clock, it is recommended that the CPU be halted by setting the Halt flag first and the clock be stopped only after the CPU has halted.
22
7.0 Power Saving Features (Continued)
DS100155-25
FIGURE 19. Wakeup from HALT 7.2 IDLE MODE
The user can enter the IDLE mode with the Timer T0 interrupt enabled. In this case, when the T0PND bit gets set, the device will first execute the Timer T0 interrupt service routine and then return to the instruction following the “Enter Idle Mode” instruction.
The device is placed in the IDLE mode by writing a “1” to the IDLE flag (G6 data bit). In this mode, all activities, except the associated on-board oscillator circuitry and the IDLE Timer T0, are stopped.
Alternatively, the user can enter the IDLE mode with the IDLE Timer T0 interrupt disabled. In this case, the device will resume normal operation with the instruction immediately following the “Enter IDLE Mode” instruction.
As with the HALT mode, the device can be returned to normal operation with a reset, or with a Multi-Input Wakeup from the L Port. Alternately, the microcontroller resumes normal operation from the IDLE mode when the twelfth bit (representing 4.096 ms at internal clock frequency of 10 MHz, t C = 1 µs) of the IDLE Timer toggles.
Note: It is necessary to program two NOP instructions following both the set HALT mode and set IDLE mode instructions. These NOP instructions are necessary to allow clock resynchronization following the HALT or IDLE modes.
This toggle condition of the twelfth bit of the IDLE Timer T0 is latched into the T0PND pending flag. The user has the option of being interrupted with a transition on the twelfth bit of the IDLE Timer T0. The interrupt can be enabled or disabled via the T0EN control bit. Setting the T0EN flag enables the interrupt and vice versa.
DS100155-26
FIGURE 20. Wakeup from IDLE
23
www.national.com
7.0 Power Saving Features (Continued)
to negative (high going low) for L Port bit 5, where bit 5 has previously been enabled for an input interrupt. The program would be as follows:
7.3 MULTI-INPUT WAKEUP The Multi-Input Wakeup feature is used to return (wakeup) the device from either the HALT or IDLE modes. Alternately Multi-Input Wakeup/Interrupt feature may also be used to generate up to 8 edge selectable external interrupts. Figure 21 shows the Multi-Input Wakeup logic.
R BI T SBIT
5 , W KE N 5, WKEDG
; Di sa bl e M IW U ; Change edge polarity
RBIT S BI T
5, WKPND 5 , W KE N
; Reset pending flag ; En ab le MI WU
If the L port bits have been used as outputs and then changed to inputs with Multi-Input Wakeup/Interrupt, a safety procedure should also be followed to avoid wakeup conditions. After the selected L port bits have been changed from output to input but before the associated WKEN bits are enabled, the associated edge select bits in WKEDG should be set or reset for the desired edge selects, followed by the associated WKPND bits being cleared.
The Multi-Input Wakeup feature utilizes the L Port. The user selects which particular L port bit (or combination of L Port bits) will cause the device to exit the HALT or IDLE modes. The selection is done through the register WKEN. The register WKEN is an 8-bit read/write register, which contains a control bit for every L port bit. Setting a particular WKEN bit enables a Wakeup from the associated L port pin.
This same procedure should be used following reset, since the L port inputs are left floating as a result of reset.
The user can select whether the trigger condition on the selected L Port pin is going to be either a positive edge (low to high transition) or a negative edge (high to low transition). This selection is made via the register WKEDG, which is an 8-bit control register with a bit assigned to each L Port pin. Setting the control bit will select the trigger condition to be a negative edge on that particular L Port pin. Resetting the bit selects the trigger condition to be a positive edge. Changing an edge select entails several steps in order to avoid a Wakeup condition as a result of the edge change. First, the associated WKEN bit should be reset, followed by the edge select change in WKEDG. Next, the associated WKPND bit should be cleared, followed by the associated WKEN bit being re-enabled.
The occurrence of the selected trigger condition for MultiInput Wakeup is latched into a pending register called WKPND. The respective bits of the WKPND register will be set on the occurrence of the selected trigger edge on the corresponding Port L pin. The user has the responsibility of clearing these pending flags. Since WKPND is a pending register for the occurrence of selected wakeup conditions, the device will not enter the HALT mode if any Wakeup bit is both enabled and pending. Consequently, the user must clear the pending flags before attempting to enter the HALT mode. WKEN and WKEDG are all read/write registers, and are cleared at reset. WKPND register contains random value after reset.
An example may serve to clarify this procedure. Suppose we wish to change the edge select from positive (low going high)
DS100155-27
FIGURE 21. Multi-Input Wake Up Logic
www.national.com
24
8.0 USART
Other functions functions of the ENUR regis register ter include saving the ninth bit received in the data frame, enabling or disabling the USART’s attention attention mode of opera operation tion and provi providing ding additional receiver/transmitter status information via RCVG and XMTG bits. The determination of an internal internal or external clock source is done by the ENUI register, as well as selecting the number of stop bits and enabling or disabling transmit and receive interrupts. A control flag in this register can also selectt the USAR lec USART T mod mode e of ope operat ration ion:: asy asynch nchron ronous ous or synchronous.
Each device contains a full-duplex software programmable USART. The USART (Figure 22 ) consists of a transmit shift register, a receive shift register and seven addressable registers, as follows: a transmit buffer register (TBUF), a receiver buffer register (RBUF), a USART control and status register (ENU), a USART receive control and status register (ENUR), (ENU R), a USAR USART T int interr errupt upt and clo clock ck sou source rce reg registe isterr (ENUI), a prescaler select register (PSR) and baud (BAUD) register. The ENU register contains flags for transmit and receive functions; this register also determines the length of the data frame (7, 8 or 9 bits), the value of the ninth bit in transmission, and parity selection bits. The ENUR register flags framing, data overrun and parity errors while the USART is receiving.
DS100155-39
FIGURE 22. USART Block Diagram 25
www.national.com
8.0 USART (Continued)
DOE = 1
8.1 USART CONTROL AND STATUS STATUS REGISTERS
FE: Flags a Framin Framing g Error Error.. Read only, only, cleare cleared d on read, cleared on reset.
The operation of the USART is programmed through three registers: ENU, ENUR and ENUI. 8.2 DESCRIPTION OF USART REGISTER BITS ENU-USART Control and Status Register (Address at 0BA) PEN
PSEL1 X BI BI T9 T9/
CHL1
CHL0
ERR
RBFL
FE = 0
Indica Ind icates tes no Framin Framing g Error Error has been been detecte detected d since the last time the ENUR register was read.
FE = 1
Indica Ind icates tes the the occu occurre rrence nce of a Frami Framing ng Error Error..
PE: Flags a Parity Error. Read only, cleared on read, cleared PE: Flags on reset.
TBMT
PSEL0 Bit 7
PE = 0
Indicates Indic ates no Parity Error has been detec detected ted since the last time the ENUR register was read.
PE = 1
Indica Ind icates tes the the occu occurre rrence nce of a Parit Parity y Error Error..
Bit 0
PEN: This bit enables/disables Parity (7- and 8-bit modes only). Read/Write, cleared on reset. PEN = 0
Pari Pa rity ty di disa sabl bled ed..
PEN = 1
Pari Pa rity ty en enab able led. d.
SPARE: Reserved for future use. Read/Write, cleared on reSPARE: Reserved set. RBIT9: Contains the ninth data bit received when the USART is operating with nine data bits per frame. Read only, cleared on reset.
PSEL1, PSEL0: Parity PSEL0: Parity select bits. Read/Write, cleared on reset. PSEL1 PSEL 1 = 0, 0, PSEL0 PSEL0 = 0
Odd Par Parity ity (if (if Parity Parity ena enable bled) d)
PSEL1 PSEL 1 = 0, PSEL0 PSEL0 = 1
Even Eve n Parity Parity (if (if Parity Parity ena enable bled) d)
PSEL1 PSEL 1 = 1, 1, PSEL0 PSEL0 = 0
Mark(1 Mar k(1)) (if Par Parity ity enab enabled led))
PSEL1 PSEL 1 = 1, 1, PSEL0 PSEL0 = 1
Space( Spa ce(0) 0) (if (if Parity Parity ena enable bled) d)
ATTN: ATTENTION Mode is enabled while this bit is set. This bit is cleared automatically on receiving a character with data bit nine set. Read/Write, cleared on reset. XMTG: This bit is set to indicate that the USART is transmitXMTG: This ting. It gets reset at the end of the last frame (end of last Stop bit). Read only, cleared on reset.
XBIT9/PSEL0: Programs the ninth bit for transmission when XBIT9/PSEL0: Programs the USART is operating with nine data bits per frame. For seven or eight data bits per frame, this bit in conjunction with PSEL1 selects parity. Read/Write, cleared on reset.
RCVG: This bit is set high whenever a framing error occurs RCVG: This and goes low when RDX goes high. Read only, cleared on reset.
CHL1, CHL0: These CHL0: These bits select the character frame format. Parity is not included and is generated/verified by hardware. Read/Write, cleared on reset.
ENUI-USART Interrupt and Clock Source Register (Address at 0BC)
The fra frame me cont contain ains s eight eight dat data a bits. bits.
STP2
CHL1 CHL 1 = 0, CHL CHL0 0=1
The fr The fram ame e co cont ntai ains ns se seve ven n da data ta bits.
Bit 7
CHL1 CHL 1 = 1, CHL0 CHL0 = 0
The fram frame e conta contains ins nine nine data data bits bits..
CHL1 CHL 1 = 1, CHL CHL0 0 =1
Loopback Loopba ck Mode selected selected.. Tr Trans ans-mitter output internally looped back to receiver input. Nine bit framing format is used.
CHL1 CHL 1 = 0, CHL0 CHL0 = 0
Indicates Indic ates the occur occurrence rence of a Data Overr Overrun un Error.
STP78
One Sto Stop p bit tra transm nsmitte itted. d.
STP2 = 1
Two Tw o Stop Stop bits tran transmi smitte tted. d.
SSEL: USART SSEL: USART mode select. Read/Write, cleared on reset. SSEL = 0
Asynch Asy nchron ronous ous Mod Mode. e.
SSEL = 1
Synchr Syn chrono onous us Mod Mode. e.
XRCLK: This bit selects the clock source for the receiver section. Read/Write, cleared on reset.
(Address (Addre ss at 0BB) RBIT9
ATTN
XMTG
Bit 0
STP2 = 0
XRCLK XRC LK = 0
The Th e cl cloc ock k so sour urce ce is se sele lect cted ed throu through gh the PSR and BAUD registers.
XRCLK XRCL K=1
Signal Sig nal on CKX CKX (L1) (L1) pin pin is use used d as the clo clock. ck.
ENUR-USART Receive Control and Status Register
Reserved
ETI
ETDX: TDX (USART Transmit ETDX: TDX Transmit Pin) is the altern alternate ate function assigned to Port L pin L2; it is selected by setting ETDX bit. To simula simulate te line break gener generation ation,, softwa software re shoul should d reset ETDX bit and output logic zero to TDX pin through Port L data and configuration registers. Read/Write, cleared on reset.
TBMT: This bit is set when the USART transfers a byte of TBMT: This data from the TBUF register into the TSFT register for transmission. It is automatically reset when software writes into the TBUF register. Read only, bit is set to “one” on reset; it cannot be written by software.
PE
ERI
STP78: This bit is set to program the last Stop bit to be 7/8th STP78: This of a bit in length. Read/Write, cleared on reset.
RBFL: This bit is set when the USART has received a comRBFL: This plete character and has copied it into the RBUF register. It is automatically reset when software reads the character from RBUF. Read only; it cannot be written by software, cleared on reset.
FE
SSEL XR XRCLK XT XTCLK
STP2: This bit programs the number of Stop bits to be transSTP2: This mitted. Read/Write, cleared on reset.
ERR: This bit is a global USART error flag which gets set if ERR: This any or a combination of the errors (DOE, FE, PE) occur. Read only; it cannot be written by software, cleared on reset.
DOE
ETDX
XTCLK: This bit selects the clock source for the transmitter XTCLK: section. Read/Write, cleared on reset.
RCVG
(Note 14)
XTCLK XTC LK = 0
The Th e cl cloc ock k so sour urce ce is se sele lect cted ed throu through gh the PSR and BAUD registers.
Note 14: Bit is reserved for future use. User must set to zero.
XTCLK XTCL K=1
Signal Sig nal on on CKX (L1 (L1)) pin is used used as the the cloc clock. k.
DOE: Flags a Data Overrun Error. Read only, cleared on read, cleared on reset.
ERI: This bit enab enables/dis les/disables ables interrupt interrupt from the recei receiver ver section. Read/Write, cleared on reset.
DOE = 0
ERI = 0
Interr Int errupt upt fro from m the the recei receiver ver is disa disable bled. d.
ERI = 1
Interr Int errupt upt fro from m the the recei receiver ver is enab enabled led..
Bit 7
www.national.com
Bit 0
Indica Ind icates tes no no Data Data Overru Overrun n Error Error has has been been dedetected since the last time the ENUR register was read. 26
8.0 USART (Continued)
This mode is selected by setting SSEL bit in the ENUI register. The input frequency to the USART is the same as the baud rate.
ETI: This bit enables/disables interrupt from the transmitter ETI: section. Read/Write, cleared on reset. ETI = 0
Interr Int errupt upt fro from m the tra transm nsmitte itterr is disa disable bled. d.
ETI = 1
Interr Int errupt upt fro from m the tra transm nsmitte itterr is enab enabled led..
When an external clock input is selected at the CKX pin, data transmit and receive are performed synchronously with this clock through TDX/RDX pins. If data transmit and receive are selected with the CKX pin as clock output, the devic device e gene generates rates the synch synchronou ronous s clock output at the CKX pin. The internal baud rate generator is used to produce the synchronous clock. Data transmit and receive are performed synchronously with this clock.
8.3 Associated Associated I/O Pins Data is transmitted on the TDX pin and received on the RDX pin. 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 no setup.
8.5 FRAMING FORMATS The USART supports several serial framing formats ( Figure 23 ). ). The format is selected using control bits in the ENU, ENUR and ENUI registers.
The baud rate clock for the USART can be generated onchip, 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 either an input or an output, as determined by Port L Configuration and Data registers (Bit 1). As an input, it accepts a clock signal which may be selected to drive the transmitter and/or receiver. As an output, it presents the internal Baud Rate Generator output.
The first format (1, 1a, 1b, 1c) for data transmission (CHL0 = 1, CHL1 = 0) consists of Start bit, seven Data bits (excluding parity) and 7/8, one or two Stop bits. In applications using parity, the parity bit is generated and verified by hardware. The second format (CHL0 = 0, CHL1 = 0) consists of one Start bit, eight Data bits (excluding parity) and 7/8, one or two Stop bits. Parity bit is generated and verified by hardware.
8.4 USART Operat Operation ion The USART has two modes of opera operation: tion: asynchronou asynchronous s mode and synchronous mode.
The third format for transmission (CHL0 = 0, CHL1 = 1) consists of one Start bit, nine Data bits and 7/8, one or two Stop bits. This format also supports the USART “ATTENTION” “ATTENTION” feature. When operating in this format, all eight bits of TBUF and RBUF are used for data. The ninth data bit is transmitted and received using two bits in the ENU and ENUR registers, called XBIT9 and RBIT9. RBIT9 is a read only bit. Parity is not generated or verified in this mode.
8.4.1 ASYNCHRONOUS MODE This mode is selected by resetting the SSEL (in the ENUI register) bit to zero. The input frequency to the USART is 16 times the baud rate. The TSFT and TBUF registers double-buffer data for transmission. missio n. While TSFT is shifting out the current character character on the TDX pin, the TBUF register may be loaded by software with the next byte to be transmitted. When TSFT finishes transmitting trans mitting the current character the conte contents nts of TBUF are transferred trans ferred to the TSFT regis register ter and the Transmit Transmit Buffe Bufferr Empty Flag (TBMT in the ENU register) is set. The TBMT flag is automa automatically tically reset by the USART when software loads a new character into the TBUF register. There is also the XMTG bit which is set to indicate that the USART is transmitting. This bit gets reset at the end of the last frame (end of last Stop bit). TBUF is a read/write register.
For any of the above framing formats, the last Stop bit can be programmed programmed to be 7/8th of a bit in lengt length. h. If two Stop bits are selected and the 7/8th bit is set (selected), the second Stop bit will be 7/8th of a bit in length. The parity is enabled/disabled by PEN bit located in the ENU register. Parity is selected for 7- and 8-bit modes only. If parity is enabled (PEN = 1), the parity selection is then performed by PSEL0 and PSEL1 bits located in the ENU register. Note that the XBIT9/PSEL0 bit located in the ENU register serves two mutually exclusive functions. This bit programs the ninth bit for transmission when the USART is operating with nine data bits per frame. There is no parity selection in this framing format. For other framing formats XBIT9 is not needed and the bit is PSEL0 used in conjunction with PSEL1 to select parity.
The RSFT and RBUF registers double-buffer data being received. The USART receiver continually monitors the signal on the RDX pin for a low level to detect the beginning of a Start bit. Upon sensing this low level, it waits for half a bit time and samples again. If the RDX pin is still low, the receiver considers this to be a valid Start bit, and the remaining bits in the character frame are each sampled a single time, at the mid-bit mid-bit pos positio ition. n. Serial data input on the RDX pin is shifted into the RSFT register. Upon receiving the complete character, the contents of the RSFT register are copied into the RBUF register and the Received Buffer Full Flag (RBFL) is set. RBFL is autom automatical atically ly reset when software software reads the character from the RBUF register. RBUF is a read only register. There is also the RCVG bit which is set high when a framing framin g error occu occurs rs and goes low once RDX goes high. TBMT, XMTG, RBFL and RCVG are read only bits.
The frame formats for the receiver differ from the transmitter in the number of Stop bits required. The receiver only requires one Stop bit in a frame, regardless of the setting of the Stop bit selection bits in the control register. Note that an implicit assumption is made for full duplex USART operation that the framing formats are the same for the transmitter and receiver.
8.4.2 SYNCHRONOUS MODE In thi this s mod mode e dat data a is tra transf nsferr erred ed syn synchr chrono onousl usly y wit with h the clock. Data is transmitted on the rising edge and received on the falling edge of the synchronous clock.
27
www.national.com
8.0 USART (Continued)
DS100155-40
FIGURE 23. Framing Formats 8.6 USART INTERRUPTS
the basic baud clock is created from the oscillator frequency through a two-stage divider chain consisting of a 1–16 (increments 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 Baud Rate Divisor spills over into the Prescaler Select Register (PSR). PSR is cleared upon reset.
The USART is capable of generating interrupts. Interrupts are generated on Receive Buffer Full and Transmit Buffer Empty. Both interrupts have individual interrupt vectors. Two bytes of program memory space are reserved for each interrupt vector. The two vectors are located at addresses 0xEC to 0xEF Hex in the program memory space. The interrupts can be individually enabled or disabled using Enable Transmit Interrupt (ETI) and Enable Receive Interrupt (ERI) bits in the ENUI register.
As shown in Table 5 , a Prescaler Factor of 0 corresponds to NO CLOCK. This condition is the USART power down mode where the USART clock is turned off for power saving purpose. The user must also turn the USART clock off when a different baud rate is chosen.
The interrupt from the Transmitter is set pending, and remains pending, as long as both the TBMT and ETI bits are set. To remove this interrupt, software must either clear the ETI bit or write to the TBUF register (thus clearing the TBMT bit).
The correspondences between the 5-bit Prescaler Select and Prescaler factors are shown in Table 5 . There are many ways to calculate the two divisor factors, but one particularly effective method would be to achieve a 1.8432 MHz frequency coming out of the first stage. The 1.8432 MHz prescaler output is then used to drive the software programmable baud rate counter to create a 16x clock for the following baud rates: 110, 134.5, 150, 300, 600, 1200, 1800, 2400, 3600, 4800, 7200, 9600, 19200 and 38400 ( Table 4 ). Other baud rates may be created by using appropriate divisors. The 16x clock is then divided by 16 to provide the rate for the serial shift registers of the transmitter and receiver.
The interrupt from the receiver is set pending, and remains pending, as long as both the RBFL and ERI bits are set. To remove this interrupt, software must either clear the ERI bit or read from the RBUF register (thus clearing the RBFL bit). 8.7 Baud Clock Generation The clock inputs to the transmitter and receiver sections of the USART can be individually selected to come either from an external source at the CKX pin (port L, pin L1) or from a source selected in the PSR and BAUD registers. Internally,
www.national.com
28
8.0 USART (Continued)
DS100155-41
FIGURE 24. USART BAUD Clock Generation
DS100155-42
FIGURE 25. USART BAUD Clock Divisor Registers TABLE 4. Baud Rate Divisors (1.8432 MHz Prescaler Output)
Prescaler
Prescaler
Select
Factor 4.5
Baud
Baud Rate
01000
Rate
Divisor − 1 (N-1)
01001
5
01010
5.5
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
2
Note: 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
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
Prescaler
Prescaler
11110
15.5
Select
Factor
11111
16
00000
NO CLOCK
00001
1
00010
1.5
00011
2
00100
2.5
00101
3
00110
3.5
00111
4 29
www.national.com
8.0 USART (Continued)
cause of the finite start up time requirement of the crystal oscillator. The idle timer (T0) generates a fixed (256 t c) delay to ensure that the oscillator has indeed stabilized before allowing the device to execute code. The user has to consider this delay when data transfer is expected immediately after exiting the HALT mode.
As an example, considering Asynchronous Mode and a CKI clock 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 prescaler output is then used with proper Baud Rate Divisor (Table 4 ) to obtain different baud rates. For a baud rate of 19200 e.g., the entry in Table 4 is 5.
8.9 Diagnostic Bits CHARL0 and CHARL1 in the ENU register provide a loopback feature for diagnostic testing of the USART. When these bits are set to one, the following occur: The receiver input pin (RDX) is internally connected to the transmitter output pin (TDX); the output of the Transmitter Shift Register is “looped back” into the Receive Shift Register input. In this mode, data that is transmitted is immediately received. This feature allows the processor to verify the transmit and receive data paths of the USART.
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 asynchronous mode, the input frequency to the USART is 16 times the baud rate. The equation to calculate baud rates is given below.
Note that the framing format for this mode is the nine bit format; one Start bit, nine data bits, and 7/8, one or two Stop bits. Parity is not generated or verified in this mode.
The actual Baud Rate may be found from: BR = Fc/(16 x N x P) Where: BR is the Baud Rate
8.10 Attention Mode
Fc is the CKI frequency
The USART Receiver section supports an alternate mode of operation, referred to as ATTENTION Mode. This mode of operation is selected by the ATTN bit in the ENUR register. The data format for transmission must also be selected as having nine Data bits and either 7/8, one or two Stop bits.
N is the Baud Rate Divisor ( Table 4 ). P is the Prescaler Divide Factor selected by the value in the Prescaler Select Register (Table 5 ) Note: In the Synchronous Mode, the divisor 16 is replaced by two.
The ATTENTION mode of operation is intended for use in networking the device with other processors. Typically in such environments the messages consists of device addresses, indicating which of several destinations should receive them, and the actual data. This Mode supports a scheme in which addresses are flagged by having the ninth bit of the data field set to a 1. If the ninth bit is reset to a zero the byte is a Data byte.
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 ) to obtain a value closest to an integer. This factor happens to be 6.5 (P = 6.5).
While in ATTENTION mode, the USART monitors the communication flow, but ignores all characters until an address character is received. Upon receiving an address character, the USART signals that the character is ready by setting the RBFL flag, which in turn interrupts the processor if USART Receiver interrupts are enabled. The ATTN bit is also cleared automatically at this point, so that data characters as well as address characters are recognized. Software examines the contents of the RBUF and responds by deciding either to accept the subsequent data stream (by leaving the ATTN bit reset) or to wait until the next address character is seen (by setting the ATTN bit again).
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 10 6)/(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 or IDLE modes are entered. This reinitialization sets the TBMT flag and resets all read only bits in the USART control and status registers. Read/Write bits remain unchanged. The Transmit Buffer (TBUF) is not affected, but the Transmit Shift register (TSFT) bits are set to one. The receiver registers RBUF and RSFT are not affected.
Operation of the USART Transmitter is not affected by selection of this Mode. The value of the ninth bit to be transmitted is programmed by setting XBIT9 appropriately. The value of the ninth bit received is obtained by reading RBIT9. Since this bit is located in ENUR register where the error flags reside, a bit operation on it will reset the error flags.
The device will exit from the HALT/IDLE modes when the Start bit of a character is detected at the RDX (L3) pin. This feature is obtained by using the Multi-Input Wakeup scheme provided on the device. Before entering the HALT or IDLE modes the user program must select the Wakeup source to be on the RDX pin. This selection is done by setting bit 3 of WKEN (Wakeup Enable) register. The Wakeup trigger condition is then selected to be high to low transition. This is done via the WKEDG register (Bit 3 is one.) If the device is halted and crystal oscillator is used, the Wakeup signal will not start the chip running immediately be-
www.national.com
30
9.0 Comparators
A Comparator Select Register (CMPSL) is used to enable the comparators, read the outputs of the comparators internally, and enable the outputs of the comparators to the pins. Two control bits (enable and output enable) and one result bit are associated with each comparator. The comparator result bits (CMP1RD and CMP2RD) are read only bits which will read as zero if the associated comparator is not enabled. The Comparator Select Register is cleared with reset, resulting in the comparators being disabled. The comparators should also be disabled before entering either the HALT or IDLE modes in order to save power. The configuration of the CMPSL register is as follows:
The device contains two differential comparators, each with a pair of inputs (positive and negative) and an output. Ports F1–F3 and F4–F6 are used for the comparators. The following 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
CMPSL REGISTER (ADDRESS X’00B7) Reserved
CMP20E
CMP2RD
CMP2EN
CMP10E
CMP1RD
CMP1EN
Reserved
Bit 7
Bit 0
10.0 Interrupts
The CMPSL register contains the following bits: Reserved These bits are reserved and should be zero CMP20E
10.1 INTRODUCTION
Selects pin I6 as comparator 2 output provided that CMP2EN is set to enable the comparator
Each device supports thirteen vectored interrupts. Interrupt sources include Timer 0, Timer 1, Timer 2, Timer 3, Port L Wakeup, Software Trap, MICROWIRE/PLUS, and External Input.
CMP2RD Comparator 2 result (this is a read only bit, which will read as 0 if the comparator is not enabled) CMP2EN Enable comparator 2 CMP10E
All interrupts force a branch to location 00FF Hex in program memory. The VIS instruction may be used to vector to the appropriate service routine from location 00FF Hex.
Selects pin I3 as comparator 1 output provided that CMPIEN is set to enable the comparator
CMP1RD Comparator 1 result (this is a read only bit, which will read as 0 if the comparator is not enabled)
The Software trap has the highest priority while the default VIS has the lowest priority.
CMP1EN Enable comparator 1
Each of the 13 maskable inputs has a fixed arbitration ranking and vector.
Note that the two unused bits of CMPSL may be used as software flags.
Figure 26 shows the Interrupt Block Diagram.
Note: For compatibility with existing code and with existing Mask ROMMed devices the bits of the CMPSL register will take precedence over the associated Port F configuration and data output bits.
DS100155-28
FIGURE 26. Interrupt Block Diagram
31
www.national.com
10.0 Interrupts (Continued)
interrupt, and jump to the interrupt handling routine corresponding to the highest priority enabled and active interrupt. Alternately, the user may choose to poll all interrupt pending and enable bits to determine the source(s) of the interrupt. If more than one interrupt is active, the user’s program must decide which interrupt to service.
10.2 MASKABLE INTERRUPTS All interrupts other than the Software Trap are maskable. Each maskable interrupt has an associated enable bit and pending flag bit. The pending bit is set to 1 when the interrupt condition occurs. The state of the interrupt enable bit, combined with the GIE bit determines whether an active pending flag actually triggers an interrupt. All of the maskable interrupt pending and enable bits are contained in mapped control registers, and thus can be controlled by the software.
Within a specific interrupt service routine, the associated pending bit should be cleared. This is typically done as early as possible in the service routine in order to avoid missing the next occurrence of the same type of interrupt event. Thus, if the same event occurs a second time, even while the first occurrence is still being serviced, the second occurrence will be serviced immediately upon return from the current interrupt routine.
A maskable interrupt condition triggers an interrupt under the following conditions: 1.
The enable bit associated with that interrupt is set.
An interrupt service routine typically ends with an RETI instruction. This instruction sets the GIE bit back to 1, pops the address stored on the stack, and restores that address to the program counter. Program execution then proceeds with the next instruction that would have been executed had there been no interrupt. If there are any valid interrupts pending, the highest-priority interrupt is serviced immediately upon return from the previous interrupt.
2. The GIE bit is set. 3.
The device is not processing a non-maskable interrupt. (If a non-maskable interrupt is being serviced, a maskable interrupt must wait until that service routine is completed.)
An interrupt is triggered only when all of these conditions are met at the beginning of an instruction. If different maskable interrupts meet these conditions simultaneously, the highest priority interrupt will be serviced first, and the other pending interrupts must wait.
10.3 VIS INSTRUCTION The general interrupt service routine, which starts at address 00FF Hex, must be capable of handling all types of interrupts. The VIS instruction, together with an interrupt vector table, directs the device to the specific interrupt handling routine based on the cause of the interrupt.
Upon Reset, all pending bits, individual enable bits, and the GIE bit are reset to zero. Thus, a maskable interrupt condition cannot trigger an interrupt until the program enables it by setting both the GIE bit and the individual enable bit. When enabling an interrupt, the user should consider whether or not a previously activated (set) pending bit should be acknowledged. If, at the time an interrupt is enabled, any previous occurrences of the interrupt should be ignored, the associated pending bit must be reset to zero prior to enabling the interrupt. Otherwise, the interrupt may be simply enabled; if the pending bit is already set, it will immediately trigger an interrupt. A maskable interrupt is active if its associated enable and pending bits are set.
VIS is a single-byte instruction, typically used at the very beginning of the general interrupt service routine at address 00FF Hex, or shortly after that point, just after the code used for context switching. The VIS instruction determines which enabled and pending interrupt has the highest priority, and causes an indirect jump to the address corresponding to that interrupt source. The jump addresses (vectors) for all possible interrupts sources are stored in a vector table. The vector table may be as long as 32 bytes (maximum of 16 vectors) and resides at the top of the 256-byte block containing the VIS instruction. However, if the VIS instruction is at the very top of a 256-byte block (such as at 00FF Hex), the vector table resides at the top of the next 256-byte block. Thus, if the VIS instruction is located somewhere between 00FF and 01DF Hex (the usual case), the vector table is located between addresses 01E0 and 01FF Hex. If the VIS instruction is located between 01FF and 02DF Hex, then the vector table is located between addresses 02E0 and 02FF Hex, and so on.
An interrupt is an asychronous event which may occur before, during, or after an instruction cycle. Any interrupt which occurs during the execution of an instruction is not acknowledged until the start of the next normally executed instruction is to be skipped, the skip is performed before the pending interrupt is acknowledged. At the start of interrupt acknowledgment, the following actions occur: 1.
2.
The GIE bit is automatically reset to zero, preventing any subsequent maskable interrupt from interrupting the current service routine. This feature prevents one maskable interrupt from interrupting another one being serviced.
Each vector is 15 bits long and points to the beginning of a specific interrupt service routine somewhere in the 32 kbyte memory space. Each vector occupies two bytes of the vector table, with the higher-order byte at the lower address. The vectors are arranged in order of interrupt priority. The vector of the maskable interrupt with the lowest rank is located to 0yE0 (higher-order byte) and 0yE1 (lower-order byte). The next priority interrupt is located at 0yE2 and 0yE3, and so forth in increasing rank. The Software Trap has the highest rank and its vector is always located at 0yFE and 0yFF. The number of interrupts which can become active defines the size of the table.
The address of the instruction about to be executed is pushed 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 the actions listed above. If the user wishes to allow nested interrupts, the interrupts service routine may set the GIE bit to 1 by writing to the PSW register, and thus allow other maskable interrupts to interrupt the current service routine. If nested interrupts are allowed, caution must be exercised. The user must write the program in such a way as to prevent stack overflow, loss of saved context information, and other unwanted conditions.
Table 6 shows the types of interrupts, the interrupt arbitration ranking, and the locations of the corresponding vectors in the vector table.
The vector table should be filled by the user with the memory locations of the specific interrupt service routines. For ex-
The interrupt service routine stored at location 00FF Hex should use the VIS instruction to determine the cause of the www.national.com
32
10.0 Interrupts (Continued)
gram context (A, B, X, etc.) and executing the RETI instruction, an interrupt service routine can be terminated by returning to the VIS instruction. In this case, interrupts will be serviced in turn until no further interrupts are pending and the default VIS routine is started. After testing the GIE bit to ensure that execution is not erroneous, the routine should restore the program context and execute the RETI to return to the interrupted program.
ample, if the Software Trap routine is located at 0310 Hex, then the vector location 0yFE and -0yFF should contain the data 03 and 10 Hex, respectively. When a Software Trap interrupt occurs and the VIS instruction is executed, the program jumps to the address specified in the vector table. The interrupt sources in the vector table are listed in order of rank, from highest to lowest priority. If two or more enabled and pending interrupts are detected at the same time, the one with the highest priority is serviced first. Upon return from the interrupt service routine, the next highest-level pending interrupt is serviced.
This technique can save up to fifty instruction cycles (t c), or more, (50µs at 10 MHz oscillator) of latency for pending interrupts with a penalty of fewer than ten instruction cycles if no further interrupts are pending. To ensure reliable operation, the user should always use the VIS instruction to determine the source of an interrupt. Although it is possible to poll the pending bits to detect the source of an interrupt, this practice is not recommended. The use of polling allows the standard arbitration ranking to be altered, but the reliability of the interrupt system is compromised. The polling routine must individually test the enable and pending bits of each maskable interrupt. If a Software Trap interrupt should occur, it will be serviced last, even though it should have the highest priority. Under certain conditions, a Software Trap could be triggered but not serviced, resulting in an inadvertent “locking out” of all maskable interrupts by the Software Trap pending flag. Problems such as this can be avoided by using VIS instruction.
If the VIS instruction is executed, but no interrupts are enabled and pending, the lowest-priority interrupt vector is used, and a jump is made to the corresponding address in the vector table. This is an unusual occurrence, and may be the result of an error. It can legitimately result from a change in the enable bits or pending flags prior to the execution of the VIS instruction, such as executing a single cycle instruction which clears an enable flag at the same time that the pending flag is set. It can also result, however, from inadvertent execution of the VIS command outside of the context of an interrupt. The default VIS interrupt vector can be useful for applications in which time critical interrupts can occur during the servicing of another interrupt. Rather than restoring the pro-
TABLE 6. Interrupt Vector Table Arbitration Ranking
Source
Description INTR Instruction
Vector Address (Note 15) (Hi-Low Byte)
(1) Highest
Software
(2)
Reserved
0yFE–0yFF
(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
(8)
Reserved
(9)
UART
(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
0yFC–0yFD
0yF2–0yF3 0yF0–0yF1
Receive
0yEE–0yEF
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 address of a block. In this case, the table must be in the next block.
33
www.national.com
10.0 Interrupts (Continued)
mains unchanged. The new PC is therefore pointing to the vector of the active interrupt with the highest arbitration ranking. This vector is read from program memory and placed into the PC which is now pointed to the 1st instruction of the service routine of the active interrupt with the highest arbitration ranking.
10.3.1 VIS Execution When the VIS instruction is executed it activates the arbitration logic. The arbitration logic generates an even number between E0 and FE (E0, E2, E4, E6 etc...) depending on which active interrupt has the highest arbitration ranking at the time of the 1st cycle of VIS is executed. For example, if the software trap interrupt is active, FE is generated. If the external interrupt is active and the software trap interrupt is not, then FA is generated and so forth. If the only active interrupt is software trap, than E0 is generated. This number replaces the lower byte of the PC. The upper byte of the PC re-
Figure 27 illustrates the different steps performed by the VIS instruction. Figure 28 shows a flowchart for the VIS instruction.
The non-maskable interrupt pending flag is cleared by the RPND (Reset Non-Maskable Pending Bit) instruction (under certain conditions) and upon RESET.
DS100155-29
FIGURE 27. VIS Operation
www.national.com
34
10.0 Interrupts (Continued)
DS100155-30
FIGURE 28. VIS Flowchart
35
www.national.com
10.0 Interrupts (Continued) Programming Example: External Interrupt
WAIT:
PSW
=00EF
CNTRL RBIT
=00EE 0,PORTGC
RBIT SBIT
0,PORTGD IEDG, CNTRL
; G0 pin configured Hi-Z ; Ext interrupt polarity; falling edge
SBIT SBIT
EXEN, PSW GIE, PSW
; Enable the external interrupt ; Set the GIE bit
JP .
WAIT
; Wait for external interrupt
. . .=0FF VIS
; The interrupt causes a ; branch to address 0FF ; The VIS causes a branch to ;interrupt vector table
. . . .=01FA .ADDRW SERVICE
; Vector table (within 256 byte ; 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
www.national.com
INT_EXIT
; Return, set the GIE bit
36
10.0 Interrupts (Continued)
flag; upon return to the first Software Trap routine, the STPND flag will have the wrong state. This will allow maskable interrupts to be acknowledged during the servicing of the first Software Trap. To avoid problems such as this, the user program should contain the Software Trap routine to perform a recovery procedure rather than a return to normal execution.
10.4 NON-MASKABLE INTERRUPT 10.4.1 Pending Flag There is a pending flag bit associated with the non-maskable interrupt, called STPND. This pending flag is not memorymapped and cannot be accessed directly by the software.
Under normal conditions, the STPND flag is reset by a RPND instruction in the Software Trap service routine. If a programming error or hardware condition (brownout, power supply glitch, etc.) sets the STPND flag without providing a way for it to be cleared, all other interrupts will be locked out. To alleviate this condition, the user can use extra RPND instructions in the main program and in the WATCHDOG service routine (if present). There is no harm in executing extra RPND instructions in these parts of the program.
The pending flag is reset to zero when a device Reset occurs. When the non-maskable interrupt occurs, the associated pending bit is set to 1. The interrupt service routine should contain an RPND instruction to reset the pending flag to zero. The RPND instruction always resets the STPND flag. 10.4.2 Software Trap The Software Trap is a special kind of non-maskable interrupt which occurs when the INTR instruction (used to acknowledge interrupts) is fetched from program memory and placed in the instruction register. This can happen in a variety of ways, usually because of an error condition. Some examples of causes are listed below.
10.5 PORT L INTERRUPTS Port L provides the user with an additional eight fully selectable, edge sensitive interrupts which are all vectored into the same service subroutine. The interrupt from Port L shares logic with the wake up circuitry. The register WKEN allows interrupts from Port L to be individually enabled or disabled. The register WKEDG specifies the trigger condition to be either a positive or a negative edge. Finally, the register WKPND latches in the pending trigger conditions.
If the program counter incorrectly points to a memory location beyond the available program memory space, the nonexistent or unused memory location returns zeroes which is interpreted as the INTR instruction. If the stack is popped beyond the allowed limit (address 06F Hex), a 7FFF will be loaded into the PC, if this last location in program memory is unprogrammed or unavailable, a Software Trap will be triggered.
The GIE (Global Interrupt Enable) bit enables the interrupt function. A control flag, LPEN, functions as a global interrupt enable for Port L interrupts. Setting the LPEN flag will enable interrupts and vice versa. A separate global pending flag is not needed since the register WKPND is adequate.
A Software Trap can be triggered by a temporary hardware condition 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 GIE bit is not affected and the pending bit (not accessible by the user) is used to inhibit other interrupts and to direct the program to the ST service routine with the VIS instruction. Nothing can interrupt a Software Trap service routine except for another Software Trap. The STPND can be reset only by the RPND instruction or a chip Reset.
Since Port L is also used for waking the device out of the HALT or IDLE modes, the user can elect to exit the HALT or IDLE modes either with or without the interrupt enabled. If he elects to disable the interrupt, then the device will restart execution from the instruction immediately following the instruction that placed the microcontroller in the HALT or IDLE modes. In the other case, the device will first execute the interrupt service routine and then revert to normal operation. (See HALT MODE for clock option wakeup information.)
The Software Trap indicates an unusual or unknown error condition. Generally, returning to normal execution at the point where the Software Trap occurred cannot be done reliably. Therefore, the Software Trap service routine should reinitialize the stack pointer and perform a recovery procedure that restarts the software at some known point, similar to a device Reset, but not necessarily performing all the same functions as a device Reset. The routine must also execute the RPND instruction to reset the STPND flag. Otherwise, all other interrupts will be locked out. To the extent possible, the interrupt routine should record or indicate the context of the device so that the cause of the Software Trap can be determined.
10.6 INTERRUPT SUMMARY The device uses the following types of interrupts, listed below in order of priority:
If the user wishes to return to normal execution from the point at which the Software Trap was triggered, the user must first execute RPND, followed by RETSK rather than RETI or RET. This is because the return address stored on the stack is the address of the INTR instruction that triggered the interrupt. The program must skip that instruction in order to proceed with the next one. Otherwise, an infinite loop of Software Traps and returns will occur. Programming a return to normal execution requires careful consideration. If the Software Trap routine is interrupted by another Software Trap, the RPND instruction in the service routine for the second Software Trap will reset the STPND 37
1.
The Software Trap non-maskable interrupt, triggered by the INTR (00 opcode) instruction. The Software Trap is acknowledged immediately. This interrupt service routine can be interrupted only by another Software Trap. The Software Trap should end with two RPND instructions followed by a restart procedure.
2.
Maskable interrupts, triggered by an on-chip peripheral block or an external device connected to the device. Under ordinary conditions, a maskable interrupt will not interrupt any other interrupt routine in progress. A maskable interrupt routine in progress can be interrupted by the non-maskable interrupt request. A maskable interrupt routine should end with an RETI instruction or, prior to restoring context, should return to execute the VIS instruction. This is particularly useful when exiting long interrupt service routiness if the time between interrupts is short. In this case the RETI instruction would only be executed when the default VIS routine is reached. www.national.com
11.0 WATCHDOG/Clock Monitor
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 and pin G1 becomes the WATCHDOG output with a weak pullup.
Each device contains a user selectable WATCHDOG and clock monitor. The following section is applicable only if WATCHDOG feature has been selected in the ECON register. The WATCHDOG is designed to detect the user program getting stuck in infinite loops resulting in loss of program control or “runaway” programs.
The WATCHDOG and Clock Monitor are disabled during reset. The device comes out of reset with the WATCHDOG armed, the WATCHDOG Window Select bits (bits 6, 7 of the WDSVR Register) set, and the Clock Monitor bit (bit 0 of the WDSVR Register) enabled. Thus, a Clock Monitor error will occur after coming out of reset, if the instruction cycle clock frequency has not reached a minimum specified value, including the case where the oscillator fails to start.
The WATCHDOG logic contains two separate service windows. While the user programmable upper window selects the WATCHDOG service time, the lower window provides protection against an infinite program loop that contains the WATCHDOG service instruction.
The WDSVR register can be written to only once after reset and the key data (bits 5 through 1 of the WDSVR Register) must match to be a valid write. This write to the WDSVR register involves two irrevocable choices: (i) the selection of the WATCHDOG service window (ii) enabling or disabling of the Clock Monitor. Hence, the first write to WDSVR Register involves selecting or deselecting the Clock Monitor, select the WATCHDOG service window and match the WATCHDOG key data. Subsequent writes to the WDSVR register will compare the value being written by the user to the WATCHDOG service window value and the key data (bits 7 through 1) in the WDSVR Register. Table 9 shows the sequence of events that can occur.
The Clock Monitor is used to detect the absence of a clock or a 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 the upper limit on the service window and WD LOWER defines the lower limit of the service window. Servicing the WATCHDOG consists of writing a specific value to a WATCHDOG Service Register named WDSVR which is memory mapped in the RAM. This value is composed of three fields, consisting of a 2-bit Window Select, a 5-bit Key Data field, and the 1-bit Clock Monitor Select field. Table 7 shows the WDSVR register.
The user must service the WATCHDOG at least once before the upper limit of the service window expires. The WATCHDOG may not be serviced more than once in every lower limit of the service window.
TABLE 7. WATCHDOG Service Register (WDSVR) Window Select
Key Data
Clock Monitor
X
X
0
1
1
0
0
Y
7
6
5
4
3
2
1
0
The WATCHDOG has an output pin associated with it. This is the WDOUT pin, on pin 1 of the port G. WDOUT is active low and must be externally connected to the RESET pin or to some other external logic which handles WATCHDOG event. The WDOUT pin has a weak pullup in the inactive state. This pull-up is sufficient to serve as the connection to V CC for systems which use the internal Power On Reset. Upon triggering the WATCHDOG, the logic will pull the WDOUT (G1) pin low for an additional 16 t C –32 tC cycles after the signal level on WDOUT pin goes below the lower Schmitt trigger threshold. After this delay, the device will stop forcing the WDOUT output low. The WATCHDOG service window will restart when the WDOUT pin goes high.
The lower limit of the service window is fixed at 256 instruction cycles. Bits 7 and 6 of the WDSVR register allow the user to pick an upper limit of the service window. Table 8 shows the four possible combinations of lower and upper limits for the WATCHDOG service window. This flexibility in choosing the WATCHDOG service window prevents any undue burden on the user software.
Bits 5, 4, 3, 2 and 1 of the WDSVR register represent the 5-bit Key Data field. The key data is fixed at 01100. Bit 0 of the WDSVR Register is the Clock Monitor Select bit.
A WATCHDOG service while the WDOUT signal is active will be ignored. The state of the WDOUT pin is not guaranteed on reset, but if it powers up low then the WATCHDOG will time out and WDOUT will go high.
TABLE 8. WATCHDOG Service Window Select WDS VR WDSV R
Cl ock
S ervice Wi ndo w (Lower-Upper Limits)
Bit 7
Bit 6
Monitor
0
0
x
2048–8k t C Cycles
0
1
x
2048–16k t C Cycles
1
0
x
2048–32k t C Cycles
1
1
x
2048–64k t C Cycles
x
x
0
Clock Monitor Disabled
x
x
1
Clock Monitor Enabled
The Clock Monitor forces the G1 pin low upon detecting a clock frequency error. The Clock Monitor error will continue until the clock frequency has reached the minimum specified value, after which the G1 output will go high following 16 tC –32 tC clock cycles. The Clock Monitor generates a continual Clock Monitor error if the oscillator fails to start, or fails to reach the minimum specified frequency. The specification for the Clock Monitor is as follows: 1/tC > 10 kHz— No clock rejection. 1/tC < 10 Hz — Guaranteed clock rejection.
11.1 CLOCK MONITOR The Clock Monitor aboard the device can be selected or deselected under program control. The Clock Monitor is guaranteed not to reject the clock if the instruction cycle clock (1/ tC) is greater or equal to 10 kHz. This equates to a clock input rate on CKI of greater or equal to 100 kHz.
www.national.com
38
11.0 WATCHDOG/Clock Monitor (Continued) TABLE 9. WATCHDOG Service Actions Key
Window
Clock
Data
Data
Monitor
Action
Mat ch
Mat ch
Match
Vali d S ervi ce: Restart S ervi ce 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
•
A hardware WATCHDOG service occurs just as the device exits the IDLE mode. Consequently, the WATCHDOG should not be serviced for at least 256 instruction cycles following IDLE, but must be serviced within the selected window to avoid a WATCHDOG error.
•
Following RESET, the initial WATCHDOG service (where the service window and the CLOCK MONITOR enable/ disable must be selected) may be programmed anywhere within the maximum service window (65,536 instruction cycles) initialized by RESET. Note that this initial WATCHDOG service may be programmed within the initial 256 instruction cycles without causing a WATCHDOG error.
The following salient points regarding the WATCHDOG and CLOCK MONITOR should be noted:
•
Both the WATCHDOG and CLOCK MONITOR detector circuits are inhibited during RESET.
•
Following RESET, the WATCHDOG and CLOCK MONITOR are both enabled, with the WATCHDOG having the maximum service window selected.
•
The WATCHDOG service window and CLOCK MONITOR enable/disable option can only be changed once, during the initial WATCHDOG service following RESET.
•
The initial WATCHDOG service must match the key data value in the WATCHDOG Service register WDSVR in order to avoid a WATCHDOG error.
11.4 DETECTION OF ILLEGAL CONDITIONS
•
Subsequent WATCHDOG services must match all three data fields in WDSVR in order to avoid WATCHDOG errors.
The device can detect various illegal conditions resulting from coding errors, transient noise, power supply voltage drops, runaway programs, etc.
•
The correct key data value cannot be read from the WATCHDOG Service register WDSVR. Any attempt to read this key data value of 01100 from WDSVR will read as key data value of all 0’s.
Reading of undefined ROM gets zeroes. The opcode for software interrupt is 00. If the program fetches instructions from undefined ROM, this will force a software interrupt, thus signaling that an illegal condition has occurred.
•
The WATCHDOG detector circuit is inhibited during both the HALT and IDLE modes.
•
The CLOCK MONITOR detector circuit is active during both the HALT and IDLE modes. Consequently, the device inadvertently entering the HALT mode will be detected as a CLOCK MONITOR error (provided that the CLOCK MONITOR enable option has been selected by the program).
•
With the single-pin R/C oscillator option selected and the CLKDLY bit reset, the WATCHDOG service window will resume following HALT mode from where it left off before entering the HALT mode.
The subroutine stack grows down for each call (jump to subroutine), interrupt, or PUSH, and grows up for each return or POP. The stack pointer is initialized to RAM location 06F Hex during reset. Consequently, if there are more returns than calls, the stack pointer will point to addresses 070 and 071 Hex (which are undefined RAM). Undefined RAM from addresses 070 to 07F (Segment 0), and all other segments (i.e., Segments 4 … etc.) is read as all 1’s, which in turn will cause the program to return to address 7FFF Hex. It is recommended that the user either leave this location unprogrammed or place an INTR instruction (all 0’s) in this location to generate a software interrupt signaling an illegal condition.
•
With the crystal oscillator option selected, or with the single-pin R/C oscillator option selected and the CLKDLY bit set, the WATCHDOG service window will be set to its selected value from WDSVR following HALT. Consequently, the WATCHDOG should not be serviced for at least 256 instruction cycles following HALT, but must be serviced within the selected window to avoid a WATCHDOG error.
• •
Thus, the chip can detect the following illegal conditions: 1.
Executing from undefined ROM.
2.
Over “POP”ing the stack by having more returns than calls.
When the software interrupt occurs, the user can re-initialize the stack pointer and do a recovery procedure before restarting (this recovery program is probably similar to that following reset, but might not contain the same program initialization procedures). The recovery program should reset the software interrupt pending bit using the RPND instruction.
The IDLE timer T0 is not initialized with external RESET. The user can sync in to the IDLE counter cycle with an IDLE counter (T0) interrupt or by monitoring the T0PND flag. The T0PND flag is set whenever the twelfth bit of the IDLE counter toggles (every 4096 instruction cycles). The user is responsible for resetting the T0PND flag.
39
www.national.com
12.0 MICROWIRE/PLUS
12.1 MICROWIRE/PLUS OPERATION Setting the BUSY bit in the PSW register causes the MICROWIRE/PLUS to start shifting the data. It gets reset when eight data bits have been shifted. The user may reset the BUSY bit by software to allow less than 8 bits to shift. If enabled, an interrupt is generated when eight data bits have been shifted. The device may enter the MICROWIRE/PLUS mode either as a Master or as a Slave. Figure 29 shows how two microcontroller devices and several peripherals may be interconnected using the MICROWIRE/PLUS arrangements.
MICROWIRE/PLUS is a serial SPI compatible synchronous communications interface. The MICROWIRE/PLUS capability enables the device to interface with MICROWIRE/PLUS or SPI peripherals (i.e. A/D converters, display drivers, EEPROMs etc.) and with other microcontrollers which support the MICROWIRE/PLUS or SPI interface. It consists of an 8-bit serial shift register (SIO) with serial data input (SI), serial data output (SO) and serial shift clock (SK). Figure 29 shows a block diagram of the MICROWIRE/PLUS logic.
WARNING
The shift clock can be selected from either an internal source or an external source. Operating the MICROWIRE/PLUS arrangement with the internal clock source is called the Master mode of operation. Similarly, operating the MICROWIRE/ PLUS arrangement with an external shift clock is called the Slave mode of operation.
The SIO register should only be loaded when the SK clock is in the idle phase. Loading the SIO register while the SK clock is in the active phase, will result in undefined data in the SIO register. Setting the BUSY flag when the input SK clock is in the active phase while in the MICROWIRE/PLUS is in the slave mode may cause the current SK clock for the SIO shift register to be narrow. For safety, the BUSY flag should only be set when the input SK clock is in the idle phase.
The CNTRL register is used to configure and control the MICROWIRE/PLUS mode. To use the MICROWIRE/PLUS, the MSEL bit in the CNTRL register is set to one. In the master mode, the SK clock rate is selected by the two bits, SL0 and SL1, in the CNTRL register. Table 10 details the different clock rates that may be selected.
12.1.1 MICROWIRE/PLUS Master Mode Operation In the MICROWIRE/PLUS Master mode of operation the shift clock (SK) is generated internally. The MICROWIRE Master always initiates all data exchanges. The MSEL bit in the CNTRL register must be set to enable the SO and SK functions onto the G Port. The SO and SK pins must also be selected as outputs by setting appropriate bits in the Port G configuration register. In the slave mode, the shift clock stops after 8 clock pulses. Table 11 summarizes the bit settings required for Master mode of operation.
TABLE 10. MICROWIRE/PLUS Master Mode Clock Select SL1
SL0
SK Period
0
0
2 x tC
0
1
4 x tC
1
x
8 x tC
Where tC is the instruction cycle clock
DS100155-32
FIGURE 29. MICROWIRE/PLUS Application
www.national.com
40
12.0 MICROWIRE/PLUS (Continued)
The user must set the BUSY flag immediately upon entering the Slave mode. This ensures that all data bits sent by the Master is shifted properly. After eight clock pulses the BUSY flag is clear, the shift clock is stopped, and the sequence may be repeated.
12.1.2 MICROWIRE/PLUS Slave Mode Operation In the MICROWIRE/PLUS Slave mode of operation the SK clock is generated by an external source. Setting the MSEL bit in the CNTRL register enables the SO and SK functions onto the G Port. The SK pin must be selected as an input and the SO pin is selected as an output pin by setting and resetting the appropriate bits in the Port G configuration register. Table 11 summarizes the settings required to enter the Slave mode of operation.
12.1.3 Alternate SK Phase Operation and SK Idle Polarity The device allows either the normal SK clock or an alternate phase SK clock to shift data in and out of the SIO register. In both 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 the normal mode data is shifted in on the rising edge of the SK clock and the data is shifted out on the falling edge of the SK clock. In the alternate SK phase operation, data is shifted in on the falling edge of the SK clock and shifted out on the rising edge of the SK clock. Bit 6 of Port G configuration register selects the SK edge.
TABLE 11. MICROWIRE/PLUS Mode Settings This table assumes that the control flag MSEL is set. G4 (SO)
G5 (SK)
G4
G5
Config. Bit
Config. Bit
Fun.
Fun.
1
1
SO
Int.
MICROWIRE/PLUS
SK
Master
0
1
1
TRI-
Int.
MICROWIRE/PLUS
ST AT E
SK
M as ter
SO
Ext.
MICROWIRE/PLUS
SK
Sl av e
0
0
0
Operation
TRI-
Ext.
MICROWIRE/PLUS
ST AT E
SK
Sl av e
A control flag, SKSEL, allows either the normal SK clock or the alternate SK clock to be selected. Resetting SKSEL causes the MICROWIRE/PLUS logic to be clocked from the normal SK signal. Setting the SKSEL flag selects the alternate SK clock. The SKSEL is mapped into the G6 configuration 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 Data Bit
SO Clocked Out On:
SI Sampled On:
SK Id le Phase
Normal
0
0
Alternate
1
0
SK Falling Edge
SK Rising Edge
Low
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 41
www.national.com
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 Map All RAM, ports and registers (except A and PC) are mapped into data memory address space. Address
Address
Contents
Contents
S/ADD REG
S/ADD REG On-Chip RAM bytes (112 bytes)
xxC9
MIWU Enable Register (Reg:WKEN)
0070 to 007F
Unused RAM Address Space (Reads As All Ones)
xxCA
MIWU Pending Register (Reg:WKPND)
xxCB to xxCF
Reserved
xx80 to xx93
Unused RAM Address Space (Reads Undefined Data)
xxD0
Port L Data Register
xxD1
Port L Configuration Register
xx94
P ort F data regi st er, PORT FD
xxD2
Port L Input Pins (Read Only)
xx95
Port F configuration register, PORTFC
xxD3
Reserved for Port L
xx96
Port F input pins (read only), PORTFP
xxD4
Port G Data Register
xx97 to xxAF
Unused address space (Reads Undefined Data)
xxD5
Port G Configuration Register
xxD6
P or t G I nput Pi ns (Read Only)
xxB0
Timer T3 Lower Byte
xxD7
xxB1
Timer T3 Upper Byte
Port I Input Pins (Read Only) (Actually reads Port F input pins)
xxB2
Timer T3 Autoload Register T3RA Lower Byte
xxD8
Port C Data Register
xxD9
Port C Configuration Register
Timer T3 Autoload Register T3RA Upper Byte
xxDA
Port C Input Pins (Read Only)
xxB4
Timer T3 Autoload Register T3RB Lower Byte
xxDB
Reserved for Port C
xxDC
Port D
xxB5
Timer T3 Autoload Register T3RB Upper Byte
xxB 6
0000 to 006F
xxB3
xxDD to xxDF
Reserved for Port D
xxE0 to xxE5
Reserved for EE Control Registers
T imer T3 Control Register
xxE6
xxB7
Comparator Select Register (Reg:CMPSL)
Timer T1 Autoload Register T1RB Lower Byte
xxE7
xxB8
UART Transmit Buffer (Reg:TBUF)
Timer T1 Autoload Register T1RB Upper Byte
xxB9
UART Receive Buffer (Reg:RBUF)
xxE8
ICNTRL Register
xxBA
UART Control and Status Register (Reg:ENU)
xxE9
MICROWIRE/PLUS Shift Register
xxEA
Timer T1 Lower Byte
xxBB xxBC
UART Receive Control and Status Register (Reg:ENUR) UART Interrupt and Clock Source Register (Reg:ENUI)
xxEB
Timer T1 Upper Byte
xxEC
Timer T1 Autoload Register T1RA Lower Byte
xxED
Timer T1 Autoload Register T1RA Upper Byte
xxBD
UART Baud Register (Reg:BAUD)
xxBE
UART Prescale Select Register (Reg:PSR)
xxEE
C NTRL Control Register
xxEF
PSW Register
xxBF
Reserved for UART
xxF0 to FB
On-Chip RAM Mapped as Registers
xxC0
Timer T2 Lower Byte
xxFC
X Register
Timer T2 Upper Byte
xxFD
SP Register
xxC2
Timer T2 Autoload Register T2RA Lower Byte
xxFE
B Register
xxFF
S Register
xxC3
Timer T2 Autoload Register T2RA Upper Byte
0100–017F
On-Chip 128 RAM Bytes
0200–027F
xxC4
Timer T2 Autoload Register T2RB Lower Byte
On-Chip 128 RAM Bytes (Reads as undefined data on COP8SGE)
0300–037F
xxC5
Timer T2 Autoload Register T2RB Upper Byte
On-Chip 128 RAM Bytes (Reads as undefined data on COP8SGE)
xxC 6
T imer T2 Control Register
xxC7
WATCHDOG Service Register (Reg:WDSVR)
xxC 8
MI WU E dge Select Regi ster (Reg:WKEDG)
xxC1
Note: Reading memory locations 0070H–007FH (Segment 0) will return all ones. Reading unused memory locations 0080H–0093H (Segment 0) will return undefined data. Reading memory locations from other Segments (i.e., Segment 4, Segment 5, … etc.) will return undefined data.
43
www.national.com
14.0 Instruction Set
The available addressing modes are:
• Direct • Register B or X Indirect • Register B or X Indirect with Post-Incrementing/
14.1 INTRODUCTION This section defines the instruction set of the COPSAx7 Family members. It contains information about the instruction set features, addressing modes and types.
Decrementing
• Immediate • Immediate Short • Indirect from Program Memory
14.2 INSTRUCTION FEATURES The strength of the instruction set is based on the following features:
•
Mostly single-byte opcode instructions minimize program size.
•
One instruction cycle for the majority of single-byte instructions to minimize program execution time.
•
Many single-byte, multiple function instructions such as DRSZ.
•
Three memory mapped pointers: two for register indirect addressing, and one for the software stack.
•
Sixteen memory mapped registers that allow an optimized implementation of certain instructions.
•
•
The addressing modes are described below. Each description includes an example of an assembly language instruction using the described addressing mode. Direct. The memory address is specified directly as a byte in the instruction. In assembly language, the direct address is written as a numerical value (or a label that has been defined elsewhere in the program as a numerical value). Example: Load Accumulator Memory Direct LD A,05
Ability to set, reset, and test any individual bit in data memory address space, including the memory-mapped I/O ports and registers.
Con ten ts
Co ntent s
Memory
Before
After
Accumulator
XX Hex
A6 Hex
Memor y Locati on
A 6 Hex
A6 Hex
0005 Hex Register B or X Indirect. The memory address is specified by the contents of the B Register or X register (pointer register). In assembly language, the notation [B] or [X] specifies which register serves as the pointer.
Register-Indirect LOAD and EXCHANGE instructions with optional automatic post-incrementing or decrementing of the register pointer. This allows for greater efficiency (both in cycle time and program code) in loading, walking across and processing fields in data memory.
Example: Exchange Memory with Accumulator, B Indirect
• Unique instructions to optimize program size and throughput efficiency. Some of these instructions are DRSZ, IFBNE, DCOR, RETSK, VIS and RRC.
X A,[B]
14.3 ADDRESSING MODES The instruction set offers a variety of methods for specifying memory addresses. Each method is called an addressing mode. These modes are classified into two categories: operand addressing modes and transfer-of-control addressing modes. Operand addressing modes are the various methods of specifying an address for accessing (reading or writing) data. Transfer-of-control addressing modes are used in conjunction with jump instructions to control the execution sequence of the software program.
Reg /Data
Con ten ts
Co ntent s
Memory
Before
After
Accumulator
01 Hex
87 Hex
Memor y Locati on
87 H ex
01 Hex
0005 Hex B Pointer 05 Hex 05 Hex Register B or X Indirect with Post-Incrementing/ Decrementing. The relevant memory address is specified by the contents of the B Register or X register (pointer register). The pointer register is automatically incremented or decremented after execution, allowing easy manipulation of memory blocks with software loops. In assembly language, the notation [B+], [B−], [X+], or [X−] specifies which register serves as the pointer, and whether the pointer is to be incremented or decremented.
14.3.1 Operand Addressing Modes The operand of an instruction specifies what memory location is to be affected by that instruction. Several different operand addressing modes are available, allowing memory locations to be specified in a variety of ways. An instruction can specify an address directly by supplying the specific address, or indirectly by specifying a register pointer. The contents of the register (or in some cases, two registers) point to the desired memory location. In the immediate mode, the data byte to be used is contained in the instruction itself.
Example: Exchange Memory with Accumulator, B Indirect with Post-Increment X A,[B+]
Each addressing mode has its own advantages and disadvantages with respect to flexibility, execution speed, and program compactness. Not all modes are available with all instructions. The Load (LD) instruction offers the largest number of addressing modes.
www.national.com
Reg /Data
Reg /Data
Con ten ts
Co ntent s
Memory
Before
After
Accumulator
03 Hex
62 Hex
Memor y Locati on
62 H ex
03 Hex
0005 Hex B Pointer 05 Hex 06 Hex Intermediate. The data for the operation follows the instruction opcode in program memory. In assembly language, the number sign character ( #) indicates an immediate operand.
44
14.0 Instruction Set (Continued)
The available transfer-of-control addressing modes are:
• • • •
Example: Load Accumulator Immediate LD A,#05 Reg/Data
Contents
Contents
Memory
Before
After
Jump Relative Jump Absolute Jump Absolute Long Jump Indirect
The transfer-of-control addressing modes are described below. Each description includes an example of a Jump instruction using a particular addressing mode, and the effect on the Program Counter bytes of executing that instruction.
Accumulator XX Hex 05 Hex Immediate Short. This is a special case of an immediate instruction. In the “Load B immediate” instruction, the 4-bit immediate value in the instruction is loaded into the lower nibble of the B register. The upper nibble of the B register is reset to 0000 binary.
Jump Relative. In this 1-byte instruction, six bits of the instruction opcode specify the distance of the jump from the current program memory location. The distance of the jump can range from −31 to +32. A JP+1 instruction is not allowed. The programmer should use a NOP instead.
Example: Load B Register Immediate Short LD B,#7
Example: Jump Relative
Reg/Data
Contents
Contents
Memory
Before
After
JP 0A
B Pointer 12 Hex 07 Hex Indirect from Program Memory. This is a special case of an indirect instruction that allows access to data tables stored in program memory. In the “Load Accumulator Indirect” (LAID) instruction, the upper and lower bytes of the Program Counter (PCU and PCL) are used temporarily as a pointer to program memory. For purposes of accessing program memory, the contents of the Accumulator and PCL are exchanged. The data pointed to by the Program Counter is loaded into the Accumulator, and simultaneously, the original contents of PCL are restored so that the program can resume normal execution.
Reg
Co ntent s
Con tents
Before
After
PCU
02 Hex
02 Hex
PCL 05 Hex 0F Hex Jump Absolute. In this 2-byte instruction, 12 bits of the instruction opcode specify the new contents of the Program Counter. The upper three bits of the Program Counter remain unchanged, restricting the new Program Counter address to the same 4 kbyte address space as the current instruction. (This restriction is relevant only in devices using more than one 4 kbyte program memory space.)
Example: Load Accumulator Indirect
Example: Jump Absolute
LAID
JMP 0125 Reg/ Dat a
Co ntents
Con tents
Memory
Before
After
PCU
04 Hex
04 Hex
PCL
35 Hex
36 Hex
Accumulator
1F Hex
25 Hex
Memory Location
25 Hex
25 Hex
Reg PCU
Co ntent s
Con tents
Before
After
0C Hex
01 Hex
PCL 77 Hex 25 Hex Jump Absolute Long. In this 3-byte instruction, 15 bits of the instruction opcode specify the new contents of the Program Counter.
041F Hex
Example: Jump Absolute Long 14.3.2 Tranfer-of-Control Addressing Modes
JMP 03625
Program instructions are usually executed in sequential order. However, Jump instructions can be used to change the normal execution sequence. Several transfer-of-control addressing modes are available to specify jump addresses. A change in program flow requires a non-incremental change in the Program Counter contents. The Program Counter consists of two bytes, designated the upper byte (PCU) and lower byte (PCL). The most significant bit of PCU is not used, leaving 15 bits to address the program memory.
Reg/
Co ntent s
Con tents
Memory
Before
After
PCU
42 Hex
36 Hex
PCL
36 Hex
25 Hex
Different addressing modes are used to specify the new address for the Program Counter. The choice of addressing mode depends primarily on the distance of the jump. Farther jumps sometimes require more instruction bytes in order to completely specify the new Program Counter contents.
45
www.national.com
14.0 Instruction Set (Continued)
Jump to Subroutine Long (JSRL) Return from Subroutine (RET)
Jump Indirect. In this 1-byte instruction, the lower byte of the jump address is obtained from a table stored in program memory, with the Accumulator serving as the low order byte of a pointer into program memory. For purposes of accessing program memory, the contents of the Accumulator are written to PCL (temporarily). The data pointed to by the Program Counter (PCH/PCL) is loaded into PCL, while PCH remains unchanged.
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 registers or memory. The addressing mode determines the source of the data.
Example: Jump Indirect JID
Load (LD)
Reg/
Contents
C ontents
Memory
Before
After
PCU
01 Hex
01 Hex
PCL
C4 Hex
32 Hex
14.4.4 Logical Instructions
Accumulator
26 Hex
26 Hex
32 Hex
32 Hex
The logical instructions perform the operations AND, OR, and XOR (Exclusive OR). Other logical operations can be performed by combining these basic operations. For example, complementing is accomplished by exclusiveORing the Accumulator with FF Hex.
Load Accumulator Indirect (LAID) Exchange (X)
Memory Location
0126 Hex The VIS instruction is a special case of the Indirect Transfer of Control addressing mode, where the double-byte vector associated with the interrupt is transferred from adjacent addresses in program memory into the Program Counter in order to jump to the associated interrupt service routine.
Logical AND (AND) Logical OR (OR) Exclusive OR (XOR) 14.4.5 Accumulator Bit Manipulation Instructions The Accumulator bit manipulation instructions allow the user to shift the Accumulator bits and to swap its two nibbles.
14.4 INSTRUCTION TYPES The instruction set contains a wide variety of instructions. The available instructions are listed below, organized into related groups.
Rotate Right Through Carry (RRC) Rotate Left Through Carry (RLC)
Some instructions test a condition and skip the next instruction if the condition is not true. Skipped instructions are executed as no-operation (NOP) instructions.
Swap Nibbles of Accumulator (SWAP) 14.4.6 Stack Control Instructions Push Data onto Stack (PUSH)
14.4.1 Arithmetic Instructions
Pop Data off of Stack (POP)
The arithmetic instructions perform binary arithmetic such as addition and subtraction, with or without the Carry bit.
14.4.7 Memory Bit Manipulation Instructions
Add (ADD)
The memory bit manipulation instructions allow the user to set and reset individual bits in memory.
Add with Carry (ADC) Subtract (SUB)
Set Bit (SBIT)
Subtract with Carry (SUBC)
Reset Bit (RBIT)
Increment (INC)
Reset Pending Bit (RPND)
Decrement (DEC)
14.4.8 Conditional Instructions
Decimal Correct (DCOR)
The conditional instruction test a condition. If the condition is true, the next instruction is executed in the normal manner; if the condition is false, the next instruction is skipped.
Clear Accumulator (CLR) Set Carry (SC) Reset Carry (RC)
If Equal (IFEQ) If Not Equal (IFNE)
14.4.2 Transfer-of-Control Instructions
If Greater Than (IFGT)
The transfer-of-control instructions change the usual sequential program flow by altering the contents of the Program Counter. The Jump to Subroutine instructions save the Program Counter contents on the stack before jumping; the Return instructions pop the top of the stack back into the Program Counter.
If Carry (IFC) If Not Carry (IFNC) If Bit (IFBIT) If B Pointer Not Equal (IFBNE) And Skip if Zero (ANDSZ)
Jump Relative (JP)
Decrement Register and Skip if Zero (DRSZ)
Jump Absolute (JMP) Jump Absolute Long (JMPL) Jump Indirect (JID) Jump to Subroutine (JSR) www.national.com
46
14.0 Instruction Set (Continued)
Registers
14.4.9 No-Operation Instruction
C
1 B it of PSW Regi st er for Carry
The no-operation instruction does nothing, except to occupy space in the program memory and time in execution.
HC
1 Bit of PSW Register for Half Carry
GIE
1 Bit of PSW Register for Global Interrupt Enable
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 is transferred from adjacent addresses in the program memory into the program counter (PC) in order to jump to the associated interrupt service routine.
Registers 8-Bit Accumulator Register 8-Bit Address Register
X
8-Bit Address Register
Interrupt Vector Lower Byte
[B]
The following abbreviations represent the nomenclature used in the instruction description and the COP8 cross-assembler.
B
Interrupt Vector Upper Byte
VL
Symbols
14.5 REGISTER AND SYMBOL DEFINITION
A
VU
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] or Immediate Data
Imm
8-Bit Immediate Data
Reg
Register Memory: Addresses F0 to FF (Includes B, X and SP)
SP
8-Bit Stack Pointer Register
Bit
Bit Number (0 to 7)
PC
15-Bit Program Counter Register
←
Loaded with
PU
Upper 7 Bits of PC
↔
Exchanged with
PL
Lower 8 Bits of PC
14.6 INSTRUCTION SET SUMMARY ADD
A,Meml
ADD
ADC
A,Meml
ADD with Carry
A← A + Meml 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
A← A and Meml
Logical AND
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
IFEQ
A,Meml
IF EQual
Compare MD and Imm, Do next if MD = Imm 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
DRSZ
Reg
Decrement Reg., Skip if Zero
Do next if lower 4 bits of B ≠ Imm 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
Reset PeNDing Flag
Reset Software Interrupt Pending Flag
EXchange A with Memory
A ↔Mem
RPND X
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)
47
www.national.com
14.0 Instruction Set (Continued) LD
A, [B ±]
LoaD A with Memory [B]
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
Load A InDirect from ROM
A←ROM (PU,A)
LAID
A←[B], (B← B ± 1)
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
Vector to Interrupt Service Routine
VIS JMPL
Addr.
Jump absolute Long
PU←[VU], PL← [VL] 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],
RETI
RETurn from Interrupt
SP + 2, PL
INTR
Generate an Interrupt
[SP]←PL,
NOP
No OPeration
PC← PC + 1
skip next instruction
www.national.com
48
←[SP],PU ←[SP−1],GIE ←1
[SP−1]← PU, SP−2, PC← 0FF
14.0 Instruction Set (Continued)
Instructions Using A & C
14.7 INSTRUCTION EXECUTION TIME
CLRA
1/1
Most instructions are single byte (with immediate addressing mode instructions taking two bytes).
INCA
1/1
DECA
1/1
Most single byte instructions take one cycle time to execute.
LAID
1/3
Skipped instructions require x number of cycles to be skipped, where x equals the number of bytes in the skipped instruction opcode.
DCORA
1/1
RRCA
1/1
RLCA
1/1
See the BYTES and CYCLES per INSTRUCTION table for details.
SWAPA
1/1
Bytes and Cycles per Instruction
SC
1/1
The following table shows the number of bytes and cycles for each instruction in the format of byte/cycle.
RC
1/1
IFC
1/1
Arithmetic and Logic Instructions
IFNC
1/1
[B]
Direct
Immed.
ADD
1/1
3/4
2/2
ADC
1/1
3/4
2/2
SUBC
1/1
3/4
2/2
PUSHA
1/3
POPA
1/3
ANDSZ
2/2
Transfer of Control Instructions
AND
1/1
3/4
2/2
JMPL
3/4
OR
1/1
3/4
2/2
JMP
2/3
XOR
1/1
3/4
2/2
JP
1/3
IFEQ
1/1
3/4
2/2
JSRL
3/5
IFGT
1/1
3/4
2/2
JSR
2/5
IFBNE
1/1
JID
1/3
DRSZ
1/3
VIS
1/5
SBIT
1/1
3/4
RET
1/5
RBIT
1/1
3/4
RETSK
1/5
IFBIT
1/1
3/4
RETI
1/5
RPND
1/1
INTR
1/7
NOP
1/1
Memory Transfer Instructions Register
Direct
Immed.
Indirect [B]
[X]
X A, (Note 16)
1/1
1/3
2/3
LD A, (Note 16)
1/1
1/3
2/3
[B+, B−] 2/2
LD B, Imm
1/1
LD B, Imm
2/2
LD Mem, Imm
2/2
Register Indirect Auto Incr. & Decr.
3/3
LD Reg, Imm
2/3
IFEQ MD, Imm
3/3
[X+, X−]
1/2
1/3
1/2
1/3 (If B < 16) (If B > 15)
2/2
Note 16: = > Memory location addressed by B or X or directly.
49
www.national.com
14.0 Instruction Set (Continued)
e l b b i N r e w o L
0
1
2
3
4
5
6
7
8
2 + P J
3 + P J
4 + P J
5 + P J
6 + P J
7 + P J
8 + P J
9 + P J
9 0 1 + P J 6 2 + P J
F A B C D E 1 2 3 4 5 6 R 1 1 1 1 1 1 + + + + + + 0 T N P P P P P P I J J J J J J 7 8 9 0 1 2 3 4 5 7 8 9 0 1 2 1 1 1 2 2 2 2 2 2 2 2 2 3 3 3 + + + + + + + + + + + + + + 1 + P P P P P P P P P P P P P P P J J J J J J J J J J J J J J J F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F 0 1 2 3 4 5 6 7 8 9 A B C D E P x P x P x P x P x P x P x P x P x P x P x P x P x P x P x P F x 2 M – M – M – M – M – M – M – M – M – M – M – M – M – M – M – M – J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 F A B C D E x x x x x x x x x x x x x x x x F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F 0 1 2 3 4 5 6 7 8 9 A B C D E F R x R x R x R x R x R x R x R x R x R x R x R x R x R x R x R x 3 S – S – S – S – S – S – S – S – S – S – S – S – S – S – S – S – J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 J 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 7 8 9 0 1 2 3 4 5 F A B C D E x x x x x x x x x x x x x x x x F A B C D E 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 E E E E E E E E E E E E E E E 4 N N N N N N N N N N N N E N N N N B B B B B B B B B B B B B B B B F F F F F F F F F F I I I I I I I I I I F F F F F F I I I I I I 5
e 6 l b b i N r 7 e p p U 8
9 8 7 6 5 4 3 2 1 0 F E A D C B D 0 D 0 D 0 D 0 D 0 D 0 D 0 D 0 D 0 D 0 D 0 D 0 D 0 D 0 D 0 D 0 L # , L # , L # , L # , L # , L # , L # , L # , L # , L # , , L # , L # , L # , L # , L # , L # B B B B B B B B B B B B B B B B A A Z i A A T ] T ] T ] T ] T ] T ] T ] T ] P S # R H I B I B I B I B I B I B I B I B R A * * D , * S O B [ , B [ , B [ , B [ , B [ , B [ , B [ , B [ , L N A R 0 R 1 R 2 R 3 R 4 R 5 R 6 R 7 C W C U A P S D ] T ] T ] T ] T ] T ] T ] T ] T ] I T ] I T ] I T ] I T ] I T ] I T ] I T ] I I B B [ B B [ B B [ B B [ B B [ B B [ B B [ B T [ B I B I B I B I B I B I B I B B [ B , B [ , B [ , B [ , B [ , B [ , B [ , B [ , , , , , , , , , F F F F F F F F 0 1 2 3 4 5 6 7 0 S 1 S 2 S 3 S 4 S 5 S 6 S 7 S I I I I I I I I ] C ] Q ] T ] D ] D ] R ] C ] B B E [ B G [ B B B B R [ B C [ [ [ [ D [ , B D N , , , , , O , , F O A I F F A A U S A I A I A A A A A X A
i # , C i T i R i C i D i D i # Q i # # # # # # B , , , , , , G D N O A E 9 D , F A A A A A X A R F A I A A U S A I O ] ] ] + − D D C X [ [ , * B X [ B I I X B A C R S , , A J A A A L A C
B R
*
R
E L B A T E D O C P O 8 . 4 1
] ] + − X X [ X S I X [ , , V A A
D N P R
] X [ , A X
*
i # , A D L
C N F I
A C N I
A C E D
A P O P
K S T E R
T E R
I T E R
i i # d , # , B D M D ] L , L B D [ A L ] L R D B [ , * L A S J
A C L R
i i d # E i , D # , M ] # , D , N L + L ] − A F A I B B [ [ X ] ] L i + − Q # , D B D B P E d L [ , L [ , M F I M A A J
P O N
] ] i + − E ] # , R [ , D [ X D [ X D d I N B L , L , L F I A M D A A
] D X [ , * L A
Z 0 Z 1 Z 2 Z 3 Z 4 Z 5 Z 6 Z 7 Z 8 Z 9 Z Z Z Z Z Z S S A S B S C S D S E S F S S S S S S S S S 0 0 0 0 0 0 0 0 0 0 D D D D D D D D D D D 0 D 0 D 0 D 0 D 0 D 0
C R F R F R F R F R F R F R F R F R F R F R F R F R F R F R F R F
i # , 0 D F 0 D L
i # , 1 F 0 D L
i # , 2 F 0 D L
i # , 3 F 0 D L
i # , 4 F 0 D L
i # , 5 F 0 D L
i # , 6 F 0 D L
i # , 7 F 0 D L
i # , 8 F 0 D L
i # , 9 F 0 D L
i # , A F 0 D L
i # , B F 0 D L
i # , C F 0 D L
i # , D F 0 D L
i # , E F 0 D L
i # , F F 0 D L
E
1 3 − P J
0 3 − P J
9 2 − P J
8 2 − P J
7 2 − P J
6 2 − P J
5 2 − P J
4 2 − P J
3 2 − P J
2 2 − P J
1 2 − P J
0 2 − P J
9 1 − P J
8 1 − P J
7 1 − P J
6 1 − P J
F
5 1 − P J
4 1 − P J
3 1 − P J
2 1 − P J
1 1 − P J
0 1 − P J
9 − P J
8 − P J
7 − P J
6 − P J
5 − P J
4 − P J
3 − P J
2 − P J
1 − P J
0 − P J
www.national.com
50
A i , # n T I o i B t F a I c r o l o f y r e o d m o c e p m o d e e h s t a s e o t e d l s a r d d o c a s e d i a p t o a l i y d x e d t e H e c e r s m i u 0 m d n i u 6 e e a n d s h a o i t , i s c d s i p e r i M * o e e h h W T
• COP8-NSDEV: Very low cost Software Development
15.0 Development Tools Support
Package for Windows. An integrated development environment for COP8, including WCOP8 IDE, COP8C (limited version), COP8-NSASM, COP8-MLSIM.
15.1 OVERVIEW National is engaged with an international community of independent 3rd party vendors who provide hardware and software development tool support. Through National’s interaction and guidance, these tools cooperate to form a choice of solutions that fits each developer’s needs.
• COP8C: Moderately priced C Cross-Compiler and Code Development System from Byte Craft (no code limit). Includes BCLIDE (Byte Craft Limited Integrated Development Environment) for Win32, editor, optimizing C CrossCompiler, macro cross assembler, BC-Linker, and MetaLink tools support. (DOS/SUN versions available; Compiler is installable under WCOP8 IDE; Compatible with DriveWay COP8).
This section provides a summary of the tool and development kits currently available. Up-to-date information, selection guides, free tools, demos, updates, and purchase information can be obtained at our web site at: www.national.com/cop8.
• EWCOP8-KS: Very Low cost ANSI C-Compiler and Embedded Workbench from IAR (Kickstart version: COP8Sx/Fx only with 2k code limit; No FP). A fully integrated Win32 IDE, ANSI C-Compiler, macro assembler, editor, linker, Liberian, C-Spy simulator/debugger, PLUS MetaLink EPU/DM emulator support.
15.2 SUMMARY OF TOOLS COP8 Evaluation Tools
• COP8–NSEVAL: Free Software Evaluation package for Windows. A fully integrated evaluation environment for COP8, including versions of WCOP8 IDE (Integrated Development Environment), COP8-NSASM, COP8-MLSIM, COP8C, DriveWay™ COP8, Manuals, and other COP8 information.
• EWCOP8-AS: Moderately priced COP8 Assembler and Embedded Workbench from IAR (no code limit). A fully integrated Win32 IDE, macro assembler, editor, linker, librarian, and C-Spy high-level simulator/debugger with I/O and interrupts support. (Upgradeable with optional C-Compiler and/or MetaLink Debugger/Emulator support).
• COP8–MLSIM: Free Instruction Level Simulator tool for Windows. For testing and debugging software instructions only (No I/O or interrupt support).
• EWCOP8-BL: Moderately priced ANSI C-Compiler and
• COP8–EPU: Very Low cost COP8 Evaluation & Programming Unit. Windows based evaluation and hardware-simulation tool, with COP8 device programmer and erasable samples. Includes COP8-NSDEV, Driveway COP8 Demo, MetaLink Debugger, I/O cables and power supply.
Embedded Workbench from IAR (Baseline version: All COP8 devices; 4k code limit; no FP). A fully integrated Win32 IDE, ANSI C-Compiler, macro assembler, editor, linker, librarian, and C-Spy high-level simulator/debugger. (Upgradeable; CWCOP8-M MetaLink tools interface support optional).
• COP8–EVAL-HIxx: Low cost target application evalua-
• EWCOP8: Full featured ANSI C-Compiler and Embed-
tion and development board for COP8Sx Families, from Hilton Inc. Real-time environment with integrated A/D, Temp Sensor, and Peripheral I/O.
ded Workbench for Windows from IAR (no code limit). A fully integrated Win32 IDE, ANSI C-Compiler, macro assembler, editor, linker, librarian, and C-Spy high-level simulator/debugger. (CWCOP8-M MetaLink tools interface support optional).
• COP8–EVAL-ICUxx: Very Low cost evaluation and design 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 reference designs.
• EWCOP8-M: Full featured ANSI C-Compiler and Embedded Workbench for Windows from IAR (no code limit). A fully integrated Win32 IDE, ANSI C-Compiler, macro assembler, editor, linker, librarian, C-Spy high-level simulator/debugger, PLUS MetaLink debugger/hardware interface (CWCOP8-M).
• Manuals, Applications Notes, Literature:Available free from our web site at: www.national.com/cop8. COP8 Integrated Software/Hardware Design Development Kits
COP8 Productivity Enhancement Tools
• COP8-EPU: Very Low cost Evaluation & Programming
• WCOP8 IDE: Very Low cost IDE (Integrated Develop-
Unit. Windows based development and hardwaresimulation tool for COPSx/xG families, with COP8 device programmer and samples. Includes COP8-NSDEV, Driveway COP8 Demo, MetaLink Debugger, cables and power supply.
ment Environment) from KKD. Supports COP8C, COP8NSASM, COP8-MLSIM, DriveWay COP8, and MetaLink debugger under a common Windows Project Management environment. Code development, debug, and emulation tools can be launched from the project window framework.
• COP8-DM: Moderate cost Debug Module from MetaLink.
• DriveWay-COP8: Low cost COP8 Peripherals Code
A Windows based, real-time in-circuit emulation tool with COP8 device programmer. Includes COP8-NSDEV, DriveWay COP8 Demo, MetaLink Debugger, power supply, emulation cables and adapters.
Generation tool from Aisys Corporation. Automatically generates tested and documented C or Assembly source code modules containing I/O drivers and interrupt handlers for each on-chip peripheral. Application specific code can be inserted for customization using the integrated editor. (Compatible with COP8-NSASM, COP8C, and WCOP8 IDE.)
COP8 Development Languages and Environments
• COP8-NSASM: Free COP8 Assembler v5 for Win32. Macro assembler, linker, and librarian for COP8 software development. Supports all COP8 devices. (DOS/Win16 v4.10.2 available with limited support). (Compatible with WCOP8 IDE, COP8C, and DriveWay COP8).
• COP8-UTILS: Free set of COP8 assembly code examples, device drivers, and utilities to speed up code development.
51
www.national.com
15.0 Development Tools Support
COP8-NSDEV, Driveway COP8 Demo, MetaLink Windows Debugger, and power supply. Package-specific probes and surface mount adaptors are ordered separately.
(Continued)
• COP8-MLSIM: Free Instruction Level Simulator tool for Windows. For testing and debugging software instructions only (No I/O or interrupt support).
COP8 Device Programmer Support
•
MetaLink’s EPU and Debug Module include development device programming capability for COP8 devices.
• COP8-DM: MetaLink Debug Module. A moderately
•
priced real-time in-circuit emulation tool, with COP8 device programmer. Includes MetaLink Debugger, power supply, emulation cables and adapters.
Third-party programmers and automatic handling equipment cover needs from engineering prototype and pilot production, to full production environments.
•
Factory programming available for high-volume requirements.
COP8 Real-Time Emulation Tools
• IM-COP8: MetaLink iceMASTER ® . A full featured, realtime in-circuit emulator for COP8 devices. Includes
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 National
Tools
Cost
Notes
CO P8- NSEV AL
COP8-NSE VAL
F ree
Web sit e downl oad
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 target cable, manuals, software, 16/20/28/40 DIP OTP programming socket; add DM target adapter or OTP adapter (if needed)
COP8-DM
COP8SG-DM (10 MHz)
M
Included p/s, 28/40/44 pin DIP/SO/PLCC target cables, manuals, software, 16/20/28/40 DIP/SO and 44 PLCC programming socket; add OTP adapter or target adapter (if needed)
DM Target Adapters
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
Development Devices
COP8FGx7
VL
8k or 32k Eraseable or OTP devices
OTP Programming Adapters
COP8SA-PGMA
L
For programming 16/20/28 SOIC and 44 PLCC on the EPU
COP8-PGMA-44QFP
L
For programming 44 QFP on any programmer
IM-COP8
www.national.com
Order Number
COP8-PGMA-28CSP
L
For programming 28 CSP on any programmer
COP8-PGMA-28SO
VL
For programming 16/20/28 SOIC on any programmer
Call MetaLink
52
15.0 Development Tools Support (Continued) MetaLink COP 8-E PU
E PU-CO P8S G
VL
1 = 110V, 2 = 220V ; included p/s, 40 pin DI P target cable, manuals, software, 16/20/28/40 DIP OTP programming socket; add DM target adapter or OTP adapter (if needed)
COP 8-DM
D M5-COP 8-F Gx (15 MHz) 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 or PLCC; i.e. DM-COP8/28D), 16/20/28/40 DIP/SO and 44 PLCC programming sockets. Add OTP adapter (if needed) and target adapter (if needed)
DM Target Adapters
MHW-CNVxx (xx = 33, 34 etc.)
L
DM target converters for 16DIP/20SO/28SO/44QFP/28CSP; (i.e. MHW-CNV38 for 20 pin DIP to SO package converter)
OTP Programming Adapters
MHW-COP8-PGMA-DS
L
For programming 16/20/28 SOIC and 44 PLCC on the EPU
KKD
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); included software 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
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-CON V33
L
44 pin QFP adapt er for 44 P LCC probe card
IM Probe Target Adapters
ICU or National
MHW-COP8-PGMA-44QFP L
COP8-EVAL-ICUxx ICU-303 WCOP8-IDE
L
No power supply
CO P8- EVA L-I CUSG
L
No power supply
WCOP8-IDE
VL
Included in EPU and DM
IAR
EWCOP8-xx
See summary above
L-H
Included all software and manuals
Byte Craft
COP8C
COP8C
M
Included all software and manuals
Aisys
DriveWay COP8
DriveWay COP8
L
Included all software and manuals
Go to: www.national.com/cop8
L-H
A wide variety world-wide
OTP Programmers
Cost: Free; VL = < $100; L = $100 - $300; M = $300 - $1k; H = $1k - $3k; VH = $3k - $5k
53
www.national.com
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 Aisys
Home Office
Electronic Sites
U.S.A.: Santa Clara, CA
www.aisysinc.com
1-408-327-8820
info @aisysinc.com
Other Main Offices Distributors
fax: 1-408-327-8830 Byte Craft
U.S.A.
www.bytecraft.com
1-519-888-6911
info @bytecraft.com
Distributors
fax: 1-519-746-6751 IAR
Sweden: Uppsala
www.iar.se
U.S.A.: San Francisco
+46 18 16 78 00
info @iar.se
1-415-765-5500
fax: +46 18 16 78 38
info @iar.com
fax: 1-415-765-5503
info @iarsys.co.uk
U.K.: London
info @iar.de
+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
support @icu.se
+41 34 497 28 20
fax: +46 8 630 11 70
support @icu.ch
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
sales @metaice.com
80-91-5696-0
f ax: 1-602-926-1198
support @met ai ce.com
fax: 80-91-2386
bbs: 1-602-962-0013
islanger @metalink.de
www .met al ink.de
Distr ibut ors Worl dwide
National
U.S.A.: Santa Clara, CA
www.national.com/cop8
Europe: +49 (0) 180 530 8585
1-800-272-9959
support @nsc.com
fax: +49 (0) 180 530 8586
fax: 1-800-737-7018
europe.support @nsc.com
Distributors Worldwide
The following companies have approved COP8 programmers in a variety of configurations. Contact your local office or distributor. You can link to their web sites and get the latest listing of approved programmers from National’s COP8 OTP Support page at: www.national.com/cop8.
15.5 CUSTOMER SUPPORT Complete product information and technical support is available from National’s customer response centers, and from our on-line COP8 customer support sites.
Advantech; Advin; BP Microsystems; Data I/O; Hi-Lo Systems; ICE Technology; Lloyd Research; Logical Devices; MQP; Needhams; Phyton; SMS; Stag Programmers; System General; Tribal Microsystems; Xeltek.
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
55
www.national.com
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
57
www.national.com
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
59
www.national.com
s r T o R t A a r S a U p d m n o a C o w T , y r o m e M k 2 3 r o k 8 h t i w s r e l l o r t n o c o r c i M P T O S O M C t i B 8 , y l i m a F 7 x G S 8 P O C
Notes
LIFE SUPPORT POLICY NATIONAL’S PRODUCTS ARE NOT AUTHORIZED FOR USE AS CRITICAL COMPONENTS IN LIFE SUPPORT DEVICES OR SYSTEMS WITHOUT THE EXPRESS WRITTEN APPROVAL OF THE PRESIDENT AND GENERAL COUNSEL OF NATIONAL SEMICONDUCTOR CORPORATION. As used herein: 1. Life support devices or systems are devices or systems which, (a) are intended for surgical implant into the body, or (b) support or sustain life, and whose failure to perform when properly used in accordance with instructions for use provided in the labeling, can be reasonably expected to result in a significant injury to the user. National Semiconductor Corporation Americas Tel: 1-800-272-9959 Fax: 1-800-737-7018 Email: [email protected] www.national.com
National Semiconductor Europe Fax: +49 (0) 1 80-530 85 86 Email: [email protected] Deutsch Tel: +49 (0) 1 80-530 85 85 English Tel: +49 (0) 1 80-532 78 32 Français Tel: +49 (0) 1 80-532 93 58 Italiano Tel: +49 (0) 1 80-534 16 80
2. A critical component is any component of a life support device or system whose failure to perform can be reasonably expected to cause the failure of the life support device or system, or to affect its safety or effectiveness.
National Semiconductor Asia Pacific Customer Response Group Tel: 65-2544466 Fax: 65-2504466 Email: [email protected]
National Semiconductor Japan Ltd. Tel: 81-3-5639-7560 Fax: 81-3-5639-7507
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 X A,ADR1 JSR DESPLI1 LD A,#0FF IFEQ A,ADR1 JSR FULL LD A,#000 IFEQ A,ADR1 JSR EMPTY JP MAIN
;SE LEE EL PUERTO ;Y SE GUARDA EN ADR1 ;SALTA A DESPLIEGA
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,':' .DB 000,0C6 .DB 002,'L' .DB 002,'I' .DB 002,'T' .DB 002,'R' .DB 002,'O' .DB 002,'S' .DB
;15 ;DIRECCION POSICIÓN 2a. LÍNEA
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 .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB
.DB 002,' ' 002,' ' 002,'E' 002,'L' 002,' ' 002,'T' 002,'A' 002,'N' 002,'Q' 002,'U' 002,'E' 002,' ' 002,'S'
000,001 000,080 ;1 ;2 ;3 ;4 ;5 ;6 ;7 ;8 ;9 ;10 ;11 ;12 ;13
105
Programa principal del sensor de nivel de líquidos .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB
002,'E'
;14 002,' ' ;15 000,0C0 ;DIRECCION POSICIÓN 2a. LÍNEA 002,'L' 002,'L' 002,'E' 002,'N' 002,'O' 002,' ' 002,'P' 002,'L' 002,'E' 002,'N' 002,'A' 002,'M' 002,'E' 002,'N' 002,'T' 002,'E' 0ff ;terminador de tabla
.=0500 MENLLENUEZ: DENUEZ: .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB
DISPLAY DENUEZ,LLENUEZ RET .DB 000,001 .DB 000,080 ;Set DDRAM 002,'E' ;1 002,'L' ;2 002,' ' ;3 002,'N' ;4 002,'I' ;5 002,'V' ;6 002,'E' ;7 002,'L' ;8 002,' ' ;9 002,'E' ;10 002,'S' ;11 002,' ' ;12 002,'D' ;13 002,'E' ;14 002,':' ;15 000,0C6 ;DIRECCION POSICIÓN 2a. LÍNEA 002,'L' 002,'I' 002,'T' 002,'R' 002,'O' 002,'S' 002,' ' 002,' ' 002,' ' 002,' ' 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 DISPLAY MENVA,VACIO RET
PLEVACIO: MENVA: .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB
.DB
000,001 .DB 000,080 002,' ' ;1 002,' ' ;2 002,'E' ;3 002,'L' ;4 002,' ' ;5 002,'T' ;6 002,'A' ;7 002,'N' ;8 002,'Q' ;9 002,'U' ;10 002,'E' ;11 002,' ' ;12 002,'S' ;13 002,'E' ;14 002,' ' ;15 000,0C0 ;DIRECCION POSICIÓN 2a. LÍNEA 002,'V' 002,'A' 002,'C' 002,'I' 002,'O' 002,' ' 002,'P' 002,'L' 002,'E' 002,'N' 002,'A' 002,'M' 002,'E' 002,'N' 002,'T' 002,'E' 0ff ;terminador de tabla
107
Programa principal del sensor de nivel de líquidos .=0800 MENVANUEZ: DISPLAY DTNUEZ,VANUEZ RET DTNUEZ: .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB .DB
.DB
000,001 000,080 ;Set DDRAM ;1 ;2 ;3 ;4 ;5 ;6 ;7 ;8 ;9 ;10 ;11 ;12 ;13 ;14 002,':' ;15 000,0C6 ;DIRECCION POSICIÓN 2a. LÍNEA 002,'L' 002,'I' 002,'T' 002,'R' 002,'O' 002,'S' 002,' ' 002,' ' 002,' ' 002,' ' 0ff ;terminador de tabla .DB 002,'E' 002,'L' 002,' ' 002,'N' 002,'I' 002,'V' 002,'E' 002,'L' 002,' ' 002,'E' 002,'S' 002,' ' 002,'D' 002,'E'
.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 PORTFC PORTFD
= 094 = 095 = 096
; DATOS DEL PUERTO F DE ESCRITURA ; CONFIGURACION DEL PUERTO F ; DATOS DEL PUERTO F DE LECTURA
PORTLDS PORTLC PORTLDE
= 0D0 = 0D1 = 0D2
; DATOS DEL PUERTO L DE SALIDA ; CONFIGURACION DEL PUERTO L ; DATOS DEL PUERTO L DE ENTRADA
PORTGDD PORTGC PORTGD
= 0D4 ; DATOS DEL PUERTO G DE ESCRITURA = 0D5 ; CONFIGURACION DEL PUERTO G = 0D6 ; DATOS DEL PUERTO G DE LECTURA
PORTCDD PORTCC PORTCD
= 0D8 ; DATOS DEL PUERTO C DE ESCRITURA = 0D9 ; CONFIGURACION DEL PUERTO C = 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 LD
B,#TABRAM ;B =DIRECCION VARIABLE EN RAM 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
N1:
N2:
JP N1 ;SI SON DIFERENTES SALTA A N1 JP FINMAC ;SALTA A FIN DE MACRO CLR A IFNE A,VAR1 ; ? VAR1=0 JP N2 JP COMAND ;SALTA A PROTOCOLO DE COMANDO DEL LCD. 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