Está en la página 1de 350

Autorizada la entrega del proyecto:

Diseo de un sistema de control de velocidad de


un motor de corriente continua basado en
acelermetros
Realizado por

Fernando Moreno Prez

El director del Proyecto:

_________

________

D. Eduardo Santamara Navarrete


Fecha: //.

V B del Coordinador de Proyectos

_________

________

D. lvaro Snchez Miralles


Fecha: //.

UNIVERSIDAD PONTIFICIA COMILLAS


ESCUELA TCNICA SUPERIOR DE INGENIERA (ICAI)
INGENIERO INDUSTRIAL

PROYECTO FIN DE CARRERA

DISEO DE UN SISTEMA DE
CONTROL DE VELOCIDAD DE UN
MOTOR DE CORRIENTE CONTINUA
BASADO EN ACELERMETROS

AUTOR: Fernando Moreno Prez


MADRID, Junio 2010

RESUMEN

DISEO DE UN SISTEMA DE CONTROL DE VELOCIDAD DE UN MOTOR DE


CORRIENTE CONTINUA BASADO EN ACELERMETROS
Autor: Moreno Prez, Fernando.
Director: Santamara Navarrete, Eduardo.
Entidad Colaboradora: ICAI Universidad Pontificia Comillas
RESUMEN DEL PROYECTO
OBJETIVO
Se pretende disear un sistema de control que permita regular la velocidad de una maqueta de tren
elctrico, accionado por un motor de corriente continua, en funcin de la aceleracin normal que
experimente en cada instante. Dicho control ser implantado en un microprocesador. Para ello, ser
necesario realizar:

La estimacin de los parmetros fsicos de la planta mediante ensayos.

El modelado del sistema a partir de dichos parmetros.

El diseo y construccin del hardware del sistema: etapa de potencia (que contendr el driver

del motor), y circuitos de acondicionamiento de seales de medida (aceleracin, intensidad que


recorrer el motor, etc.).

El diseo del sistema de control, y su adecuacin al tiempo discreto para su posterior desarrollo

software e implantacin en el microprocesador.

Programacin del microprocesador basada en el SOTR FreeRTOS.

DESARROLLO
1. Estimacin de parmetros fsicos y modelado del sistema
Antes de realizar el diseo del control, es necesario conocer y modelar los distintos parmetros
fsicos que intervienen en el sistema a controlar. Esos parmetros son los siguientes:

Resistencia interna del motor

Masa del conjunto planta-actuador

Inductancia del motor

Constantes asociadas al par y a la fuerza contraelectromotriz del motor

Friccin viscosa

Velocidad mxima

Una vez obtenidos dichos parmetros, se ha obtenido un modelo del sistema, a partir de cual
trabajar en el diseo del control, ya que, sin una modelizacin del sistema fsico, habra sido
imposible realizar dicho diseo o las simulaciones pertinentes para comprobar la validez del mismo.
Una primera aproximacin del modelo del sistema podra ser la que se observa en la figura
siguiente:

RESUMEN

2. Hardware del sistema


El control fue implantado sobre un hardware, el cual est compuesto por una etapa de potencia, que
sirve de nexo entre el control y el actuador, y de distintos circuitos de acondicionamiento de las
seales de medida que intervienen en el control y del microprocesador.
La etapa de potencia es la encargada de adecuar la seal de salida del microprocesador, que es el
mando del control, para hacerla capaz de mover el actuador, que, en este caso, es el motor de
corriente continua del tren. Para ello se ha utilizado como elemento principal un puente en H.
Los circuitos de acondicionamiento de seal cumplen la funcin de acondicionar las seales que se
desean medir para realimentar el control de manera que dicha medicin se efecte con la mayor
precisin y sensibilidad posibles, y sin perturbar a la seal original. Para ello se han utilizado
bsicamente etapas basadas en amplificadores operacionales y los propios sensores.
3. Diseo e implantacin del sistema de control
El diseo del sistema de control se puede dividir en dos partes: un sistema que genera una
referencia de velocidad, de acuerdo con los valores de aceleracin medidos, y otro sistema que se
encarga de hacer que la planta siga esa referencia; las cuales, se han implantado en un
microprocesador Motorola ColdFire MCF5282.
La generacin de la referencia se realiza mediante una tarea cuyo diagrama de flujo simplificado es:

La segunda parte del control se basa en dos reguladores PI discretos en cascada, cuyos parmetros

RESUMEN

se fijaron a partir de distintos diseos, que se describen brevemente a continuacin: en una primera
aproximacin se dise aproximando los parmetros por simulacin, para comprobar
posteriormente que este mtodo de diseo no es el ms acertado, y se procedi a disear aplicando
tcnicas de respuesta en frecuencia: diseo por margen de fase y diseo por margen de ganancia.
Ante el comportamiento de la salida con los controles anteriores, se pens que se poda mejorar
filtrando la corriente medida que va al microprocesador. Para ello se disearon dos filtros digitales:
un filtro paso bajo de primer orden, y un filtro FIR paso bajo. Despus de haber rediseado el
control para el sistema incluyendo esos filtros, se comprob mediante simulacin que no
mejoraban, sino que empeoraban la respuesta del sistema.
Una vez claro el regulador que se iba a utilizar (el diseado por tcnicas de respuesta en frecuencia,
sin filtro de corriente), se procedi a realizar un escalado del sistema, para adecuar las variables del
sistema para que pudiesen ser tratadas con registros de 8, 16 32 bits; con el fin de aumentar el
rendimiento del microprocesador.
Por ltimo, una vez escalado el problema con variables de 16 bits, que se vio que resultaban ser las
ms adecuadas, se desarroll el programa que fue implantado en el microprocesador y que gestiona
todos los aspectos del control: toma de medidas mediante conversor A/D, algoritmos de control,
gestin de salidas mediante onda PWM, etc., sobre el sistema operativo en tiempo real FreeRTOS.
RESULTADOS Y CONCLUSIONES
Se muestra a continuacin la respuesta que se obtuvo con el control, ante dos escalones a la entrada
de 0.5 y 0.1 m/s, el primero de los cuales se utiliza para llevar al sistema al rgimen permanente:

Se puede observar una respuesta que se adapta con bastante precisin a la referencia, lo que induce
a pensar que el control ha sido diseado de forma satisfactoria, tal y como demostraron los ensayos.

ABSTRACT

ABSTRACT
OBJECTIVE
The main objective of this project is to design a control system to control the speed of an electric
model railroad, operated by a DC motor, depending on the normal acceleration that it experiments
in every moment. The control will be embedded in a microprocessor. The steps for the design will
be:

Physical parameters estimation.

System model design, according to those parameters.

Design and construction of the systems hardware: power stage (which contains the motor

driver), and measure signals conditioning circuits (acceleration, current through the motor)

Control system design, and translation to discreet time for its software development and

microprocessor implementation.

Microprocessor programming, based on the RTOS FreeRTOS.

DEVELOPMENT
1. Physical parameters estimation
Before the control system is designed, it is necessary to know and model the different physical
parameter values that interfere in the system that is going to be controlled. These parameters are:

Motors internal resistance

Systems mass

Motors inductance

Constants associated to the motors torque

Viscous friction

Maximum speed

Once these parameters have been measured, a systems model can be obtained, which will be the
base to work on in order to design the control. Without a model of the physical system it would
have been impossible to accomplish the mentioned design or the simulations that were performed to
verify its adequacy. A first approximation of the model is shown in the following figure:

ABSTRACT

2. Hardware
The control system needs to interact with the hardware to be useful. The hardware of the system is
composed of a power stage, which links the control and the DC motor, and different conditioning
circuits for the measure signals and the microprocessor.
The power stage is in charge of adequate the output signal of the microprocessor to make it able to
move the DC motor. The main component of this stage is an H bridge.
The signal conditioning circuits adequate the signals that are needed to be measured to feedback the
control with the most sensibility and accuracy possible, and without disturbing the original signal.
In these circuits have been basically used stages based on operational amplifiers, and sensors.
3. Design and implementation of the control system
The control system design can be divided into 2 different parts: a system to generate the speed
reference, depending on the acceleration values measured, and another system that will make the
train follow that reference. These 2 parts have been implemented in a Motorola ColdFire MCF5282
microprocessor.
The reference generations simplified flowchart is shown in the following image:

The second part of the control is bsed on two PI reculators in cascade, whose parameters have been
fixed according to different designs: in the first place, the design was made approximating the

ABSTRACT

parameters by different simulations. This method didnt give very good results, and aftger realizing
that, some techniques of frequency response were applied to the design.
When the behaviour of the output signal of the control system was analyzed, it could be thought
that it could be improved by filtering the measured current that goes into the microprocessor. In
order to do so, 2 digital filters were designed: a first-order low-pass filter, and a los-pass FIR filter.
Afer redesigning the system control including those filters, and after simulating the system, it was
shown that, instead of improving the output, the filters worsed it.
Once the control was selected, a systems escalating was performed, so the microprocessor could
work with 8, 16 or 32 bit variables, in order to increase its performing.
In the last place, once the system and the control was escalated with 16 bit variables (which were
considered the best variable type according to the simulations), the program for the microprocessor
was developed, and it was implanted using the real time operatie system FreeRTOS.
RESULTS AND CONCLUSIONS
The following figure shows the control response with two step-functions in the reference (the first
step, of 0.5m/s was used to take the system into the steady state):

It can be observed that the systems response adapts to the reference with a considerable adequacy,
which induces to think that the control has been designed in a satisfactory way. This premise was
corroborated with the experiments performed.

I.- MEMORIA

MEMORIA

ndice

NDICE

NCIDE DE FIGURAS .................................................................................4


NDICE DE TABLAS ...................................................................................9
CAPTULO 1: INTRODUCCIN ...............................................................10
1.1.

Motivacin ................................................................................................ 10

1.2.

Objetivos y fases del proyecto .................................................................. 12

1.3.

Estructura de la memoria ........................................................................ 15

CAPTULO 2: ESTADO DEL ARTE .........................................................17


2.1.

Introduccin ............................................................................................. 17

2.2.

Sistemas de control de trenes ................................................................... 17

2.3.

Control de motores de corriente continua ............................................... 24

CAPTULO 3: DESCRIPCIN Y MODELADO DEL SISTEMA ...............27


3.1.

Introduccin ............................................................................................. 27

3.2.

Descripcin del sistema ............................................................................ 29

3.3.

Estimacin de parmetros fsicos ............................................................ 33


3.2.1. Clculo de la resistencia interna del motor ...............................33
3.2.2. Clculo de la inductancia del motor ..........................................34
3.2.3. Clculo de la constante asociada a la fuerza
contraelectromotriz del motor (Ke) ..............................37
3.2.4. Clculo de la constante del par motor (Km) ..............................38
3.2.5. Clculo de la friccin viscosa ...................................................39
3.2.6. Clculo de la masa ....................................................................40
3.2.7. Estimacin de la velocidad mxima ..........................................41

3.4.

Obtencin del modelo ............................................................................... 42


3.3.1. Modelo de la planta ...................................................................42
3.3.2. Modelo del actuador (motor DC) ..............................................43

3.5.

Conclusiones ............................................................................................ 46

MEMORIA

ndice

CAPTULO 4: DISEO DEL HARDWARE ..............................................47


4.1.

Introduccin ............................................................................................. 47

4.2.

Etapa de potencia ..................................................................................... 48

4.3.

Reguladores de tensin ............................................................................ 61

4.4.
Circuito de acondicionamiento de medida de la intensidad que atraviesa
el motor ................................................................................................................. 63
4.5.

Circuito de acondicionamiento de la seal del acelermetro ................. 67

4.6.

Diseo de las balizas ................................................................................ 72

4.7.

Conclusiones ............................................................................................ 77

CAPTULO 5: SISTEMA DE CONTROL ..................................................79


5.1.

Introduccin ............................................................................................. 79

5.2.

Sistemas de control digital ....................................................................... 79

5.3.

Control proporcional-integral discreto.................................................... 83

5.4.

Diseo del control .................................................................................... 86


5.4.1. Diseo mediante ajuste por simulacin.....................................88
5.4.2. Diseo basado en tcnicas de respuesta en frecuencia en lazo
abierto con modelado de los efectos de retrasos de
actualizacin de valores y PWM .................................99

5.5.

Filtros digitales: filtro de primer orden y filtro FIR ............................ 109


5.5.1. Filtro paso bajo de primer orden .............................................109
5.5.2. Filtro paso bajo FIR ................................................................115

5.6.

Escalado del problema ........................................................................... 123

5.7.

Conclusiones .......................................................................................... 128

CAPTULO 6: IMPLANTACIN EN EL MICROPROCESADOR ...........129


6.1.

El microprocesador ColdFire MCF5282 .............................................. 129

6.2.

Implantacin: programacin del microprocesador .............................. 134


6.2.1. Main ................................................................................137
6.2.2. Control.................................................................................138
6.2.3. ADCTask.................................................................................139
6.2.4. IntGPTA0 ................................................................................140
6.2.5. IntPIT0........140

MEMORIA

ndice

6.2.6. Programacin del regulador PI discreto ..................................142


6.3.

Conclusiones .......................................................................................... 145

CAPTULO 7: RESULTADOS EXPERIMENTALES ..............................146


7.1.

Introduccin ........................................................................................... 146

7.2.

Pruebas del circuito de potencia ............................................................ 146

7.3.

Pruebas del prototipo ............................................................................. 149

CAPTULO 8: CONCLUSIONES Y TRABAJO FUTURO ......................150


AGRADECIMIENTOS .............................................................................154
BIBLIOGRAFA ......................................................................................155
ANEXOS .................................................................................................157

MEMORIA

ndice
NCIDE DE FIGURAS

Figura 1.1: Diagrama de bloques del sistema a disear .................................... 13


Figura 3.1: diagrama funcional de bloques de un sistema de control continuo
tipo...... .................................................................................................................. 29
Figura 3.2: Primera aproximacin del diagrama funcional de bloques del
sistema completo................................................................................................... 32
Figura 3.3: corriente que atraviesa el motor ...................................................... 35
Figura 3.4: Esquema elctrico de un motor DC ................................................. 36
figura 3.5: fuerza contraelectromotriz en funcin de la velocidad del tren
desarrollada en el experimento. ........................................................................... 38
figura 3.6: fuerza del par motor en funcin de la velocidad del tren
desarrollada en el experimento. ........................................................................... 40
Figura 3.7: velocidad en funcin de tensin de alimentacin. .......................... 41
Figura 3.8: representacin mecnica de la planta ............................................. 42
Figura 3.9: diagrama funcional de bloques de la planta ................................... 43
Figura 3.10: diagrama funcional de bloques del actuador ................................ 45
Figura 4.1: representacin esquemtica del funcionamiento de un puente en H
..49
Figura 4.2: esquema interno simplificado de un puente en H comercial ......... 50
Figura 4.3: configuracin para frenado del motor utilizando el puente en H .. 51
Figura 4.4: Esquema del circuito de la etapa de potencia ................................. 53
Figura 4.5: disposicin de los pines del ILQ74 .................................................. 55
Figura 4.6: Corriente colector-emisor frente a corriente por el LED y
temperatura en el optoacoplador ......................................................................... 56
Figura 4.7: cada de tensin en el diodo en conduccin directa, en funcin de la
corriente que lo atraviesa ..................................................................................... 56
Figura 4.8: esquema del puente en H L298N ..................................................... 59
Figura 4.9: 78SR. Se pueden observar los elementos discretos integrados ....... 62

MEMORIA

ndice

Figura 4.10: circuito de regulacin de tensin de 14V a 3V .............................. 62


Figura 4.11: circuito de regulacin de tensin de 14V a 5V .............................. 63
Figura 4.12: circuito de acondicionamiento de medida de la intensidad que
atraviesa el motor ................................................................................................. 64
Figura 4.13A: situacin del acelermetro sobre la maqueta del tren ................ 67
Figura 4.13B: configuracin de los pines del ADXL320 ................................... 68
Figura 4.14: circuito de acondicionamiento de la seal del acelermetro ........ 70
Figura 4.15: caracterstica del rectificador de precisin .................................... 72
Figura 4.16: Circuito de una baliza .................................................................... 73
Figura 4.17: sumador, inversor y proteccin del microprocesador ................... 77
Figura 5.1: discretizacin de una seal continua y efecto aliasing ................... 80
Figura 5.2: esquema genrico de un sistema de control digital ......................... 81
Figura 5.3: diagrama de Bode del control proporcional-integral...................... 84
Figura 5.4: diagrama de bloques del control PI en tiempo discreto ................. 85
Figura 3.2: Primera aproximacin del diagrama funcional de bloques del
sistema completo................................................................................................... 87
Figura 5.5: diagrama de bloques del lazo de control de corriente ..................... 89
Figura 5.6: relacin entre Ti y K para un amortiguamiento de 0.7 ................... 90
Figura 5.7: respuesta ante un escaln de la salida del lazo de corriente
linealizado con distintos valores de K y Ti ........................................................... 91
Figura 5.8: respuesta ante un escaln del mando de corriente ......................... 92
con distintos valores de K y Ti .............................................................................. 92
Figura 5.9: ajuste de la parte proporcional del control ...................................... 93
Figura 5.10: ajuste de la parte integral del control ............................................ 94
Figura 5.11: diagrama de bloques del sistema simulado ................................... 96
Figura 5.12: simulacin del sistema con distintos valores de K ........................ 97
Figura 5.13: simulacin del sistema con distintos valores de Ti ........................ 97

MEMORIA

ndice

Figura 5.14: respuesta del mando de corriente .................................................. 98


Figura 5.15: respuesta del mando de tensin ..................................................... 98
Figura 5.16: respuesta del sistema en simulacin con retardos de actualizacin
de salidas y PWM modelados ............................................................................. 100
Figura 5.17: diagrama de bloques del sistema, incluyendo retardos de
actualizacin de salidas y efecto del PWM........................................................ 101
Figura 5.18: diagrama de bloques del lazo de control completo abierto, en
tiempo continuo .................................................................................................. 102
Figura 5.19: diagrama de bloques del lazo de control de corriente abierto, .. 103
en tiempo continuo ............................................................................................. 103
Figura 5.20: diagrama de Black del lazo de corriente abierto, antes de aplicar el
control 104
Figura 5.21: diagrama de Black del lazo de corriente abierto, despus de aplicar
el primer diseo del control ............................................................................... 105
Figura 5.22: diagrama de Black del lazo de corriente abierto, despus de aplicar
el segundo diseo del control ............................................................................. 106
Figura 5.23: diagrama de Black del lazo completo abierto, antes de aplicar el el
control 106
Figura 5.24: diagrama de Black del lazo completo abierto, despus de aplicar
diseo del control ............................................................................................... 107
Figura 5.25: respuesta de la simulacin del sistema ....................................... 108
Figura 5.26: ampliacin de la respuesta de la simulacin del sistema ............ 108
Figura 5.27: diagrama de bloques del filtro de primer orden .......................... 110
Figura 5.28: diagrama de Bode del filtro .......................................................... 111
Figura 5.29: diagrama de Black del lazo de corriente abierto, antes de aplicar el
control ..112
Figura 5.30: diagrama de Black del lazo de corriente abierto, una vez aplicado
el control ............................................................................................................. 112
Figura 5.31: diagrama de Black del lazo completo abierto, antes de aplicar el
control 113
Figura 5.30: diagrama de Black del lazo completo, con control aplicado ...... 114

MEMORIA

ndice

Figura 5.31: respuesta del sistema en simulacin ............................................ 114


Figura 5.32: diagrama de ceros y polos del filtro FIR diseado ..................... 117
Figura 5.33: diagrama de Bode del filtro FIR diseado .................................. 117
Figura 5.34: diagrama de bloques del filtro FIR diseado .............................. 118
Figura 5.35: diagrama de Black del lazo de corriente abierto, antes de aplicar el
control .119
Figura 5.36: diagrama de Black del lazo de corriente abierto, despus de aplicar
el control ............................................................................................................. 119
Figura 5.37: diagrama de Black del lazo completo abierto, antes de aplicar el
control 120
Figura 5.38: diagrama de Black del lazo completo abierto, una vez aplicado el
control 121
Figura 5.39: respuesta simulada del sistema ante un escaln ......................... 122
Figura 5.40: sistema en coma flotante y sistema escalado, con los distintos
tiempos de muestreo del sistema representados ................................................ 124
Figura 5.41: bloque PI3 escalado a 8 bits ......................................................... 125
Figura 5.42: bloque PI4 escalado a 8 bits ......................................................... 126
Figura 5.43: respuesta del sistema en coma flotante y del sistema escalado a
enteros de 8,16 y 32 bits ante un escaln de amplitud 0.1 m/s. ........................ 127
Figura 6.1: diagrama de bloques del microprocesador .................................... 130
Figura 6.2: caractersticas mecnicas del microprocesador MCF5282 .......... 131
Figura 6.3: asignacin de pines (pinout) del microprocesador ....................... 131
Figura 6.4: diagrama de flujo de la funcin main ........................................... 137
Figura 6.5: diagrama de flujo de la tarea de control........................................ 138
Figura 6.6: diagrama de flujo de la tarea ADCTask ........................................ 139
Figura 6.7: diagrama de flujo de la interrupcin IntGPTA0........................... 140
Figura 6.8: diagrama de flujo de la interrupcin PIT0 ................................... 141
Figura 6.9: diagrama de flujo del sistema completo ........................................ 144
Figura 7.1: prototipo de la etapa de potencia en protoboard para pruebas I .. 146
7

MEMORIA

ndice

Figura 7.2 : generador de seales Thandar TG501 ......................................... 147


Figura 7.3: osciloscopio Tektroniks TDS 1002B .............................................. 147
Figura 7.4: medidas osciloscopio ...................................................................... 148
Figura 7.5: medidas osciloscopio ...................................................................... 148
Figura 7.6: prototipo final ................................................................................. 149

MEMORIA

ndice

NDICE DE TABLAS
Tabla 4.1: caractersticas elctricas del circuito ILQ74 ..................................... 54
Tabla 4.2: funciones de cada uno de los pines del L298N ................................. 59
Tabla 4.3: caractersticas elctricas ms relevantes del L298N ......................... 60
Tabla 4.4: Caractersticas del acelermetro ADXL320 ...................................... 68
Tabla 6.1: caractersticas elctricas mximas del MCF5282 ........................... 132
Tabla 6.2: caractersticas elctricas DC del MCF5282 .................................... 132
Tabla 6.3: caractersticas elctricas DC del MCF5282 (continuacin) ........... 133
Tabla 6.4: funciones asociadas a cada mdulo ................................................ 136

MEMORIA

Introduccin

Captulo 1: Introduccin
1.1. Motivacin
Los sistemas automticos de control han desempeado, y desempean, un
papel muy importante dentro y fuera de la industria. Se pueden encontrar
ejemplos de ello ya en el siglo III antes de Cristo, en la Antigua Grecia, con el
diseo del reloj de agua, tambin conocido como Clepsydra, por parte de
Ktesibios. El primer uso del control automtico en la industria parece haber sido
el regulador centrfugo de la mquina de vapor de Watt, en el ao 1775, pero no
fue hasta 1868 cuando se comienza a estudiar la teora del control por
realimentacin, gracias a la explicacin matemtica del regulador centrfugo por
James Clerk Maxwell.

Hoy en da, el control de sistemas es una de las reas de estudio ms


interesantes y completas para el alumno de Ingeniera Electrnica, tanto por la
complejidad que en s mismo representa el control, como por la amplia gama de
campos de conocimiento paralelos que se han de dominar a la hora de modelar el
sistema (mecnica, teora de fluidos, transmisin de calor etc., dependiendo
del tipo de sistema), disear el actuador que actuar sobre la planta del sistema
(electrnica de potencia, funcionamiento de mquinas elctricas), o disear el
circuito de acondicionamiento de medida de seales (electrnica analgica,
instrumentacin electrnica).

Adems, son muy amplias las aplicaciones que tiene el control de sistemas,
por lo cual el presente proyecto adquiere gran valor didctico de cara a la
incorporacin del alumno al mercado laboral.

El hecho de que se haya decidido implantar el control en un microprocesador


aporta al proyecto un indudable valor formativo en el rea del control digital de
sistemas, as como del tratamiento de seales discretas, la programacin en
general, y la orientada a microprocesadores en particular.

10

MEMORIA

Introduccin

Se consider bastante interesante desde el principio que la planta a controlar


fuese una pequea maqueta de tren elctrico. De esta forma se podran observar
fsicamente los efectos del control, en vez de tener que intuirlos a partir de
simulaciones por ordenador. Adems, el sector del transporte ferroviario es un
campo de trabajo bastante atractivo, y que presumiblemente ganar aceptacin
en el futuro frente a otros medios de transporte (avin, coche) de seguir como
hasta ahora las tendencias inflacionistas del precio del petrleo.

Adems, se puede consultar en la bibliografa una relacin de noticias de


accidentes ferroviarios por llevar una elevada velocidad al recorrer una curva.
Este tipo de accidentes se podran haber evitado con un sistema automtico de
control como el que propone el presente proyecto, aplicado a los sistemas
ferroviarios reales, en vez de a una maqueta.

11

MEMORIA

Introduccin

1.2. Objetivos y fases del proyecto


El objetivo del presente proyecto es el diseo de un sistema de control de
velocidad de una maqueta de tren a escala, accionado por un motor de corriente
continua, basado en acelermetros, que ser implantado en un microprocesador.
Dicho control actuar sobre el motor de la maqueta, haciendo que el tren
desarrolle la mxima velocidad posible en cada tramo, dependiendo de la
aceleracin normal que experimente en cada instante. Cuando el tren entre en
una curva, una baliza enviar una seal al microprocesador para que el tren
adopte una velocidad moderada, entonces, el tren comenzar a aumentar su
velocidad hasta alcanzar un mximo que vendr dado por la aceleracin normal,
la cual ser proporcional a la velocidad y al radio de la curva, que experimente el
tren en dicha curva.

Se deber disear tanto el circuito de potencia que permita actuar sobre el


motor del tren, como el circuito de acondicionamiento de seal que permita
medir las variables necesarias para efectuar el control. Adems, se debern
disear distintos controles, y realizar pruebas mediante simulacin de los
mismos, para finalmente elegir el que mejor se adece a las funciones
anteriormente descritas.

Por ltimo, se deber implantar el control en un microprocesador, trabajando


con un sistema operativo en tiempo real. Para ello se habr de realizar la
adaptacin del control al tiempo discreto, y posteriormente programar el
microprocesador para que efecte dicho control.

La figura 1.1 ilustra un esquema completo del sistema que se ha de disear.

12

MEMORIA

Introduccin

Figura 1.1: Diagrama de bloques del sistema a disear

13

MEMORIA

Introduccin

A continuacin se hace referencia a los diferentes pasos a seguir para la


realizacin del proyecto:
1. Diseo del circuito de potencia
2. Estimacin de los parmetros fsicos del sistema
3. Diseo y simulacin del control
4. Diseo de los circuitos de acondicionamiento de seal para la medida
5. Adaptacin del control al microprocesador. Escalado.
6. Implantacin del control en el microprocesador. Programacin.
7. Elaboracin del circuito completo (potencia, acondicionamiento, balizas)
8. Elaboracin de la memoria.

Diagrama de Gantt de la planificacin del proyecto

SEPT

OCT

NOV

DIC

ENE

FEB

MAR

ABR

MAY

JUN

1
2
3
4
5
6
7
8

14

MEMORIA

Introduccin

1.3. Estructura de la memoria


A continuacin se comentan los captulos de los que est compuesta la
memoria y el contenido de los mismos:

Captulo 2: Estado del arte. Abarca:


o Breve historia de la evolucin de los mecanismos de control
ferroviario, hasta llegar a los sistemas de control actuales.
o Breve historia de la evolucin de los mecanismos de control
de motores de corriente continua.

Captulo 3: Descripcin y modelado del sistema. Abarca:


o Introduccin a los sistemas de control continuo.
o Estimacin de los parmetros fsicos necesarios a la hora de
disear el control.
o Obtencin de los modelos de la planta y del actuador del
sistema, as como una descripcin del sistema completo.

Captulo 4: Diseo y construccin del hardware. Abarca:


o Diseo de la etapa de potencia del sistema.
o Eleccin de los reguladores de tensin.
o Diseo del circuito de acondicionamiento de medida de la
corriente que atraviesa el motor.
o Diseo del circuito de acondicionamiento de medida de la
aceleracin.
o Diseo de las balizas.

Captulo 5: Sistema de control. Abarca:


o Introduccin a los sistemas de control discreto.
o Diseos del control del sistema sin filtros.
o Diseos del control del sistema con filtros de primer orden y
filtros FIR.

15

MEMORIA

Introduccin
o Escalado del problema a 16 bits.

Captulo 6: Implantacin en el microprocesador. Abarca:


o Breve introduccin al microprocesador ColdFire MCF5282 y
sus caractersticas ms importantes para este proyecto.
o Programacin del microprocesador, explicando las tareas y
funciones ms relevantes.

Captulo 7: Resultados experimentales. Abarca:


o Pruebas del circuito de potencia
o Pruebas del prototipo

Captulo 8: Conclusiones y trabajo futuro. Abarca:


o Recopilacin de las conclusiones que se han obtenido a lo
largo de todos los captulos mencionados.
o Breve descripcin del trabajo futuro que se podra desarrollar.

16

MEMORIA

Estado del arte

Captulo 2: Estado del arte

2.1. Introduccin
En el presente captulo se tratarn distintos aspectos del desarrollo
tecnolgico aplicado hoy en da tanto a sistemas de control de trenes como a
control de velocidad de motores. Tambin se expondr brevemente la evolucin
tecnolgica a largo de la historia de dichas disciplinas.

2.2. Sistemas de control de trenes


Por razones histricas, la terminologa ferroviaria mezcla a menudo dos
conceptos diferentes bajo el trmino "control de tren": la intervencin
automtica sobre el movimiento del tren (en los sistemas ms simples
generalmente slo bajo la forma de frenado de emergencia) y la sealizacin en
cabina (que no obligatoriamente controla la marcha del tren).
Los primeros elementos no visuales para apoyar la sealizacin lateral son
muy antiguos. Ya en 1842, E. A. Cowper patent la primera seal acstica, el
"detonador", que era prcticamente un petardo unido al carril, que estallaba
cuando pasaba un tren por encima. Puesto que los petardos tenan que ser
colocados manualmente, el uso era limitado a las situaciones de emergencia.
El paso siguiente fue, en Gran Bretaa y los E.E.U.U. y a partir de 1850, la
automatizacin de seales acsticas, mediante contactos mecnicos entre las
seales y las locomotoras. Los primeros aparatos eran una seal acstica
(tpicamente un gong) instalada lateralmente a la va, p. e., en el soporte de la
seal. Si la seal indicaba parada una barra tocaba las ruedas y sonaba el gong.
Ms adelante el gong fue instalado en la locomotora constituyendo, as, la forma
ms temprana sealizacin en cabina.
Alrededor de 1872, se cre en Francia el "Crocodile", el sistema de control de
tren (al principio slo repeticin de seales laterales) con un ciclo de vida ms

17

MEMORIA
Estado del arte
largo, pues todava est en operacin en las redes francesa y belga. El trmino
"Crocodile" deriva de la forma del dispositivo de la rampa colocada entre los
carriles, que se utiliza para establecer un contacto galvnico (electromecnico) y
transmitir informacin a la locomotora.
A partir de ese momento, la introduccin del primer verdadero sistema de
control del tren estaba slo a un paso. Alrededor de 1870, Axel Vogt, el jefe de
mecnicos del ferrocarril de Pennsylvania coloc un tubo de vidrio en la cabina,
conectado con el tubo del freno neumtico. Si un tren sobrepasaba una seal de
parada, una palanca de la seal golpeaba y rompa el tubo de vidrio y se
aplicaban los frenos.
El primer sistema de control del tren utilizado a gran escala fue el ATC
(control automtico del tren) de la compaa britnica GWR, que fue introducido
en 1906. El ATC se bas en el sistema francs "Crocodile" pero, adems de la
seal acstica, el ATC tambin tuvo desde el principio mtodos de visualizacin
mecnica en la cabina y de accionamiento automtico del freno de emergencia.
Aunque el ATC y los sistemas similares han experimentado varias
modificaciones, el principio de base es el mismo, y todava se utiliza hoy.
En 1920, el ferrocarril de Pennsylvania introdujo el sistema de CCS
(Continuous Cab Signals), que a menudo est considerado como un hito en la
historia del control del tren. El CCS es el antepasado de muchos sistemas
existentes, incluyendo el BACC italiano y el ATB holands. En vez de contactos
electromecnicos (y sus partes mviles posibles fuentes de averas), el CCS se
basa en un contacto inductivo entre circuitos cifrados en la va y un receptor en
la locomotora. Desde el principio fueron utilizadas luces de colores para
anunciar en la cabina el aspecto de la prxima seal. El sistema original tena
dispositivo de intervencin automtica del freno, pero fue desactivado ms
adelante por algunas compaas. El CCS anunciaba las seales en la cabina tan
correctamente que algunas compaas ferroviarias americanas quitaron las
seales laterales para reducir gastos de explotacin. Despus de la primera
guerra mundial, CCS fue transferido a la Unin Sovitica. En lo que se refiere a
longitud de lneas equipadas, CCS es el sistema mayoritario en el mundo.

18

MEMORIA
Estado del arte
Mientras, en Alemania, Siemens comenzaba el desarrollo de Indusi, el primer
sistema de control aplicado a gran escala que incorpor la supervisin de la
curva de frenado. De una forma semejante al CCS americano, tambin utiliza
induccin para transmitir la informacin, pero la transmisin tiene lugar
solamente en puntos discretos, mediante circuitos magnticos en la locomotora y
en las seales. Debido a su confiabilidad, a la simplicidad y a la capacidad de
parar el tren antes del punto de peligro, Indusi y sus derivados se convirti en el
sistema de control ms popular en buena parte de Europa (Alemania, Austria,
Polonia, la antigua Yugoeslavia, Rumania, Turqua).
La transmisin de informacin mediante transponders es ms reciente y en
ella se basan los sistemas espaoles ASFA y el sueco EBICAB (en Espaa se
utiliza la versin EBICAB 900). Mas reciente an es la transmisin sin hilos que
es el sistema utilizado por el europeo ERTMS y sus antecesores FFB
(FunkFahrBetrieb) y FZB (FunkZugBeeinflussung) de la Deutsche Bahn.
Basados en los "antepasados" comunes (el Crocodile francs, el CCS
americano y el Indusi alemn, los tres sistemas de control han evolucionado
histricamente de maneras muy diferentes en las distintas compaas
ferroviarias. Los sistemas modernos incluyen el clculo dinmico en tiempo real
del perfil de la velocidad. En 1990, haba por lo menos 30 diversos sistemas de
control del tren en operacin en la red europea de va ancha. A pesar de los
antepasados comunes, casi todos los sistemas existentes son completamente
incompatibles. La creacin de las eurobalizas y sobre todo de ERTMS, debe
terminar con esta "torre de Babel de estndares".

Se pueden considerar dos grupos de sistemas de control de tren:

Sistemas

"auxiliares"

(sealizacin

lateral

prominente,

la

sealizacin en cabina repite la lateral, control de tren slo en algunas


situaciones de emergencia): ASFA, PZB/Indusi, Crocodile, ...

Sistemas completos de sealizacin en cabina (sealizacin

lateral inexistente o subordinada a la de cabina). Son utilizados en LAV y


19

MEMORIA
Estado del arte
en lneas de cercanas y metro con mucha densidad de trfico. Los
sistemas mensajes que son evaluados en el computador central del
vehculo. El sistema supervisa continuamente la velocidad del tren, y
gobierna su marcha por medio de sistemas que controlan la traccin y el
frenado del vehculo (como por ejemplo el sistema ATF, Automatismo
de Traccin y Frenado, de las locomotoras de la serie 252 de Renfe. El
equipo del vehculo emite la posicin del tren, velocidad, caractersticas
de frenado y otras informaciones al sistema central para su posterior
tratamiento y realimentacin del sistema.

En la actualidad, se pueden encontrar diversos sistemas de control de


velocidad de trenes y sealizacin, entre los cuales, caben destacar los
siguientes:

ATP (Proteccin Automtica de Tren, del ingls Automatic Train


Protection) se puede encontrar implantado de distintas maneras:
-

Doble sealizacin y ATP de una portadora


En los sistemas de doble sealizacin el tren siempre est protegido
por dos seales de control. Existe un cantn tramo por el que un tren
est autorizado a circular nico entre seal y seal, que por lo general
se compone de uno o ms circuitos de va, conformando un cantn.
Cada circuito de va tiene asignada una velocidad mxima de
seguridad (lmite civil) a travs del sistema de ATP, que es invariable
en funcin de los pasos por diagonales, radios de curva, las pendientes,
etc. (perfil de la va). En caso de superar la velocidad asignada o rebasar
una seal de control el tren aplica freno de emergencia hasta su total
detencin.
El sistema de ATP se comunica de forma continua con el tren por
medio de una seal que recorre los carriles y aporta un cdigo con la
velocidad mxima en el circuito de va. Este sistema consigue

20

MEMORIA
Estado del arte
intervalos tericos de entre 2 min 20 seg y 2 min 50 seg dependiendo de
las configuraciones de la va.

Sealizacin Simple y ATP de dos portadoras


En este sistema las parejas de cdigos (portadoras) indican la
Velocidad Mxima de Seguridad y la Velocidad Objetivo. Para un
tren que circula por una Lnea con sistema de cdigos de dos portadoras
el sistema avisa con antelacin cual va a ser la velocidad mxima
permitida en el siguiente circuito de va, de tal manera que si el tren
llegara a ese circuito de va a una velocidad superior, se aplicara freno
de emergencia hasta la completa detencin del tren.
En los sistemas de ATP de dos portadoras existe una seal a la salida
de la estacin y sta puede autorizar la salida de los trenes en, blanco,
verde o en un aspecto M Roja Rojo para trenes conducidos en
Manual y va libre para los trenes conducidos con ATP que indica
que la va no est libre hasta la siguiente estacin, por lo que el tren
debe posteriormente guiarse por los cdigos de ATP existentes en la
va.
Los tramos de va con cdigos de dos portadoras tienen una
velocidad mxima de seguridad (lmite civil) que puede variar hacia una
velocidad menor en funcin de la proximidad del tren anterior o el
aspecto de las seales (por la posicin de agujas, vueltas automticas,
etc.)
As mismo se imposibilita la aplicacin de traccin cuando la
velocidad del tren es superior a la objetivo.
El ATP de dos portadoras consigue intervalos tericos de entre 1 min
55 seg y 2 min 15 seg dependiendo de las configuraciones de la va.

21

MEMORIA
Estado del arte
ATO (Conduccin Automtica de Tren, del ingls Automatic Train
Operation)
El sistema de conduccin automtica se compone de un conjunto de
equipos, que situados en va y tren sustituyen la funcin del conductor,
excepto la apertura y cierre de puertas y la orden de arranque.
Este modo de conduccin est bajo la supervisin del ATP que
indica al sistema las velocidades mximas para cada tramo, y
proporciona un menor tiempo de recorrido y un mejor confort de
marcha respecto a la conduccin en Manual con ATP.
El tren puede recibir diferentes tipos de rdenes y en especial la de
velocidad de marcha por regulacin de trfico que se realiza desde el
Puesto Central a travs del SIRAT.
Tambin permite la maniobra de vuelta en terminales (autoshunt),
sin conductor en una de las cabinas (la de entrada al saco), siempre que
existan cdigos de ATP.
Para la correcta parada de los trenes en las estaciones existen en la
va una serie de balizas denominadas X1, X2 y X3. Por medio de ellas
es posible transmitir datos de geometra de va al tren y desde el Puesto
Central rdenes como por ejemplo; el paso sin parada en la estacin,
situacin del punto de parada, velocidad en la interestacin, perfil de
va, autoshunt, etc.

SIRAT (Sistema Integrado de Regulacin Automtica de Trenes)


Este sistema permite la regulacin de trenes a intervalo y a horario
en horas de menor afluencia de viajeros. Tambin realiza de una forma
gradual la incorporacin o encierre de trenes de la lnea y las
transiciones de circulacin por intervalo a circulacin con horario.

22

MEMORIA
Estado del arte
El Sistema Integrado de Regulacin Automtica de Trenes est
plenamente integrado en las lneas con circulacin en ATO, este
sistema permite, por medio de una simulacin predictiva, un ajuste
preciso en la regularidad de los trenes, utilizando las diferentes
velocidades que las balizas de ATO pueden transmitir al tren en las
interestaciones. As mismo en las lneas no dotadas de ATO realiza la
regulacin mediante el uso de las seales.
Como resultado de estos ajustes en la regulacin se mejora la
capacidad de transporte de las lneas y se consiguen unos elevados
ahorros de energa derivados de la aplicacin de marchas con menor
consumo de los trenes y evitando paradas por regulacin en las
estaciones.
Otra de las prestaciones del sistema son los informes en tiempo real
en forma de grficos de los ndices de calidad de la regularidad.

Distancia Objetivo
En este sistema el tren recibe de la instalacin de va no slo la
velocidad mxima a la que el tren puede circular en el cantn por el que
circula, sino tambin que cantn precedente se encuentra ocupado por
otro tren. De esta forma, cada tren tiene informacin de la distancia que
le queda por recorrer hasta el cantn realmente ocupado por delante.
Con ello se posibilita un mayor acercamiento de cada tren a su
precedente, reducindose el intervalo entre trenes en la lnea y
aumentando la capacidad de transporte de la misma.

Cantn mvil
En este sistema el tren va informando va radio permanentemente a
un sistema de control ubicado en la instalacin fija de su situacin. A su
vez, cada tren recibe informacin va radio acerca de la situacin del
23

MEMORIA
Estado del arte
tren anterior, de esta forma un tren puede aproximarse al mximo al
tren precedente segn lo que su parbola o distancia de frenado le exija
(en funcin de su velocidad, el perfil de va, tiempos de respuesta y
seguridad, etc.)
La diferencia fundamental con el sistema anterior es que su
proximidad es relativa al tren anterior y no a un cantn ocupado, ya que
ste en funcin de su longitud provoca unas distancias mayores entre
trenes, esto es, un mayor intervalo.

2.3. Control de motores de corriente continua


El motor de corriente continua aparece en el siglo XIX. Esta mquina es una
de las ms verstiles en la industria. Su fcil control de posicin, par y velocidad
la han convertido en una de las mejores opciones en aplicaciones de control y
automatizacin de procesos. La principal caracterstica del motor de corriente
continua es la posibilidad de regular la velocidad desde vaco a plena carga.

Una mquina de corriente continua (generador o motor) se compone


principalmente de dos partes, un estator que da soporte mecnico al aparato y
tiene un hueco en el centro generalmente de forma cilndrica. En el estator
adems se encuentran los polos, que pueden ser de imanes permanentes o
devanados con hilo de cobre sobre ncleo de hierro. El rotor es generalmente de
forma cilndrica, tambin devanado y con ncleo, al que llega la corriente
mediante dos escobillas. Tambin se construyen motores de CC con el rotor de
imanes permanentes para aplicaciones especiales.

En 1896 aparece el control Ward Leonard para variacin de velocidad. De las


tres formas de variar la velocidad de un motor, la ms eficaz es la del control de
voltaje de armadura, puesto que permite una amplia variacin de la velocidad sin
afectar el par mximo del motor. La forma normal de variar el voltaje de
armadura de un motor de cc, era suministrndolo desde un generador de cc.
24

MEMORIA
Estado del arte
Un motor primo trifsico que mueve al rotor del generador de cc el cual se usa
para alimentar un voltaje de cc a un motor de cc; a ste sistema se le llama
Ward-Leonard y es extremadamente verstil. El voltaje de armaura se puede
variar mediante cambios en la corriente de campo en el generador de cc, ste
voltaje de armadura permite que la velocidad del motor pueda variarse
suavemente entre un valor muy pequeo y la velocidad base. La velocidad del
motor puede ajustarse por encima de la velocidad base reduciendo la corriente de
campo del motor, por eso es que este sistema es tan flexible que permite control
total de la velocidad del motor. Adems permite tambin el cambio del sentido
de rotacin, solamente cambiando la polaridad del voltaje de armadura, as es
posible obtener un rango muy amplio de variacin de la velocidad en cualquier
sentido de rotacin. Otra funcin es la de regenerar o retornar a las lneas de
alimentacin la energa de movimiento de las mquinas. Si una carga pesada se
eleva y luego se baja mediante el motor de cc de un sistema Ward-Leonard,
cuando la carga esta cayendo, el motor de cc actua como generador,
suministrando potencia hacia el sistema de ca. En esta forma, mucha de la
energa requerida en el primer momento para alzar la carga puede recuperarse
reduciendo el costo total de operacin de la mquina. La desventaja del sistemna
Ward-Leonard, es la de tener que comprar tres mquinas completas de valores
nominales esencialmente iguales, lo cual es muy costoso. Otra es que tres
mquinas son mucho menos eficientes que una, por ello han sido reemplazado
por circuitos controladores basados en SCRs , que resultan definitivamente ms
barato que dos mquinas extra.

En 1911 aparece el control Kramer para el motor de Rotor Devanado. Basado


en el principio de Leblanc, este mtodo difiere en que el transformador variable
va conectado a los anillos colectores del motor bobinado en vez de a la lnea.
Como en el caso del sistema de Leblanc, la frecuencia del rotor bobinado es
tambin la frecuencia del voltaje en el conmutador. Decalando la posicin de
fase de las escobillas se alternar el factor de potencia del motor de rotor
devanado, e incrementado el voltaje aplicado al rotor del convertidor se
incrementar la velocidad. Se pueden conseguir velocidades superiores e
inferiores a la sncrona. Adems el convertidor de frecuencia tambin acta
25

MEMORIA
Estado del arte
como motor al convertir la potencia que se le suministra a travs del
autotransformador en potencia mecnica disponible en el eje. Las mayores
aplicaciones de los sistemas de Leblanc y Kramer son para grandes motores de
rotor bobinado de 500 CV hasta unos 3000 CV. Las ventajas de devolver la
energa al sistema, adems de las bajas prdidas en lnea del convertidor y el
autotransformador (el aparato elctrico de mayor rendimiento desarrollado hasta
el momento), combinado con la ventaja de correccin del factor de potencia,
hace que el sistema de Kramer sea particularmente til en aplicaciones de
control de velocidad de elevada potencia. Su mayor inconveniente reside en su
elevado costo inicial.

La evolucin del control de motores a partir de entonces va de la mano del


desarrollo de distintos dispositivos elctricos y electrnicos. Durante los aos 20
aparecen los primeros dispositivos electrnicos de arco (ignitron, tiratron,
vlvula de mercurio). Durante los aos 50 aparecen los semiconductores de
estado slido (diodo y transistor). En la dcada del 60 aparece el tiristor, que es
considerado el dispositivo ms importante para la Electrnica de potencia. En la
dcada de los 70 comienza a evolucionar la microelectrnica

En la dcada del 80 se desarrolla el microprocesador. Este hecho, junto con el


avance de la electrnica, ha hecho que los motores de corriente continua hayan
cado en desuso pues los motores de corriente alterna del tipo asncrono, pueden
ser controlados de igual forma a precios ms accesibles para el consumidor
medio de la industria. A pesar de esto el uso de motores de corriente continua
contina y se usan en muchas aplicaciones de potencia (trenes y tranvas) o de
precisin (mquinas, micromotores, etc.)

En este proyecto se han utilizado tcnicas de control por modulacin de


ancho de pulso (PWM), las cuales se vern con mayor profundidad en el
captulo cuarto.

26

MEMORIA

Modelado del sistema

Captulo 3: Descripcin y modelado del sistema

3.1. Introduccin
Se define sistema como un elemento o conjunto de elementos que da una
respuesta o salida ante una determinada excitacin o entrada. Existen diversos
tipos de sistemas, clasificados atendiendo a distintas caractersticas o
propiedades de los mismos, pudindose clasificar el sistema que se va a tratar a
continuacin como un sistema cuantitativo (se puede tratar siguiendo modelos
matemticos), dinmico (su respuesta en un instante depende de valores
anteriores de la entrada, y no slo del valor de la entrada para ese instante),
lineal (se cumple el principio de superposicin para las ecuaciones del modelo),
e invariante en el tiempo (el sistema va a ser el mismo en cualquier instante de
tiempo). Aquellos sistemas lineales e invariantes en el tiempo suelen
denominarse comnmente LTI, del ingls linear time-invariant.

Un modelo es un conjunto de ecuaciones matemticas que se emplean para


describir la relacin entre la entrada y la salida del sistema. Es poco probable
que el modelo pueda representar exactamente las relaciones entre la entrada y la
salida de un sistema. En cualquier etapa de modelado hay una serie de efectos
que se desprecian para hacer el problema tratable. No obstante, no deja de ser
til el uso de modelos que pueden aproximar la realidad, permitiendo una serie
de estudios, como la simulacin (obtencin de forma numrica o grfica de la
respuesta de un sistema ante una excitacin conocida), el control (regulacin de
la salida de un sistema para que sea igual o parecida a una determinada entrada o
consgina) o la prediccin (obtencin de la respuesta de un sistema en el futuro,
supuestas diversa condiciones de entrada), con distintas aplicaciones. Si no se
indica lo contrario, en el resto del texto se considerar que el modelo es el
sistema, esto es, que las ecuaciones representan suficientemente bien la realidad.
De hecho, abusando del lenguaje, se llamar habitualmente sistema al conjunto
de ecuaciones que forman el modelo.

27

MEMORIA

Modelado del sistema

De ahora en adelante, se utilizar el trmino seal para referirse a una


variable o magnitud que puede variar en el tiempo. La seal de entrada de un
sistema, o excitacin, es la variable que normalmente controla o impone el
usuario. La respuesta de este sistema, o salida, es la variable de inters. Ntese
que las variables de salida son, en ocasiones, elegidas por el usuario. Adems,
pueden existir otras variables o seales internas en el sistema, normalmente de
menor inters. La mayor parte de las seales estarn modeladas por funciones
sencillas. En otros casos la seal ser una composicin de estas funciones. El uso
de estas funciones sencillas est justificado por varios motivos:
Se dan comnmente en la prctica.
Se usan, en algunos casos, como seales normalizadas.
Son ms fciles de tratar analticamente.
Se utilizar habitualmente la notacin u(t) para la seal de entrada e y(t) para
la salida.

Cabe sealar que un sistema dinmico, lineal e invariante en el tiempo, est


representado por una ecuacin diferencial lineal de coeficientes constantes, del
tipo:

d n y(t )
d n1 y(t )
dy(t )
a
+
+ ... + a1
+ a0 y(t ) =
n 1
n
n 1
dt
dt
dt
d m y(t )
d m1 y(t )
dy(t )
b
= bm
+
+ ... + b1
+ b0 y(t )
m1
m
m1
dt
dt
dt

an

[3.1]

La cual puede ser resuelta utilizando la transformada de Laplace. Se define la


trasformada de Laplace X(s) de una variable x(t) como:

X (s ) = L{x(t )} = x( )e s d

[3.2]

Para ms informacin acerca de la trasformacin de Laplace y sus


propiedades, as como de las trasformadas de las funciones que se van a utilizar

28

MEMORIA
Modelado del sistema
ms adelante, se puede consultar cualquier texto sobre ecuaciones diferenciales,
como por ejemplo las referencias bibliogrficas nmero 6, 7 y 8.

3.2. Descripcin del sistema

Como todo problema de control, se puede seguir el siguiente esquema para su


modelizacin:
Perturbacin
Ref.

CONTROL

CONVERTIDOR
DE POTENCIA

SISTEMA A Salida
CONTROLAR

SENSOR
Figura 3.1: diagrama funcional de bloques de un sistema de control
continuo tipo.
El bloque de control consistir en dos lazos de control proporcional integral
discretos, implantados en un microprocesador. Como se puede apreciar en la
figura 3.2, el primero de esos bloques de control, compara la referencia de
velocidad con la medida de la misma mediante un sensor, que en este caso est
representado por la ganancia Ks. Despus de aplicar su accin proporcionalintegral, que se ver con ms detalle en el captulo de Software y sistema de
control, obtiene como salida un valor de corriente (el cual oscilar entre dos
valores, mnimo y mximo, que sern los valores de saturacin, por encima de
los cuales, en valor absoluto, el motor podra sufrir daos), que ser denominada
corriente de referencia de ahora en adelante, y que se introduce como entrada en
otro bloque de control. Este segundo bloque de control comparar dicha
corriente de referencia con la corriente real que circula por el motor en cada
instante, para, posteriormente, aplicar su accin proporcional-integral, y generar
una seal (mando), que, debidamente acondicionada, tras pasar por la etapa de

29

MEMORIA
Modelado del sistema
potencia, representa la tensin de alimentacin del motor en un instante
determinado.

El mando, o salida del microprocesador que ejecuta el algoritmo de control,


es una onda PWM entre 0 y 3V. Esta seal es debidamente acondicionada para
obtener a la salida del circuito de potencia una onda PWM entre -14V y 14V, lo
que permite variar el valor medio de la tensin que se le procura al motor entre
los valores mencionados anteriormente. El proceso de acondicionamiento de la
seal efectuado en el circuito de potencia se encuentra detallado en el apartado
primero del captulo cuarto, denominado Etapa de potencia.

El sistema a controlar se compone de dos partes:

Actuador: modelo elctrico del motor de corriente continua. Se


estimarn sus parmetros (inductancia y resistencia internas) como se
describe en el apartado de estimacin de parmetros fsicos, y se
modelizar de acuerdo a un modelo matemtico, descrito con ms
detalle en el apartado 3.4.

Planta: modelo mecnico del motor y la maqueta del tren. Sus


parmetros (masa y friccin viscosa producto del rozamiento del tren
con las vas y de las holguras de los engranajes del motor) sern
estimados tal y como se describe en el apartado 3.3. Se tratar la
planta como un modelo matemtico cuya obtencin se detalla en el
apartado 3.4.

En cuanto al sensor, o elemento utilizado para medir la variable de salida,


para poder as realimentar el sistema, se disear un circuito de
acondicionamiento para poder medir la intensidad que se le est suministrando al
tren, y se usar esa intensidad para estimar su velocidad. Tanto su diseo como
implantacin estn detallados en el apartado 4.4, denominado Diseo del
circuito de acondicionamiento.

30

MEMORIA

Modelado del sistema

El diagrama de bloques del sistema completo, simplificando distintos


aspectos del mismo como la etapa de potencia o la discretizacin de las seales
de

control

es

el

que

muestra

la

figura

3.2:

31

MEMORIA

Modelado del sistema

Figura 3.2: Primera aproximacin del diagrama funcional de bloques del sistema completo

32

MEMORIA

Modelado del sistema

3.3. Estimacin de parmetros fsicos

3.2.1. Clculo de la resistencia interna del motor


Para calcular la resistencia interna del motor, se mide con un polmetro la
resistencia que existe entre las dos bornas del motor. Como el control se va a
aplicar a una maqueta de tren elctrico, cuyo motor es alimentado a travs de las
vas metlicas sobre las que circula dicha maqueta, habr que comprobar que la
resistencia de las vas es despreciable con respecto a la resistencia interna del
motor.

Se demuestra que la resistencia elctrica de un conductor es directamente


proporcional a su longitud, e inversamente proporcional a su seccin y a su
conductividad:
R =

l
S

[3.3]

Integrando entre los extremos a y b del conductor, resulta:

R( a ,b ) =

1
dl
S

[3.4]

Cuando el conductor tiene seccin constante, como es este caso, la expresin


anterior puede simplificarse, obtenindose as:

Rab =

L
1 Lab

= ab
S
S

[3.5]

Una vez demostrado, queda comprobar lo enunciado con anterioridad, esto es,
que la resistencia elctrica que ofrecen las vas es despreciable respecto a la
resistencia interna del motor. Para ello se realiz un ensayo experimental, viendo
cmo cambiaba la resistencia del conjunto motor-vas conforme se desplazaba el
tren por las mismas de forma manual (esto es, sin aplicarle ninguna tensin al
motor). De este ensayo se sac la conclusin de que la resistencia de las vas es

33

MEMORIA
Modelado del sistema
despreciable, ya que, a lo largo de todo el circuito, la resistencia del conjunto
variaba como mximo 1 sobre 35 .

3.2.2. Clculo de la inductancia del motor


Con ayuda de la etapa de potencia, se hace pasar una onda cuadrada, de
amplitud 28V y valor medio 0V por el motor, al cual se le ha instalado una
resistencia en serie de 1 para medir la intensidad que recorre la bobina del
motor.

Se mide con el osciloscopio la tensin tanto a un lado como a otro de la


resistencia, tomando como referencia de masa la misma que tiene la etapa de
potencia. La intensidad que circula por la inductancia del motor ser igual a la
diferencia de las dos tensiones medidas anteriormente, dividida entre el valor de la
resistencia antes mencionada, esto es, 1.

Para obtener dicha variable con la mayor precisin posible, se almacenan los
datos del osciloscopio en un fichero .txt, llamado corriente.txt, y desde
Matlab se efectan las operaciones pertinentes mediante un fichero .m, llamado
leer_datos.m (ver anexo 2 para ms informacin) con el fin de representar
dicha corriente, dando como resultado:

34

MEMORIA

Modelado del sistema

Figura 3.3: corriente que atraviesa el motor


Se observa que dicha corriente, como era de esperar, toma la forma de una
exponencial, por tanto, su expresin analtica ser del tipo:
+

I (t ) = I () + ( I (0 ) I ()) e

[3.6]

Siendo la constante de tiempo de la exponencial.

Despejando de la ecuacin anterior, queda:

t
I (t ) I ()

Ln
+
(
I
(
0
)

I
(

[3.7]

Y sustituyendo por los valores pertinentes, obtenidos de la medida, y


ponderados gracias a Matlab, como se puede apreciar en el fichero

35

MEMORIA
Modelado del sistema
leer_datos.m, se obtiene un valor para la constante de tiempo de la exponencial
de:

= 5.6662 10-5 s

Una vez se ha obtenido el valor de la constante de tiempo de la exponencial de


la corriente, slo har falta hallar la relacin entre la inductancia del motor y dicha
constante de tiempo para calcular la primera. A partir del esquema elctrico del
motor de corriente continua, representado en la figura 3.4, se obtiene:

U em
U em t L
I ( s) =
i (t ) =
e
R + Ls
L

[3.8]

Figura 3.4: Esquema elctrico de un motor DC


Como se vio anteriormente, la corriente es una exponencial cuya expresin

analtica se define como: I (t ) = I () + ( I (0+ ) I ()) e . Comparando estas dos


expresiones obtenidas, se deduce que:

Por lo tanto,

L
R

[3.9]

L = 2 mH

36

MEMORIA

Modelado del sistema

3.2.3. Clculo de la constante


contraelectromotriz del motor (Ke)

asociada

la

fuerza

A partir del circuito elctrico del actuador (motor DC), se concluye que:

Fm = i K m =

u em
K m
R + Ls

[3.10]

De lo que se deduce que, en rgimen permanente:

Fm(0) = i(0) K m =

u em
K m
R

[3.11]

La corriente, en rgimen permanente se puede calcular como:

i=

u em
em = u R i
R

[3.12]

Adems, la fuerza contraelectromotriz del motor se puede expresar como:

em = K e v

[3.13]

Para el clculo de la friccin viscosa por rozamiento del tren con las vas, as
como para el clculo de la constante del par motor (Km) y de la constante asociada
a la fuerza electromotriz del motor (Ke) se realiz el siguiente experimento: sobre
un circuito circular, se le hizo al tren completar N vueltas a dicho circuito,
midiendo el tiempo que tardaba en completar las N vueltas. Este proceso se repiti
varias veces, aplicando distintas tensiones al motor del tren cada vez. A su vez,
tambin se midi el valor medio de la corriente que suministraba la fuente con la
que se aliment el motor a este. Todas las medidas mencionadas, representan las
magnitudes medidas en rgimen permanente.

Una vez obtenidos los distintos valores descritos anteriormente, se representa


grficamente la fuerza contraelectromotriz en funcin de la velocidad, y se realiza
una regresin lineal simple, obtenindose:

37

MEMORIA

Modelado del sistema

figura 3.5: fuerza contraelectromotriz en funcin de la velocidad del tren


desarrollada en el experimento.
Como se ha visto anteriormente, la fuerza electromotriz puede expresarse como
el producto de la constante asociada a ella (Ke) y la velocidad. Por tanto, se puede
deducir fcilmente que dicha constante asociada a la fuerza electromotriz ser la
pendiente de la recta representada anteriormente.
Por tanto: K e = 5.8347 Vs/m

3.2.4. Clculo de la constante del par motor (Km)


La constante asociada a la fuerza contraelectromotriz del motor, y la constante
del par motor, que se ha calculado anteriormente, son iguales. Teniendo en cuenta
esto, se deduce que:

Km = 5.8347 Nm/A

38

MEMORIA
3.2.5. Clculo de la friccin viscosa

Modelado del sistema

Debido al rozamiento que se produce entre las ruedas del tren y las vas, y a
posibles holguras en los engranajes del motor, se produce un efecto de friccin
que se puede modelar como una friccin viscosa.

Como ya se explicar ms adelante, la funcin de transferencia de la planta del


sistema es:

v=

1
D

1
(Fm Ff ) =
(Fm Ff )
M
Ms + D
s +1
D

[3.14]

De lo que se deduce que, en rgimen permanente (es decir, cuando =0):

v(0) = vs= j , =0 =

1
D

(Fm Ff ) Dv + Ff = Fm [3.15]
M
j + 1
D

Como se vio anteriormente:

Fm = i K m =

u em
K m
R + Ls

[3.16]

De lo que se deduce que, en rgimen permanente:

Fm() = i() K m =

u ( ) em ( )
K m
R

[3.17]

Como Km es ya una constante conocida, as como em tambin lo es, se puede


representar la fuerza del par del motor (Fm) con respecto a la velocidad, y hacer
de nuevo una regresin lineal simple, lo cual se puede observar en la figura 3.6:

39

MEMORIA

Modelado del sistema

figura 3.6: fuerza del par motor en funcin de la velocidad del tren
desarrollada en el experimento.
Como la fuerza del par motor si no hay perturbaciones se puede expresar como
el producto entre la friccin viscosa y la velocidad, se puede afirmar que la
friccin viscosa asociada al rozamiento del tren con las vas ser la pendiente de la
recta anteriormente representada.
Por tanto: D = 0.6703

Nms/rad

3.2.6. Clculo de la masa


La medida de la masa se realiz con una balanza electrnica. De este ensayo se
concluy que: M

= 0.7kg

40

MEMORIA
3.2.7. Estimacin de la velocidad mxima

Modelado del sistema

Por ltimo, se trat de estimar la velocidad mxima que puede desarrollar el


tren cuando se alimenta su motor con una tensin mxima de 14V. Para ello se
represent es una grfica los distintos datos de velocidad en funcin de la tensin
de alimentacin. Se puede observar dicha representacin en la figura 3.7:

Figura 3.7: velocidad en funcin de tensin de alimentacin.


A partir de ella, y mediante interpolacin, se obtuvo la velocidad que habra de
tener el tren cuando ste es alimentado a 14V. Se considera que el tren va a
conservar su tendencia lineal de velocidad en funcin de tensin de alimentacin,
la cual se puede observar en la grfica.
Se concluye pues que:

Vmax = 1.1178 m/s 1.12 m/s

41

MEMORIA

Modelado del sistema

3.4. Obtencin del modelo


En este apartado se describen con detalle los procesos seguidos para obtener
los distintos elementos que componen el modelo del sistema.

3.3.1. Modelo de la planta


La planta se puede modelar como un sistema de primer orden, en forma de
sistema mecnico de traslacin, tal y como puede verse en la figura 3.8:

v
Ff
m
Fm

M
D
x

Figura 3.8: representacin mecnica de la planta


Es un sistema dinmico, lineal e invariante, y la ecuacin diferencial que rige
el comportamiento de la planta es la siguiente:

d 2 x(t )
dx(t )
dv(t )
Fm Ff = M
+
D

Fm

Ff
=
M
+ Dv(t ) [3.18]
dt
dt
dt 2
Aplicando la transformada de Laplace, se obtiene:

Fm(s ) Ff (s ) = (M s + D ) V (s )

[3.19]

Y despejando la variable a controlar, esto es, la velocidad:

V (s ) =

Fm(s ) Ff (s )
M s + D

[3.20]

42

MEMORIA
Modelado del sistema
Como el sistema es lineal, si se supone nula la perturbacin (Ff(s)), la ecuacin
anterior queda:

V (s ) =

Fm(s )
V (s )
1
=

M s + D Fm(s ) M s + D

[3.21]

La cual es la funcin de transferencia (funcin matemtica que modela el


comportamiento de un sistema) de la planta.

Si dicha funcin de transferencia es traducida a un diagrama de bloques, en el


cual nicamente se utilizan ganancias e integradores (esto es as para poder
obtener informacin sobre las seales intermedias que actan sobre la planta, y no
slo de la entrada y la salida) se obtiene lo siguiente:

Figura 3.9: diagrama funcional de bloques de la planta

3.3.2. Modelo del actuador (motor DC)


El par motor Tm , se relaciona con la corriente de armadura i mediante una
constante K m :
43

MEMORIA

Modelado del sistema


Tm = K m i

[3.22]

La fuerza contraelectromotriz em es proporcional a la velocidad de giro del


motor , con constante de proporcionalidad K e :

em = K e

[3.23]

Aplicando la 1 ley de Kirchoff al circuito elctrico del motor, ya representado


en la figura 3.3, resulta:

di
L + R i = V K e
dt

[3.24]

Donde:
di
V L = L
dt

[3.25]

siendo L y R la bobina y resistencia propias del motor, respectivamente.


Tomando transformadas de Laplace:

(Ls + R )I (s ) = V K e I (s ) = V K e
Ls + R

[3.26]

Por tanto, la funcin de transferencia:


I (s )
1
=
V (s ) Ls + R

[3.27]

Por otra parte, la ecuacin mecnica del motor es:


J

d
+ Dm = Tm TR = K m i TR
dt

[3.28]

Donde:
J: es el momento de inercia del motor.
Dm: es la constante de friccin viscosa del motor.

: es la velocidad angular del eje del motor.


TR: es el par de carga del motor.

44

MEMORIA
Modelado del sistema
Como se puede observar, el modelo del motor trabaja con parmetros propios
de un sistema mecnico de rotacin, sin embargo, en la planta se ha utilizado un
modelo de sistema mecnico de traslacin. Tanto el momento de inercia como la
constante de friccin viscosa del motor estn tenidos en cuenta en la masa y la
constante de friccin viscosa de la planta. La velocidad angular del eje del motor,
multiplicada por el radio de las ruedas y por la constante obtenida de las
reductoras a las que aplica su par el motor, se transforma en la velocidad lineal
que adquiere la planta al ser aplicado el par del motor. Por ltimo, el par de carga
del motor ya viene dado como la fuerza de carga Ff, que se aplica sobre la planta.

Adems, el par Tm que da el motor se relaciona con la fuerza Fm que se aplica


al tren mediante la constante que relaciona velocidad angular del eje del motor
con velocidad lineal desarrollada por el tren. Las constantes Km y Ke obtenidas en
los experimentos descritos en la seccin Estimacin de parmetros fsicos ya
tienen en cuenta ese efecto, y de ellas se obtiene directamente la relacin entre
corriente del motor (i) y fuerza aplicada al tren (Fm) en el caso de Km, y velocidad
lineal del tren (v) y fuerza contraelectromotriz (em) del motor en el caso de Ke
As pues, el diagrama de bloques del modelo del motor de corriente continua es
el siguiente:

Figura 3.10: diagrama funcional de bloques del actuador

45

MEMORIA

Modelado del sistema

3.5. Conclusiones
A lo largo del captulo se ha expuesto la metodologa seguida para obtener los
distintos parmetros necesarios a la hora de disear el control, as como la base
terica sobre la que se sustentan los clculos realizados para dicha obtencin de
los mencionados parmetros.

Una vez obtenidos, se ha procedido a obtener un modelo del sistema, a partir


de cual trabajar en el diseo del control, ya que, sin una modelizacin del sistema
fsico, sera imposible realizar dicho diseo o las simulaciones pertinentes para
comprobar la validez del mismo.

46

MEMORIA

Hardware

Captulo 4: Diseo del hardware


4.1. Introduccin
Se distinguirn distintas fases dentro del diseo del hardware:

Diseo de la etapa de potencia: conlleva el acondicionamiento de la


seal de PWM generada en el microprocesador, entre 0V y 5V, para
convertirla en otra seal PWM entre -14V y 14V, mrgenes impuestos
por el motor de continua, con el mismo ciclo de trabajo que la primera,
y que sea capaz de suministrar al motor la corriente necesaria para el
correcto funcionamiento del mismo.

Diseo de los reguladores de tensin: como se ver ms adelante,


para conseguir la seal PWM antes descrita entre -14V y 14V, ser
necesario alimentar el circuito a 14V DC. Debido a esto, es necesario
utilizar dos reguladores de tensin para obtener 3.3V para la
alimentacin del microprocesador y 5V para activar el puente en H de
la etapa de potencia. Desde el punto de vista de la eficiencia energtica,
se descartan los reguladores lineales, ya que disipan mucha potencia en
forma de calor, lo cual, es altamente indeseable; por tanto, se emplearn
dos reguladores de tensin conmutados, cuyo diseo se detallar ms
adelante.

Diseo del circuito de acondicionamiento para medir la intensidad


que atraviesa el motor: se estimar la velocidad lineal del tren,
variable que cierra el lazo de control del sistema, por medio de la
intensidad que atraviesa el motor del mismo. Para ello se ha de disear
un circuito de acondicionamiento que permita medir dicha intensidad
con la mayor precisin y sensibilidad posibles.

47

MEMORIA

Hardware

Diseo del circuito de acondicionamiento para medir la seal del


acelermetro:

se

detallar

ms

adelante

el

proceso

de

acondicionamiento de seal de los acelermetros, para llevarla hasta el


conversor analgico/digital del microprocesador. A grandes rasgos, el
circuito consistir de un rectificador de precisin y una etapa de ajuste
de ganancia, que tomar como ganancia terica mxima 4G.

Diseo de las balizas: las balizas estarn colocadas al comienzo de


cada curva, y mandarn una seal al microprocesador cuando el tren
pase por su lado, con el fin de aminorar su velocidad antes de entrar a la
curva. Estarn constituidas por un diodo emisor de luz roja, y un
fotodiodo encargado de detectar dicha luz roja.

4.2. Etapa de potencia


Como ya se ha comentado, la etapa de potencia adeca la seal PWM de salida
del microprocesador para que pueda ser utilizada en el motor. Como se puede
observar en la hoja de caractersticas del microprocesador utilizado (ver anexo 4),
la corriente mxima de salida que es capaz de suministrar entre todas sus patillas
es de 60mA. Experimentalmente, se midi la corriente mxima que requiere el
motor en su situacin ms desfavorable, esto es, cuando el tren est parado y se le
aplica la tensin mxima, que en este caso son 14V, obteniendo un pico mximo
de corriente de 390mA. Resulta evidente pues la necesidad de emplear una
circuitera adicional para poder alimentar al motor, lo cual se conseguir gracias al
puente en H.

El puente en H es un circuito tpico utilizado para el control de motores. En la


figura 4.1 se muestra una representacin esquemtica del circuito. Hay que tener
en cuenta que es una simplificacin: faltan los diodos de libre circulacin, la
circuitera de activacin/desactivacin de los transistores, etc. Para que el motor
gire, se activan dos de los transistores opuestos diagonalmente. En funcin del par
48

MEMORIA
Hardware
de transistores activados, la corriente fluye en uno u otro sentido, lo que permite
controlar el sentido de giro del motor.

Figura 4.1: representacin esquemtica del funcionamiento de un puente en


H
El sentido de giro del motor se controla activando y desactivando pares de
transistores diagonalmente opuestos. De esta forma, la corriente fluye a travs del
motor por dos caminos distintos: desde Q1 a Q4 o desde Q3 a Q2. Segn el
camino seleccionado, la corriente fluye a travs del motor en un sentido u otro, lo
que se traduce en un giro horario o antihorario del motor.

Es muy importante que nunca se activen simultneamente los transistores de la


misma rama de la H. Si eso ocurre la corriente fluira desde el terminal positivo
de la fuente de alimentacin de los motores al terminal negativo. Al no haber ms
resistencia que la que ofrecen los propios transistores, la cantidad de corriente que
fluira por el circuito sera mxima y estara limitada por la propia fuente de
alimentacin o por la autodestruccin de los transistores.

Los puentes-H se pueden realizar a partir de transistores individuales, o bien se


pueden adquirir integrados en un chip. La ltima opcin suele ser ms cara, pero
mucho ms cmoda y robusta. Los circuitos integrados que proporcionan puentesH incorporan protecciones que impiden que dos transistores de la misma rama de
la H se activen a la vez. Para ello, integran con los transistores una serie de
puertas AND e inversoras (NOT) siguiendo el esquema de la figura 4.2

49

MEMORIA

Hardware

Figura 4.2: esquema interno simplificado de un puente en H comercial


Con lo visto hasta ahora, el puente-H nos permite realizar las siguientes
operaciones: activar y desactivar el paso de corriente hacia el motor y cambiar el
sentido de giro. Cuando desactivamos el circuito, no fluye corriente a travs del
motor. Al no haber flujo de corriente el motor deja de funcionar y la plataforma se
detiene lentamente a medida que pierde velocidad.

Cuando una fuerza externa mueve el eje de un motor, este produce electricidad,
es decir, se comporta como un generador de corriente elctrica. Si se conecta una
carga a los terminales del motor, entonces presentara una resistencia al giro
proporcional al valor de la carga que tiene conectada. De este modo, a medida que
la carga aumenta el motor presenta una mayor resistencia a girar. Pero si se
conectan los dos terminales de motor entre s, se produce el mismo efecto que si el
motor estuviese conectado a una carga infinita. El resultado final es que el motor
se para porque no puede vencer esa resistencia.

Aprovechando el anterior efecto, se puede conseguir que la plataforma se


detenga inmediatamente bloqueando las ruedas. Para ello las dos seales de
direccin deben tener el mismo estado (ambas cero o ambas uno). Por ejemplo, si
se fuerza que ambas valgan uno (ver figura 4.3), se conseguir que los dos
terminales del motor estn conectados al terminal negativo de la fuente de
alimentacin del motor (generalmente, tierra) a travs de los transistores Q2 y Q4,
por lo que el motor tendr sus dos terminales a una tensin de 0,4 V, determinada

50

MEMORIA
Hardware
por la cada de tensin de los transistores. En este caso, los transistores actan
como un cable que une los dos terminales del mismo motor, producindose el
efecto comentado anteriormente de que el motor debe hacer frente a una carga
infinita. Como no puede, se para prcticamente en seco en el momento en que se
activa esta configuracin.

Figura 4.3: configuracin para frenado del motor utilizando el puente en H


La modulacin por ancho de pulsos (pulse-width modulation o PWM) es una
tcnica que se basa en la modificacin del ciclo de trabajo de una seal peridica
(por ejemplo sinusoidal o cuadrada). El ciclo de trabajo de una seal peridica es
el ancho relativo de su parte positiva en relacin al perodo.
Matemticamente:
DC =

[4.1]

Donde:
DC es el ciclo de trabajo (o duty cycle)
es el ancho de pulso (o pulse width), esto es, el tiempo en que la funcin es
positiva
T es el perodo de la funcin.

En un motor de continua, la magnitud de entrada que determina la cantidad de


par que va a aplicar es el valor medio de la tensin de la seal de entrada, esto es,

51

MEMORIA
Hardware
el valor de tensin continua que tiene la entrada (esta afirmacin slo es cierta si
se est en rgimen permanente).

El valor medio de una seal cualquiera x(t) se define como:


T

1
< x(t ) > = x(t ) dt
T0

[4.2]

Para seales con forma sencilla, como la onda cuadrada que se ha empleado en
el presente PWM, se puede calcular su valor medio como:

1
< x(t )cuadrada > = (DT (1 D )T )x(t ) = (2 D 1)x(t )
T

[4.3]

En funcin de su ancho de pulso, la seal tendr ms o menos valor medio, lo


que har que el motor aplique ms o menos par.

Se puede observar en la figura 4.4 el esquema del circuito diseado, el cual se


explicar a continuacin:

52

MEMORIA

Hardware

Puente en H
Optoacoplador

Salida PWM
43

Inversor
Puente de diodos de
libre circulacin
Figura 4.4: Esquema del circuito de la etapa de potencia

53

MEMORIA

Hardware

La seal de salida del microprocesador se hace pasar por la resistencia


R1, la cual ha sido calculada para que el transistor asociado al
optoacoplador est siempre en corte o en saturacin. El optoacoplador
utilizado ha sido el ILQ74. Se detallan a continuacin las caractersticas ms
relevantes de dicho circuito, as como la disposicin de sus pines:

Tabla 4.1: caractersticas elctricas del circuito ILQ74

54

MEMORIA

Hardware

Figura 4.5: disposicin de los pines del ILQ74

Se detallan a continuacin los clculos realizados para R1:

Se quiere que, cuando la seal de salida del microprocesador est en


nivel alto (3V de valor tpico), la corriente colector-emisor por el
fototransistor del optoacoplador sea de 25mA. Dicha corriente colectoremisor viene dada por la grfica de la figura 4.6, en funcin de la corriente
que atraviesa el LED del optoacoplador, y de la temperatura:

Como se puede observar en la figura 4.6, para obtener la corriente


colector-emisor deseada, es necesario que la corriente del LED sea de
40mA. Para esa corriente, se puede observar en la figura 4.7 que la cada de
tensin en el diodo ser de 1.2V.

55

MEMORIA

Hardware

Figura 4.6: Corriente colector-emisor frente a corriente por el LED y


temperatura en el optoacoplador

Figura 4.7: cada de tensin en el diodo en conduccin directa, en funcin de


la corriente que lo atraviesa
Por tanto, aplicando la ley de Ohm:

56

MEMORIA
R1 =

Hardware
3 V 1 .2 V
= 45 normalizad a
40 mA

R1 = 43

Ahora se recalcula la intensidad que circular por R1:


ID =

3 V 1 .2 V
= 41.86mA potencia de R1 PR1 = 41.86mA 1.8V = 75mW
43

Como ya se ha visto, la corriente colector-emisor del fototransistor del


optoacoplador es de 25mA cuando la seal de salida del microprocesador
tiene valor lgico alto, y 0 cuando tiene valor lgico bajo. La siguiente etapa
del circuito transforma esa seal en una similar, pero entre 0V y 5V, e
invertida respecto a la seal original del microprocesador. Para ello se
utiliza R2:

Cuando se tiene una corriente colector-emisor del fototransistor de


25mA, se ver ms adelante que Q1 est en corte, luego por R3 no pasar
corriente. Entonces, esos 25mA pasarn ntegros por R2, por lo que, para
obtener la seal de la que se habl con anterioridad:
R2 =

5V
= 200 para ese valor de R2, el fototransistor estar
25 mA

saturado, porque su tensin colector-emisor ser menor que su tensin


colector-emisor de saturacin, luego, en los instantes en los que la salida del
microprocesador est en estado lgico alto, tendremos en el colector de
fototransistor una tensin de 0.2V (que equivale a la tensin colector-emisor
de saturacin).

El fototransistor estar en corte cuando la salida del microprocesador est


en valor lgico bajo (0V), ya que, como se ha visto, entonces la corriente
por el diodo del optoacoplador ser nula. Cuando el fototransistor est en
este estado, impedir que circule corriente por su colector, lo que har que
toda la corriente proveniente de la fuente de 5V pase por R2 y R3. Habr
pues que calcular R3 de tal forma que en el colector del fototransistor se

57

MEMORIA
Hardware
alcance una tensin lo ms cercana posible a 5V en ese instante, de tal
forma, que entonces Q1 est saturado:

Se selecciona una tensin de colector mayor que 4.8V, para la cual se


disear:
4.8V 0.7V 5V 0.7V
=
R3 > 4.1k normalizad a R3 = 5.6k
R3
0 .2 + R 3

Se comprueba ahora la intensidad que circular por R2 y R3:


i=

5V 0.7V
= 0.741mA
0 .2 + R 3

Por tanto, la tensin en el colector del fototransistor ser:


VC = 0.7V + 0.741mA 5.6k = 4.85V

Por ltimo queda disear R4 para que ciertamente Q1 est en estado de


saturacin en las circunstancias anteriores:

Para que Q1 est saturado:


i B = 0.741mA >

iC

tomando 50 ic < 37.05mA

VCEsat + ic R 4 = 5V ic =

4.8V
= 4.8mA < 37.05mA R 4 = 1k
R4

Para estos valores de R1, R2, R3 y R4 se consigue obtener en el colector


del fototransistor y del transistor Q1 valores de tensin que pueden ser 0V
5V (en realidad oscilan alrededor de los 0,2V para valores lgicos bajos, y
los 4,85V para valores lgicos altos), de tal forma que cuando en el colector
del fototransistor se tienen 0V, en el del transistor Q1 se tienen 5V y
viceversa. Los cambios de valor lgico para estas seales, como ya se ha
mencionado, vienen dados por la seal PWM de salida del microprocesador.

58

MEMORIA

Hardware

Para obtener como salida del circuito una onda PWM entre -14V y 14V,
as como por motivos de suministro de corriente, como se ha comentado con
anterioridad, se ha utilizado un puente en H L298N, cuyo funcionamiento se
ha descrito con anterioridad, conectando su entrada Vs a 14V. Se especifican
a continuacin las caractersticas ms relevantes del L298N:

Figura 4.8: esquema del puente en H L298N

Tabla 4.2: funciones de cada uno de los pines del L298N

59

MEMORIA

Hardware

Tabla 4.3: caractersticas elctricas ms relevantes del L298N

Para el correcto funcionamiento del puente en H para la utilidad que se le


va a dar en el presente circuito, dicho componente requiere que se le
introduzca por su entrada In1 una seal entre 0V y 5V (valores tpicos), y
por su entrada In2 esa misma seal negada. Esto se consigue mediante el
transistor Q1 y las resistencias R2, R3 y R4. Se conectar la carga entre las
salidas Out1 y Out2, en serie con una resistencia de medida que servir para
indicar el sentido de la corriente. En la salida Sense A se conectar otra
resistencia de medida, que indicar el valor absoluto de la intensidad. Una
vez se tienen el sigo y el valor absoluto de la intensidad, se podr calcular el
valor real de la misma, tarea que ser desempeada va software por el
microprocesador, y que ser explicada con detalle en el captulo 5. Por
ltimo, indicar que tanto C1 como C2 cumplen una misin de filtro de las
posibles fluctuaciones de la tensin de alimentacin.

60

MEMORIA

Hardware

4.3. Reguladores de tensin


Se eligi utilizar dos reguladores de tensin conmutados para obtener los 3V
DC de alimentacin del microprocesador y los 5V DC del puente en H a partir de
los 14V DC de alimentacin del circuito.

Los reguladores conmutados tienen como principal ventaja sobre los


reguladores lineales su alto rendimiento (de entre el 70% y el 93% en los
reguladores conmutados frente al 30% - 60% en los reguladores lineales). Su
salida se mantiene estable an con grandes variaciones de tensin en la entrada,
estando la primera aislada de la segunda. Adems, se pueden lograr mltiples
tensiones de salida reguladas, de diferente polaridad. Por ltimo, mencionar que
los elementos pasivos de un regulador de tensin conmutado son ms pequeos,
que los utilizados en un regulador lineal, ya que el primero trabaja con frecuencias
de switching (conmutacin de los transistores) bastante ms altas.

A la hora de elegir el regulador conmutado adecuado para el diseo del


circuito, se encontraron dos tipos de reguladores, dependiendo de su nivel de
integracin, con una gran diferencia de precio entre ellos. El primero de ellos es
un regulador en el cual, el fabricante nicamente provee el circuito de control de
tensin, teniendo que ser incorporados a posteriori componentes discretos como
diodos, condensadores, bobina y resistencias. La principal ventaja de este tipo es
su reducido precio, lo que los hace ideales si se quieren utilizar en circuitos de los
que se va a fabricar gran cantidad de ellos. El segundo tipo de regulador que se
encontr consiste en un slo componente de tres pines (entrada, tierra y salida) en
el cual vienen integrados todos los elementos necesarios para realizar la
regulacin de tensin, desde el circuito de control, hasta los componentes pasivos
como condensadores, bobina, resistencias y diodos. Esto hace que sea mucho ms
fcil de manejar e implantar en un circuito, a pesar de su elevado precio. Como en
el presente proyecto se pretende disear y construir un prototipo, y no realizar una
fabricacin en serie del circuito, se opt por los reguladores conmutados
integrados 78SR-3.3/2-C (para tensin de 3V) y 78SR-5/2-C (para tensin de 5V).

61

MEMORIA

Hardware

Se pueden consultar sus caractersticas en su hoja de caractersticas, incluida en


el anexo 4.

Figura 4.9: 78SR. Se pueden observar los elementos discretos integrados


No obstante, si se desease realizar una fabricacin en serie del equipo, se
propone el siguiente circuito para el regulador de tensin, a partir del componente
integrado LM2736Y, el cual tiene un precio del orden de 10 veces menor que los
78SR:

Figura 4.10: circuito de regulacin de tensin de 14V a 3V

62

MEMORIA

Hardware

Figura 4.11: circuito de regulacin de tensin de 14V a 5V

4.4. Circuito de acondicionamiento de medida de la


intensidad que atraviesa el motor
El circuito de acondicionamiento de medida de la intensidad que atraviesa el
motor tiene la misin de adecuar la seal a medir (en este caso la intensidad que
recorre el motor) para que pueda ser medida con la mayor precisin y sensibilidad
posibles por el microprocesador, mediante su conversor analgico/digital.

Para realizar una medida fiable, el circuito de acondicionamiento no debe


perturbar la seal que se va a medir. Como esta es una intensidad, se necesitar
que el circuito tenga una gran impedancia de entrada. Esto se consigue mediante
amplificadores operacionales.

En la figura 4.12 se puede observar el circuito completo de acondicionamiento


de medida, el cual, se explicar a continuacin
63

MEMORIA

Hardware
Estimador del
mdulo de corriente

Estimador del signo


de la corriente
Puente de diodos
de libre circulacin

Diodo de proteccin
del micro

Estimador analgico
de la velocidad

Diodo de proteccin
del micro
Figura 4.12: circuito de acondicionamiento de medida de la intensidad que atraviesa el motor

64

MEMORIA

Hardware

La medida de la intensidad que recorre la carga (esto es, el motor) se realiza en


dos fases: hay un circuito encargado de medir la magnitud de la seal (a travs el
amplificador operacional U5), y otro encargado de medir el signo (a travs del
amplificador operacional (U4). Ser el microprocesador el encargado de unir estos
dos datos, y obtener la medida de la intensidad con signo.

La realimentacin del amplificador operacional U5 ha sido calculada de modo


que para una intensidad de 0.4A por la carga (que coincide con la intensidad
mxima estimada), la salida del mismo sean 3.3V, que es la mxima tensin
admitida por el conversor analgico-digital del microprocesador, al haber
establecido la tensin de comparacin a 3.3V. En J9 estar situada la resistencia
Rs, que ser la resistencia de medida del mdulo de la corriente. Se detalla a
continuacin los clculos realizados para Rs=1:
R7 = 2 k
R8 3.3V
R8
vo MAX = Rs iMAX 1 +
=

1+
R7 0.4 A R8 = 13 k
R7

Donde:

vo MAX = tensin mxima de entrada del microprocesador

iMAX = corriente mxima que atraviesa el motor

Los amplificadores operacionales U6 y U7 se emplean para emular la misma


funcin de transferencia de la planta. De esta forma, la seal resultante que le
llega al microprocesador despus de pasar por ellos es la velocidad a la que va el
tren en cada instante. Los clculos realizados fueron los siguientes (para una
resistencia Rs de 1):

v o = Rs i

Km i
1
R11
0 .6
R11 )

1 +
1 +
= Rs i
; v =
R9 C 3 s + 1 R10
0.6R9 C 3 s + 0.6 R10
M s + D

65

MEMORIA

Hardware

R11 = 6.8 k
R11 vo MAX
3
R11

K m =
5.8347
25
= )
0.6Rs 1 +
1 .2
R10
R10 v MAX
R10 = 270

C = 10 F
0.6 R9 C 3 = M = 0.7
R9 = 150 k

0.6 D = 0.67

Donde:

vo = tensin de entrada del microprocesador


)
v = velocidad

i = corriente que atraviesa el motor

M, D, Km : ver secciones 3.2 y 3.3

El amplificador operacional U4 siempre estar saturado: alrededor de 5V


cuando la corriente que atraviesa el motor va en sentido OUT1OUT2 (salidas
del puente en H) y a 0V cuando lo haga en sentido inverso. Dicha salida se leer
como una entrada digital al microprocesador, la cual estar en estado lgico alto
cuando la seal est alrededor de 5V, y en estado lgico bajo cuando la seal est
en 0V. A partir de esta entrada, se multiplicar, o no, el valor del mdulo de la
corriente, medido mediante U5, por -1, estableciendo as el signo a la misma.

Tanto U5, como U6 y U7 estn alimentados a 5V. Esto es as para que si


saturan, los operacionales no pierdan rango dinmico de tensin. Tericamente,
sus respectivas realimentaciones estn calculadas para que con un valor mximo
en sus entradas, obtengan una salida de 3.3V, pero ante eventuales picos en los
valores de esas entradas, su tensin de salida sera mayor. Para evitar que esto
dae al microprocesador, se han utilizado diodos zener como proteccin. Los
diodos zener que aparecen en el circuito tienen una tensin inversa de 3.3V, por lo
que impiden que en las entradas del microprocesador se alcancen valores de
tensin por encima de esos 3.3V, la cual es la tensin mxima admitida por el

66

MEMORIA
Hardware
mismo. De este modo, el microprocesador queda protegido ante eventuales picos
de tensin en sus entradas.

4.5. Circuito de acondicionamiento de la seal del


acelermetro
El acelermetro ir situado en la parte superior del tren, tal y como muestra la
figura 4.13A. De esa forma, se podr calcular la aceleracin normal en cada
instante, la cual ser proporcional a la velocidad instantnea del tren y al radio de
la curva por la que circule, segn la frmula:

Donde v es la velocidad instantnea, y es el radio de curvatura.

Sensor N: Normal

Sensor T:
Tangencial
Direccin del movimiento
Figura 4.13A: situacin del acelermetro sobre la maqueta del tren
El circuito de acondicionamiento de la seal del acelermetro tiene por objeto
adecuar la seal que proporciona dicho componente, para poder ser medida con la
mayor precisin y sensibilidad posibles por el microprocesador, utilizando su
conversor analgico/digital.

El acelermetro que se ha utilizado es el ADXL320, un acelermetro de dos


ejes, cuyas caractersticas se detallan en la tabla 4.4:

67

MEMORIA

Hardware

Tabla 4.4: Caractersticas del acelermetro ADXL320

La configuracin de los pines del encapsulado se detalla en la figura 4.13B.

Figura 4.13B: configuracin de los pines del ADXL320


El primer paso para disear el circuito de acondicionamiento del acelermetro
es estimar la aceleracin mxima que se va a medir. Al investigar sobre las
diferentes aceleraciones a las que se ven sometidos distintos medios de transporte,
se descubrieron los siguientes datos:

68

MEMORIA

Hardware

Aceleracin de un monoplaza de F1 al girar: entorno a 4G.

Aceleracin de un monoplaza de F1 al frenar: entorno a 5G.

Aceleracin mxima en la montaa rusa Dragon Khan: 3.75G.

Aceleracin mxima del caza F-16 Falcon: 9G.

Aceleracin mxima del caza F-18 Hornet: 7.5G.

En base a estos datos, resulta lgico no esperar medir aceleraciones superiores


a los 4G. Por tanto, se seleccionar esa aceleracin como cota superior de las
aceleraciones a medir, y se har coincidir la mxima salida del circuito (5V) con
esa aceleracin de 4G.

Se puede observar el circuito detallado en la figura 4.14.

69

MEMORIA

Hardware

Etapa de ganancia
Filtro paso alto

Salida ADXL320

Rectificador de precisin

Figura 4.14: circuito de acondicionamiento de la seal del acelermetro

70

MEMORIA

Hardware

La primera etapa es un filtro paso alto a 0.5 Hz para eliminar la continua. Los
clculos para el mismo han sido los siguientes:
R1 = 100k fijada
C1 =

1
= 3.18uF
2 R f c

Al normalizar C1 = 3.3uF , por consiguiente :


f c = 0.48 Hz

La siguiente etapa, es la etapa de ganancia. En ella se elevar la ganancia del


circuito para conseguir la mxima sensibilidad posible en la medida. Segn la
hoja de caractersticas del acelermetro, la sensibilidad tpica cuando ste est
alimentado a 3.3V es de 174mV/G. Como se ha tomado como lmite de
aceleracin 4G, el sensor dar como mximo una salida de 174mV/G4G =
696mV. Como el valor mximo de entrada establecido para el conversor A/D es
de 3.3V, habr que amplificar esos 696mV hasta 3.3V, por lo que habr que
multiplicarlos por un factor de 4.74. Entonces:

R 7 = 5 .6 k
R7 + R8
= 4.74
R8
R8 = 1.5k

La ltima etapa se trata de un rectificador de precisin. Hasta esta etapa, el


circuito mide y amplifica la seal del acelermetro con signo, sin embargo, slo
es necesario medir el mdulo de la aceleracin, ya que el signo de la aceleracin
slo servira para indicar en qu direccin se est tomando la curva en cuestin.
Adems, el microprocesador no admite niveles de tensin negativos en sus
entradas. Por tanto, en esta etapa, se rectificarn las seales negativas, y se
transformarn en positivas. La caracterstica del rectificador de precisin est
ilustrada en la figura 4.15:

71

MEMORIA

Hardware
Vout
1

Vin
-1

Figura 4.15: caracterstica del rectificador de precisin


Las resistencias estn escogidas de modo que limitan la corriente para no daar
los diodos. Como la tensin mxima que va a entrar al rectificador son 3.3V, y la
intensidad mxima que puede circular por los diodos es 25mA, si dividimos estas
dos cifras, obtenemos una resistencia mnima de 120 . Para proteger mejor el
circuito, se han seleccionado resistencias de 1k.

4.6. Diseo de las balizas


Las balizas, como ya se ha comentado anteriormente, se colocarn al principio
de cada curva, y sern las encargadas de mandar una seal al microprocesador
cuando el tren las cruce, para que ste pueda aminorar la velocidad del tren y que
no descarrile al entrar en la curva, antes de que les d tiempo a actuar a los
acelermetros. Estarn constituidas por un diodo LED 4300H1LC rojo, y un
fotodiodo selectivo EPIGAP-EPD-740-5/0.5, que es sensible a la longitud de onda
de 740nm (luz roja), y que tiene las siguientes caractersticas:

Typ Wavelength:740nm

Sensibilidad:0.5

Half Angle:20

Dark Current:0.2nA

Max Voltage Vr:10V

rea activa:0.13mm

Max Spectral Range:780nm

Min Spectral Range:700nm

72

MEMORIA

Hardware

Negador

Inversor
Resistencia
de entrada
al sumador
Diodo LED

Acondicionamiento del
fotodiodo
Figura 4.16: Circuito de una baliza

73

MEMORIA
Hardware
Se quiere conseguir que cuando el tren cruce el haz de luz que emite el LED
hacia el fotodiodo, se enve una seal de 3.3V al microprocesador, y que en caso
contrario, la seal permanezca por debajo de los 1.15V, que es el umbral para que
una seal se considere a nivel bajo. Para ello se ha diseado el circuito de la figura
4.16, que se explica a continuacin.

En primer lugar se ha diseado el circuito que alimenta al diodo LED para que
est siempre encendido. Segn la hora de caractersticas del mismo, la corriente
que atraviesa el diodo cuando est polarizado directamente es de 7mA, y la cada
de tensin es de 1.8V. Segn esto, y sabiendo que la tensin de alimentacin es de
5V, se puede calcular R14:

R14 =

5V 1.8V
= 0.46k R14 = 0.47k
7 mA

Seguidamente se ha diseado el circuito de acondicionamiento del fotodiodo.


Se sabe que la intensidad que recorre la rama donde est colocado el fotodiodo, en
sentido ctodo-nodo, es I0+kPL. I0 es la denominada dark current, o corriente
oscura, que atraviesa el diodo cuando est polarizado de forma inversa, y su
valor depende de las caractersticas constructivas del fotodiodo en cuestin. El
factor k PL es un factor proporcional a la cantidad de luz, en la longitud de onda a
la que es sensible el fotodiodo, que incide en ste. Para medir dicha cantidad de
luz de la forma ms precisa posible, primero se requiere eliminar los efectos de la
corriente oscura. Para ello se coloca otro fotodiodo de las mismas caractersticas
constructivas que el primero, al que llamaremos dummy diode, sobre el cual
incidir una cantidad nula de luz en la longitud de onda a la que es sensible el
diodo. Como los fotodiodos seleccionados son sensibles a la luz roja, basta con
tapar el dummy diode con una cpsula opaca para conseguir ese objetico. Con
ello se consigue una corriente oscura del mismo valor que la que recorre la rama
del fotodiodo 1, pero de signo contrario, lo cual har que se anulen al sumarse en
el nudo donde confluyen las dos ramas. Eso quiere decir, que la resistencia R1 ya
no ser atravesada por la intensidad I0+kPL , sino por una intensidad igual a kPL.

74

MEMORIA
Hardware
De forma emprica se determin que, para que cuando el haz de luz estuviese
interrumpido por el tren se obtuviese una salida aproximada de -0.5V, y cuando
no estuviese interrumpido se obtuviese una salida aproximada de -2V, la
resistencia R1 deba ser de 0.33k.

Como, debido a la topografa del circuito de acondicionamiento del fotodiodo,


slo se pueden obtener a su salida tensiones negativas, es necesario aadir a
continuacin una etapa inversora. Para ello se utiliz un amplificador inversor de
ganancia -1.

La siguiente etapa del circuito es un negador. ste es necesario porque tras la


etapa inversora, las tensiones que se tienen a la salida del circuito son de 0.5V si
el haz de luz se ve interrumpido, y 2V cuando el haz de luz no se ve interrumpido.
Todas las salidas de los circuitos de acondicionamiento de las balizas van a entrar
a un sumado, que sumar todas esas salidas, para llevar la suma de esas seales
(previamente tratada) al micro. Este sistema funciona porque slo habr una o
ninguna baliza con su haz de luz cortado al mismo tiempo, lo cual significa que
cuando la salida del sumador valga 0 (o un valor por debajo de los 1.15V),
significar que no hay ninguna baliza cuyo haz de luz est siendo cortado, y
cuando valga 3.3V, significar que hay una baliza cuyo haz de luz est siendo
interrumpido. Para que este sistema funcione como se ha descrito anteriormente,
se necesita que cuando el haz de luz se corte, la seal que entre al sumador valga
3.3V (o el equivalente al estado lgico alto), y que valga 0V cuando el haz de luz
no sea interrumpido. Para lograr este objetivo, se ha introducido el transistor Q1.
Como se mencion anteriormente, cuando el haz de luz no est interrumpido, la
seal a la salida del inversor vale 2V y cuando se interrumpe, vale 0.5V. Se desea
pues que el transistor est saturado para una tensin en su base de 2V, y en corte
para una tensin de 0.5V. Se realizan pues los siguientes clculos:

Saturacin :
VC = 5

R 4 = 4 .7 k
2 0 .7
1 .3
R4
R 4 0 .2 R 4 4 .8
0.037
R3
R3
R3
R3 = 100k

75

MEMORIA
Hardware
Al ser 0.5 menor que 0.7, el corte se produce automticamente cuando el haz
de luz que incide en el fotodiodo se corta. Para que la cada de tensin en R4 sea
la menor posible cuando se produce el corte, R11 tendr que ser grande en
comparacin con sta, por ello se ha elegido un valor de 100k para ella, lo que
produce una cada en R4 cuando Q1 est en corte de 0.22V, obteniendo los
siguientes valores en el colector de Q1:

4.78V cuando el haz de luz que incide en el fotodiodo se corta

0.2V cuando el haz de luz que incide en el fotodiodo no se corta

El tener esos 0.2V, en vez de los 0V que en principio se desearan, acarrea


consecuencias negativas, y es que como se sumaran las diferentes tensiones de
distintos fotodiodos, se podran tener como mximo 5 fotodiodos repartidos por el
recorrido del tren para que la suma de las tensiones cuando el haz de luz que llega
a los fotodiodos no se ve interrumpido no supere los 1.15V que fijan el lmite
superior de la seal lgica en estado bajo para el microprocesador. Para optimizar
el nmero de fotodiodos que se pueden instalar, se puede ajustar la ganancia del
sumador. Como el nivel alto de la seal que entra al sumador es de 4.78V, y slo
se requieren 3.3V, podemos establecer la ganancia del sumador en 0.7, y poder
conseguir instalar as 8 balizas acopladas a un solo sumador. En el caso de que se
necesitase un mayor nmero de balizas, podra llevarse la seal de salida de los
diferentes negadores a una puerta OR con tantas entradas como balizas sean
necesarias.

El circuito del sumador queda ilustrado en la figura 4.17. Se aprecia como


despus del sumador, hay una etapa inversora de ganancia -1. Esto es as porque
la ganancia del sumador tiene fase 180. Adems, se ha colocado un diodo zener
de 3.3V para proteger al microprocesador frente a tensiones mayores de 3.3V.

76

MEMORIA

Hardware

Proteccin

Sumador

Inversor

Figura 4.17: sumador, inversor y proteccin del microprocesador

4.7. Conclusiones
Se ha expuesto en el presente captulo todo lo relacionado con el hardware del
sistema: desde la etapa de potencia, que servir de nexo entre el control y el
actuador, hasta los reguladores de tensin que han sido utilizados, pasando por los
diferentes circuitos de acondicionamiento de seal.

En una primera seccin se ha hablado de todo el diseo de la etapa de potencia,


exponiendo los clculos, as como informacin detallada de todos los elementos
que la componen: optoacoplador, inversor y puente en H.

En la segunda seccin se han presentado los distintos tipos de reguladores


existentes, y se argumenta la eleccin de uno de ellos sobre el resto. Adems, se
han propuesto diseos alternativos de los reguladores para que, en caso de una
fabricacin en serie del prototipo que se propone en el presente proyecto, los
gastos en componentes disminuyesen drsticamente en esta parte del circuito.

77

MEMORIA
Hardware
En las siguientes tres secciones se han abordado los distintos circuitos de
acondicionamiento de seal: la medida de la corriente que atraviesa el motor, el
acondicionamiento de la seal del acelermetro, y el diseo de las balizas. Como
ya se ha expuesto, estos circuitos cumplen la funcin de acondicionar las seales
que se desean medir para realimentar el control de manera que dicha medicin se
efecte con la mayor precisin y sensibilidad posibles, y sin perturbar a la seal
original. Para ello se han utilizado bsicamente etapas basadas en amplificadores
operacionales, tanto en realimentacin negativa como en bucle abierto, diodos
zener para la proteccin del microprocesador, y los propios elementos cuya seal
se haba de acondicionar.

78

MEMORIA

Sistema de Control

Captulo 5: Sistema de control

5.1. Introduccin
Se utiliza como sistema de control un regulador con accin proporcionaldiferencial (PI) discreto, que va programado en un microprocesador
MC9S08QG4/8. Para realizar el ajuste de los distintos parmetros del control se
han utilizado diferentes herramientas informticas (Matlab y Simulink) para
simular la respuesta del sistema ante distintas entradas o hallar su respuesta en
frecuencia.

En el presente captulo se tratarn, por este orden, los fundamentos tericos


subyacentes de la teora de control discreta, el diseo de distintos controles y la
eleccin del ms conveniente al sistema a controlar, la implementacin de filtros
para intentar mejorar la respuesta de los controles antes mencionados, el escalado
del problema a 8bits, el cual es el tamao de los registros del microprocesador, se
introducirn brevemente algunas de las caractersticas del mismo, y se expondr el
desarrollo del programa que posteriormente ser implementado en el
microprocesador.

5.2. Sistemas de control digital


Ya se vio en el captulo tercero el esquema general de un sistema de control
analgico o continuo. En l, las seales vienen representadas en forma de
funciones continuas, como la que se muestra en la figura 5.1(a). En un sistema
digital o discreto, las seales, o al menos algunas de ellas, se representan como
secuencias discretas (ver figura 5.1(b)). Esas secuencias discretas son una serie
de nmeros que provienen de tomar los valores instantneos de seales analgicas
en instantes de tiempo concretos. Es lo que se denomina muestreo. Esos instantes
suelen estar equiespaciados por un tiempo T que se denomina periodo de
muestreo. A cada uno de los valores se les denomina muestras y se identifican por

79

MEMORIA
Sistema de Control
su nmero de muestra k. En la figura 5.1(b) se observa una secuencia yk = {y0, y1,
y2, . . .}, que proviene de una seal analgica y(t) (figura 5.1(a)), con la relacin
entre muestra k e instante de tiempo kT. La eleccin del periodo de muestreo es
muy importante puesto que un valor demasiado grande hace que se pierda
informacin cuando se muestrean seales rpidas (figuras 5.1(c) y 5.1(d)), que en
el caso de tratarse de un problema de control provendrn de sistemas rpidos. Es
lo que se conoce como efecto aliasing.

Figura 5.1: discretizacin de una seal continua y efecto aliasing


Por tanto, el esquema genrico de un sistema de control digital es el mostrado
en la figura 5.2:

80

MEMORIA

Sistema de Control
Perturbacin
-

Ref.

CONTROL

POT

SISTEMA A Salida
CONTROLAR

Retenedor
(Hold)
T
Muestreador
(Sampler)

SENSOR

Sistema Digital

Figura 5.2: esquema genrico de un sistema de control digital


Al igual que en los sistemas continuos se puede obtener la funcin de
transferencia a partir de la ecuacin diferencial por medio de la Transformada de
Laplace teniendo en cuenta que:

[5.1]

Para obtener:

[5.2]

En los sistemas discretos se puede obtener su funcin de transferencia a partir


de la ecuacin en diferencias y por medio de la Transformada en Z, sin ms que
tener en cuenta:
[5.3]

Con lo que se obtiene la funcin de transferencia discreta:

81

MEMORIA

Sistema de Control

[5.4]

A la hora de realizar el diseo de los reguladores digitales, existen dos


enfoques:

- Disear directamente en z: trabajar con sistemas discretos y


metodologas aplicables a los mismos.

- Disear en s y pasar a z: se pueden aplicar todos los conocimientos


de sistemas continuos para obtener un regulador continuo y luego
convertir ese regulador continuo en uno discreto (discretizar).

En el presente texto, se han aplicado los conocimientos de sistemas continuos


para discretizar posteriormente. Se comentan a continuacin algunas tcnicas de
discretizacin:

Para obtener la versin discreta de un sistema continuo se dispone, a grandes


rasgos, de dos posibilidades:
- Mtodo exacto: tener en cuenta la relacin z = e sT

- Mtodos aproximados: tcnicas de simplificacin para hacer ms


sencilla la discretizacin. Se explicar a continuacin uno de los
mtodos utilizados en el presente texto a la hora de discretizar: el
mtodo de la derivada:

El mtodo de la derivada, consiste en aproximar la derivada por la pendiente de


la recta que pasa por dos muestras consecutivas, con lo cual se obtiene:

82

MEMORIA

Sistema de Control

[5.5]

Que visto en sus correspondientes transformadas se convierte en:

[5.6]

Por lo tanto para obtener el regulador discreto a partir del continuo basta
sustituir en la funcin de transferencia las s

por

z[ 5.7]

5.3. Control proporcional-integral discreto


El tipo de control seleccionado para regular el sistema ha sido el control
proporcional-integral discreto. Se detallan a continuacin algunas de las
caractersticas de dicho control en continuo, que pueden hacerse extensibles a su
versin discreta:
La funcin de transferencia del control es la siguiente:

1 K (1 + Ti s )
=
C ( s ) = K 1 +
T

s
Ti s
i

[5.8]

Se puede observar el diagrama de Bode del control en la figura 5.3, el cual


servir para obtener distintas conclusiones:

83

MEMORIA

Sistema de Control

20log(K)

1/Ti

Figura 5.3: diagrama de Bode del control proporcional-integral


El control proporcional-integral (de ahora en adelante, PI) tiene una desventaja
importante frente al control proporcional o al proporcional-diferencial, y es que,
como se puede observar en su diagrama de Bode, su fase nunca es positiva. Esto
se traduce en que la fase del sistema siempre va a sufrir un retraso por el hecho de
incorporar la accin integral al control, retraso que se tratar de aminorar en la
medida de lo posible (se manejarn valores entre los 5 y los 15)

El control PI se puede implementar en tiempo discreto mediante distintas


aproximaciones. En este texto se considerar la regla trapezoidal para realizar
t

dicha aproximacin. Si se tiene una funcin y (t ) = u ( )d y la seal u ( ) es


0

84

MEMORIA
Sistema de Control
una seal discreta, se puede demostrar que el valor de la funcin y en un instante
u[k 1] integral inferior de Riemann
1

k es: y[k ] = y[k 1] + t s (u[k ] + u[k 1]) regla trapezoidal


2
u[k ] integral superior de Riemann

[5.9]

Por consiguiente, utilizando la regla trapezoidal como mtodo de aproximacin


de la integral, el diagrama de bloques del control PI incremental (calcula
incrementos sobre el mando anterior, y no mandos absolutos) en tiempo discreto
ser el mostrado en la figura 5.4:

Figura 5.4: diagrama de bloques del control PI en tiempo discreto


(el bloque b representa una posible ponderacin de la referencia, no utilizada
en este texto)

85

MEMORIA

Sistema de Control

5.4. Diseo del control


Como se pudo apreciar con anterioridad en la figura 3.2, el control del sistema
se compone de dos bloques de control PI en cascada. El primero de ellos se
encarga de comparar el valor de consigna de velocidad con la velocidad del tren
(la cual se estimar convenientemente a partir de la corriente que circula por el
motor) y, en funcin de dicha comparacin, obtener una variable de error, a partir
de la cual generar un mando de corriente, dentro de unos lmites de saturacin que
no podr superar, y que corresponden a los valores de corriente por encima, en el
caso del lmite superior o por debajo, en el caso de lmite inferior, de los cuales el
motor podra sufrir daos. El segundo bloque PI compara el mando de corriente
que le viene dado por el bloque anterior, y la corriente que circula por el motor.
Despus de aplicar su accin proporcional-diferencial generar un valor de ciclo
de trabajo (duty cycle) con el que el microprocesador generar su onda PWM, la
cual ser tratada en distintas etapas por el circuito de potencia, ya explicado en el
captulo cuarto.

Las principales ventajas que se derivan de la implantacin de dos bloques de


control en cascada son las siguientes:

- Proteccin del motor frente a sobreintensidades que pudieran daarlo: al


generar el primer bloque de control un mando de corriente con lmites de
saturacin, el segundo bloque se encargar de generar el mando de
tensin adecuado (el cual tambin se encuentra entre dos lmites de
saturacin) para que la corriente del motor se encuentre entre esos
lmites.

- Mayor precisin en el control de la intensidad aplicada al motor: al controlar


la intensidad que recorre el motor con un control PI, se asegura un error
nulo en el seguimiento de la referencia.

86

MEMORIA

Sistema de Control

Figura 3.2: Primera aproximacin del diagrama funcional de bloques del sistema completo

87

MEMORIA

Sistema de Control

Los parmetros del control han sido diseados varias veces, atendiendo a
distintos criterios, y utilizando distintas tcnicas de diseo. Una vez obtenidos
todos los resultados, se ha elegido aqul que mejor satisface las necesidades del
sistema.

Todos los diseos se han realizado en base a una aproximacin lineal del
sistema equivalente continuo, obtenida a partir de la herramienta Linear
Analisys, contenida dentro de la toolbox de control de Matlab y Simulink. En
cuanto a las distintas simulaciones del sistema, realizadas para comprobar la
eficacia del regulador diseado, en una primera aproximacin, se supuso el
sistema como continuo, a excepcin de los bloques de control, sin tener en cuenta
el efecto de la onda PWM sobre el resto del sistema (se supuso que la frecuencia
de dicha seal era lo suficientemente alta como para que los valores medios del
resto de las seales del sistema slo se viesen afectados en un ligero rizado
alrededor de dicho valor medio). Ms adelante, y ante respuestas del sistema
inesperadas, debidas al desprecio de efectos fsicos no modelados, se fueron
aadiendo al modelo del sistema elementos que simulaban dichos efectos fsicos,
tales como retrasos en la actualizacin de los valores, distintos tiempos de
muestreo para los distintos bloques de control, efectos de la seal de PWM, etc.
Todo ello se explica con detenimiento a continuacin.

5.4.1. Diseo mediante ajuste por simulacin


El primer control diseado se realiz bajo la hiptesis de que los efectos de la
no continuidad de las seales del sistema, excepto en lo referente al control, eran
despreciables. No se tuvieron en cuenta pues retrasos de actualizacin de las
salidas o los efectos del PWM sobre la corriente del motor (se tom el mando del
control no como un valor de ciclo de trabajo aplicado al PWM para obtener una

88

MEMORIA
Sistema de Control
1
tensin, sino como dicha tensin directamente ). Adems, se trabaj con el mismo
tiempo de muestreo para los dos bloques de control, resultando ste demasiado
rpido para lo que el microprocesador puede ofrecer. El diagrama de bloques del
sistema completo se puede observar en la figura 3.2.

El diseo se realiz en dos partes: en primer lugar se ajust el lazo de control


de corriente, ya que es considerablemente ms rpido que el lazo de control del
sistema completo, para ms tarde ajustar este ltimo.

Al incluir el control y aplicar las propiedades del lgebra de bloques para cerrar
el lazo de corriente, se obtiene una funcin de transferencia de segundo orden
entre su entrada y su salida. Se pueden modelar pues sus parmetros de forma
analtica, de modo que adquieran los valores que se desee.

Figura 5.5: diagrama de bloques del lazo de control de corriente


Funcin de transferencia una vez cerrado el lazo:

G( s ) =

(1 + Ti s )
K (1 + Ti s )
=
Ti s (R + Ls ) + K(1 + Ti s ) Ti L s 2 (R + K )Ti s + 1
K
K

[5.10]

1
, se puede apreciar que tiene el
M s + D
aspecto de un filtro paso bajo, de frecuencia de corte: f c D = 0.152 Hz , por tanto, es de
2 M
esperar que filtre las fluctuaciones de velocidad que pudieran surgir debido a las conmutaciones de
la onda PWM.
1

Si se observa la funcin de transferencia de la planta:

89

MEMORIA
Sistema de Control
Se observa que G(s) es un sistema de segundo orden con un cero adicional. Por
tanto, su respuesta ser la suma de la respuesta del sistema de segundo orden ms
la derivada de dicha respuesta. En lo que concierne al diseo, slo se tendr en
cuenta la respuesta del sistema de segundo orden:

K
n =
Ti L

1
R + K Ti

G ( s) =
=
Ti L 2 (R + K )Ti
2
K L
s
s + 1
G (0) = 1
K
K

[5.11]

Se dise entonces para tener un amortiguamiento de 0.7 (con lo que se


consigue que el sistema no sea resonante) y una pulsacin natural lo mayor
posible. Para dichos valores, se obtuvo la siguiente expresin que relaciona Ti con
K:

Ti =

0.00392
625
+ 50 + K
K

[5.12]

Se puede observar en la siguiente grfica la relacin entre Ti y K:

Figura 5.6: relacin entre Ti y K para un amortiguamiento de 0.7

90

MEMORIA
Sistema de Control
Teniendo en cuenta la relacin anterior, se ensay la respuesta del lazo de
corriente linealizado frente a un escaln de 0 a 0.2A con distintos valores de K y
Ti:
-Ensayo 1: K = 9.5;

Ti = 3.1288e-005; wn = 1.2321e+004

-Ensayo 2: K = 49.5; Ti = 3.4961e-005; wn = 2.6607e+004


-Ensayo 3: K = 99.5; Ti = 2.5163e-005; wn = 4.4464e+004
-Ensayo 4: K = 149.5; Ti = 1.9246e-005; wn = 6.2321e+004
-Ensayo 5: K = 249.5; Ti = 1.2980e-005; wn = 9.8036e+004

Figura 5.7: respuesta ante un escaln de la salida del lazo de corriente


linealizado con distintos valores de K y Ti

91

MEMORIA

Sistema de Control

Figura 5.8: respuesta ante un escaln del mando de corriente


con distintos valores de K y Ti
Los valores de K y Ti elegidos despus de comparar las distintas respuestas
fueron los del ensayo 3. Una vez fijados esos valores, se procedi a disear el
regulador del lazo de control del sistema completo.

El diseo del lazo de control del sistema completo se realiz a partir de


distintos ensayos de la respuesta ante un escaln del sistema linealizado,
utilizando un mtodo de aproximacin para ajustar los parmetros del control.
Una vez fueron obtenidas respuestas ms o menos aceptables, se realiz un ajuste
ms fino con parmetros cercanos a aquellos que haban dado esas respuestas.

A continuacin se muestran distintas grficas de los resultados obtenidos en el


diseo:

Ajuste de la parte proporcional del control:

92

MEMORIA

Sistema de Control
- Ensayo 1: Ti = inf; K = 5
- Ensayo 2: Ti = inf; K = 10
- Ensayo 3: Ti = inf; K = 15
- Ensayo 4: Ti = inf; K = 25
- Ensayo 5: Ti = inf; K = 50

Figura 5.9: ajuste de la parte proporcional del control


Como el lazo de corriente es muy rpido, a los ojos del regulador del lazo de
control del sistema completo es como si slo tuviese que actuar sobre la planta, la
cual, es un sistema de primer orden. Al aplicarle nicamente la accin
proporcional a un sistema de primer orden, la salida mejorar a medida que
aumenta K, por muy alta que esta sea. Ahora bien, como el sistema fsico
realmente no es un sistema de primer orden, ya que hay efectos fsicos que
siempre se van a despreciar a la hora de hacer un modelo (de lo contrario, modelar
un sistema resultara imposible), una K demasiado alta hara al sistema oscilante,
aunque no se reflejase as en la simulacin. Para prevenir esto, se ha elegido el
valor de K del ensayo 4.

Ajuste de la parte integral del control:

93

MEMORIA

Sistema de Control
- Ensayo 1:

K = 25; Ti = 100

- Ensayo 2:

K = 25; Ti = 1

- Ensayo 3:

K = 25; Ti = 0.1

- Ensayo 4:

K = 25; Ti = 0.01

- Ensayo 5:

K = 25; Ti = 0.001

Figura 5.10: ajuste de la parte integral del control


Se seleccion el valor de Ti del ensayo 4, por ser el que mayor rapidez
presenta.

Posteriormente, se corrobor el ajuste anterior mediante simulacin del


sistema, esta vez sin linealizarlo previamente. Para ello se introdujeron dos
escalones al sistema, el primero de amplitud 0.5m/s, para dejar al sistema estable
en rgimen permanente, y una vez estabilizado, otro de amplitud 0.1m/s, para
comprobar la respuesta del sistema ante pequeas variaciones. La figura 5.11 se
utiliz para fijar el valor de K, dejando fijo el valor de Ti, que fue seleccionado
anteriormente. Una vez fijado el valor de K, se utiliz la figura 5.12 para fijar el

94

MEMORIA
Sistema de Control
valor de Ti. Las figuras 5.13 y 5.14 son distintas respuestas del mando de corriente
y del mando de tensin en funcin de los distintos valores de Ti. Los valores de
los parmetros utilizados en cada ensayo se detallan a continuacin de las
grficas. En la figura 5.10 se observa el diagrama de bloques del sistema
simulado:

95

MEMORIA

Sistema de Control

Figura 5.11: diagrama de bloques del sistema simulado

96

MEMORIA

Sistema de Control

Figura 5.12: simulacin del sistema con distintos valores de K

Figura 5.13: simulacin del sistema con distintos valores de Ti

97

MEMORIA

Sistema de Control

Figura 5.14: respuesta del mando de corriente

Figura 5.15: respuesta del mando de tensin

98

MEMORIA

Sistema de Control
Valores utilizados en la figura 5.12:

- Ensayo 1:

K = 5;

Ti = 0.01

- Ensayo 2:

K = 10;

Ti = 0.01

- Ensayo 3:

K = 15;

Ti = 0.01

- Ensayo 4:

K = 25;

Ti = 0.01

- Ensayo 5:

K = 50;

Ti = 0.01

Valores utilizados en las figuras 5.13, 14 y 15:

- Ensayo 1:

K = 25;

Ti = 0.001

- Ensayo 2:

K = 25;

Ti = 0.005

- Ensayo 3:

K = 25;

Ti = 0.01

- Ensayo 4:

K = 25;

Ti = 0.02

- Ensayo 5:

K = 25;

Ti = 0.05

Una vez concluidos todos los ensayos, los valores escogidos fueron los
siguientes:
K=25, Ti = 0.005

5.4.2. Diseo basado en tcnicas de respuesta en frecuencia en lazo


abierto con modelado de los efectos de retrasos de actualizacin de
valores y PWM
Con el fin de comprobar que el control diseado anteriormente funcionara
correctamente implantado en el sistema real, se decidi modelar el efecto de los
retrasos en la actualizacin de los valores de salida del control, as como el efecto
que tiene el que el mando de tensin no sea una tensin continua sino una seal
PWM. El diagrama de bloques del sistema, una vez modelados dichos efectos,
queda como se muestra en la figura 5.17.

99

MEMORIA
Sistema de Control
Al realizar la simulacin del sistema con los parmetros del control
seleccionados anteriormente, se obtuvo la siguiente respuesta:

Figura 5.16: respuesta del sistema en simulacin con retardos de


actualizacin de salidas y PWM modelados
Como dicha respuesta no es demasiado buena, se opt por realizar un segundo
diseo del sistema de control, esta vez teniendo en cuenta los efectos de los
retardos y del PWM. Adems, para este segundo diseo, se aplicaron tcnicas de
diseo por respuesta en frecuencia en lazo abierto, como son el diseo por margen
de ganancia y el diseo por margen de fase (para ms informacin acerca de las
tcnicas de diseo de controles por respuesta en frecuencia, ver las referencias
bibliogrficas nmero 9 y 10).

100

MEMORIA

Sistema de Control

Retardo en la
actualizacin
del mando

Modulacin
PWM

Figura 5.17: diagrama de bloques del sistema, incluyendo retardos de actualizacin de salidas y efecto del PWM

101

MEMORIA

Sistema de Control

PI 2

PI 1

Retardo en la
actualizacin del mando
y retardo por el
retenedor de orden cero

Figura 5.18: diagrama de bloques del lazo de control completo abierto, en tiempo continuo

102

MEMORIA

Sistema de Control
PI 2

Retardo en la
actualizacin del mando
y retardo por el
retenedor de orden cero
Figura 5.19: diagrama de bloques del lazo de control de corriente abierto,
en tiempo continuo

Como se comenta al principio de la seccin, los diseos no se realizan sobre el


modelo propio del sistema, sino sobre una linealizacin del sistema, una vez
pasado a continuo. Para ello, se han de sustituir los bloques de control discreto por
sus equivalentes en continuo (ver seccin 5.2), y los retrasos en el dominio de la
transformada z por sus equivalentes en el dominio de la transformada de
Laplace. Como se tiene un retraso de actualizacin de las salidas de un periodo de
muestreo, y la salida del control discreto es transformada a continuo por un
retenedor de orden cero, en total se tendr un retraso en las salidas de 1.5 tiempo
de muestreo, lo que equivale a un retraso, en dominio de la transformada de
Laplace, de:

e 1.5t s s

[5.13]

Una vez se tiene el modelo en tiempo continuo, se puede linearizar y sacar su


diagrama de Black en lazo abierto. De l se obtiene la informacin necesaria para
disear el control. Como ya se hizo en el primer diseo, se comienza con el lazo
de control de corriente.

Se disea en primer lugar por margen de ganancia:


3
m = 50
G ( j 0 ) = 1260 +60 = 1320 0 = 3.57 10 rad / s

[5.14]

G ( j 0 ) dB = 17.7 dB
c = 10

103

MEMORIA

Sistema de Control

Figura 5.20: diagrama de Black del lazo de corriente abierto, antes de aplicar
el control

C ( j 0 ) dB = 17.7 dB C ( j 0 ) = 10

c = 90 + arctg (Ti 0 ) = 10 Ti =
C ( j 0 ) = K

17.7
20

= 7.6736

tan 80

= 1.6 10 3

1 + (Ti 0 )
= 7.6736 K = 7.56
Ti 0
2

[5.15]

Donde:

(Nomenclatura extensiva a todos los diseos por respuesta en frecuencia)

m = margen de fase

Am = margen de ganancia

0 = pulsacin de cruce

u = pulsacin de oscilacin

G = funcin de transferencia del sistema a controlar en lazo abierto

C = funcin de transferencia del control

c = retraso del control (debido a la parte integral del mismo)

Ti y K = ver seccin 5.2 de la memoria

104

MEMORIA

Sistema de Control

Como se puede observar en la figura 5.21, el control diseado resulta en un


margen de fase adecuado, sin embargo el margen de ganancia, que debera estar
por encima de los 8 dB, se hace demasiado pequeo.

Figura 5.21: diagrama de Black del lazo de corriente abierto, despus de


aplicar el primer diseo del control
Entonces, se decide disear por margen de ganancia:
G ( j 0 ) = 1260 +10 = 1270 0 = 5 10 3 rad / s
Am = 8dB

G ( j 0 ) dB = 17.8dB
c = 10
9.8

C ( j 0 ) dB = 17.7 dB 8dB = 9.8dB C ( j 0 ) = 10 20 = 3.1

c = 90 + arctg (Ti 0 ) = 10 Ti =
C ( j 0 ) = K

1 + (Ti 0 )
Ti 0

tan 80

= 1.134 10 3 10 3

= 3.1 K = 3.05 3

[5.16]

Una vez aplicado el control, se obtiene el siguiente diagrama de Black:

105

MEMORIA

Sistema de Control

Figura 5.22: diagrama de Black del lazo de corriente abierto, despus de


aplicar el segundo diseo del control

Figura 5.23: diagrama de Black del lazo completo abierto, antes de aplicar el
el control
Una vez observado el diagrama de Black del lazo completo abierto, se decide
disear el regulador que lo controle por margen de fase:
106

MEMORIA

Sistema de Control

G ( j 0 ) = 1260 +60 = 1320 0 = 300rad / s


m = 50

G ( j 0 ) dB = 33.8 dB
c = 10

Una vez obtenidos los puntos caractersticos del sistema en lazo abierto, se
procede a disear el control:

C ( j 0 ) dB = 33.8 dB C ( j 0 ) = 10

c = 90 + arctg (Ti 0 ) = 10 Ti =
C ( j 0 ) = K

1 + (Ti 0 )
Ti 0

33.8
20

tan 80

= 48.978

= 1.89 10 2 2 10 2

= 78.978 K = 48.234 50

[5.17]

(Las aproximaciones en los valores de control se han realizado para facilitar el


posterior escalado del problema en 8bits)

Figura 5.24: diagrama de Black del lazo completo abierto, despus de aplicar
diseo del control
Una vez implantado el control con los valores diseados, se simula el sistema
tomando como referencia dos escalones: el primero, de 0 a 0.5m/s, para estabilizar
el sistema en rgimen permanente, y el segundo de 0.1m/s de amplitud, para

107

MEMORIA
Sistema de Control
observar la reaccin del sistema ante pequeas variaciones, una vez est
estabilizado en rgimen permanente. Se obtiene como respuesta:

Figura 5.25: respuesta de la simulacin del sistema


La cual, si bien no es perfecta, como se puede observar en la figura 5.26, es
bastante mejor que la obtenida con el control anterior.

Figura 5.26: ampliacin de la respuesta de la simulacin del sistema

108

MEMORIA

Sistema de Control

5.5. Filtros digitales: filtro de primer orden y filtro FIR


Dadas las fluctuaciones que se producen en la salida del sistema al simularlo,
se decide probar a filtrar la intensidad medida antes de entrar al microprocesador,
para ver si se pueden atenuar dichas fluctuaciones. Aprovechando la versatilidad
de los filtros digitales frente a los analgicos (los valores de los filtros digitales se
pueden cambiar mediante software en cualquier momento, mientras que los filtros
analgicos una vez implantados no se pueden modificar), se decide disear un
filtro paso bajo de primer orden, y posteriormente un filtro paso bajo FIR para
eliminar (o al menos atenuar) las altas frecuencias que pueda haber en la medida
de la corriente que atraviesa el motor.

5.5.1. Filtro paso bajo de primer orden


Para disear un filtro digital paso bajo de primer orden, se disear en primer
lugar el filtro paso bajo en tiempo continuo, y ms tarde, utilizando las tcnicas
expuestas en la seccin 5.1 de la memoria, se discretizar.

La funcin de transferencia de un filtro paso bajo tiene la forma:


F (s) =

1
1
es la frecuencia de corte..
, donde
1 + s
2

Se aplica la aproximacin de la integral superior de Riemann para hallar la


transformada z de la funcin de transferencia del filtro. Para ello, se sustituye
s por

Ts
1 z 1
, quedando pues: F ( z ) =
. Por tanto, su ecuacin en
Ts
Ts + z 1

diferencias ser:

y[k ] =

Ts u[k ] + y[k 1]
Ts +

[5.18]

109

MEMORIA

Sistema de Control

Figura 5.27: diagrama de bloques del filtro de primer orden

110

MEMORIA
Sistema de Control
Si se hace = 1, se obtendr una frecuencia de corte de 0.16 Hz, la cual
satisface la premisa de eliminar las posibles fluctuaciones en altas frecuencias que
pudiera tener la corriente medida

Figura 5.28: diagrama de Bode del filtro


Una vez diseado el filtro, se procede a disear el control del lazo de corriente.
Despus de observar el diagrama de black en lazo abierto, se decide disear por
margen de ganancia:
3
Am = 10 dB G ( j 0 ) = 1260 +10 = 1270 0 = 5 10 rad / s

G ( j 0 ) dB = 82 dB
c = 10

C ( j 0 ) dB = 82dB 10dB = 72dB C ( j 0 ) = 10

c = 90 + arctg (Ti 0 ) = 10 Ti =
C ( j 0 ) = K

1 + (Ti 0 )
Ti 0

tan 80

72
20

= 3981

= 3.38 10 3

= 3981 K = 3920.5

[5.19]

111

MEMORIA

Sistema de Control

Figura 5.29: diagrama de Black del lazo de corriente abierto, antes de aplicar
el control

Figura 5.30: diagrama de Black del lazo de corriente abierto, una vez
aplicado el control

112

MEMORIA
Sistema de Control
A la hora de disear el control del lazo completo, se tiene en cuenta el
siguiente diagrama de Black:

Figura 5.31: diagrama de Black del lazo completo abierto, antes de aplicar el
control
A partir de l, se decide que se va a disear por margen de fase. Se especifican
los clculos a continuacin:
m = 45
G ( j 0 ) = 180 +50 = 130 0 = 2.1rad / s

G ( j 0 ) dB = 3.87 dB
c = 5

C ( j 0 ) dB = 3.87dB C ( j 0 ) = 10

c = 90 + arctg (Ti 0 ) = 5 Ti =
C ( j 0 ) = K

1 + (Ti 0 )
Ti 0

3.87
20

= 0.65

tan 85

= 5 .4

= 0.65 K = 0.65

[5.20]

Una vez aplicado el control, se obtiene un diagrama de Black en lazo abierto:

113

MEMORIA

Sistema de Control

Figura 5.30: diagrama de Black del lazo completo, con control aplicado
Sin embargo, se observa una respuesta del sistema ms lenta y fluctuante que
con controles anteriores:

Figura 5.31: respuesta del sistema en simulacin

114

MEMORIA
5.5.2. Filtro paso bajo FIR

Sistema de Control

Ante la mala respuesta del sistema con el filtro paso bajo de primer orden, se
decide disear un filtro FIR, que tiene la ventaja de ofrecer una gran atenuacin e
incluso completa eliminacin de determinadas frecuencias con una fase lineal,
para sustituir al filtro de primer orden, y observar si la respuesta del sistema
mejora.

Se define un filtro FIR como aquel en el que cada muestra de salida es una
suma ponderada de un nmero finito de muestras de la secuencia de entrada ya
recibida, lo que significa que su respuesta es causal. Esta funcionalidad se puede
expresar como:

Para obtener ms informacin sobre la teora que rodea a los filtros FIR
(aspecto en el cual no se va a ahondar ms en el presente texto) se puede consultar
cualquier libro de tratamiento de seales discretas, como por ejemplo los
enunciados en las referencias bibliogrficas 1, 2 y 3.

Los filtros FIR se disean en funcin de las frecuencias que se desean eliminar.
A partir de la transformada z del filtro, se hallan los ceros de la funcin. stos
sern complejos, que, en forma mdulo-argumental tendrn por mdulo la unidad,
y por argumento la pulsacin normalizada (pulsacin / pulsacin de muestreo) que
elimine ese cero. Si se disea dicha transformada para que tenga ceros en ciertas
frecuencias normalizadas (pulsacin normalizada / 2), que, multiplicadas por la
frecuencia de muestreo dan como resultado las frecuencias que se quieren
eliminar, stas resultarn eliminadas (se vuelve a hacer hincapi en que el presente
texto no pretende ahondar en los aspectos tericos de los filtros FIR y los
teoremas de muestreo. Se puede consultar las referencias bibliogrficas 1, 2 y 3
para ms informacin). Como se quiere disear un filtro paso bajo, se har de tal

115

MEMORIA
Sistema de Control
forma que elimine frecuencias equidistantes a partir de una pulsacin normalizada
de /2 hasta una pulsacin normalizada de 3/2.

Idealmente, se querran tener tantos ceros entre esas dos frecuencias como
fuese posible, para eliminar el mayor nmero posible de altas frecuencias, pero
cuantos ms ceros se introduzcan en la funcin, ms carga de trabajo tendr que
soportar el microprocesador, y ms altos (y, por consiguiente, difciles de escalar
en 8 bits, que es el tamao de los registros del microprocesador utilizado)
resultarn los coeficientes que acompaan a las z-n en la transformada z del
filtro, los cuales son los mismos coeficientes que acompaan a las x[n-k] en la
ecuacin en diferencias del filtro.
Se decidi que cinco ceros, en ej/2, ej3/4 y ej , conforman un filtro que
cumple las caractersticas necesarias para la funcin que ha de desempear en el
diseo. Una vez redondeados los coeficientes, para su posterior implantacin en el
microprocesador con enteros de 8 bits, queda la siguiente ecuacin en diferencias
del filtro:

y[n] =

2 z 6 + 7 z 5 + 12 z 4 + 14 z 3 + 12 z 2 + 7 z + 2
z6

[5.21]

Se pueden observar el diagrama de ceros y polos del filtro, as como su


diagrama de Bode y su diagrama de bloques en las figuras 5.32, 5.33 y 5.34
respectivamente:

116

MEMORIA

Sistema de Control

Figura 5.32: diagrama de ceros y polos del filtro FIR diseado

Figura 5.33: diagrama de Bode del filtro FIR diseado

117

MEMORIA

Sistema de Control

Figura 5.34: diagrama de bloques del filtro FIR diseado

Como en el filtro de primer orden, una vez diseado el filtro FIR, se procede a
disear el control mediante tcnicas de respuesta en frecuencia en lazo abierto.

Se comienza, como en anteriores diseos, por el diseo del regulador del lazo
de control de corriente:
3
Am = 8 dB G ( j 0 ) = 180 +10 = 190 0 = 4.24 10 rad / s

G ( j 0 ) dB = 16.8 dB
c = 10

C ( j 0 ) dB = 16.8dB 8dB = 24.8dB C ( j 0 ) = 10

c = 90 + arctg (Ti 0 ) = 10 Ti =
C ( j 0 ) = K

1 + (Ti 0 )
Ti 0

tan 80

24.8
20

= 0.058

= 1.34 10 3

= 0.058 K = 0.057

[5.22]

118

MEMORIA

Sistema de Control

Figura 5.35: diagrama de Black del lazo de corriente abierto, antes de aplicar
el control

Figura 5.36: diagrama de Black del lazo de corriente abierto, despus de


aplicar el control

119

MEMORIA
Sistema de Control
Despus de disear el regulador del lazo de control de corriente, se realiza el
diseo del regulador del lazo de control completo:

G ( j 0 ) = 540 +60 = 600 0 = 6.99rad / s


m = 50

G ( j 0 ) dB = 33.6 dB
c = 10

C ( j 0 ) dB = 33.6dB C ( j 0 ) = 10

c = 90 + arctg (Ti 0 ) = 10 Ti =
C ( j 0 ) = K

1 + (Ti 0 )
Ti 0

33.6
20

= 0.02

tan 80

= 0.81

= 0.02 K = 0.02

[5.23]

Figura 5.37: diagrama de Black del lazo completo abierto, antes de aplicar el
control

120

MEMORIA

Sistema de Control

Figura 5.38: diagrama de Black del lazo completo abierto, una vez aplicado el
control
Una vez diseados los dos reguladores en tiempo continuo, se procede a
efectuar la simulacin de la respuesta del sistema en tiempo discreto ante un
escaln, dando como resultado la grfica de la figura 5.39.

Si se comparan todas las grficas obtenidas de la simulacin de la respuesta del


sistema con y sin filtros, se puede determinar que el sistema ofrece una mejor
respuesta (al menos en simulacin) sin filtrar la medida de corriente que le llega al
microprocesador. Por ello, se elige el mencionado diseo para desarrollar el
software pertinente en base a l, e implantarlo en el sistema fsico.

121

MEMORIA

Sistema de Control

Figura 5.39: respuesta simulada del sistema ante un escaln

122

MEMORIA

Sistema de Control

5.6. Escalado del problema


Al realizar los diseos y simularlos en el ordenador, se ha trabajado siempre
con variables codificadas en formato de coma flotante y doble precisin. Con el
fin de optimizar el rendimiento del microprocesador, se va a realizar lo que se
conoce como un escalado del problema. Se simular el control trabajando con
variables enteras de 32, 16 y 8 bits, y dependiendo de los resultados obtenidos
trabajando con los distintos tipos de dato, se elegir el ms pequeo dentro de un
rango aceptable de resultados para trabajar con l.

El escalado se efecta multiplicando las variables del sistema que estn dentro
de los bloques de control por potencias de 2. Esto es as ya que para que el
microprocesador multiplique o divida por 2 nicamente tiene que hacer un
desplazamiento (shift left o shift right, respectivamente) al registro que contenga
el nmero a multiplicar, y dicha operacin de desplazamiento se efecta de forma
muy rpida. Mediante estas operaciones se consigue que las variables estn dentro
del rango de valores deseado, que en este caso es de -128 a 127 en el caso de 8
bits, de -32768 a 32767 en el caso de 16 bits, y de -2147483648 a 2147483647 en
el caso de 32 bits.

Se puede observar en las figuras 5.40, 5.41 y 5.42 los diferentes diagramas de
bloques del sistema escalado. Se representan tambin los diferentes tiempos de
muestreo del sistema mediante distintos colores, as como el tipo de dato de todas
las seales del sistema.

Una vez realizado el escalado, se simul el sistema para comprobar su correcto


funcionamiento y comparar la salida del sistema en coma flotante con la del
sistema escalado trabajando con enteros de 8, 16 y 32 bits. El resultado de dicha
simulacin se puede observar en la figura 5.43.

123

MEMORIA

Sistema de Control

Figura 5.40: sistema en coma flotante y sistema escalado, con los distintos tiempos de muestreo del sistema representados
124

MEMORIA

Sistema de Control

Figura 5.41: bloque PI3 escalado a 8 bits

125

MEMORIA

Sistema de Control

Figura 5.42: bloque PI4 escalado a 8 bits

126

MEMORIA

Sistema de Control

Figura 5.43: respuesta del sistema en coma flotante y del sistema escalado a
enteros de 8,16 y 32 bits ante un escaln de amplitud 0.1 m/s.
Existe en el ensayo realizado con las variables escaladas a enteros de 8 bits un
pequeo error en rgimen permanente, producido por dos causas: la primera de
ellas es el error que se introduce con la perdida de sensibilidad al realizar la
conversin A/D, en la cual, se pasa de valores continuos a valores discretos con
una sensibilidad igual al cociente entre el valor de tensin mximo de entrada al
conversor, y la n-sima potencia de dos, siendo n el nmero de bits del conversor
A/D; la segunda causa es la prdida de precisin al utilizar variables de 8 bits,
bien sea por la inexactitud de algunas operaciones (desprecio de decimales,
overflows, etc.), o por el escalado de las constantes a 8 bits, con la consiguiente
prdida de informacin debida al desprecio de cifras decimales. En el escalado a
constantes de 16 y 32 bits no se aprecia prcticamente diferencia con las variables
en coma flotante y doble precisin. Se elige pues trabajar con el escalado a 16
bits.

127

MEMORIA

Sistema de Control

5.7. Conclusiones
Se presenta en este captulo toda la informacin relativa al diseo del control
del sistema, desde los fundamentos tericos bsicos para comprender el
funcionamiento de los sistemas de control discreto y sus posibles mtodos de
diseo, hasta el programa que se implantar en el microprocesador para realizar el
control del sistema.

Se ha tratado con bastante profundidad el diseo de los reguladores PI. En una


primera aproximacin se disean aproximando los parmetros por simulacin,
para comprobar posteriormente que este mtodo de diseo no es el ms acertado,
y se procede a disear aplicando tcnicas de respuesta en frecuencia: diseo por
margen de fase y diseo por margen de ganancia.

Ante el comportamiento que tiene la salida con los controles anteriores, se


piensa que se puede mejorar filtrando la corriente medida que va al
microprocesador. Para ello se disean dos filtros digitales: un filtro paso bajo de
primer orden, y un filtro FIR paso bajo. Despus de redisear el control para el
sistema incluyendo esos filtros, se comprueba mediante simulacin que no
mejoran, sino que empeoran la respuesta del sistema.

Una vez claro el regulador que se va a utilizar (el diseado por tcnicas de
respuesta en frecuencia, sin filtro de corriente), se procede con el escalado del
problema, para adecuar las variables del sistema para que puedan ser tratadas con
registros de 32, 16 u 8bits, en lugar de utilizar variables en doble precisin, que
disminuiran notablemente el rendimiento del microprocesador. Despus de haber
realizado el escalado con los tres tipos de variables, se elige trabajar con enteros
de 16 bits, ya que son la variable ms pequea que ofrece una calidad aceptable en
las simulaciones.

128

MEMORIA

Implantacin

Captulo 6: Implantacin en el microprocesador


6.1. El microprocesador ColdFire MCF5282
El microprocesador utilizado es el ColdFire MCF5282 de Motorola. Posee un
reloj interno de 80Mhz, 16 registros de propsito general de 32 bits y una
memoria RAM esttica de 64kB. En la figura 6.1 se puede observar un diagrama
de bloques con los distintos perifricos y funciones.

El soporte fsico del microprocesador es un encapsulado MAPBGA de 256


pines. En la figura 6.2 se pueden observar las caractersticas mecnicas del
microprocesador.

La asignacin de pines del microprocesador viene ilustrada en la figura 6.3, y


las caractersticas elctricas se pueden observar en las tablas 6.1, 6.2 y 6.3.

El MCF5282 posee un conversor analgico/digital de 10 bits gestionado por


colas, que ser fundamental para la medicin de las diversas seales del circuito
(aceleracin, intensidad por el motor, velocidad). Adems, posee una salida PWM
configurable por software, y diversos timers y entradas/salidas de propsito
general, que sern utilizados en el proyecto.

129

MEMORIA

Implantacin

Figura 6.1: diagrama de bloques del microprocesador

130

MEMORIA

Implantacin

Figura 6.2: caractersticas mecnicas del microprocesador MCF5282

Figura 6.3: asignacin de pines (pinout) del microprocesador

131

MEMORIA

Implantacin

Tabla 6.1: caractersticas elctricas mximas del MCF5282

Tabla 6.2: caractersticas elctricas DC del MCF5282

132

MEMORIA

Implantacin

Tabla 6.3: caractersticas elctricas DC del MCF5282 (continuacin)

133

MEMORIA

Implantacin

6.2. Implantacin: programacin del microprocesador


La ltima fase del diseo del control es implantar ste en el microprocesador.
Para ello, se programarn en lenguaje C las instrucciones necesarias para tal fin,
con ayuda del compilador Freescale CodeWarrior, el cual tambin se usar para
grabar el programa en el microprocesador.

Para llevar a cabo la implantacin se usar el sistema operativo en tiempo real


(de ahora en adelante SOTR) FreeRTOS. El SOTR FreeRTOS es un sistema
desarrollado en cdigo abierto, por lo que, adems de ser simple y adecuado al fin
que se quiere conseguir, es gratuito.

A grandes rasgos, el microprocesador ejecutar una secuencia de tareas como


la que sigue:

1. La seal analgica de salida del circuito de acondicionamiento del


acelermetro es pasada a digital en el conversor A/D.

2. Se ajusta el mando para alcanzar el valor de aceleracin normal mxima


programada (a_max). Si el tren est en una recta, ese valor ser imposible de
alcanzar, luego el tren desarrollar su mxima velocidad. Por el contrario, si
circula por una curva, se ajustar su velocidad para que mantenga la
aceleracin normal cercana a la mxima dentro de unos mrgenes.

3. Si se detecta una baliza, salta una interrupcin que pone la referencia de


velocidad a un valor moderado (la mitad de la velocidad mxima que puede
desarrollar el tren, esto es, 0.6m/s)

4. El control del micro disminuye duty cycle del PWM para igualar velocidad a
la referencia, y a partir de ah, empieza a gestionar la referencia de velocidad

134

MEMORIA
Implantacin
en funcin de la aceleracin normal que se mida en cada instante, pasando de
nuevo al punto 1.

El programa se ha desarrollado en 3 mdulos distintos: main.c, control.c y


configuracin.c.

Adems,

se

han

creado

los

archivos

.h

control.h,

configuracin.h y constantes.h.

En la tabla 6.4 se pueden observar las diferentes funciones asociadas a cada


mdulo, y a continuacin se dar una explicacin ms detallada de las funciones
ms relevantes.

135

MEMORIA

Implantacin

MDULO

FUNCIN

Main.c

Main
InitM5282Lite_ES

Configuracin
.c

TAREA
Inicializacin, creacin de tareas y arranque
del planificador.
Inicializacin

InitPWM

Inicializacin PWM.

SetPWM

Fija un Duty Cycle en el PWM.

InitControl

Inicializacin.

ADCTask

Tarea que realiza conversiones en el conversor

(TAREA)

A/D.
Tarea que realiza las gestiones para modificar

Control (TAREA)

la referencia de velocidad del tren de acuerdo


a la aceleracin normal leda en cada instante.

CopiaRef
CopiaEnRef
Control.c

Funciones de copia de datos para proteger


zonas crticas.
Funciones que realizan el control PI discreto

PI1 y PI2

en el lazo de corriente y el lazo de velocidad


del control.

QadcInit

Inicializacin del conversor A/D.

ArrancaConversion Arranca la conversin en AN0-AN3.


Funcin de encuesta que devuelve 1 si el
Convirtiendo

conversor A/D est ejecutando una conversin


en ese momento.

LeeAN0, 1, 2 y 3

IntGPTA0
Interrupts
(en Control.c)

Lee el valor digital convertido en el conversor


analgico para las 4 entradas.
Salta cuando hay flanco de subida en GPTA0.
Deteccin de baliza. Modera la referencia.
Salta cada 0.5ms (tiempo de muestreo).

IntPIT0

Realiza el control del lazo de corriente y


velocidad.

Tabla 6.4: funciones asociadas a cada mdulo

136

MEMORIA
6.2.1. Main

Implantacin

En la funcin main se realizan todas las inicializaciones pertinentes para el


correcto funcionamiento del programa. Desde esta funcin se llamar a
InitM5282Lite_ES, InitPWM, QadcInit e InitControl. Acontinuacin se crearn
las dos tareas que se van a ejecutar de acuerdo al planificador del SOTR, y por
ltimo se arrancar dicho planificador.

La figura 6.4 muestra un diagrama de flujo de la funcin:

Figura 6.4: diagrama de flujo de la funcin main

137

MEMORIA
6.2.2. Control

Implantacin

La tarea de control se ejecuta cada 20 ms, y realiza los clculos necesarios para
la gestin de la referencia de velocidad del tren, en funcin de la aceleracin
normal medida. La figura 6.5 muestra su diagrama de flujo.

Figura 6.5: diagrama de flujo de la tarea de control

138

MEMORIA
6.2.3. ADCTask

Implantacin

La tarea ADCTask realiza las conversiones de analgico a digital de los cuatro


canales AN0, AN1, AN2 y AN3, siempre y cuando no haya ninguna otra tarea
leyendo los datos de dichas conversiones. La figura 6.6 ilustra su funcionamiento
mediante su diagrama de flujo.

Figura 6.6: diagrama de flujo de la tarea ADCTask

139

MEMORIA

Implantacin

6.2.4. IntGPTA0
IntGPTA0 es la interrupcin que salta cuando hay un flanco de subida en el pin
GPTA0, que es el asociado a detectar los pasos por las balizas del tren. Su
funcionamiento viene descrito por su diagrama de flujo, que se puede observar en
la figura 6.7.

Figura 6.7: diagrama de flujo de la interrupcin IntGPTA0


6.2.5. IntPIT0
La interrupcin del PIT0 (programmable interrupt timer 0) salta cada 0.5ms. Se
ha configurado el PIT0 para que salte con ese periodo ya que coincide con el
periodo de muestreo utilizado en las simulaciones con MATLAB.

Durante la interrupcin se realiza el proceso de control tanto del lazo de


velocidad como del de corriente (una vez del primero por cada diez del segundo,
ya que el lazo de corriente es mucho ms rpido que el de velocidad).
140

MEMORIA
La figura 6.8 presenta su diagrama de bloques:

Implantacin

Figura 6.8: diagrama de flujo de la interrupcin PIT0

141

MEMORIA
6.2.6. Programacin del regulador PI discreto

Implantacin

El regulador PI se ha de implantar en el microprocesador para que este pueda


ejercer su labor de control. El regulador PI discreto, como todo regulador PI tiene
dos acciones de control, una proporcional, sobre el error generado como la
diferencia entre la referencia y la medida, y otra integral, sobre la integral de
dicho error. Una vez pasadas a discreto, mediante la regla trapezoidal, como se
explica en la seccin 5.2, queda:
e[k ] = referencia[k ] medida[k ]
e[k ] + e[k 1]
I e[k ] = Ie[k 1] +
Ts
2

[5.24]

Donde:

e[k] = error en el instante k

Ie[k] = integral del error en el instante k


e[k ] = e[k ] e[k 1]
e[k ] + e[k 1]
Ie[k ] = Ie[k ] +
ts
2

[5.25]

Por tanto, el incremento del mando entre un instante y el siguiente ser:

1
m[k ] = K e[k ] + Ie[k ]
Ti

[5.26]

Y el mando en un instante k:
m[k ] = m[k ] + m[k 1]

[5.27]

142

MEMORIA
Implantacin
Luego, si se programa una subrutina llamada PI que efecte el control
proporcional-integral a partir de las mediciones pertinentes y de la referencia,
quedar algo como:

int PI(int referencia,int salida, int* pmando_ant, int*


pe_ant, int* pIe_ant, int K, int Ti, int man_sat)
{
int e_act, Ie_act;
int inc_mando, mando;

e_act = referencia-salida;
Ie_act = *pIe_ant + (e_act + *pe_ant) * Ts/2;
inc_mando

(e_act-(*pe_ant)

((Ie_act-

(*pIe_ant))/Ti) );

mando= *pmando_ant+inc_mando;

if(mando>=man_sat){
mando=man_sat;
}else if(mando<=(-man_sat)){
mando=-man_sat;
}

*pmando_ant = mando_act
*pe_ant = e_act;
*pIe_ant = Ie_act;

return (mando);
}
Si se observa de nuevo el diagrama de flujo del sistema entero (figura 6.9), se
ve con claridad que todas las tareas que deba realizar el microprocesador han sido
implementadas

con

xito.

143

MEMORIA

Implantacin

Figura 6.9: diagrama de flujo del sistema completo

144

MEMORIA

Implantacin

6.3. Conclusiones
El presente captulo comienza con una recopilacin de datos tiles sobre el
microprocesador Motorola ColdFire MCF5282, tales como sus caractersticas
elctricas y mecnicas, o aquellas de sus funcionalidades que van a ser tiles en el
proyecto.

A continuacin, se desarrolla el programa que ir finalmente implantado en el


microprocesador y que gestionar todos los aspectos del control: toma de medidas
mediante conversor A/D, algoritmos de control, gestin de salidas mediante onda
PWM Se hace un repaso general de todas las funciones que se utilizarn a lo
largo del programa, y se profundiza en aquellas funciones y tareas que son de ms
relevancia para la comprensin del funcionamiento del programa.

El captulo concluye con el desarrollo de la programacin de los mdulos de


control PI discretizados que se utilizan en el control de los lazos de corriente y de
velocidad.

Cabe destacar que el programa completo que ha sido implementado en el


microprocesador se puede encontrar ntegro en el Anexo I de la presente memoria.

145

MEMORIA

Resultados

Captulo 7: Resultados experimentales


7.1. Introduccin
Se tratarn en este captulo los resultados obtenidos de los diferentes ensayos
experimentales realizados sobre el circuito construido.

7.2. Pruebas del circuito de potencia


Para probar la etapa de potencia del circuito, se introdujeron una serie de ondas
cuadradas de 0V a 3V con diferentes periodos, generadas por un generador de
seal Thandar TG501. Se realizaron medidas con un osciloscopio Tektroniks TDS
1002B en distintos puntos del circuito, para verificar que su tensin se hallaba
dentro de los lmites esperados.

Figura 7.1: prototipo de la etapa de potencia en protoboard para pruebas I

146

MEMORIA

Resultados

Figura 7.2 : generador de seales Thandar TG501

Figura 7.3: osciloscopio Tektroniks TDS 1002B

147

MEMORIA

Resultados

Se pueden observar a continuacin dos de esas medidas, tomadas a uno y otro


lado de la resistencia de medida en serie con la carga:

Figura 7.4: medidas osciloscopio

Figura 7.5: medidas osciloscopio

148

MEMORIA

Resultados

7.3. Pruebas del prototipo


Se realizaron pruebas con un prototipo para cerciorarse de que el sistema, a
falta de la implantacin de los acelermetros, funcionaba correctamente:

Figura 7.6: prototipo final


A travs del sistema de control se fue variando a placer la velocidad de la
maqueta de tren, cuyo motor es alimentado a travs de las vas, quedando as
constancia de la efectividad del diseo.

149

MEMORIA

Conclusiones

Captulo 8: Conclusiones y trabajo futuro


Antes de realizar el diseo del control, es necesario conocer y modelar los
distintos parmetros fsicos que intervienen en el sistema a controlar. La
metodologa seguida para obtener los distintos parmetros necesarios a la hora de
disear el control, as como la base terica sobre la que se sustentan los clculos
realizados para dicha obtencin de los mencionados parmetros se encuentra
desarrollada en el captulo segundo.

Una vez obtenidos dichos parmetros, se ha procedido a obtener un modelo del


sistema, a partir de cual trabajar en el diseo del control, ya que, sin una
modelizacin del sistema fsico, sera imposible realizar dicho diseo o las
simulaciones pertinentes para comprobar la validez del mismo.

El control ha de ir implantado sobre un hardware. Se ha expuesto en el captulo


tercero todo lo relacionado con el hardware del sistema: desde la etapa de
potencia, que servir de nexo entre el control y el actuador, hasta los reguladores
de tensin que han sido utilizados.

En una primera seccin se ha hablado de todo el diseo de la etapa de potencia,


exponiendo los clculos, as como informacin detallada de todos los elementos
que la componen: optoacoplador, inversor y puente en H.

En la segunda seccin se han presentado los distintos tipos de reguladores


existentes, y se ha argumentado la eleccin de uno de ellos sobre el resto.
Adems, se han propuesto diseos alternativos de los reguladores para que, en
caso de una fabricacin en serie del prototipo que se propone en el presente
proyecto, los gastos en componentes disminuyan drsticamente en esta parte del
circuito.

Por ltimo, se han abordado los distintos circuitos de acondicionamiento de


seal que se han utilizado. stos cumplen la funcin de acondicionar las seales
que se desean medir para realimentar el control de manera que dicha medicin se
150

MEMORIA
Conclusiones
efecte con la mayor precisin y sensibilidad posibles, y sin perturbar a la seal
original. Para ello se han utilizado bsicamente etapas basadas en amplificadores
operacionales, tanto en realimentacin negativa como en bucle abierto, diodos
zener para la proteccin del microprocesador, y los propios elementos cuya seal
se haba de acondicionar.

La ltima etapa de diseo es la relativa al diseo del control del sistema. Se han
presentado pues en el captulo quinto, desde los fundamentos tericos bsicos para
comprender el funcionamiento de los sistemas de control discreto y sus posibles
mtodos de diseo, hasta el programa que se ha implantado en el microprocesador
para realizar el control del sistema.

Se ha tratado con bastante profundidad el diseo de los reguladores PI. En una


primera aproximacin se disean aproximando los parmetros por simulacin,
para comprobar posteriormente que este mtodo de diseo no es el ms acertado,
y se procede a disear aplicando tcnicas de respuesta en frecuencia: diseo por
margen de fase y diseo por margen de ganancia.

Ante el comportamiento que tiene la salida con los controles anteriores, se


piensa que se puede mejorar filtrando la corriente medida que va al
microprocesador. Para ello se disean dos filtros digitales: un filtro paso bajo de
primer orden, y un filtro FIR paso bajo. Despus de redisear el control para el
sistema incluyendo esos filtros, se ha comprobado mediante simulacin que no
mejoran, sino que empeoran la respuesta del sistema.

Una vez claro el regulador que se va a utilizar (el diseado por tcnicas de
respuesta en frecuencia, sin filtro de corriente), se ha procedido con el escalado
del problema, para adecuar las variables del sistema para que puedan ser tratadas
con variables enteras de 8, 16 32 bits (lo cual supondr una mejora del
rendimiento del microprocesador, al no tener que trabajar con variables en coma
flotante de doble precisin, tal y como se trabaja en las simulaciones). Despus de
realizar el escalado pertinente en variables enteras de 8, 16 y 32 bits, y de realizar
la simulaciones necesarias para comprobar la efectividad del mismo, se determina
151

MEMORIA
Conclusiones
que el tipo de variable ms conveniente para realizar el escalado son los enteros
de 16 bits.

Por ltimo, una vez escalado el problema, se ha desarrollado el programa que


ir finalmente en el microprocesador y que gestionar todos los aspectos del
control: toma de medidas mediante conversor A/D, algoritmos de control, gestin
de salidas mediante onda PWM. Dicho programa ha sido implementado sobre un
sistema operativo en tiempo real como es FreeRTOS, en un microprocesador
Motorola Coldfire MCF5282.

Terminada la fase de diseo, se deben realizar las pruebas pertinentes sobre un


prototipo para verificar que el sistema funciona correctamente. Desde un principio
se concibi el diseo del sistema de control para controlar una maqueta de tren a
escala, luego se fue el sistema que se control con el prototipo del control
montado.

Se realizaron las pruebas pertinentes con el circuito de potencia, montado sobre


una proto-board, para verificar que el diseo de ste no presentaba ninguna
problemtica.

Cabe destacar que, a medida que se fueron realizando los diversos avances en
el diseo, stos se fueron acompaando de la documentacin necesaria para la
elaboracin de la presente memoria. Adems, tambin se fueron diseando las
placas de circuito impreso necesarias para construir el sistema de forma definitiva,
y no como un prototipo, las cuales se pueden encontrar en la seccin de planos, a
continuacin de la presente memoria. Para este fin se utilizaron los programas
OrCAD Capture y OrCAD LayOut.

Como trabajo futuro, sera muy interesante la implantacin de un sistema de


transmisin de todas las seales que maneja el sistema cumpliendo los estndares
elctricos y de comunicaciones que establece la NMRA (se pueden consultar en
los Anexos 4 y 5). El principal problema que se presenta es que, como la
transmisin de seales de acuerdo a estos estndares se realiza por medio de
152

MEMORIA
Conclusiones
pulsos elctricos transmitidos por medio de las vas del tren, y en el presente
proyecto se utiliza una seal PWM que se transmite tambin por las mismas vas
para llegar al motor del tren, sera complicado distinguir entre los pulsos de la
seal de comunicacin y los pulsos generados por el ruido de la onda PWM, o la
propia onda PWM. ste problema se podra solucionar por medio de filtrado, pues
la frecuencia de la onda PWM es conocida, y la frecuencia de las ondas de pulsos
de comunicacin tambin lo sera, el problema radica en que el ruido generado
por el PWM podra distorsionar distintas frecuencias, incluida aqulla en la que se
transmite la onda de pulsos de comunicacin.

153

MEMORIA

Agradecimientos

Agradecimientos
Una vez terminado el proyecto, slo queda mirar atrs con una expresin de
satisfaccin en el rostro, y agradecer a todas esas personas que han hecho
posible la realizacin del mismo:

En primer lugar, he de darles las gracias a mis padres, por toda la paciencia
que a lo largo de todos estos aos han tenido conmigo, y porque sin su ayuda y
apoyo, nada habra sido posible.

He de agradecer tambin a todos los profesores que he tenido a lo largo de la


carrera, tanto en ICAI como en The University of Arizona, ya que, en mayor o
menor medida, me han aportado los conocimientos necesarios para realizar este
proyecto.

Me gustara darle las gracias profundamente a mi director de proyecto, D.


Eduardo Santamara, por haber confiado en m, y haberme dado la oportunidad
de trabajar con l desde la lejana y rida Arizona, cuando no haba ningn
precedente de direccin de proyecto a distancia.

Por ltimo, y aunque prcticamente no han tenido nada que ver de una forma
directa con este proyecto, por ser ste el punto final de mis cincos ltimos aos de
estudios, me gustara mencionar a D. Flix Alonso y a D. Santiago Canales, por
haberme sabido inculcar all en primer curso valores tan importantes como el
trabajo y el esfuerzo.

154

MEMORIA

Bibliografa

Bibliografa
1. [MCCL98] MCCLELLAN, SCHAFER, YODER. DSP First.Ed. Prentice
Hall, 1998.
2. [OPPE00] OPPENHEIM, SCHAFER, BUCK. Discrete-Time Signal
Processing Ed. Prentice-Hall., 2000.
3. [VIJA02] VIJAY K. MADISETTI, DOUGLAS B. WILLIAMS. Digital
Signal Processing Handbook. Ed. Chapman & Hall, 2002.
4. [SEDR98] SEDRA / SMITH.Microelectronic Circuits Ed. Oxford UP, 1998
5. [COUG01] COUGHLIN/ DRISCOLL. Operational Amplifiers and Linear
InegratedCircuits Ed. Prentice Hall, 2001
6. [BORE02] BORELLI, R. Y COURTNEY, S. Ecuaciones diferenciales.
Una perspectiva de modelacin. Ed. Oxford University Press, 2002
7. [MARC90] MARCELLN, F.-CASASUS, L.-ZARZO, A. Ecuaciones
diferenciales Ed. McGraw-Hill, 1990
8. [GARC06] GARCA, A.-GARCA, F.- LPEZ, A.- RODRGUEZ, G.ROMERO, S.- VILLA, A de la. Ecuaciones diferenciales ordinarias.
Teora y problemas. Mtodos exactos. Mtodos numricos. Estudio
cualitativo Ed. CLAGSA, 2006
9. [PAGO06] PAGOLA, LUIS. Regulacin Automtica Ed. Universidad
Pontificia Comillas, 2006
10. [NISE04] NISE. Control Systems Engineering Ed. Wiley, 2004
11. [MUO09] MUOZ FRAS, JOS DANIEL. Sistemas Empotrados en
Tiempo Real Creative Commons. Febrero 2009

155

MEMORIA

Bibliografa

Relacin de pginas web consultadas, agrupadas por temtica:

ACCIDENTES DE TREN POR VELOCIDAD EXCESIVA EN CURVAS

http://www.cooperativa.cl/p4_noticias/site/artic/20060208/pags/20060208
200104.html

http://www.lukor.com/not-soc/sucesos/0902/27143852.htm

http://www.elcomerciodigital.com/gijon/20090225/asturias/maquinistatren-descarrilado-parres-20090225.html

http://www.tribuna.net/noticia/27502/CASTILLA-Y-LEN/seis-muertosheridos-descarrilar-tren-palencia.html

http://infotobarra.en.eresmas.com/descarrilamiento.htm

http://edant.clarin.com/diario/2005/04/26/elmundo/i-02401.htm

http://www.cadenaser.com/espana/articulo/muertos-descarrilar-trenprovincia-palencia/sernotnac/20060821csrcsrnac_10/Tes

ARTCULO SOBRE LAS FUERZAS G

http://xeneize.wordpress.com/2007/07/11/fuerzas-g-por-albert-illera/

CONTROL DE TRENES:

http://www.elmundo.es/papel/2006/07/05/espana/1992349.html

http://www.madrid.org/metrosur/instalaciones/senalizacion.htm

http://ferrocarriles.wikia.com/wiki/Sistemas_de_control_de_trenes

CONTROL DE MOTORES:

http://webdelprofesor.ula.ve/ingenieria/gjaime/materias/control_de_motor
es/semA2004/clase1.pdf

SISTEMAS DE CONTROL:

http://isa.uniovi.es/~cuadrado/dsac.html

http://www.seattlerobotics.org/encoder/200205/PIDmc.html

156

Fdo.: Fernando Moreno Prez


Madrid, 17 de Junio de 2010

MEMORIA

Anexos

Anexos
Anexo1. Programa completo en lenguaje C
- Anexo 1.1. Main.c
- Anexo 1.2. Control.c
- Anexo 1.3. Control.h
- Anexo 1.4. Configuracion.c
- Anexo 1.5. Configuracion.h
- Anexo 1.6. Constantes.h
Anexo 2. Archivos .m utilizados en MATLAB
Anexo 3. Manual del microprocesador
- Anexo 3.1. Captulo 10: Interrupt Controller Modules
- Anexo 3.2. Captulo19: Programmable Interrupt Timer Modules
(PIT0-PIT3)
- Anexo 3.3. Captulo 20: General Purpose Timer Modules (GPTA and
GPTB)
- Anexo 3.4. Captulo 28: Queued Analog-to-Digital Converter (QADC)
- Anexo 3.5.Captulo 33: Caractersticas Elctricas
Anexo 4. NMRA Electrical Standards for Digital Command Control, July
2004.
Anexo 5. NMRA Communications Standards for Digital Command
Control, July 2004.
Anexo 6. Hojas de caractersticas (Datasheets)

- Anexo 6.1. Fotodiodo selectivo EPD-740-5


- Anexo 6.2. Acelermetro ADXL320
- Anexo 6.3. Optoacoplador ILQ74
- Anexo 6.4. Puente en H L298

157

ANEXO 1

Programa completo en lenguaje C

MEMORIA
/*Main.c
* Autor: Fernando Moreno
* ltima modificacin: 6/Jun/2010
*/

Anexo I

#include "Constantes.h"
int main()
{
InitM5282Lite_ES();
//Inicializa
los
perifericos del M5282
InitPWM();
//Inicializa el PWM con una
resolucin de PWM_RESOLUTION unidades.
QadcInit();
//Inicializa el
conversor AD
InitControl();
//Inicializa
registros
y
variables utilizadas por el control
//Creacin de tareas
xTaskCreate(Control,(const
signed
portCHAR
const)"Control",TAM_PILA,NULL,PRIO_CONTROL,NULL);
xTaskCreate(ADCTask,(const
signed
portCHAR
const)"ADCTask",TAM_PILA,NULL,PRIO_ADCTASK,NULL);

*
*

//cast a (const signed portCHAR * const)

vTaskStartScheduler();
(scheduler)
}

//Arranca

el

planificador

MEMORIA
/*Control.c
* Autor: Fernando Moreno
* ltima modificacin: 6/Jun/2010
*/

Anexo I

#include Control.h

static int16 duty_cycle_variation;


static int16 periodo;
static int16 referencia_velocidad;
//La
referencia de velocidad en unidades fsicas (m/s) va
desde -1.2 a 1.2 m/s.
static int16 medida_i, signo_i, referencia_i;
static int16 medida_v, referencia_v;
static int16 error_i, Ierror_i;
static int16 error_v, Ierror_v;
static int16 mando_tension, mando_corriente;
static int16 contador_interrupcion;
static int16 duty_cycle;
static xSemaphoreHandle sem_AD;
void InitControl(void)
{
//Configuracin interrupciones puerto GPTA
MCF_GPTA_GPTCTL2=0x55; //Interrumpe en flanco de subida
a cada uno de los canales
MCF_GPTA_GPTIE=0x0F; //Habilita interrupciones de los 4
canales de GPTA.
MCF_GPTA_GPTSCR1=0x80;
MCF_INTC0_ICR44 = 0x08; /* Nivel 1 Prioridad 0 */
MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK44; /* Timer
Channel 0 Desenmascarada */
*(void **)(0x20000000 +(64+44)*4) = (void *)IntGPTA0;
MCF_INTC0_ICR45 = 0x08; /* Nivel 1 Prioridad 1 */
MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK45; // Timer
Channel 1 Desenmascarada
*(void **)(0x20000000 +(64+45)*4) = (void *)IntGPTA1;
MCF_INTC0_ICR46 = 0x08; /* Nivel 1 Prioridad 2 */
MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK46; /* Timer
Channel 2 Desenmascarada */
*(void **)(0x20000000 +(64+46)*4) = (void *)IntGPTA2;
MCF_INTC0_ICR47 = 0x08; /* Nivel 1 Prioridad 3 */
MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK47; /* Timer
Channel 3 Desenmascarada */
*(void **)(0x20000000 +(64+47)*4) = (void *)IntGPTA3;

MEMORIA

Anexo I

//Confguracin interrupciones PIT0


MCF_INTC0_ICR55 = 0x08; /* Nivel 1 Prioridad 4 */
MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK55; /* Timer
Channel 0 Desenmascarada */
*(void **)(0x20000000 +(64+55)*4) = (void *)IntPIT0;
//Configuracin PIT0 para que salte con un periodo de
500us
MCF_PIT0_PCSR = 0x51B; //prescalado de 64, DOZE, HALTED
Y PIF =0, OVW, PIE, RLD, EN = 1.
MCF_PIT0_PMR = 512; // Carga 512 como valor en el
contador cada vez que llega a 0.
//Configuracin puerto A del GPIO como salidas
MCF_GPIO_DDRA = 0xFF;
}
void Control(void *pvParameters)
{
uint16 ref_vel, acel;
portTickType xLastWakeTime;
vSemaphoreCreateBinary(sem_AD);
xLastWakeTime=xTaskGetTickCount();
while(1)
{
vTaskDelayUntil(&xLastWakeTime,PER_CTRL);
ref_vel = CopiaRef();
if(xSemaphoreTake(sem_AD,(portTickType)
2000)==pdTRUE)
{
acel = LeeAN0;
xSemaphoreGive(sem_AD);
}
else{
//Timeout
}
if(acel<(SAT_AD/2-10))//Equivaldra a 2G menos un
error, puesto que el conversor AD da 1024 para 4G,
segn clculos del circuito de acondicionamiento.
{
ref_vel = ref_vel + INC_REF;
}
else if(acel>(SAT_AD/2))
{

MEMORIA
ref_vel = ref_vel - INC_REF;
}
CopiaEnRef(ref_vel);
}
}

Anexo I

void ADCTask(void *pvParameters)


{
while(1)
{
if(xSemaphoreTake(sem_AD,(portTickType)
2000)==pdTRUE)
{
ArrancaConversion();
While(Convirtiendo());
xSemaphoreGive(sem_AD);
}
else{
//Timeout
}
}
}
uint16 CopiaRef(void)
{
uint16 copia_referencia;
Disable(); //Inicio zona critica
copia_referencia = referencia_v;
Enable(); //Fin zona critica
return(copia_referencia);
}
void CopiaEnRef(uint16 ref)
{
Disable(); //Inicio zona critica
referencia_v = ref;
Enable(); //Fin zona critica
return();
}
int PI1(int referencia,int salida, int man_sat, int*
pe_ant, int* pIe_ant, int* pmando_ant)
{
int e_act, Ie_act;
int inc_mando, mando;
e_act = referencia-salida;

MEMORIA
Anexo I
Ie_act = *pIe_ant + (e_act + *pe_ant) * 3;
inc_mando = 3 * (((e_act-(*pe_ant))*16) + (((Ie_act(*pIe_ant))*3)/4)) * 3;
mando= *pmando_ant+inc_mando;
if(mando>=man_sat){
mando=man_sat;
}else if(mando<=(-man_sat)){
mando=-man_sat;
}
*pmando_ant = mando;
*pe_ant = e_act;
*pIe_ant = Ie_act;
return (mando);
}
int PI2(int referencia,int salida, int man_sat, int*
pe_ant, int* pIe_ant, int* pmando_ant)
{
int e_act, Ie_act;
int inc_mando, mando;
e_act = referencia - salida;
Ie_act = *pIe_ant + (e_act + *pe_ant);
inc_mando = ((3 * ((e_act-(*pe_ant) + ((Ie_act(*pIe_ant)))))) / 13) * 2;
mando= *pmando_ant+inc_mando;
if(mando>=man_sat){
mando=man_sat;
}else if(mando<=(-man_sat)){
mando=-man_sat;
}
*pmando_ant = mando;
*pe_ant = e_act;
*pIe_ant = Ie_act;
return (mando);
}
/* Funciones para el manejo del Conversor A/D.
*
* El conversor A/D es bastante complejo. Dispone de
dos colas en las

MEMORIA
Anexo I
* que se pueden programar la realizacin de una serie
de conversiones
* automticas de una serie de canales, de forma que se
interrumpa al
* micro (o se active el bit de final de conversin si
usamos
* encuesta) cuando finalice la secuencia de
conversiones.
*
* En esta librera simple se usa una sola cola para
convertir los
* canales 0, 1, 2 y 3 (entradas AN0, AN1, AN2 y AN3).
La conversin se dispara por
* software escribiendo un 1 en el bit SSE (Single Scan
Enable) de la
* cola 1 (SSE1), que est en el registro QACR1. De
esto se encarga la
* funcin ArrancaConversion(). Por ltimo, el bit 15
del registro de
* estado de la cola QASR0 se pone a 1 cuando finaliza
la secuencia de
* conversiones. La funcin Convirtiendo() comprueba
este bit y
* devuelve un 1 si la conversin an est en marcha o
un cero si ha
* terminado.
*/
void QadcInit(void)
{
MCF_QADC_QADCMCR = 0; /* Arranca el mdulo del
conversor AD. Accesible
en modo usuario */
MCF_QADC_DDRQA = 0; /* los pines se definen como
entrada pues si por algo
estn configurados como
*/
MCF_QADC_DDRQB = 0; /* salida digital el conversor no
funcionar */
MCF_QADC_QACR0 = 7; /* Mux interno, divisin del
reloj por 16 para generar
ADCclk de 4 MHz
(suponiendo que el
micro funciona a 64 MHz
*/
MCF_QADC_QACR1 = 0x0100; /* Sin interrupciones,
disparado por software,
single scan*/

MEMORIA
Anexo I
MCF_QADC_QACR2 = 0x7f; /* No se usa la cola 2. BQ2 =
7f (>64) para
indicarlo) */
MCF_QADC_CCW(0) = 0; /* Primera conversin: AN0 */
MCF_QADC_CCW(1) = 1; /* Segunda conversin: AN1 */
MCF_QADC_CCW(2) = 2; /* Tercera conversin: AN2 */
MCF_QADC_CCW(3) = 3; /* Cuarta conversin: AN3 */
MCF_QADC_CCW(4) = 63; /* Fin de la cola */
vSemaphoreCreateBinary(sem_AD); //Crea el semforo
}
void ArrancaConversion(void)
{
MCF_QADC_QACR1 = 0x2100; /* Sin interrupciones,
disparado por software,
single scan. SSE =
1 para disparar la cola 1*/
}
int Convirtiendo()
{
if((MCF_QADC_QASR0&0x8000) == 0){
return 1; /* Est convirtiendo an */
}else{
return 0;
}
}
uint16 LeeAN0(void)
{
return MCF_QADC_RJURR(0);
}
uint16 LeeAN1(void)
{
return MCF_QADC_RJURR(1);
}
uint16 LeeAN2(void)
{
return MCF_QADC_RJURR(2);
}
uint16 LeeAN3(void)
{
return MCF_QADC_RJURR(3);
}

MEMORIA
__declspec(interrupt) IntGPTA0(void)
//Interrupcin: Deteccin baliza
{
MCF_GPTA_GPTFLG1|=(0x1<<0);//Baja el flag

Anexo I

//Si salta interrupcion, hay flanco de subida en GPTA0


-> baliza detecta tren
// Fija referencia a una velocidad moderada
referencia_velocidad = 0.6*SAT/(1.2); //mitad de la
velocidad punta.
}
__declspec(interrupt) IntPIT0(void)
//Interrupcin: Tiempo de muestreo
{
MCF_PIT0_PIF&=(0x1); // Clear flag by writting 1 to
it
medida_i = LeeAN3;
if(!(MCF_GPIO_SETA&1)) //La condicin se cumple si el
pin PA0 est a nivel bajo
medida_i = (!medida_i)+1; //Halla el opuesto del
valor de la medida
if(contador_interrupcion>=9)
{
contador_interrupcion=0;
if(MEDIR_VEL)
{
medida_v=LeeAN2; //Obtener medida de
velocidad a partir del estimador analgico;
}
else{
medida_v=(duty_cycle/100 *14 medida_i*35)/5.8; //Obtener medida de velocidad por
funcion transferencia.
}
referencia_i=PI1(referencia_velocidad,medida_v,
MAN_SAT1, &error_v, &Ierror_v, &mando_corriente);
}
duty_cycle=100/127*PI2(referencia_i, medida_i,
MAN_SAT2, &error_i, &Ierror_i, &mando_tension);
SetPWM(duty_cycle);
}

MEMORIA
/*Control.h
* Autor: Fernando Moreno
* ltima modificacin: 1/Jun/2010
*/

Anexo I

#ifndef Control_h
#define Control_h
#include "Constantes.h"
/* Funcin: InitControl
*
* Inicializa las interrupciones en el puerto GPTA,
para
* que salte una interrupcin con la deteccin de una
baliza.
* y configura el PIT0 y el GPIO.
* Versin: 0.0
*/
void InitControl(void);
/* Funcin: ADCTask
*
* Tarea que realiza las conversiones A/D,
* controlada por el planificador.
*
* Versin: 0.0
*/
void ADCTask(void *pvParameters)
/* Funcin: Control
*
* Tarea que realiza el control de la referencia de
velocidad cada 20ms
*
* Versin: 0.0
*/
void Control(void *pvParameters);
/* Funcin: CopiaRef
*
* Copia la referencia de velocidad
*
* Versin: 0.0
*/
uint16 CopiaRef(void);
/* Funcin: CopiaEnRef
*

MEMORIA
Anexo I
* Copia la referencia de velocidad calculada en la
tarea de Control.
*
* Versin: 0.0
*/
uint16 CopiaEnRef(void);
/* Funcin: PI1
*
* Realiza un control PI incremental en tiempo discreto
a partir
* de los parmetros de entrada
*
* Versin: 0.0
*/
int PI1(int referencia,int salida, int* pe_ant, int*
pIe_ant, int K, int Ti);
/* Funcin: PI2
*
* Realiza un control PI incremental en tiempo discreto
a partir
* de los parmetros de entrada
*
* Versin: 0.0
*/
int PI2(int referencia,int salida, int* pe_ant, int*
pIe_ant, int K, int Ti);
/*Funciones para el manejo del conversor AD*/
/* Funcin: QadcInit
*
* Inicializa en conversor AD para medir las entradas
AN0, AN1, AN2 y AN3. El final de
* la conversin se realizar por encuesta mediante la
funcin Convirtiendo().
*
* Versin: 0.0
*/
void QadcInit(void);
/* Funcin: ArrancaConversion
*
* Arranca una conversin. Se convertirn los canales
* AN0, AN1, AN2 y AN3.
*
* Versin: 0.0
*/

MEMORIA
void ArrancaConversion(void);

Anexo I

/* Funcin: Convirtiendo
*
* Consulta el registro de estado del conversor A/D y
devuelve un 1 si se est
* realizando la conversin o un cero si sta ha
terminado.
*
* Versin: 0.0
*/
int Convirtiendo();
/* Funcin: LeeAN0
*
* Devuelve el resultado de la conversin A/D del canal
AN0
* El valor es de 10 bits, de forma que 0V se traducen
en el valor 0 y 3.3 V
* en 1023. Los bits 10 a 15 estarn siempre a 0.
*
* Versin: 0.0
*/
uint16 LeeAN0(void);
/* Funcin: LeeAN1
*
* Idem LeeAN0 pero para el canal AN1
*
* Versin: 0.0
*/
uint16 LeeAN1(void);
/* Funcin: LeeAN2
*
* Idem LeeAN0 pero para el canal AN2
*
* Versin: 0.0
*/
uint16 LeeAN2(void);
/* Funcin: LeeAN3
*
* Idem LeeAN0 pero para el canal AN3
*
* Versin: 0.0
*/
uint16 LeeAN3(void);

MEMORIA
/*Interrupciones*/

Anexo I

/* Interrupcin: IntGPTA0
*
* Interrupcin de deteccin de baliza
*
* Versin: 0.0
*/
__declspec(interrupt) IntGPTA0(void)
/* Interrupcin: IntPIT0
*
* Interrupcin para realizar el control cada tiempo de
muestreo.
*
* Versin: 0.0
*/
__declspec(interrupt) IntPIT0(void)
#endif

MEMORIA
Anexo I
/* Funciones para el manejo del conversor AD y el PWM
*/
#include "Configuracion.h"
/*Puerto salida PWM*/

/* Inicializacin del chip-select para la CPLD */


void InitM5282Lite_ES(void)
{
MCF_CS1_CSAR = 0x0100; /* Dir base */
MCF_CS1_CSMR = 0x00000001; /* Valid CS */
MCF_CS1_CSCR = 0x1140; /* 0 WaitStates, Auto ACK,
puerto 8 bit */
}

/* Funciones para el manejo del generador PWM*/


void InitPWM(void)
{
uint8 res_mitad;
res_mitad = PWM_RESOLUTION/2;
sim.gpt[GPT_NUM].scr1=0; /* Turn the timer system off
*/
sim.gpt[GPT_NUM].ios=0x0f; /* Turn on output compare
for all four channels */
sim.gpt[GPT_NUM].oc3m=0x07;/* Set up the condition for
ch 3 output compare */
sim.gpt[GPT_NUM].oc3d=0x07;/* Set up the condition for
ch 3 output compare */
sim.gpt[GPT_NUM].tov=0; /* No toggle on overflow */
sim.gpt[GPT_NUM].ctl1=0xAA; /* Set output to 0 on
output compare */
sim.gpt[GPT_NUM].ctl2=0x00; /* No input capture */
sim.gpt[GPT_NUM].scr2=0x09; /* Enable ch 3 reset with
sys clk prescale of 2 ->
con este preescalado y el PWM_RESOLUTION A 1000
conseguimos frecuencia = 32kHz*/
sim.gpt[GPT_NUM].tie=0x00; /* No interrupts */
sim.gpt[GPT_NUM].c0=res_mitad; /* Set up the initial
compare values */
sim.gpt[GPT_NUM].c3=PWM_RESOLUTION;

MEMORIA
Anexo I
sim.gpt[GPT_NUM].ddr=0x0F; /* Set all four channel pins
as outputs. */
sim.gpt[GPT_NUM].scr1=0x90; /* Enable the timer */
}

void SetPWM(uint8 PWM_duty_dycle)


{
sim.gpt[GPT_NUM].c0=(PWM_duty_dycle/100)*PWM_RESOLUTION
;
}

MEMORIA
Anexo I
/* Funciones para el manejo del conversor A/D y el
* modulador de ancho de pulso.
*
* Autor: Modificado: Fernando Moreno Prez
*
* Versin: 0.1
*/
#ifndef Configuracion_h
#define Configuracion_h
#include "Constantes.h"
/* Funcin: InitM5282Lite_ES
*
* Inicializa el generador de Chip Select del ColdFire
para direccionar la
* CPLD de la tarjeta M5282Lite-ES.
* Es necesario llamar a esta funcin antes de usar los
interruptores/LEDS
* o el teclado.
*
* Versin: 0.0
*/
void InitM5282Lite_ES(void);
/* Funciones para el manejo del generador PWM*/
/* Funcin: InitPWM
*
* Inicializa la seal PWM en el pin GPTA0 del
microprocesador, con
*un DUTY_CYCLE del 50%, y una resolucin igual al
parmetro
*definido como PWM_RESOLUTION (ha de ser 1000 para que
la
*frecuencia del PWM sea de 32kHz).
*
* Versin: 0.0
*/
void InitPWM(void)
/* Funcin: SetPWM
*
* Cambia el valor de comparacin del PWM por el
* valor del parmetro p0.
*
* Versin: 0.0
*/
void SetPWM(int p0)

MEMORIA
#endif

Anexo I

MEMORIA
/*Constantes.h
* Autor: Fernando Moreno
* ltima modificacin: 6/Jun/2010
*/
//Archivo .h que engloba todos
includes utilizados.

Anexo I

los

defines

los

#ifndef CONSTANTES_H
#define CONSTANTES_H
#include "mcf5282.h"
#include "M5282Lite-ES.h"
//Includes del kernel
#include
#include
#include
#include
#include

"FreeRTOS.h"
"semphr.h"
"task.h"
"queue.h"
"semphr.h"

//defines
#define
bits
#define
#define
#define
#define
#define

SAT
SAT_AD
MAN_SAT1
MAN_SAT2
MEDIR_VEL
INC_REF

32768

//16

1020 //10 bits


32768
32768
1
2

#define TAM_PILA 1024


#define PRIO_CONTROL 1
#define PRIO_ADCTASK 2
#define TRUE 1
#define FALSE 0
#define GPT_NUM 1 // 0 para GPTA, 1 para GPTB
#define PWM_RESOLUTION 1000
#define ACELN_MAX
4
//Gs
vienen dadas por el circuito de acondicionamiento
#define PER_CTRL
periodo de la tarea control sea 20 ms
#endi

->

8 //Para que el

ANEXO 2

Archivos .m utilizados en Matlab

Inicializacion_PWM_con_filtro.m
%Inicializacion Parametros Proyecto Control de Velocidad por
Microprocesador
s=tf('s');
% ----- SIN SIMULACION ----- %
%PARAMETROS NUMERICOS
Ke=5.8347;
Km=5.8347;
Kpot=14/3;
Ks=1;
Ki=1;
R=35;
%[ohm]
L=5.6662e-5 * R
%[H]
M=0.7;
%[kg]
D=0.6703;
tiempo_muestreo=550e-6; %dado por el micro
ts=tiempo_muestreo;
%PARAMETROS DE CONTROL
%PI1
K_pi1 = 0.65;
Ti_pi1 = 5.4;
b_pi1 = 1;
ts_pi1 = 10*tiempo_muestreo; %0.5e-3;
sat_sup_man_pi1 = 0.4; %0.4;
sat_inf_man_pi1 = -0.4; %-0.4;
%PI2
K_pi2 = 3920.5;
%OK
Ti_pi2 = 3.38e-3;
%OK
b_pi2 = 1;
%OK
ts_pi2 = tiempo_muestreo;
sat_sup_man_pi2 = 3; %1;
sat_inf_man_pi2 = -3; %-1;
OK=1

Page 1

ANEXO 3

Manual del microprocesador

Chapter 10
Interrupt Controller Modules
This section details the functionality for the MCF5282 interrupt controllers (INTC0, INTC1). The general
features of each of the interrupt controller include:
63 interrupt sources, organized as:
56 fully-programmable interrupt sources
7 fixed-level interrupt sources
Each of the 63 sources has a unique interrupt control register (ICRnx) to define the
software-assigned levels and priorities within the level
Unique vector number for each interrupt source
Ability to mask any individual interrupt source, plus global mask-all capability
Supports both hardware and software interrupt acknowledge cycles
Wake-up signal from low-power stop modes
The 56 fully-programmable and seven fixed-level interrupt sources for each of the two interrupt controllers
on the MCF5282 handle the complete set of interrupt sources from all of the modules on the device. This
section describes how the interrupt sources are mapped to the interrupt controller logic and how interrupts
are serviced.

10.1

68K/ColdFire Interrupt Architecture Overview

Before continuing with the specifics of the MCF5282 interrupt controllers, a brief review of the interrupt
architecture of the 68K/ColdFire family is appropriate.
The interrupt architecture of ColdFire is exactly the same as the M68000 family, where there is a 3-bit
encoded interrupt priority level sent from the interrupt controller to the core, providing 7 levels of interrupt
requests. Level 7 represents the highest priority interrupt level, while level 1 is the lowest priority. The
processor samples for active interrupt requests once per instruction by comparing the encoded priority
level against a 3-bit interrupt mask value (I) contained in bits 10:8 of the machines status register (SR). If
the priority level is greater than the SR[I] field at the sample point, the processor suspends normal
instruction execution and initiates interrupt exception processing. Level 7 interrupts are treated as
non-maskable and edge-sensitive within the processor, while levels 1-6 are treated as level-sensitive and
may be masked depending on the value of the SR[I] field. For correct operation, the ColdFire requires that,
once asserted, the interrupt source remain asserted until explicitly disabled by the interrupt service routine.
During the interrupt exception processing, the CPU enters supervisor mode, disables trace mode and then
fetches an 8-bit vector from the interrupt controller. This byte-sized operand fetch is known as the interrupt
acknowledge (IACK) cycle with the ColdFire implementation using a special encoding of the transfer type
and transfer modifier attributes to distinguish this data fetch from a normal memory access. The fetched
data provides an index into the exception vector table which contains 256 addresses, each pointing to the
beginning of a specific exception service routine. In particular, vectors 64 - 255 of the exception vector
table are reserved for user interrupt service routines. The first 64 exception vectors are reserved for the
processor to handle reset, error conditions (access, address), arithmetic faults, system calls, etc. Once the
interrupt vector number has been retrieved, the processor continues by creating a stack frame in memory.
For ColdFire, all exception stack frames are 2 longwords in length, and contain 32 bits of vector and status
register data, along with the 32-bit program counter value of the instruction that was interrupted (see
Section 2.6, Exception Stack Frame Definition for more information on the stack frame format). After
the exception stack frame is stored in memory, the processor accesses the 32-bit pointer from the exception
vector table using the vector number as the offset, and then jumps to that address to begin execution of the
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
Freescale Semiconductor

10-1

Interrupt Controller Modules

service routine. After the status register is stored in the exception stack frame, the SR[I] mask field is set
to the level of the interrupt being acknowledged, effectively masking that level and all lower values while
in the service routine. For many peripheral devices, the processing of the IACK cycle directly negates the
interrupt request, while other devices require that request to be explicitly negated during the processing of
the service routine.
For the MCF5282, the processing of the interrupt acknowledge cycle is fundamentally different than
previous 68K/ColdFire cores. In the new approach, all IACK cycles are directly handled by the interrupt
controller, so the requesting peripheral device is not accessed during the IACK. As a result, the interrupt
request must be explicitly cleared in the peripheral during the interrupt service routine. For more
information, see Section 10.1.1.3, Interrupt Vector Determination.
Unlike the M68000 family, all ColdFire processors guarantee that the first instruction of the service routine
is executed before sampling for interrupts is resumed. By making this initial instruction a load of the SR,
interrupts can be safely disabled, if required.
During the execution of the service routine, the appropriate actions must be performed on the peripheral
to negate the interrupt request.
For more information on exception processing, see the ColdFire Programmers Reference Manual at
http://www.freescale.com/coldfire.

10.1.1

Interrupt Controller Theory of Operation

To support the interrupt architecture of the 68K/ColdFire programming model, the combined 63 interrupt
sources are organized as 7 levels, with each level supporting up to 9 prioritized requests. Consider the
priority structure within a single interrupt level (from highest to lowest priority) as shown in Table 10-1.
Table 10-1. Interrupt Priority Within a Level
ICR[2:0]

Priority

Interrupt
Sources

111

7 (Highest)

8-63

110

8-63

101

8-63

100

8-63

Fixed Midpoint Priority

1-7

011

8-63

010

8-63

001

8-63

000

0 (Lowest)

8-63

The level and priority is fully programmable for all sources except interrupt sources 17. Interrupt source
17 (from the Edgeport module) are fixed at the corresponding levels midpoint priority. Thus, a maximum
of 8 fully-programmable interrupt sources are mapped into a single interrupt level. The fixed interrupt
source is hardwired to the given level, and represents the mid-point of the priority within the level. For the
fully-programmable interrupt sources, the 3-bit level and the 3-bit priority within the level are defined in
the 8-bit interrupt control register (ICRnx).
The operation of the interrupt controller can be broadly partitioned into three activities:
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
10-2

Freescale Semiconductor

68K/ColdFire Interrupt Architecture Overview

Recognition
Prioritization
Vector Determination during IACK

10.1.1.1

Interrupt Recognition

The interrupt controller continuously examines the request sources and the interrupt mask register to
determine if there are active requests. This is the recognition phase.

10.1.1.2

Interrupt Prioritization

As an active request is detected, it is translated into the programmed interrupt level, and the resulting 7-bit
decoded priority level (IRQ[7:1]) is driven out of the interrupt controller. The decoded priority levels from
all the interrupt controllers are logically summed together and the highest enabled interrupt request is then
encoded into a 3-bit priority level that is sent to the processor core during this prioritization phase.

10.1.1.3

Interrupt Vector Determination

Once the core has sampled for pending interrupts and begun interrupt exception processing, it generates
an interrupt acknowledge cycle (IACK). The IACK transfer is treated as a memory-mapped byte read by
the processor, and routed to the appropriate interrupt controller. Next, the interrupt controller extracts the
level being acknowledged from address bits[4:2], and then determines the highest priority interrupt request
active for that level, and returns the 8-bit interrupt vector for that request to complete the cycle. The 8-bit
interrupt vector is formed using the following algorithm:
For INTC0,

vector_number = 64 + interrupt source number

For INTC1,

vector_number = 128 + interrupt source number

Recall vector_numbers 0 - 63 are reserved for the ColdFire processor and its internal exceptions. Thus, the
following mapping of bit positions to vector numbers applies for the INTC0:
if interrupt source 1 is active and acknowledged,

then vector_number =

65

if interrupt source 2 is active and acknowledged,

then vector_number =

66

if interrupt source 8 is active and acknowledged,

then vector_number =

72

if interrupt source 9 is active and acknowledged,

then vector_number =

73

...

...
if interrupt source 62 is active and acknowledged,

then vector_number = 126

The net effect is a fixed mapping between the bit position within the source to the actual interrupt vector
number.
If there is no active interrupt source for the given level, a special spurious interrupt vector
(vector_number = 24) is returned and it is the responsibility of the service routine to handle this error
situation.
Note this protocol implies the interrupting peripheral is not accessed during the acknowledge cycle since
the interrupt controller completely services the acknowledge. This means the interrupt source must be
explicitly disabled in the interrupt service routine. This design provides unique vector capability for all
interrupt requests, regardless of the complexity of the peripheral device.
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
Freescale Semiconductor

10-3

Interrupt Controller Modules

Vector numbers 64-71, and 91-255 are unused.

10.2

Memory Map

The register programming model for the interrupt controllers is memory-mapped to a 256-byte space. In
the following discussion, there are a number of program-visible registers greater than 32 bits in size. For
these control fields, the physical register is partitioned into two 32-bit values: a register high (the upper
longword) and a register low (the lower longword). The nomenclature <reg_name>H and <reg_name>L
is used to reference these values.
The registers and their locations are defined in Table 10-3. The offsets listed start from the base address
for each interrupt controller. The base addresses for the interrupt controllers are listed below:
Table 10-2. Interrupt Controller Base Addresses
Interrupt Controller Number

Base Address

INTC0

IPSBAR + 0xC00

INTC1
Global IACK Registers
1

IPSBAR + 0xD00
Space1

IPSBAR + 0xF00

This address space only contains the SWIACK and L1ACK-L7IACK registers. See Section 10.3.7, Software
and Level n IACK Registers (SWIACKR, L1IACKL7IACK)" for more information

Table 10-3. Interrupt Controller Memory Map


Module Offset

Bits[31:24]

Bits[23:16]

Bits[15:8]

Bits[7:0]

0x00

Interrupt Pending Register High (IPRH), [63:32]

0x04

Interrupt Pending Register Low (IPRL), [31:1]

0x08

Interrupt Mask Register High (IMRH), [63:32]

0x0c

Interrupt Mask Register Low (IMRL), [31:0]

0x10

Interrupt Force Register High (INTFRCH), [63:32]

0x14

Interrupt Force Register Low (INTFRCL), [31:1]

0x18

IRLR[7:1]

IACKLPR[7:0]

0x1c - 0x3c

Reserved

Reserved

0x40

Reserved

ICR01

ICR02

ICR03

0x44

ICR04

ICR05

ICR06

ICR07

0x48

ICR08

ICR09

ICR10

ICR11

0x4c

ICR12

ICR13

ICR14

ICR15

0x50

ICR16

ICR17

ICR18

ICR19

0x54

ICR20

ICR21

ICR22

ICR23

0x58

ICR24

ICR25

ICR26

ICR27

0x5C

ICR28

ICR29

ICR30

ICR31

0x60

ICR32

ICR33

ICR34

ICR35

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


10-4

Freescale Semiconductor

Register Descriptions

Table 10-3. Interrupt Controller Memory Map (continued)


Module Offset

Bits[31:24]

Bits[23:16]

Bits[15:8]

Bits[7:0]

0x64

ICR36

ICR37

ICR38

ICR39

0x68

ICR40

ICR41

ICR42

ICR43

0x6C

ICR44

ICR45

ICR46

ICR47

0x70

ICR48

ICR49

ICR50

ICR51

0x74

ICR52

ICR53

ICR54

ICR55

0x78

ICR56

ICR57

ICR58

ICR59

0x7C

ICR60

ICR61

ICR62

ICR63

0x80-0xDC

10.3
10.3.1

Reserved

0xE0

SWIACK

Reserved

0xE4

L1IACK

Reserved

0xE8

L2IACK

Reserved

0xEC

L3IACK

Reserved

0xF0

L4IACK

Reserved

0xF4

L5IACK

Reserved

0xF8

L6IACK

Reserved

0xFC

L7IACK

Reserved

Register Descriptions
Interrupt Pending Registers (IPRHn, IPRLn)

The IPRHn and IPRLn registers, Figure 10-1 and Figure 10-2, are each 32 bits in size, and provide a bit
map for each interrupt request to indicate if there is an active request (1 = active request, 0 = no request)
for the given source. The state of the interrupt mask register does not affect the IPRn. The IPRn is cleared
by reset. The IPRn is a read-only register, so any attempted write to this register is ignored. Bit 0 is not
implemented and reads as a zero.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

10-5

Chapter 19
Programmable Interrupt Timer Modules (PIT0PIT3)
19.1

Overview

The programmable interrupt timer (PIT) is a 16-bit timer that provides precise interrupts at regular
intervals with minimal processor intervention. The timer can either count down from the value written in
the modulus register, or it can be a free-running down-counter. This device has four programmable
interrupt timers, PIT0PIT3.

19.2

Block Diagram
IPBUS

System
Clock

Divide
by 2

16-bit PCNTR

Prescaler

COUNT = 0

16-bit PIT Counter

PIF

Load
Counter
EN
PRE[3:0]

To Interrupt
Controller

PIE

OVW

RLD

DOZE
HALTED

16-bit PMR

IPBUS

Figure 19-1. PIT Block Diagram

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

19-1

Programmable Interrupt Timer Modules (PIT0PIT3)

19.3

Low-Power Mode Operation

This subsection describes the operation of the PIT modules in low-power modes and halted mode of
operation. Low-power modes are described in the Power Management Module. Table 19-1 shows the PIT
module operation in low-power modes, and how it can exit from each mode.
NOTE
The low-power interrupt control register (LPICR) in the System Control
Module specifies the interrupt level at or above which the device can be
brought out of a low-power mode.
Table 19-1. PIT Module Operation in Low-power Modes
Low-power Mode

PIT Operation

Mode Exit

Wait

Normal if PCR[WAIT] cleared,


stopped otherwise

Any IRQx Interrupt at or above level in LPICR

Doze

Normal if PCR[DOZE] cleared,


stopped otherwise

Any IRQx Interrupt at or above level in LPICR

Stop

Stopped

Halted

Normal if PCR[HALTED] cleared,


stopped otherwise

No
No. Any IRQx Interrupt will be serviced upon
normal exit from halted mode

In wait mode, the PIT module continues to operate as in run mode and can be configured to exit the
low-power mode by generating an interrupt request. In doze mode with the PCSR[DOZE] bit set, PIT
module operation stops. In doze mode with the PCSR[DOZE] bit cleared, doze mode does not affect PIT
operation. When doze mode is exited, the PIT continues to operate in the state it was in prior to doze mode.
In stop mode, the system clock is absent, and PIT module operation stops.
In halted mode with the PCSR[HALTED] bit set, PIT module operation stops. In halted mode with the
PCSR[HALTED] bit cleared, halted mode does not affect PIT operation. When halted mode is exited, the
PIT continues to operate in its pre-halted mode state, but any updates made in halted mode remain.

19.4

Signals

The PIT module has no off-chip signals.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


19-2

Freescale Semiconductor

Memory Map and Registers

19.5

Memory Map and Registers

This subsection describes the memory map and register structure for PIT0PIT3.

19.5.1

Memory Map

Refer to Table 19-2 for a description of the memory map.


This device has four programmable interrupt timers with the following IPSBAR offset for base address
locations for each timer.
PIT0: 0x0015_0000
PIT1: 0x0016_0000
PIT2: 0x0017_0000
PIT3: 0x0018_0000
Table 19-2. Programmable Interrupt Timer Modules Memory Map
IPSBAR Offset
for PITx
Address

Bits 158

Bits 70

Access1

0x001x_0000

PIT Control and Status Register (PCSR)

0x001x_0002

PIT Modulus Register (PMR)

0x001x_0004

PIT Count Register (PCNTR)

S/U

0x001x_0006

Unimplemented2

S = CPU supervisor mode access only. S/U = CPU supervisor or user mode access. User mode accesses
to supervisor only addresses have no effect and result in a cycle termination transfer error.
2 Accesses to unimplemented address locations have no effect and result in a cycle termination transfer error.

19.5.2

Registers

The PIT programming model consists of these registers:


The PIT control and status register (PCSR) configures the timers operation.
The PIT modulus register (PMR) determines the timer modulus reload value.
The PIT count register (PCNTR) provides visibility to the counter value.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

19-3

Programmable Interrupt Timer Modules (PIT0PIT3)

19.5.2.1

PIT Control and Status Register (PCSR)


15

12

Field

Reset

Address

PRE3

PRE2

PRE1

PRE0

R/W

DOZE

HALTED

OVW

PIE

PIF

RLD

EN

Reset
R/W

10

0000_0000

R/W

Field

11

0000_0000
R

R/W

IPSBAR + 0x0015_0000 and 0x0015_0001 (PIT0); 0x0016_0000 and 0x0016_0001 (PIT1);


0x0017_0000 and 0x0017_0001 (PIT2); 0x0018_0000 and 0x0018_0001 (PIT3)

Figure 19-2. PIT Control and Status Register (PCSR)


Table 19-3. PCSR Field Descriptions
Bit(s)

Name

1512

118

PRE

Description
Reserved, should be cleared.
Prescaler. The read/write prescaler bits select the system clock divisor to generate the
PIT clock. To accurately predict the timing of the next count, change the PRE[3:0] bits
only when the enable bit (EN) is clear. Changing the PRE[3:0] resets the prescaler
counter. System reset and the loading of a new value into the counter also reset the
prescaler counter. Setting the EN bit and writing to PRE[3:0] can be done in this same
write cycle. Clearing the EN bit stops the prescaler counter.

PRE

System Clock Divisor

PRE

System Clock Divisor

0000

1000

512

0001

1001

1,024

0010

1010

2,048

0011

16

1011

4,096

0100

32

1100

8,192

0101

64

1101

16,384

0110

128

1110

32,768

0111

256

1111

65,536

Reserved.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


19-4

Freescale Semiconductor

Memory Map and Registers

Table 19-3. PCSR Field Descriptions (continued)


Bit(s)

Name

Description

DOZE

Doze mode bit. The read/write DOZE bit controls the function of the PIT in doze mode.
Reset clears DOZE.
0 PIT function not affected in doze mode
1 PIT function stopped in doze mode
When doze mode is exited, timer operation continues from the state it was in before
entering doze mode.

HALTED

Halted mode bit. Controls the function of the PIT in halted mode. Reset clears
HALTED. During halted mode, register read and write accesses function normally.
When halted mode is exited, timer operation continues from the state it was in before
entering halted mode, but any updates made in halted mode remain.
0 PIT function not affected in halted mode
1 PIT function stopped in halted mode
Note: Changing the HALTED bit from 1 to 0 during halted mode starts the PIT timer.
Likewise, changing the HALTED bit from 0 to 1 during halted mode stops the PIT timer.

OVW

Overwrite. Enables writing to PMR to immediately overwrite the value in the PIT
counter.
0 Value in PMR replaces value in PIT counter when count reaches 0x0000.
1 Writing PMR immediately replaces value in PIT counter.

PIE

PIT interrupt enable. This read/write bit enables the PIF flag to generate interrupt
requests.
0 PIF interrupt requests disabled
1 PIF interrupt requests enabled

PIF

PIT interrupt flag. This read/write bit is set when the PIT counter reaches 0x0000.
Clear PIF by writing a 1 to it or by writing to PMR. Writing 0 has no effect. Reset clears
PIF.
0 PIT count has not reached 0x0000.
1 PIT count has reached 0x0000.

RLD

Reload bit. The read/write reload bit enables loading the value of PMR into the PIT
counter when the count reaches 0x0000.
0 Counter rolls over to 0xFFFF on count of 0x0000
1 Counter reloaded from PMR on count of 0x0000

EN

19.5.2.2

PIT enable bit. Enables PIT operation. When the PIT is disabled, the counter and
prescaler are held in a stopped state. This bit is read anytime, write anytime.
0 PIT disabled
1 PIT enabled

PIT Modulus Register (PMR)

The 16-bit read/write PMR contains the timer modulus value that is loaded into the PIT counter when the
count reaches 0x0000 and the PCSR[RLD] bit is set.
When the PCSR[OVW] bit is set, PMR is transparent, and the value written to PMR is immediately loaded
into the PIT counter. The prescaler counter is reset anytime a new value is loaded into the PIT counter and
also during reset. Reading the PMR returns the value written in the modulus latch. Reset initializes PMR
to 0xFFFF.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

19-5

Programmable Interrupt Timer Modules (PIT0PIT3)

Field

15

14

13

12

11

10

PM15

PM14

PM13

PM12

PM11

PM10

PM9

PM8

Reset

1111_1111

R/W

Field

R/W
7

PM7

PM6

PM5

PM4

PM3

PM2

PM1

PM0

Reset

1111_1111

R/W

R/W

Address IPSBAR + 0x0015_0002 and 0x0015_0003 (PIT0); 0x0016_0002 and 0x0016_0003 (PIT1);
0x0017_0002 and 0x0017_0003 (PIT2); 0x0018_0002 and 0x0018_0003 (PIT3)

Figure 19-3. PIT Modulus Register (PMR)

19.5.2.3

PIT Count Register (PCNTR)

The 16-bit, read-only PCNTR contains the counter value. Reading the 16-bit counter with two 8-bit reads
is not guaranteed to be coherent. Writing to PCNTR has no effect, and write cycles are terminated
normally.

Field

15

14

13

12

11

10

PC15

PC14

PC13

PC12

PC11

PC10

PC9

PC8

Reset

1111_1111

R/W

Field

R
7

PC7

PC6

PC5

PC4

PC3

PC2

PC1

PC0

Reset

1111_1111

R/W
Address

R
IPSBAR + 0x0015_0004 and 0x0015_0005 (PIT0), 0x0016_0004 and 0x0016_0005 (PIT1),
0x0017_0004 and 0x0017_0005 (PIT2), 0x0018_0004 and 0x0018_0005 (PIT3)

Figure 19-4. PIT Count Register (PCNTR)

19.6

Functional Description

This subsection describes the PIT functional operation.

19.6.1

Set-and-Forget Timer Operation

This mode of operation is selected when the RLD bit in the PCSR register is set.
When the PIT counter reaches a count of 0x0000, the PIF flag is set in PCSR. The value in the modulus
register is loaded into the counter, and the counter begins decrementing toward 0x0000. If the PIE bit is
set in PCSR, the PIF flag issues an interrupt request to the CPU.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


19-6

Freescale Semiconductor

Interrupt Operation

When the OVW bit is set in PCSR, the counter can be directly initialized by writing to PMR without
having to wait for the count to reach 0x0000.

PIT CLOCK
COUNTER

0x0002

0x0001

MODULUS

0x0000

0x0005

0x0005

PIF

Figure 19-5. Counter Reloading from the Modulus Latch

19.6.2

Free-Running Timer Operation

This mode of operation is selected when the RLD bit in PCSR is clear. In this mode, the counter rolls over
from 0x0000 to 0xFFFF without reloading from the modulus latch and continues to decrement.
When the counter reaches a count of 0x0000, the PIF flag is set in PCSR. If the PIE bit is set in PCSR, the
PIF flag issues an interrupt request to the CPU.
When the OVW bit is set in PCSR, the counter can be directly initialized by writing to PMR without
having to wait for the count to reach 0x0000.

PIT CLOCK
COUNTER

0x0002

0x0001

MODULUS

0x0000

0xFFFF

0x0005

PIF

Figure 19-6. Counter in Free-Running Mode

19.6.3

Timeout Specifications

The 16-bit PIT counter and prescaler supports different timeout periods. The prescaler divides the system
clock as selected by the PRE[3:0] bits in PCSR. The PM[15:0] bits in PMR select the timeout period.

PRE[3:0] (PM[15:0] + 1) 2
Timeout period = --------------------------------------------------------------------------system clock

19.7

Interrupt Operation

Table 19-4 shows the interrupt request generated by the PIT.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

19-7

Programmable Interrupt Timer Modules (PIT0PIT3)

Table 19-4. PIT Interrupt Requests


Interrupt Request

Flag

Enable Bit

Timeout

PIF

PIE

The PIF flag is set when the PIT counter reaches 0x0000. The PIE bit enables the PIF flag to generate
interrupt requests. Clear PIF by writing a 1 to it or by writing to the PMR.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


19-8

Freescale Semiconductor

Chapter 20
General Purpose Timer Modules
(GPTA and GPTB)
The MCF5282 has two 4-channel general purpose timer modules (GPTA and GPTB). Each consists of a
16-bit counter driven by a 7-stage programmable prescaler.
A timer overflow function allows software to extend the timing capability of the system beyond the 16-bit
range of the counter. Each of the four timer channels can be configured for input capture, which can
capture the time of a selected transition edge, or for output compare, which can generate output waveforms
and timer software delays. These functions allow simultaneous input waveform measurements and output
waveform generation.
Additionally, one of the channels, channel 3, can be configured as a 16-bit pulse accumulator that can
operate as a simple event counter or as a gated time accumulator. The pulse accumulator uses the GPT
channel 3 input/output pin in either event mode or gated time accumulation mode.

20.1

Features

Features of the general-purpose timer include:


Four 16-bit input capture/output compare channels
16-bit architecture
Programmable prescaler
Pulse widths variable from microseconds to seconds
Single 16-bit pulse accumulator
Toggle-on-overflow feature for pulse-width modulator (PWM) generation
External timer clock input (SYNCA/SYNCB)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

20-1

General Purpose Timer Modules (GPTA and GPTB)

20.2

Block Diagram
CLK[1:0]
System
Clock

SYNCx
Pin

PR[2:0]
PACLK
PACLK/256
PACLK/65536

Divide
by 2

MUX

Channel 3 Output Compare

Prescaler

TCRE
CxI

GPTCNTH:GPTCNTL

CxF
Clear Counter
16-Bit Counter

TOF

Interrupt
Logic

TOI

TE

Interrupt
Request

Channel 0
16-Bit Comparator

Edge
Detect

C0F

IOS0

CH. 0 Capture
PT0
LOGIC

GPTC0H:GPTC0L
16-Bit Latch

EDG0A

OM:OL0

EDG0B

TOV0

CH. 0 Compare

GPTx0
Pin

CHANNEL 1
16-Bit Comparator

Edge
Detect

C1F

IOS1

CH. 1 Capture

GPTC1H:GPTC1L
16-Bit Latch

EDG1A

OM:OL1

EDG1B

TOV1

PT1
LOGIC

CH. 1 Compare

GPTx1
Pin

Channel 2
Channel3
16-Bit Comparator

Edge
Detect

C3F

IOS3
PT3
LOGIC

GPTC3H:GPTC3L
16-Bit Latch

EDG3A

OM:OL3

EDG3B

TOV3
PEDGE

PAOVF

GPTPACNTH:GPTPACNTL

PACLK/256
Interrupt
Request

Interrupt
Logic

GPTx3
Pin

PAIF

MUX
PACLK

CH. 3 Compare

EDGE
DETECT

PAE

16-Bit Counter

PACLK/65536

CH.3 Capture
PA Input

Divide-by-64

Divide
by 2

System
Clock

PAMOD

PAOVI

PAI

PAOVF

PAIF

Figure 20-1. GPT Block Diagram

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


20-2

Freescale Semiconductor

Low-Power Mode Operation

20.3

Low-Power Mode Operation

This subsection describes the operation of the general purpose time module in low-power modes and
halted mode of operation. Low-power modes are described in the Power Management Module. Table 3-1
shows the general purpose timer module operation in the low-power modes, and shows how this module
may facilitate exit from each mode.
Table 20-1. Watchdog Module Operation in Low-power Modes
Low-power Mode

Watchdog Operation

Mode Exit

Wait

Normal

No

Doze

Normal

No

Stop

Stopped

No

Halted

Normal

No

General purpose timer operation stops in stop mode. When stop mode is exited, the general purpose timer
continues to operate in its pre-stop mode state.

20.4

Signal Description

Table 20-2 provides an overview of the signal properties.


NOTE
Throughout this section, an n in the pin name, as in GPTn0, designates
GPTA or GPTB.
Table 20-2. Signal Properties

20.4.1

Pin
Name

GPTPORT
Register Bit

GPTn0

PORTTn0

GPTn1

Function

Reset State

Pull-up

GPTn channel 0 IC/OC pin

Input

Active

PORTTn1

GPTn channel 1 IC/OC pin

Input

Active

GPTn2

PORTTn2

GPTn channel 2 IC/OC pin

Input

Active

GPTn3

PORTTn3

GPTn channel 3 IC/OC or PA pin

Input

Active

SYNCn

PORTE[3:0]1

GPTn counter synchronization

Input

Active

SYNCA is available on either PORTE3 or PORTE1; SYNCB is available on either PORTE2 or


PORTE0.

GPTn[2:0]

The GPTn[2:0] pins are for channel 20 input capture and output compare functions. These pins are
available for general-purpose input/output (I/O) when not configured for timer functions.

20.4.2

GPTn3

The GPTn3 pin is for channel 3 input capture and output compare functions or for the pulse accumulator
input. This pin is available for general-purpose I/O when not configured for timer functions.
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
Freescale Semiconductor

20-3

General Purpose Timer Modules (GPTA and GPTB)

20.4.3

SYNCn

The SYNCn pin is for synchronization of the timer counter. It can be used to synchronize the counter with
externally-timed or clocked events. A high signal on this pin clears the counter.

20.5

Memory Map and Registers

See Table 20-3 for a memory map of the two GPT modules. GPTA has a base address of IPSBAR +
0x1A_0000. GPTB has a base address of IPSBAR + 0x1B_0000.
NOTE
Reading reserved or unimplemented locations returns zeroes. Writing to
reserved or unimplemented locations has no effect.
Table 20-3. GPT Modules Memory Map
IPSBAR Offset
Bits 70

Access1

GPTA

GPTB

0x1A_0000

0x1B_0000

GPT IC/OC Select Register (GPTIOS)

0x1A_0001

0x1B_0001

GPT Compare Force Register (GPTCFORC)

0x1A_0002

0x1B_0002

GPT Output Compare 3 Mask Register (GPTOC3M)

0x1A_0003

0x1B_0003

GPT Output Compare 3 Data Register (GPTOC3D)

0x1A_0004

0x1B_0004

GPT Counter Register (GPTCNT)

0x1A_0006

0x1B_0006

GPT System Control Register 1 (GPTSCR1)

0x1A_0007

0x1B_0007

Reserved2

0x1A_0008

0x1B_0008

GPT Toggle-on-Overflow Register (GPTTOV)

0x1A_0009

0x1B_0009

GPT Control Register 1 (GPTCTL1)

0x1A_000A

0x1B_000a

Reserved(2)

0x1A_000B

0x1B_000b

GPT Control Register 2 (GPTCTL2)

0x1A_000C

0x1B_000c

GPT Interrupt Enable Register (GPTIE)

0x1A_000D

0x1B_000d

GPT System Control Register 2 (GPTSCR2)

0x1A_000E

0x1B_000e

GPT Flag Register 1 (GPTFLG1)

0x1A_000F

0x1B_000f

GPT Flag Register 2 (GPTFLG2)

0x1A_0010

0x1B_0010

GPT Channel 0 Register High (GPTC0H)

0x1A_0011

0x1Bb_0011

GPT Channel 0 Register Low (GPTC0L)

0x1A_0012

0x1B_0012

GPT Channel 1 Register High (GPTC1H)

0x1A_0013

0x1B_0013

GPT Channel 1 Register Low (GPTC1L)

0x1A_0014

0x1B_0014

GPT Channel 2 Register High (GPTC2H)

0x1A_0015

0x1B_0015

GPT Channel 2 Register Low (GPTC2L)

0x1A_0016

0x1B_0016

GPT Channel 3 Register High (GPTC3H)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


20-4

Freescale Semiconductor

Memory Map and Registers

Table 20-3. GPT Modules Memory Map (continued)


IPSBAR Offset

1
2

Bits 70

Access1

GPTA

GPTB

0x1A_0017

0x1B_0017

GPT Channel 3 Register Low (GPTC3L)

0x1A_0018

0x1B_0018

Pulse Accumulator Control Register (GPTPACTL)

0x1A_0019

0x1B_0019

Pulse Accumulator Flag Register (GPTPAFLG)

0x1A_001A

0x1B_001A

Pulse Accumulator Counter Register High (GPTPACNTH)

0x1A_001B

0x1B_001B

Pulse Accumulator Counter Register Low (GPTPACNTL)

(2)

0x1A_001C

0x1B_001C

Reserved

0x1A_001D

0x1B_001D

GPT Port Data Register (GPTPORT)

0x1A_001E

0x1B_001E

GPT Port Data Direction Register (GPTDDR)

0x1A_001F

0x1B_001F

GPT Test Register (GPTTST)

S = CPU supervisor mode access only.


Writes have no effect, reads return 0s, and the access terminates without a transfer error exception.

20.5.1

GPT Input Capture/Output Compare Select Register (GPTIOS)


7

Field
Reset

IOS
0000_0000

R/W
Address

R/W
IPSBAR + 0x401A_0000, 0x401B_0000

Figure 20-2. GPT Input Capture/Output Compare Select Register (GPTIOS)


Table 20-4. GPTIOS Field Descriptions
Bit(s)

Name

74

30

IOS

Description
Reserved, should be cleared.
I/O select. The IOS[3:0] bits enable input capture or output compare operation for the
corresponding timer channels. These bits are read anytime (always read 0x00), write
anytime.
1 Output compare enabled
0 Input capture enabled

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

20-5

General Purpose Timer Modules (GPTA and GPTB)

20.5.2

GPT Compare Force Register (GPCFORC)


7

Field

Reset

FOC
0000_0000

R/W

R/W

Address

IPSBAR + 0x1A_00001, 0x1B_0001

Figure 20-3. GPT Input Compare Force Register (GPCFORC)


Table 20-5. GPTCFORC Field Descriptions
Bit(s)

Name

74

30

FOC

Description
Reserved, should be cleared.
Force output compare.Setting an FOC bit causes an immediate output compare on
the corresponding channel. Forcing an output compare does not set the output
compare flag. These bits are read anytime, write anytime.
1 Force output compare
0 No effect

NOTE
A successful channel 3 output compare overrides any compare on channels
2:0. For each OC3M bit that is set, the output compare action reflects the
corresponding OC3D bit.

20.5.3

GPT Output Compare 3 Mask Register (GPTOC3M)


7

Field
Reset
R/W
Address

OC3M
0000_0000
R/W
IPSBAR + 0x1A_0002, 0x1B_0002

Figure 20-4. GPT Output Compare 3 Mask Register (GPTOC3M)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


20-6

Freescale Semiconductor

Memory Map and Registers

Table 20-6. GPTOC3M Field Descriptions


Bit(s)

Name

74

30

OC3M

20.5.4

Description
Reserved, should be cleared.
Output compare 3 mask. Setting an OC3M bit configures the corresponding PORTTn
pin to be an output. OC3Mn makes the GPT port pin an output regardless of the data
direction bit when the pin is configured for output compare (IOSx = 1). The OC3Mn
bits do not change the state of the PORTTnDDR bits. These bits are read anytime,
write anytime.
1 Corresponding PORTTn pin configured as output
0 No effect

GPT Output Compare 3 Data Register (GPTOC3D)


7

Field

Reset

OC3D
0000_0000

R/W

R/W

Address

IPSBAR + 0x1A_0003, 0x1B_0003

Figure 20-5. GPT Output Compare 3 Data Register (GPTOC3D)


Table 20-7. GPTOC3D Field Descriptions
Bit(s)

Name

74

30

OC3D

Description
Reserved, should be cleared.
Output compare 3 data. When a successful channel 3 output compare occurs, these
bits transfer to the PORTTn data register if the corresponding OC3Mn bits are set.
These bits are read anytime, write anytime.

NOTE
A successful channel 3 output compare overrides any channel 2:0 compares.
For each OC3M bit that is set, the output compare action reflects the
corresponding OC3D bit.

20.5.5

GPT Counter Register (GPTCNT)


15

Field

CNTR

Reset

0000_0000_0000_0000

R/W
Address

Read only
IPSBAR + 0x1A_0004, 0x1B_0004

Figure 20-6. GPT Counter Register (GPTCNT)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

20-7

General Purpose Timer Modules (GPTA and GPTB)

Table 20-8. GPTCNT Field Descriptions


Bit(s)

Name

Description

150

CNTR

Read-only field that provides the current count of the timer counter. To ensure
coherent reading of the timer counter, such that a timer rollover does not occur
between two back-to-back 8-bit reads, it is recommended that only word (16-bit)
accesses be used.
A write to GPTCNT may have an extra cycle on the first count because the write is not
synchronized with the prescaler clock. The write occurs at least one cycle before the
synchronization of the prescaler clock.
These bits are read anytime. They should be written to only in test (special) mode;
writing to them has no effect in normal modes.

20.5.6

GPT System Control Register 1 (GPTSCR1)


7

Field

GPTEN

Reset

TFFCA

0000_0000

R/W
Address

R/W
IPSBAR + 0x1A_0006, 0x1B_0006

Figure 20-7. GPT System Control Register 1 (GPTSCR1)


Table 20-9. GPTSCR1 Field Descriptions
Bit(s)

Name

Description

GPTEN

Enables the general purpose timer. When the timer is disabled, only the registers are
accessible. Clearing GPTEN reduces power consumption. These bits are read
anytime, write anytime.
1 GPT enabled
0 GPT and GPT counter disabled

65

TFFCA

30

Reserved, should be cleared.


Timer fast flag clear all. Enables fast clearing of the main timer interrupt flag registers
(GPTFLG1 and GPTFLG2) and the PA flag register (GPTPAFLG). TFFCA eliminates
the software overhead of a separate clear sequence. See Figure 20-8.
When TFFCA is set:
An input capture read or a write to an output compare channel clears the
corresponding channel flag, CxF.
Any access of the GPT count registers (GPTCNTH/L) clears the TOF flag.
Any access of the PA counter registers (GPTPACNT) clears both the PAOVF and
PAIF flags in GPTPAFLG.
Writing logic 1s to the flags clears them only when TFFCA is clear.
1 Fast flag clearing
0 Normal flag clearing
Reserved, should be cleared.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


20-8

Freescale Semiconductor

Memory Map and Registers

Write GPTFLG1 Register


Data Bit n
CnF
Clear
CnF Flag

TFFCA

Read GPTCn Registers


Write GPTCn Registers

Figure 20-8. Fast Clear Flag Logic

20.5.7

GPT Toggle-On-Overflow Register (GPTTOV)


7

Field

TOV

Reset

0000_0000

R/W

R/W

Address

IPSBAR + 0x1A_0008, 0x1B_0008

Figure 20-9. GPT Toggle-On-Overflow Register (GPTTOV)


Table 20-10. GPTTOV Field Description
Bit(s)

Name

74

30

TOV

20.5.8

Description
Reserved, should be cleared.
Toggles the output compare pin on overflow for each channel. This feature only takes
effect when in output compare mode. When set, it takes precedence over forced
output compare but not channel 3 override events. These bits are read anytime, write
anytime.
1 Toggle output compare pin on overflow feature enabled
0 Toggle output compare pin on overflow feature disabled

GPT Control Register 1 (GPTCTL1)

Field
Reset
R/W
Address

OM3

OL3

OM2

OL2

OM1

OL1

OM0

OL0

0000_0000
R/W
IPSBAR + 0x1A_0009, 0x1B_0009

Figure 20-10. GPT Control Register 1 (GPTCTL1)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

20-9

General Purpose Timer Modules (GPTA and GPTB)

Table 20-11. GPTCL1 Field Descriptions


Bit(s)

Name

Description

70

OMx/OLx

Output mode/output level. Selects the output action to be taken as a result of a


successful output compare on each channel. When either OMn or OLn is set and the
IOSn bit is set, the pin is an output regardless of the state of the corresponding DDR
bit. These bits are read anytime, write anytime.
00 GPT disconnected from output pin logic
01 Toggle OCn output line
10 Clear OCn output line
11 Set OCn line
Note: Channel 3 shares a pin with the pulse accumulator input pin. To use the PAI
input, clear both the OM3 and OL3 bits and clear the OC3M3 bit in the output compare
3 mask register.

20.5.9

GPT Control Register 2 (GPTCTL2)


7

Field

EDG3B

EDG3A EDG2B EDG2A EDG1B EDG1A EDG0B

Reset

EDG0A

0000_0000

R/W

R/W

Address

IPSBAR + 0x1A_000B, 0x1B_000B

Figure 20-11. GPT Control Register 2 (GPTCTL2)


Table 20-12. GPTLCTL2 Field Descriptions
Bit(s)

Name

70

EDGn[B:A]

Description
Input capture edge control. Configures the input capture edge detector circuits for
each channel. These bits are read anytime, write anytime.
00 Input capture disabled
01 Input capture on rising edges only
10 Input capture on falling edges only
11 Input capture on any edge (rising or falling)

20.5.10 GPT Interrupt Enable Register (GPTIE)


7

Field
Reset
R/W
Address

CI
0000_0000
R/W
IPSBAR + 0x1A_000C, 0x1B_000C

Figure 20-12. GPT Interrupt Enable Register (GPTIE)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


20-10

Freescale Semiconductor

Memory Map and Registers

Table 20-13. GPTIE Field Descriptions


Bit(s)

Name

Description

74

Reserved, should be cleared.

30

CnI

Channel interrupt enable. Enables the C[3:0]F flags in GPT flag register 1 to generate
interrupt requests for each channel. These bits are read anytime, write anytime.
1 Corresponding channel interrupt requests enabled
0 Corresponding channel interrupt requests disabled

20.5.11 GPT System Control Register 2 (GPTSCR2)

Field
Reset

TOI

PUPT

RDPT

TCRE

PR

0000_0000

R/W
Address

R/W
IPSBAR + 0x1A_000D, 0x1B_000D

Figure 20-13. GPT System Control Register 2 (GPTSCR2)


Table 20-14. GPTSCR2 Field Descriptions
Bit(s)

Name

Description

TOI

PUPT

Enables pull-up resistors on the GPT ports when the ports are configured as inputs.
1 Pull-up resistors enabled
0 Pull-up resistors disabled

RDPT

GPT drive reduction. Reduces the output driver size.


1 Output drive reduction enabled
0 Output drive reduction disabled

TCRE

Enables a counter reset after a channel 3 compare.


1 Counter reset enabled
0 Counter reset disabled
Note: When the GPT channel 3 registers contain 0x0000 and TCRE is set, the GPT
counter registers remain at 0x0000 all the time. When the GPT channel 3 registers
contain 0xFFFF and TCRE is set, TOF does not get set even though the GPT counter
registers go from 0xFFFF to 0x0000.

Enables timer overflow interrupt requests.


1 Overflow interrupt requests enabled
0 Overflow interrupt requests disabled
Reserved, should be cleared.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

20-11

General Purpose Timer Modules (GPTA and GPTB)

Table 20-14. GPTSCR2 Field Descriptions (continued)


Bit(s)

Name

Description

20

PRn

Prescaler bits. Select the prescaler divisor for the GPT counter.
000 Prescaler divisor 1
001 Prescaler divisor 2
010 Prescaler divisor 4
011 Prescaler divisor 8
100 Prescaler divisor 16
101 Prescaler divisor 32
110 Prescaler divisor 64
111 Prescaler divisor 128
Note: The newly selected prescaled clock does not take effect until the next
synchronized edge of the prescaled clock when the clock count transitions to 0x0000.)

20.5.12 GPT Flag Register 1 (GPTFLG1)


7

Field

CF

Reset

0000_0000

R/W

R/W

Address

IPSBAR + 0x1A_000E, 0x1B_000E

Figure 20-14. GPT Flag Register 1 (GPTFLG1)


Table 20-15. GPTFLG1 Field Descriptions
Bit(s)

Name

74

30

CnF

Description
Reserved, should be cleared.
Channel flags. A channel flag is set when an input capture or output compare event
occurs. These bits are read anytime, write anytime (writing 1 clears the flag, writing 0
has no effect).
Note: When the fast flag clear all bit, GPTSCR1[TFFCA], is set, an input capture read
or an output compare write clears the corresponding channel flag. When a channel
flag is set, it does not inhibit subsequent output compares or input captures.

20.5.13 GPT Flag Register 2 (GPTFLG2)


7

Field
Reset
R/W
Address

TOF

CF
0000_0000
R/W

IPSBAR + 0x1A_000F, 0x1B_000F

Figure 20-15. GPT Flag Register 2 (GPTFLG2)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


20-12

Freescale Semiconductor

Memory Map and Registers

Table 20-16. GPTFLG2 Field Descriptions


Bit(s)

Name

Description

TOF

Timer overflow flag. Set when the GPT counter rolls over from 0xFFFF to 0x0000. If
the TOI bit in GPTSCR2 is also set, TOF generates an interrupt request. This bit is
read anytime, write anytime (writing 1 clears the flag, and writing 0 has no effect).
1 Timer overflow
0 No timer overflow
Note: When the GPT channel 3 registers contain 0xFFFF and TCRE is set, TOF does
not get set even though the GPT counter registers go from 0xFFFF to 0x0000. When
TOF is set, it does not inhibit subsequent overflow events.

64

30

CnF

Reserved, should be cleared.


Channel flags. A channel flag is set when an input capture or output compare event
occurs. These bits are read anytime, write anytime (writing 1 clears the flag, writing 0
has no effect).

Note: When the fast flag clear all bit, GPTSCR1[TFFCA], is set, any access to the GPT counter registers clears GPT flag register
2.

20.5.14 GPT Channel Registers (GPTCn)


15

Field

CCNT

Reset

0000_0000_0000_0000

R/W

R/W

Address

IPSBAR + 0x1A_0010, 0x1A_0012, 0x1A_0014, 0x1A_0016,


0x1B_0010, 0x1B_0012, 0x1B_0014, 0x1B_0016

Figure 20-16. GPT Channel[0:3] Register (GPTCn)


Table 20-17. GPTCn Field Descriptions
Bit(s)

Name

Description

150

CCNT

When a channel is configured for input capture (IOSn = 0), the GPT channel registers
latch the value of the free-running counter when a defined transition occurs on the
corresponding input capture pin.
When a channel is configured for output compare (IOSn = 1), the GPT channel
registers contain the output compare value.
To ensure coherent reading of the GPT counter, such that a timer rollover does not
occur between back-to-back 8-bit reads, it is recommended that only word (16-bit)
accesses be used. These bits are read anytime, write anytime (for the output compare
channel); writing to the input capture channel has no effect.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

20-13

General Purpose Timer Modules (GPTA and GPTB)

20.5.15 Pulse Accumulator Control Register (GPTPACTL)

Field
Reset

PAE

PAMOD PEDGE

CLK

PAOVI

PAI

0000_0000

R/W

R/W

Address

IPSBAR + 0x1A_0018, 0x1B_0018

Figure 20-17. Pulse Accumulator Control Register (GPTPACTL)


Table 20-18. GPTPACTL Field Descriptions
Bit(s)

Name

Description

PAE

PAMOD

Pulse accumulator mode. Selects event counter mode or gated time accumulation
mode.
1 Gated time accumulation mode
0 Event counter mode

PEDGE

Pulse accumulator edge. Selects falling or rising edges on the PAI pin to increment the
counter.
In event counter mode (PAMOD = 0):
1 Rising PAI edge increments counter
0 Falling PAI edge increments counter
In gated time accumulation mode (PAMOD = 1):
1 Low PAI input enables divide-by-64 clock to pulse accumulator and trailing rising
edge on PAI sets PAIF flag.
0 High PAI input enables divide-by-64 clock to pulse accumulator and trailing falling
edge on PAI sets PAIF flag.
Note: The timer prescaler generates the divide-by-64 clock. If the timer is not active,
there is no divide-by-64 clock.
To operate in gated time accumulation mode:
1. Apply logic 0 to RSTI pin.
2. Initialize registers for pulse accumulator mode test.
3. Apply appropriate level to PAI pin.
4. Enable GPT.

32

CLK

Select the GPT counter input clock. Changing the CLK bits causes an immediate
change in the GPT counter clock input.
00 GPT prescaler clock (When PAE = 0, the GPT prescaler clock is always the GPT
counter clock.)
01 PACLK
10 PACLK/256
11 PACLK/65536

Reserved, should be cleared.


Enables the pulse accumulator.
1 Pulse accumulator enabled
0 Pulse accumulator disabled
Note: The pulse accumulator can operate in event mode even when the GPT enable
bit, GPTEN, is clear.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


20-14

Freescale Semiconductor

Chapter 28
Queued Analog-to-Digital Converter (QADC)
The queued analog-to-digital converter (QADC) is a 10-bit, unipolar, successive approximation converter.
Up to eight analog input channels can be supported using internal multiplexing. A maximum of 18 input
channels can be supported in the expanded, externally multiplexed mode.
The QADC consists of an analog front-end and a digital control subsystem. The analog section includes
input pins, an analog multiplexer, and sample and hold analog circuits.
The digital control section contains queue control logic to sequence the conversion process and interrupt
generation logic. Also included are the periodic/interval timer, control and status registers, the conversion
command word (CCW) table, random-access memory (RAM), and the result table RAM.
The bus interface unit (BIU) provides access to registers that configure the QADC, control the
analog-to-digital converter and queue mechanism, and present formatted conversion results.

28.1

Features

Features of the QADC module include:


Internal sample and hold
Up to eight analog input channels using internal multiplexing
Up to four external analog multiplexers directly supported
Up to 18 total input channels with internal and external multiplexing
Programmable input sample time for various source impedances
Two conversion command word (CCW) queues with a total of 64 entries for setting conversion
parameters of each A/D conversion
Subqueues possible using pause mechanism
Queue complete and pause interrupts available on both queues
Queue pointers indicating current location for each queue
Automated queue modes initiated by:
External edge trigger and gated trigger
Periodic/interval timer, within QADC module (queues 1 and 2)
Software command
Single scan or continuous scan of queues
64 result registers
Output data readable in three formats:
Right-justified unsigned
Left-justified signed
Left-justified unsigned
Unused analog channels can be used as discrete input/output pins.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-1

Queued Analog-to-Digital Converter (QADC)

28.2

Block Diagram
External
MUX Address

Analog Power
Inputs

8 Analog Channels
(18 with External MUXing)
Reference
Inputs

External
Triggers
Analog Input MUX
and Digital
Signal Functions

10-bit
Analog-to-Digital
Converter

Digital
Control

64-Entry Queue
of 10-bit
Conversion
Command Words
(CCWs)

64-Entry Table
of 10-bit
Results

10-bit to 16-bit
Result Alignment

IPBUS
Interface

Figure 28-1. QADC Block Diagram

28.3

Modes of Operation

This subsection describes the two modes of operation in which the QADC does not perform conversions
in a regular fashion:
Debug mode
Stop mode

28.3.1

Debug Mode

The QDBG bit in the module configuration register (QADCMCR) governs behavior of the QADC when
the CPU enters background debug mode. When QDBG is clear, the QADC operates normally and is
unaffected by CPU background debug mode. See Section 28.6.1, QADC Module Configuration Register
(QADCMCR).
When QDBG is set and the CPU enters background debug mode, the QADC finishes any conversion in
progress and then freezes. This is QADC debug mode. Depending on when debug mode is entered, the
three possible queue freeze scenarios are:
When a queue is not executing, the QADC freezes immediately.
When a queue is executing, the QADC completes the current conversion and then freezes.
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
28-2

Freescale Semiconductor

Signals

If during the execution of the current conversion, the queue operating mode for the active queue is
changed, or a queue 2 abort occurs, the QADC freezes immediately.

When the QADC enters debug mode while a queue is active, the current CCW location of the queue
pointer is saved.
Debug mode:
Stops the analog clock
Holds the periodic/interval timer in reset
Prevents external trigger events from being captured
Keeps all QADC registers and RAM accessible
Although the QADC saves a pointer to the next CCW in the current queue, software can force the QADC
to execute a different CCW by reconfiguring the QADC. When the QADC exits debug mode, it looks at
the queue operating modes, the current queue pointer, and any pending trigger events to decide which
CCW to execute.

28.3.2

Stop Mode

The QADC enters a low-power idle state whenever the QSTOP bit is set or the CPU enters low-power stop
mode.
QADC stop:
Disables the analog-to-digital converter, effectively turning off the analog circuit
Aborts the conversion sequence in progress
Makes the data direction register (DDRQA), port data registers (PORTQA and PORTQB), control
registers (QACR2, QACR1, and QACR0) and the status registers (QASR1 and QASR0) read-only.
Only the module configuration register (QADCMCR) remains writable.
Makes the RAM inaccessible, so that valid data cannot be read from RAM (result word table and
CCW) or written to RAM (result word table and CCW)
Resets QACR1, QACR2, QASR0, and QASR1
Holds the QADC periodic/interval timer in reset
Because the bias currents to the analog circuit are turned off in stop mode, the QADC requires some
recovery time (tSR) to stabilize the analog circuits.

28.4

Signals

The QADC uses the external signals shown in Figure 28-2. There are eight channel/port signals that can
support up to 18 channels when external multiplexing is used (including internal channels). All of the
channel signals also have some general-purpose input or input/output (GPIO) functionality. In addition,
there are also two analog reference signals and two analog submodule power signals.
The QADC has external trigger inputs and multiplexer outputs that are shared with some of the analog
input signals.

28.4.1

Port QA Signal Functions

The four port QA signals can be used as analog inputs or as a bidirectional 4-bit digital input/output port.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-3

Queued Analog-to-Digital Converter (QADC)

28.4.1.1

Port QA Analog Input Signals

When used as analog inputs, the four port QA signals are referred to as AN[56:55, 53:52].
Internal Digital Power
Shared with Other Modules

VSSI
VDDI

VSSA
Analog Power and Ground V
DDA

Port QA Analog Inputs


External Trigger Inputs
External MUX Address Outputs
Digital I/O

AN0/ANW/PQB0
AN1/ANX/PQB1
AN2/ANY/PQB2
AN3/ANZ/PQB3

Analog
Mux and
Port Logic

AN52/MA0/PQA0
AN53/MA1/PQA1
AN55/ETRIG1/PQA3
AN56/ETRIG2/PQA4

Analog
Converter

Digital
Results
and
Control

PORT QA

Port QB Analog Inputs


External MUX Inputs
Digital Inputs

VRH
VRL

PORT QB

Analog References

Figure 28-2. QADC Input and Output Signals

28.4.1.2

Port QA Digital Input/Output Signals

Port QA signals are referred to as PQA[4:3, 1:0] when used as a bidirectional 4-bit digital input/output
port. These four signals may be used for general-purpose digital input or digital output.
Port QA signals are connected to a digital input synchronizer during reads and may be used as
general-purpose digital inputs when the applied voltages meet high-voltage input (VIH) and low-voltage
input (VIL) requirements.
Each port QA signal is configured as an input or output by programming the port data direction register
(DDRQA). The digital input signal states are read from the port QA data register (PORTQA) when
DDRQA specifies that the signals are inputs. The digital data in PORTQA is driven onto the port QA
signals when the corresponding bits in DDRQA specify output. See Section 28.6.4, Port QA and QB Data
Direction Register (DDRQA & DDRQB).

28.4.2

Port QB Signal Functions

The four port QB signals can be used as analog inputs or as a 4-bit digital I/O port.

28.4.2.1

Port QB Analog Input Signals

When used as analog inputs, the four port QB signals are referred to as AN[3:0].

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-4

Freescale Semiconductor

Signals

28.4.2.2

Port QB Digital I/O Signals

Port QB signals are referred to as PQB[3:0] when used as a 4-bit digital input/output port. In addition to
functioning as analog input signals, the port QB signals are also connected to the input of a synchronizer
during reads and may be used as general-purpose digital inputs when the applied voltages meet VIH and
VIL requirements.
Each port QB signal is configured as an input or output by programming the port data direction register
(DDRQB). The digital input signal states are read from the port QB data register (PORTQB) when
DDRQB specifies that the signals are inputs. The digital data in PORTQB is driven onto the port QB
signals when the corresponding bits in DDRQB specify output. See Section 28.6.4, Port QA and QB Data
Direction Register (DDRQA & DDRQB).

28.4.3

External Trigger Input Signals

The QADC has two external trigger signals, ETRIG2 and ETRIG1. Each external trigger input is
associated with one of the scan queues, queue 1 or queue 2. The assignment of ETRIG[2:1] to a queue is
made by the TRG bit in QADC control register 0 (QACR0). When TRG = 0, ETRIG1 triggers queue 1 and
ETRIG2 triggers queue 2. When TRG = 1, ETRIG1 triggers queue 2 and ETRIG2 triggers queue 1. See
Section 28.6.5, Control Registers Control Registers.

28.4.4

Multiplexed Address Output Signals

In non-multiplexed mode, the QADC analog input signals are connected to an internal multiplexer which
routes the analog signals into the internal A/D converter.
In externally multiplexed mode, the QADC allows automatic channel selection through up to four external
4-to-1 multiplexer chips. The QADC provides a 2-bit multiplexed address output to the external
multiplexer chips to allow selection of one of four inputs. The multiplexed address output signals, MA1
and MA0, can be used as multiplexed address output bits or as general-purpose I/O when external
multiplexed mode is not being used.
MA[1:0] are used as the address inputs for up to four 4-channel multiplexer chips. Because the MA[1:0]
signals are digital outputs in multiplexed mode, the state of their corresponding data direction bits in
DDRQA is ignored.

28.4.5

Multiplexed Analog Input Signals

In external multiplexed mode, four of the port QB signals are redefined so that each represent four analog
input channels. See Table 28-1.
Table 28-1. Multiplexed Analog Input Channels
Multiplexed
Analog Input

Channels

ANW

Even numbered channels from 0 to 6

ANX

Odd numbered channels from 1 to 7

ANY

Even numbered channels from 16 to 22

ANZ

Odd numbered channels from 17 to 23

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-5

Queued Analog-to-Digital Converter (QADC)

28.4.6

Voltage Reference Signals

VRH and VRL are the dedicated input signals for the high and low reference voltages. Separating the
reference inputs from the power supply signals allows for additional external filtering, which increases
reference voltage precision and stability, and subsequently contributes to a higher degree of conversion
accuracy.
NOTE
VRH and VRL must be set to VDDA and VSSA potential, respectively. For
more information, refer to Section 28.9, Signal Connection
Considerations.

28.4.7

Dedicated Analog Supply Signals

The VDDA and VSSA signals supply power to the analog subsystems of the QADC module. Dedicated
power is required to isolate the sensitive analog circuitry from the normal levels of noise present on the
digital power supply.

28.4.8

Dedicated Digital I/O Port Supply Signal

VDDH provides 5-V power to the digital I/O functions of QADC port QA and port QB. This allows those
signals to tolerate 5 volts when configured as inputs and drive 5 volts when configured as outputs.

28.5

Memory Map

The QADC occupies 1 Kbyte, or 512 half-word (16-bit) entries, of address space. Ten half-word registers
are control, port, and status registers, 64 half-word entries are the CCW table, and 64 half-word entries are
the result table which occupies 192 half-word address locations because the result data is readable in three
data alignment formats. Table 28-2 is the QADC memory map.
Table 28-2. QADC Memory Map
IPSBAR +
Offset

MSB

Access1

LSB

0x19_0000

QADC Module Configuration Register (QADCMCR)

0x19_0002

QADC Test Register (QADCTEST)2

0x19_0004

Reserved3

0x19_0006

Port QA Data Register (PORTQA)

Port QB Data Register (PORTQB)

S/U

0x19_0008

Port QA Data Direction Register


(DDRQA)

Port QB Data Direction Register


(DDRQB)

S/U

0x19_000a

QADC Control Register 0 (QACR0)

S/U

0x19_000c

QADC Control Register 1 (QACR1)

S/U

0x19_000e

QADC Control Register 2 (QACR2)

S/U

0x19_0010

QADC Status Register 0 (QASR0)

S/U

0x19_0012

QADC Status Register 1 (QASR1)

S/U

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-6

Freescale Semiconductor

Register Descriptions

Table 28-2. QADC Memory Map (continued)


IPSBAR +
Offset

MSB

LSB

Access1

0x19_0014
0x19_01fe

Reserved(3)

0x19_0200
0x19_027e

Conversion Command Word Table (CCW)

S/U

0x19_0280
0x19_02fe

Right Justified, Unsigned Result Register (RJURR)

S/U

0x19_0300
0x19_037e

Left Justified, Signed Result Register (LJSRR)

S/U

0x19_0380
0x19_03fe

Left Justified, Unsigned Result Register (LJURR)

S/U

S = CPU supervisor mode access only. S/U = CPU supervisor or user mode access. User mode accesses to
supervisor only addresses have no effect and result in a cycle termination transfer error.
2 Access results in the module generating an access termination transfer error if not in test mode.
3 Read/writes have no effect and the access terminates with a transfer error exception.

28.6

Register Descriptions

This subsection describes the QADC registers.

28.6.1

QADC Module Configuration Register (QADCMCR)

The QADCMCR contains bits that control QADC debug and stop modes and determine the privilege level
required to access most registers.

Field

15

14

QSTOP

QDBG

Reset

R/W

SUPV

Reset
R/W:

0000_0000

R/W:

Field

13

1000_0000

R/W

Address

R
IPSBAR + 0x19_0000, 0x19_0001

Figure 28-3. QADC Module Configuration Register (QADCMCR)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-7

Queued Analog-to-Digital Converter (QADC)

Table 28-3. QADCMCR Field Descriptions


Bit(s)

Name

15

QSTOP

Stop enable.
1 Force QADC to idle state.
0 QADC operates normally.

14

QDBG

Debug enable.
1 Finish any conversion in progress, then freeze in debug mode
0 QADC operates normally.

138

SUPV

60

28.6.2

Description

Reserved, should be cleared.


Supervisor/unrestricted data space.
1 All QADC registers are accessible in supervisor mode only; user mode accesses
have no effect and result in a cycle termination error.
0 Only QADCMCR and QADCTEST require supervisor mode access; access to all
other QADC registers is unrestricted
Reserved, should be cleared.

QADC Test Register (QADCTEST)

The QADCTEST is a reserved register. Attempts to access this register outside of factory test mode will
result in access privilege violation.

28.6.3

Port Data Registers (PORTQA & PORTQB)

QADC ports QA and QB are accessed through the 8-bit PORTQA and PORTQB.
Port QA signals are referred to as PQA[4:3, 1:0] when used as a bidirectional, 4-bit, input/output port. Port
QA can also be used for analog inputs (AN[56:55, 53:52]), external trigger inputs (ETRIG[2:1]), and
external multiplexer address outputs (MA[1:0]).
Port QB signals are referred to as PQB[3:0] when used as a 4-bit, digital input-only port. Port QB can also
be used for non-multiplexed (AN[3:0]) and multiplexed (ANZ, ANY, ANX, ANW) analog inputs.
PORTQA and PORTQB are not initialized by reset.
7

PQA4
(AN56)
(ETRIG2)

PQA3
(AN55)
(ETRIG1)

PQA1
(AN53)
(MA1)

PQA0
(AN52)
(MA0)

Field

Reset

000

See Note

See Note

R/W:

R/W

R/W

Address

IPSBAR + 0x19_0006

Figure 28-4. QADC Port QA Data Register (PORTQA)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-8

Freescale Semiconductor

Register Descriptions

PQB3
(AN3)
(ANZ)

PQB2
(AN2)
(ANY)

PQA1
(AN1)
(ANX)

PQA0
(AN0)
(ANW)

Field

Reset

0000

See Note

R/W:

R/W

Address

IPSBAR + 0x19_0007

Figure 28-5. QADC Port QB Data Register (PORTQB)


Note: The reset value for these fields is the current signal state if DDR is an input; otherwise, they are undefined.

28.6.4

Port QA and QB Data Direction Register (DDRQA & DDRQB)

DDRQA and DDRQB are associated with port QA and QB digital I/O signals. Setting a bit in these
registers configures the corresponding signal as an output. Clearing a bit in these registers configures the
corresponding signal as an input. During QADC initialization, port QA and QB signals that will be used
as direct or multiplexed analog inputs must have their corresponding data direction register bits cleared.
When a port QA or QB signal that is programmed as an output is selected for analog conversion, the
voltage sampled is that of the output digital driver as influenced by the load.
When the MUX (externally multiplexed) bit is set in QACR0, the data direction register settings are
ignored for the bits corresponding to PQA[1:0], and the two multiplexed address (MA[1:0]) output signals.
The MA[1:0] signals are forced to be digital outputs, regardless of their data direction setting, and the
multiplexed address outputs are driven. The data returned during a port data register read is the value of
the MA[1:0] signals, regardless of their data direction setting.
Similarly, when the external trigger signals are assigned to port signals and external trigger queue
operating mode is selected, the data direction setting for the corresponding signals, PQA3 and/or PQA4,
is ignored. The port signals are forced to be digital inputs for ETRIG1 and/or ETRIG2. The data returned
during a port data register read is the value of the ETRIG[2:1] signals, regardless of their data direction
setting.
NOTE
Use caution when mixing digital and analog inputs. They should be isolated
as much as possible. Rise and fall times should be as large as possible to
minimize ac coupling effects.
7

Field

Reset
R/W:
Address

DDQA4

DDQA3

DDQA1

DDQA0

0000_0000
R

R/W

R/W

IPSBAR + 0x19_0008

Figure 28-6. QADC Port QA Data Direction Register (DDRQA)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-9

Queued Analog-to-Digital Converter (QADC)

Field

Reset

DDQB3

DDQB2

DDQB1

DDQB0

0000_0000

R/W

Address

IPSBAR + 0x19_0009

Figure 28-7. Port QB Data Direction Register (DDRQB)

28.6.5

Control Registers

This subsection describes the QADC control registers.

28.6.5.1

QADC Control Register 0 (QACR0)

QACR0 establishes the QADC sampling clock (QCLK) with prescaler parameter fields and defines
whether external multiplexing is enabled. Typically, these bits are written once when the QADC is
initialized and not changed thereafter. The bits in this register are read anytime, write anytime (except
during stop mode).

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-10

Freescale Semiconductor

Register Descriptions

15

Field

14

MUX

13

12

Field

0000_0000
R/W

R/W

QPR6

QPR5

QPR4

QPR3

QPR2

QPR1

QPR0

Reset
R/W:

TRG

Reset
R/W:

11

0001_0011
R

R/W

Address

IPSBAR + 0x19_000a, 0x19_000b

Figure 28-8. QADC Control Register 0 (QACR0)


Table 28-4. QACR0 Field Descriptions
Bit(s)

Name

Description

15

MUX

Externally multiplexed mode. Configures the QADC for operation in externally


multiplexed mode, which affects the interpretation of the channel numbers and forces
the MA[1:0] signals to be outputs.
1 Externally multiplexed, up to 18 possible channels
0 Internally multiplexed, up to 8 possible channels

1413

12

TRG

117

60

QPR

Reserved, should be cleared.


Trigger assignment. Determines the queue assignment of the ETRIG[2:1] signals.
1 ETRIG1 triggers queue 2; ETRIG2 triggers queue 1.
0 ETRIG1 triggers queue 1; ETRIG2 triggers queue 2.
Reserved, should be cleared.
Prescaler clock divider. Selects the system clock divisor to generate the QADC clock
as Table 28-5 shows. The resulting QADC clock rate can be given as:
fQCLK =

fSYS

2(QPR[6:0] + 1)
where:
1 QPR[6:0] 127.
If QPR[6:0] = 0, then the QPR register field value is read as a 1 and the prescaler
divisor is 2.
The prescaler should be selected so that the QADC clock rate is within the required
fQCLK range. See MCF5282 Electrical Characteristics.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-11

Queued Analog-to-Digital Converter (QADC)

Table 28-5. Prescaler fSYS Divide-by Values


QPR[6:0]

fSYS
Divisor

QPR[6:0]

fSYS
Divisor

QPR[6:0]

fSYS
Divisor

QPR[6:0]

fSYS
Divisor

0000000

0100000

66

1000000

130

1100000

194

0000001

0100001

68

1000001

132

1100001

196

0000010

0100010

70

1000010

134

1100010

198

0000011

0100011

72

1000011

136

1100011

200

0000100

10

0100100

74

1000100

138

1100100

202

0000101

12

0100101

76

1000101

140

1100101

204

0000110

14

0100110

78

1000110

142

1100110

206

0000111

16

0100111

80

1000111

144

1100111

208

0001000

18

0101000

82

1001000

146

1101000

210

0001001

20

0101001

84

1001001

148

1101001

212

0001010

22

0101010

86

1001010

150

1101010

214

0001011

24

0101011

88

1001011

152

1101011

216

0001100

26

0101100

90

1001100

154

1101100

218

0001101

28

0101101

92

1001101

156

1101101

220

0001110

30

0101110

94

1001110

158

1101110

222

0001111

32

0101111

96

1001111

160

1101111

224

0010000

34

0110000

98

1010000

162

1110000

226

0010001

36

0110001

100

1010001

164

1110001

228

0010010

38

0110010

102

1010010

166

1110010

230

0010011

40

0110011

104

1010011

168

1110011

232

0010100

42

0110100

106

1010100

170

1110100

234

0010101

44

0110101

108

1010101

172

1110101

236

0010110

46

0110110

110

1010110

174

1110110

238

0010111

48

0110111

112

1010111

176

1110111

240

0011000

50

0111000

114

1011000

178

1111000

242

0011001

52

0111001

116

1011001

180

1111001

244

0011010

54

0111010

118

1011010

182

1111010

246

0011011

56

0111011

120

1011011

184

1111011

248

0011100

58

0111100

122

1011100

186

1111100

250

0011101

60

0111101

124

1011101

188

1111101

252

0011110

62

0111110

126

1011110

190

1111110

254

0011111

64

0111111

128

1011111

192

1111111

256

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-12

Freescale Semiconductor

Register Descriptions

28.6.5.2

QADC Control Register 1 (QACR1)

QACR1 is the mode control register for queue 1. This register governs queue operating mode and the use
of completion and/or pause interrupts. Typically, these bits are written once when the QADC is initialized
and are not changed thereafter.
Stop mode resets this register.

Field

15

14

13

12

11

10

CIE1

PIE1

SSE1

MQ112

MQ111

MQ110

MQ19

MQ18

Reset

0000_0000

R/W:

R/W

Field

Reset

0000_0000

R/W:

Address

IPSBAR + 0x19_000c, 0x19_000d

Figure 28-9. QADC Control Register 1 (QACR1)


Table 28-6. QACR1 Field Descriptions
Bit(s)

Name

Description

15

CIE1

Queue 1 completion interrupt enable. Enables an interrupt request upon completion


of queue 1. The interrupt request is initiated when the conversion is complete for the
last CCW in queue 1.
1 Enable queue 1 completion interrupt.
0 Disable queue 1 completion interrupt.

14

PIE1

Queue 1 pause interrupt enable. Enables an interrupt request when queue 1 enters
the pause state. The interrupt request is initiated when conversion is complete for a
CCW that has the pause bit set.
1 Enable the queue 1 pause interrupt.
0 Disable the queue 1 pause interrupt.

13

SSE1

Queue 1 single-scan enable. Enables a single-scan of queue 1 after a trigger event


occurs. SSE1 may be set during the same write cycle that sets the MQ1 bits for one
of the single-scan queue operating modes. The single-scan enable bit can be written
to 1 or 0, but is always read as a 0, unless the QADC is in test mode. The QADC clears
SSE1 when the single-scan is complete.
1 Allow a trigger event to start queue 1 in a single-scan mode.
0 Trigger events are ignored for queue 1 single-scan modes.

128

MQ1n

Selects the operating mode for queue 1. Table 28-7 shows the bits in the MQ1 field
which enable different queue 1 operating modes.

70

Reserved, should be cleared.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-13

Queued Analog-to-Digital Converter (QADC)

Table 28-7. Queue 1 Operating Modes


MQ1[12:8]

Operating Mode

00000

Disabled mode, conversions do not occur

00001

Software-triggered single-scan mode (started with SSE1)

00010

External-trigger rising-edge single-scan mode

00011

External-trigger falling-edge single-scan mode

00100

Interval timer single-scan mode: time = QCLK period 27

00101

Interval timer single-scan mode: time = QCLK period 28

00110

Interval timer single-scan mode: time = QCLK period 29

00111

Interval timer single-scan mode: time = QCLK period 210

01000

Interval timer single-scan mode: time = QCLK period 211

01001

Interval timer single-scan mode: time = QCLK period 212

01010

Interval timer single-scan mode: time = QCLK period 213

01011

Interval timer single-scan mode: time = QCLK period 214

01100

Interval timer single-scan mode: time = QCLK period 215

01101

Interval timer single-scan mode: time = QCLK period 216

01110

Interval timer single-scan mode: time = QCLK period 217

01111

Externally gated single-scan mode (started with SSE1)

10000

Reserved mode

10001

Software-triggered continuous-scan mode

10010

External-trigger rising-edge continuous-scan mode

10011

External-trigger falling-edge continuous-scan mode

10100

Periodic timer continuous-scan mode: time = QCLK period 27

10101

Periodic timer continuous-scan mode: time = QCLK period 28

10110

Periodic timer continuous-scan mode: time = QCLK period 29

10111

Periodic timer continuous-scan mode: time = QCLK period 210

11000

Periodic timer continuous-scan mode: time = QCLK period 211

11001

Periodic timer continuous-scan mode: time = QCLK period 212

11010

Periodic timer continuous-scan mode: time = QCLK period 213

11011

Periodic timer continuous-scan mode: time = QCLK period 214

11100

Periodic timer continuous-scan mode: time = QCLK period 215

11101

Periodic timer continuous-scan mode: time = QCLK period 216

11110

Periodic timer continuous-scan mode: time = QCLK period 217

11111

Externally gated continuous-scan mode

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-14

Freescale Semiconductor

Register Descriptions

28.6.5.3

QADC Control Register 2 (QACR2)

QACR2 is the mode control register for queue 2. This register governs queue operating mode and the use
of completion and/or pause interrupts. Typically, these bits are written once when the QADC is initialized
and not changed thereafter.
QACR2 also includes a resume feature that selects the resumption point for queue 2 after its operation is
suspended by a queue 1 trigger event. The primary reason for selecting re-execution of the entire queue or
subqueue is to guarantee that all samples are taken consecutively in one scan (coherency).
When subqueues are not used, queue 2 execution restarts after suspension with the first CCW in queue 2.
When a pause has previously occurred in queue 2 execution, queue execution restarts after suspension with
the first CCW in the current subqueue.
A subqueue is considered to be a stand-alone sequence of conversions. Once a pause flag has been set to
report subqueue completion, that subqueue is not repeated until all CCWs in queue 2 are executed.
For example, the RESUME bit can be used when the frequency of queue 1 trigger events prohibit queue
2 completion. If the rate of queue 1 execution is too high, it is best for queue 2 execution to continue with
the CCW that was being converted when queue 2 was suspended. This allows queue 2 to eventually
complete execution.
The beginning of queue 2 is defined by programming the BQ2 field in QACR2. BQ2 is usually set before
or at the same time as the queue operating mode for queue 2 is selected. If BQ2[6:0] 64, queue 2 has no
entries, the entire CCW table is dedicated to queue 1, and CCW63 is the end-of-queue 1. If BQ2[6:0] is 0,
the entire CCW table is dedicated to queue 2. A special case occurs when an operating mode is selected
for queue 1 and a trigger event occurs for queue 1 with BQ2 set to 0. Queue 1 execution starts momentarily,
but is terminated after CCW0 is read. No conversions occur.
The BQ2[6:0] pointer may be changed dynamically to alternate between queue 2 scan sequences. A
change in BQ2 after queue 2 has begun or when queue 2 has a trigger pending does not affect queue 2 until
it is started again. For example, two scan sequences could be defined as follows: The first sequence starts
at CCW10, with a pause after CCW11 and an end of queue (EOQ) programmed in CCW15; the second
sequence starts at CCW16, with a pause after CCW17 and an EOQ programmed in CCW39.
With BQ2[6:0] set to CCW10 and the continuous-scan mode selected, queue execution begins. When the
pause is encountered in CCW11, an interrupt service routine can retarget BQ2[6:0] to CCW16. When the
end-of-queue is recognized in CCW15, an internal retrigger event is generated and execution restarts at
CCW16. When the pause software interrupt occurs again, BQ2 can be changed back to CCW10. After the
end-of-queue is recognized in CCW39, an internal retrigger event is created and execution now restarts at
CCW10.
If BQ2[6:0] is changed while queue 1 is active, the effect of BQ2[6:0] as an end-of-queue indication for
queue 1 is immediate. However, beware of the risk of losing the end-of-queue 1 when changing BQ2[6:0].
Using EOQ (channel 63) to end queue 1 is recommended.
NOTE
If BQ2[6:0] was assigned to the CCW that queue 1 is currently working on,
then that conversion is completed before the change to BQ2[6:0] takes
effect.
Each time a CCW is read for queue 1, the CCW location is compared with the current value of the
BQ2[6:0] pointer to detect a possible end-of-queue condition. For example, if BQ2[6:0] is changed to
CCW3 while queue 1 is converting CCW2, queue 1 is terminated after the conversion is completed.
However, if BQ2[6:0] is changed to CCW1 while queue 1 is converting CCW2, the QADC would not

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-15

Queued Analog-to-Digital Converter (QADC)

recognize a BQ2[6:0] end-of-queue condition until queue 1 execution reached CCW1 again, presumably
on the next pass through the queue.
Stop mode resets this register (0x007f)

Field

15

14

13

12

11

10

CIE2

PIE2

SSE2

MQ212

MQ211

MQ210

MQ29

MQ28

Reset

0000_0000

R/W:

R/W

Field RESUME

BQ26

BQ25

BQ24

BQ23

BQ22

BQ21

BQ20

Reset

0111_1111

R/W:

R/W

Address

IPSBAR + 0x19_000e, 0x19_000f

Figure 28-10. QADC Control Register 2 (QACR2)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-16

Freescale Semiconductor

Register Descriptions

Table 28-8. QACR2 Field Descriptions


Bit(s)

Name

Description

15

CIE2

Queue 2 completion software interrupt enable. Enables an interrupt request upon


completion of queue 2. The interrupt request is initiated when the conversion is
complete for the last CCW in queue 2.
1 Enable queue 2 completion interrupt.
0 Disable queue 2 completion interrupt.

14

PIE2

Queue 2 pause interrupt enable. Enables an interrupt request when queue 2 enters
the pause state. The interrupt request is initiated when conversion is complete for a
CCW that has the pause bit set.
1 Enable the queue 2 pause interrupt.
0 Disable the queue 2 pause interrupt.

13

SSE2

Queue 2 single-scan enable. Enables a single-scan of queue 2 after a trigger event


occurs. SSE2 may be set during the same write cycle that sets the MQ2 bits for one
of the single-scan queue operating modes. The single-scan enable bit can be written
to 1 or 0, but is always read as a 0, unless the QADC is in test mode. The QADC clears
SSE2 when the single-scan is complete.
1 Allow a trigger event to start queue 2 in a single-scan mode.
0 Trigger events are ignored for queue 2 single-scan modes.

128

MQ2

Selects the operating mode for queue 2. Table 28-9 shows the bits in the MQ1 field
which enable different queue 2 operating modes.

RESUME

Selects the resumption point for queue 2 after its operation is suspended due to a
queue 1 trigger event. If RESUME is changed during the execution of queue 2, the
change is not recognized until an end-of-queue condition is reached or the operating
mode of queue 2 is changed.
1 After suspension, begin execution with the aborted CCW in queue 2.
0 After suspension, begin execution with the first CCW of queue 2 or the current
subqueue of queue 2.

60

BQ2

Beginning of queue 2. Denotes the CCW location where queue 2 begins. This allows
the length of queue 1 and queue 2 to vary. The BQ2 field also serves as an
end-of-queue condition for queue 1.

Table 28-9. Queue 2 Operating Modes


MQ2[12:8]

Operating Modes

00000

Disabled mode, conversions do not occur

00001

Software triggered single-scan mode (started with SSE2)

00010

Externally triggered rising edge single-scan mode

00011

Externally triggered falling edge single-scan mode

00100

Interval timer single-scan mode: time = QCLK period x 27

00101

Interval timer single-scan mode: time = QCLK period x 28

00110

Interval timer single-scan mode: time = QCLK period x 29

00111

Interval timer single-scan mode: time = QCLK period x 210

01000

Interval timer single-scan mode: time = QCLK period x 211

01001

Interval timer single-scan mode: time = QCLK period x 212

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-17

Queued Analog-to-Digital Converter (QADC)

Table 28-9. Queue 2 Operating Modes (continued)


MQ2[12:8]

28.6.6

Operating Modes

01010

Interval timer single-scan mode: time = QCLK period x 213

01011

Interval timer single-scan mode: time = QCLK period x 214

01100

Interval timer single-scan mode: time = QCLK period x 215

01101

Interval timer single-scan mode: time = QCLK period x 216

01110

Interval timer single-scan mode: time = QCLK period x 217

01111

Reserved mode

10000

Reserved mode

10001

Software triggered continuous-scan mode

10010

Externally triggered rising edge continuous-scan mode

10011

Externally triggered falling edge continuous-scan mode

10100

Periodic timer continuous-scan mode: time = QCLK period x 27

10101

Periodic timer continuous-scan mode: time = QCLK period x 28

10110

Periodic timer continuous-scan mode: time = QCLK period x 29

10111

Periodic timer continuous-scan mode: time = QCLK period x 210

11000

Periodic timer continuous-scan mode: time = QCLK period x 211

11001

Periodic timer continuous-scan mode: time = QCLK period x 212

11010

Periodic timer continuous-scan mode: time = QCLK period x 213

11011

Periodic timer continuous-scan mode: time = QCLK period x 214

11100

Periodic timer continuous-scan mode: time = QCLK period x 215

11101

Periodic timer continuous-scan mode: time = QCLK period x 216

11110

Periodic timer continuous-scan mode: time = QCLK period x 217

11111

Reserved mode

Status Registers

This subsection describes the QADC status registers.

28.6.6.1

QADC Status Register 0 (QASR0)

QASR0 contains information about the state of each queue and the current A/D conversion. The bits in
this register are read anytime. For flag bits (CF1, PF1, CF2, PF2, TOR1, TOR2), writing a 1 has no effect;
writing a 0 clears the bit. For QS[9:6] and CWP, writes have no effect. Stop mode resets this register.
The end of a queue is identified in the following cases:
When execution is complete on the CCW in the location prior to the one
pointed to by BQ2
When the current CCW contains the end-of-queue code (channel 63) instead of a valid channel
number
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
28-18

Freescale Semiconductor

Register Descriptions

When the currently completed CCW is in the last location of the CCW RAM.

Once PFn is set, the queue enters the paused state and waits for a trigger event to allow queue execution
to continue. However, a special case occurs when the CCW with the pause bit set is the last CCW in a
queue; queue execution is complete. The queue status becomes idle, not paused, and both the pause and
completion flags are set.
Another special case occurs when the queue is operating in software-initiated single-scan or
continuous-scan mode and a CCW pause bit is set. The QADC will set PFn and will also automatically
generate a retrigger event that restarts execution after two QCLK cycles. Pause mode is never entered.
In externally gated single-scan and continuous-scan mode, the behavior of PFn has been redefined. When
the gate closes before the end of the queue is reached, PFn is set to indicate that an incomplete scan has
occurred. In single-scan mode, a resultant interrupt can be used to determine if the queue should be enabled
again. In either externally gated mode, setting PFn indicates that the results for the queue have not been
collected during one scan (coherently).
NOTE:
If a set CCW pause bit is encountered in either externally gated mode, the
pause flag will not set, and execution continues without pausing. This has
allowed for the modified behavior of PF1 in the externally gated modes.
PFn is maintained by the QADC regardless of whether the corresponding
interrupt is enabled. PFn may be polled to determine if the QADC has
reached a pause in scanning a queue.
A trigger event generated by a transition on the external trigger signal or by the periodic/interval timer may
be captured as a trigger overrun. TORn cannot be set when the software-initiated single-scan mode or the
software-initiated continuous-scan mode is selected.
TORn is set when a trigger event is received while a queue is executing and before the scan has completed
or paused. TORn has no effect on queue execution.
After a trigger event has occurred for queue 1, and before the scan has completed or paused, additional
queue 1 trigger events are not retained. Such trigger events are considered unexpected, and the QADC sets
the TORn error status bit. An unexpected trigger event may denote a system overrun situation.
In externally gated continuous-scan mode, the behavior of TORn has been redefined. In the case that the
queue reaches an end-of-queue condition for the second time during an open gate, TORn is set. This is
considered an overrun condition. In this case, CF1 has been set for the first end-of-queue condition and
TORn sets for the second end-of-queue condition. For TOR1 to set, CF2 must not be cleared before the
second end-of-queue.
The QS field indicates the status of queue 1 and queue 2. Following are the five queue status conditions:
Idle
Active
Paused
Suspended
Trigger pending
The idle state occurs when a queue is disabled, when a queue is in a reserved mode, or when a queue is in
a valid queue operating mode awaiting a trigger event to initiate queue execution. One or both queues may
be in the idle state. When a queue is idle, CCWs are not being executed for that queue, the queue is not in
the pause state, and no trigger is pending.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-19

Queued Analog-to-Digital Converter (QADC)

A queue is in the active state when a valid queue operating mode is selected, when the selected trigger
event has occurred, or when the QADC is performing a conversion specified by a CCW from that queue.
Only one queue can be active at a time.
One or both queues can be in the paused state. A queue is paused when the previous CCW executed from
that queue had the pause bit set. The QADC does not execute any CCWs from the paused queue until a
trigger event occurs. Consequently, the QADC can service queue 2 while queue 1 is paused.
Only queue 2 can be in the suspended state. When a trigger event occurs on queue 1 while queue 2 is
executing, the current queue 2 conversion is aborted and the queue 2 status is reported as suspended. Queue
2 transitions back to the active state when queue 1 becomes idle or paused.
A trigger pending state is required because both queues cannot be active at the same time. The status of
queue 2 is changed to trigger pending when a trigger event occurs for queue 2 while queue 1 is active. In
the opposite case, when a trigger event occurs for queue 1 while queue 2 is active, queue 2 is aborted and
the status is reported as queue 1 active, queue 2 suspended. So due to the priority scheme, only queue 2
can be in the trigger pending state.
Two transition cases cause the queue 2 status to be trigger pending before queue 2 is shown to be in the
active state. When queue 1 is active and there is a trigger pending on queue 2, after queue 1 completes or
pauses, queue 2 continues to be in the trigger pending state for a few clock cycles. The fleeting status
conditions are:
Queue 1 idle with queue 2 trigger pending
Queue 1 paused with queue 2 trigger pending
Figure 28-12 displays the status conditions of the QS field as the QADC goes through the transition from
queue 1 active to queue 2 active.
When a queue enters the paused state, CWP points to the CCW with the pause bit set. While in pause, the
CWP value is maintained until a trigger event occurs on either queue. Usually, the CWP is updated a few
clock cycles before the queue status field shows that the queue has become active. For example, a read of
CWP may point to a CCW in queue 2, while the queue status field shows queue 1 paused and queue 2
trigger pending.
When the QADC finishes a queue scan, the CWP points to the CCW where the end-of-queue condition
was detected. Therefore, when the end-of-queue condition is a CCW with the EOQ code (channel 63), the
CWP points to the CCW containing the EOQ.
When the last CCW in a queue is the last CCW table location (CCW63), and it does not contain the EOQ
code, the end-of-queue is detected when the following CCW is read, so the CWP points to word CCW0.
Finally, when queue 1 operation is terminated after a CCW is read that is pointed to by BQ2, the CWP
points to the same CCW as BQ2.

Field

15

14

13

12

11

10

CF1

PF1

CF2

PF2

TOR1

TOR2

QS9

QS8

Reset
R/W:

0000_0000
R/W

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-20

Freescale Semiconductor

Register Descriptions

Field

QS7

QS6

CWP5

CWP4

CWP3

CWP2

CWP1

CWP0

Reset

0000_0000

R/W:

Address

IPSBAR + 0x19_0010, 0x19_0011

Figure 28-11. QADC Status Register 0 (QASR0)


Table 28-10. QASR0 Field Descriptions
Bit(s)

Name

Description

15, 13

CFn

Queue completion flag. Indicates that a queue scan has been completed. CF[1:2] is
set by the QADC when the input channel sample requested by the last CCW in the
queue is converted, and the result is stored in the result table.
When CFn is set and queue completion interrupts are enabled (QACRn[CIEn] = 1),
the QADC requests an interrupt. The interrupt request is cleared when a 0 is written
to the CF1 bit after it has been read as a 1. Once set, CF1 can be cleared only by a
reset or by writing a 0 to it.
CF[1:2] is updated by the QADC regardless of whether the corresponding interrupt is
enabled. This allows polled recognition of the queue scan completion.

14, 12

PFn

Queue pause flag. Indicates that a queue scan has reached a pause. PF[1:2] is set by
the QADC when the current queue 1 CCW has the pause bit set, the selected input
channel has been converted, and the result has been stored in the result table.
When PFn is set and interrupts are enabled (QACRn[PIEn] = 1), the QADC requests
an interrupt. The interrupt request is cleared when a 0 is written to PFn, after it has
been read as a 1. Once set, PFn can be cleared only by reset or by writing a 0 to it.
PF1:
1 Queue 1 has reached a pause or gate closed before end-of-queue in gated mode.
0 Queue 1 has not reached a pause or gate has not closed before end-of-queue in
gated mode.
PF2:
1 Queue 2 has reached a pause.
0 Queue 2 has not reached a pause.
See Table 28-11 for a summary of CCW pause bit response in all scan modes.

1110

TORn

Queue trigger overrun flag. Indicates that an unexpected trigger event has occurred
for queue 1. TOR[1:2] can be set only while the queue is in the active state.
Once set, TOR[1:2] is cleared only by a reset or by writing a 0 to it.
1 At least one unexpected queue 1 trigger event has occurred or queue 1 reaches an
end-of-queue condition for the second time in externally gated continuous scan.
0 No unexpected queue 1 trigger events have occurred.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-21

Queued Analog-to-Digital Converter (QADC)

Table 28-10. QASR0 Field Descriptions (continued)


Bit(s)

Name

Description

96

QS

Queue status. Indicates the current condition of queue 1 and queue 2. The two most
significant bits are associated primarily with queue 1, and the remaining two bits are
associated with queue 2. Because the priority scheme between the two queues
causes the status to be interlinked, the status bits must be considered as one 4-bit
field. Table 28-12 shows the bits in the QS field and how they denote the status of
queue 1 and queue 2.
The queue status field is affected by QADC stop mode. Because all of the analog logic
and control registers are reset, the queue status field is reset to queue 1 idle, queue
2 idle.
During debug mode, the queue status field is not modified. The queue status field
retains the status it held prior to freezing. As a result, the queue status can show
queue 1 active, queue 2 idle, even though neither queue is being executed during
freeze.

50

CWP

Command word pointer. Denotes which CCW is executing at present or was last
completed. CWP is a read-only field with a valid range of 0 to 63; write operations have
no effect.
During stop mode, CWP is reset to 0 because the control registers and the analog
logic are reset. When debug mode is entered, CWP is not changed; it points to the last
executed CCW.

Table 28-11. CCW Pause Bit Response


Scan Mode

Queue Operation

PF Asserts?

Externally triggered single-scan

Pauses

Yes

Externally triggered continuous-scan

Pauses

Yes

Interval timer trigger single-scan

Pauses

Yes

Interval timer continuous-scan

Pauses

Yes

Software-initiated single-scan

Continues

Yes

Software-initiated continuous-scan

Continues

Yes

Externally gated single-scan

Continues

No

Externally gated continuous-scan

Continues

No

Table 28-12. Queue Status


QS[9:6]

Queue 1/Queue 2 States

0000

Queue 1 idle, queue 2 idle

0001

Queue 1 idle, queue 2 paused

0010

Queue 1 idle, queue 2 active

0011

Queue 1 idle, queue 2 trigger pending

0100

Queue 1 paused, queue 2 idle

0101

Queue 1 paused, queue 2 paused

0110

Queue 1 paused, queue 2 active

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-22

Freescale Semiconductor

Register Descriptions

Table 28-12. Queue Status (continued)


QS[9:6]

Queue 1/Queue 2 States

0111

Queue 1 paused, queue 2 trigger pending

1000

Queue 1 active, queue 2 idle

1001

Queue 1 active, queue 2 paused

1010

Queue 1 active, queue 2 suspended

1011

Queue 1 active, queue 2 trigger pending

1100

Reserved

1101

Reserved

1110

Reserved

1111

Reserved

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-23

Queued Analog-to-Digital Converter (QADC)

Q2 Trigger Event

Q1 Idle/
Q2 Active

Q1 Trigger Event

Q1 Idle/
Q2 Idle

Q2 Complete
Q1 Complete

Q1 Active/
Q2 Idle

Delayed Transition
Q2 Pause Bit Set

Q1 Pause Bit Set

Q1 Idle/
Q2 Trigger
Pending
(Temporary)

Q2 Trigger Event

Q2 Trigger Event
Q1 Trigger Event

Q1 Trigger Event

Q1 Paused/
Q2 Idle

Q1 Complete
Q1 Complete
Q1 Idle/
Q2 Paused

Q1 Trigger Event

Q1 Active/
Q2 Trigger
Pending

Q1 Active/
Q2 Suspended

Q1 Pause Bit Set

Q1 Complete

Q1 Paused/
Q2 Trigger
Pending
(Temporary)

Q1 Pause Bit Set


Q1 Active/
Q2 Paused

Delayed Transition
Q1 Trigger Event

Q2 Complete

Q1 Pause Bit Set


Q1 Paused/
Q2 Active

Q1 Trigger Event
Q2 Trigger Event
Q1 Paused/
Q2 Paused

Q2 Pause Bit Set

Figure 28-12. Queue Status Transition

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-24

Freescale Semiconductor

Register Descriptions

28.6.6.2

QADC Status Register 1 (QASR1)

Stop mode resets this register .


15

14

Field

13

12

11

10

CWPQ15

CWPQ14

CWPQ13

CWPQ12

CWPQ11

CWPQ10

Reset

0011_1111

R/W:

Field

CWPQ25

CWPQ24

CWPQ23

CWPQ22

CWPQ21

CWPQ20

Reset

0011_1111

R/W:

Address

IPSBAR + 0x19_0012, 0x19_0013

Figure 28-13. QADC Status Register 1 (QASR1)


Table 28-13. QASR1 Field Descriptions
Bit(s)

Name

1514

138

CWPQ1

76

50

CWPQ

28.6.7

Description
Reserved, should be cleared.
Queue 1 command word pointer. Points to the last queue 1 CCW executed. This is a
read-only field with a valid range of 0 to 63; writes have no effect. CWPQ1 always
points to the last executed CCW in queue 1, regardless of which queue is active.
In contrast to CWP, CPWQ1 is updated when a conversion result is written. When the
QADC finishes a conversion in queue 1, both the result register is written and CWPQ1
is updated.
When queue 1 operation is terminated after a CCW is read that is pointed to by BQ2,
CWP points to BQ2 while CWPQ1 points to the last queue 1 CCW.
During stop mode, CWPQ1 is reset to 63, because the control registers and the
analog logic are reset. When debug mode is entered, CWPQ1 is not changed; it points
to the last executed CCW in queue 1.
Reserved, should be cleared.
Queue 2 command word pointer. Points to the last queue 2 CCW executed. This is a
read-only field with a valid range of 0 to 63; writes have no effect. CWPQ2 always
points to the last executed CCW in queue 2, regardless which queue is active.
In contrast to CWP, CPWQ2 is updated when a conversion result is written. When the
QADC finishes a conversion in queue 2, both the result register is written and CWPQ2
is updated.
During stop mode, CWPQ2 is reset to 63 because the control registers and the analog
logic are reset. When debug mode is entered, CWPQ2 is not changed; it points to the
last executed CCW in queue 2.

Conversion Command Word Table (CCW)

The CCW table is 64 half-word (128 byte) long RAM with 10 bits of each entry implemented. The CCW
table is written by the user and is not modified by the QADC. Each CCW requests the conversion of one
analog channel to a digital result. The CCW specifies the analog channel number, the input sample time,
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
Freescale Semiconductor

28-25

Queued Analog-to-Digital Converter (QADC)

and whether the queue is to pause after the current CCW. The bits in this register are read anytime (except
during stop mode), write anytime (except during stop mode).
15

10

BYP

Field

Reset

0000_00

Unaffected

R/W:

R/W

Field

IST1

IST0

CHAN5

CHAN4

CHAN3

CHAN2

CHAN1

CHAN0

Reset

Undefined

R/W:

Address

IPSBAR + 0x19_0200, 0x19_027e

Figure 28-14. Conversion Command Word Table (CCW)


Table 28-14. CCW Field Descriptions
Bit(s)

Name

Description

1510

Reserved, should be cleared.

Pause. Allows subqueues to be created within queue 1 and queue 2. The QADC
performs the conversion specified by the CCW with the pause bit set and then the
queue enters the pause state. Another trigger event causes execution to continue from
the pause to the next CCW.
1 Enter pause state after execution of current CCW.
0 Do not enter pause state after execution of current CCW.
NOTE: The P bit does not cause the queue to pause in software-initiated modes or
externally gated modes.

BYP

Sample amplifier bypass. Enables the amplifier bypass mode for a conversion and
subsequently changes the timing. The initial sample time is eliminated, reducing the
potential conversion time by two QCLKs. However, due to internal RC effects, a
minimum final sample time of four QCLKs must be allowed. When using this mode,
the external circuit should be of low source impedance. Loading effects of the external
circuitry need to be considered because the benefits of the sample amplifier are not
present.
1 Amplifier bypass mode enabled
0 Amplifier bypass mode disabled
NOTE: BYP is maintained for software compatibility but has no functional benefit on
this version of the QADC.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-26

Freescale Semiconductor

Register Descriptions

Table 28-14. CCW Field Descriptions (continued)


Bit(s)

Name

Description

76

IST

Input sample time. Specifies the length of the sample window. The input sample time
can be varied, under software control, to accommodate various input channel source
impedances. Longer sample times permit more accurate A/D conversions of signals
with higher source impedances.
Table 28-15 shows the four selectable input sample times.
The programmable sample time can also be used to adjust queue execution time or
sampling rate by increasing the time interval between conversions.

50

CHAN

Selects the input channel number. The CCW channel field is programmed with the
channel number corresponding to the analog input signal to be sampled and
converted. The analog input signal channel number assignments and the signal
definitions vary depending on whether the QADC multiplexed or non-multiplexed
mode is used by the application. As far as queue scanning operations are concerned,
there is no distinction between an internally or externally multiplexed analog input.
Table 28-16 shows the channel number assignments for non-multiplexed mode.
Table 28-17 shows the channel number assignments for multiplexed mode.
Programming the channel field to channel 63 denotes the end of the queue. Channels
60 to 62 are special internal channels. When one of the special channels is selected,
the sampling amplifier is not used. The value of VRL, VRH, or (VRHVRL)/2 is converted
directly. Programming any input sample time other than two has no benefit for the
special internal channels except to lengthen the overall conversion time.

Table 28-15. Input Sample Times


IST[1:0]

Input Sample Times

00

Input sample time = QCLK period 2

01

Input sample time = QCLK period 4

10

Input sample time = QCLK period 8

11

Input sample time = QCLK period 16

Table 28-16. Non-Multiplexed Channel Assignments and Signal Designations


Channel Number1
in CCW CHAN Field

Non-Multiplexed Input Signals

Port Signal Name

Analog Signal Name

Other
Functions

Signal Type

Binary

Decimal

PQB0
PQB1
PQB2
PQB3

AN0
AN1
AN2
AN3

Input
Input
Input
Input

000000
000001
000010
000011

0
1
2
3

PQA0
PQA1

AN52
AN53

Input/Output
Input/Output

110100
110101

52
53

PQA3
PQA4

AN55
AN56

ETRIG1
ETRIG2

Input/Output
Input/Output

110111
111000

55
56

VRL
VRH

Low reference
High reference

(VRHVRL)/2

Input
Input

111100
111101
111110

60
61
62

End-of-Queue Code

111111

63

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-27

Queued Analog-to-Digital Converter (QADC)


1

All channels not listed are reserved or unimplemented and return undefined results.

Table 28-17. Multiplexed Channel Assignments and Signal Designations


Channel Number1
in CCW CHAN Field

Multiplexed Input Signals

Port Signal
Name

Analog
Signal Name

Other
Functions

Signal Type

Binary

Decimal

PQB0
PQB1
PQB2
PQB3

ANW
ANX
ANY
ANZ

Input
Input
Input
Input

000XX0
000XX1
010XX0
010XX1

0, 2, 4, 6
1, 3, 5, 7
16, 18, 20, 22
17, 19, 21, 23

PQA0
PQA1

MA0
MA1

Output
Output

52
53

PQA3
PQA4

AN55
AN56

ETRIG1
ETRIG2

Input/Output
Input/Output

110111
111000

55
56

VRL
VRH

Low Reference
High Reference

(VRHVRL)/2

Input
Input

111100
111101
111110

60
61
62

End-of-Queue Code

111111

63

All channels not listed are reserved or unimplemented and return undefined results.

28.6.8

Result Registers

The result word table is a 64 half-word (128 byte) long by 10-bit wide RAM. An entry is written by the
QADC after completing an analog conversion specified by the corresponding CCW table entry.

28.6.8.1

Right-Justified Unsigned Result Register (RJURR)


15

10

Field

RESULT

Reset

0000_00

Undefined

R/W:

R/W

Field

RESULT

Reset

Undefined

R/W:

R/W

Address

IPSBAR + 0x19_0280, 0x19_02fe

Figure 28-15. Right-Justified Unsigned Result Register (RJURR)

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-28

Freescale Semiconductor

Register Descriptions

Table 28-18. RJURR Field Descriptions


Bit(s)

Name

1510

90

RESULT

28.6.8.2

Description
Reserved, should be cleared.
The conversion result is unsigned, right-justified data.

Left-Justified Signed Result Register (LJSRR)


15

Field

14

RESULT

Reset

Undefined

R/W:

R/W

Field

RESULT

Reset

Undefined

R/W:

R/W

Address

IPSBAR + 0x19_0300, 0x19_037e

Figure 28-16. Left-Justified Signed Result Register (LJSRR)


Table 28-19. LJSRR Field Descriptions
Bit(s)

Name

Description

15

The left justified, signed format corresponds to a half-scale, offset binary, twos
complement data format. Conversion values corresponding to 1/2 full scale, 0x0200,
or higher are interpreted as positive values and have a sign bit of 0. An unsigned, right
justified conversion of 0x0200 would be represented as 0x0000 in this signed register,
where the sign = 0 and the result = 0. For an unsigned, right justified conversion of
0x3FF (full range or VRH), the signed equivalent in this register would be 0x7FC0, sign
= 0 and result = 0x1FF. For an unsigned, right justified conversion of 0x0000 (VRL), the
signed equivalent in this register would be 0x8000, sign = 1 and result = 0x000, a twos
complement value representing 512.

146

RESULT

50

28.6.8.3

The conversion result is signed, left-justified data.


Reserved, should be cleared.

Left-Justified Unsigned Result Register (LJURR)


15

Field

RESULT

Reset

Undefined

R/W:

R/W

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-29

Queued Analog-to-Digital Converter (QADC)

Field

RESULT

Reset

Undefined

R/W:

R/W

Address

IPSBAR + 0x19_0380, 0x19_03fe

Figure 28-17. Left-Justified Unsigned Result Register (LJURR)


Table 28-20. LJURR Field Descriptions
Bit(s)

Name

156

RESULT

50

28.7

Description
The conversion result is unsigned, left-justified data.
Reserved, should be cleared.

Functional Description

This subsection provides a functional description of the QADC.

28.7.1

Result Coherency

The QADC supports byte and half-word reads and writes across a 16-bit data bus interface. All conversion
results are stored in half-word registers, and the QADC does not allow more than one result register to be
read at a time. For this reason, the QADC does not guarantee read coherency.
Specifically, this means that while the QADC is operating, the data in the result registers can change from
one read to the next. Simply initiating a read of one result register will not prevent another from being
updated with a new conversion result.
Thus, to read any given number of result registers coherently, the queue or queues capable of modifying
these registers must be inactive. This can be guaranteed by system operating conditions (such as, known
completion of a software-initiated queue single-scan or no possibility of an externally triggered/gated
queue scan) or by simply disabling the queues (writing MQ1 and/or MQ2 to 0).

28.7.2

External Multiplexing

External multiplexer chips concentrate a number of analog signals onto a few QADC inputs. This is useful
for applications that need to convert more analog signals than the QADC converter can normally support.
External multiplexing also puts the multiplexed chip closer to the signal source. This minimizes the
number of analog signals that need to be shielded due to the proximity of noisy high speed digital signals
at the microcontroller chip.
For example, four 4-input multiplexer chips can be put at the connector where the analog signals first
arrive on the printed circuit board. As a result, only four analog signals need to be shielded from noise as
they approach the microcontroller chip, rather than having to protect 16 analog signals. However, external
multiplexer chips may introduce additional noise and errors if not properly utilized. Therefore, it is
necessary to maintain low on resistance (the impedance of an analog switch when active within a
multiplexed chip) and insert a low pass filter (R/C) on the input side of the multiplexed chip.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-30

Freescale Semiconductor

Functional Description

28.7.2.1

External Multiplexing Operation

The QADC can use from one to four external multiplexer chips to expand the number of analog signals
that may be converted. Up to 16 analog channels can be converted through external multiplexer selection.
The externally multiplexed channels are automatically selected from the channel field of the CCW, the
same as internally multiplexed channels. The QADC is configured for the externally multiplexed mode by
setting the MUX bit in control register 0 (QACR0).
Figure 28-18 shows the maximum configuration of four external multiplexer chips connected to the
QADC. The external multiplexer chips select one of four analog inputs and connect it to one analog output,
which becomes an input to the QADC. The QADC provides two multiplexed address signals, MA[1:0], to
select one of four inputs. These inputs are connected to all four external multiplexer chips. The analog
output of the four multiplexer chips are each connected to separate QADC inputs (ANW, ANX, ANY, and
ANZ) as shown in Figure 28-18

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-31

Queued Analog-to-Digital Converter (QADC)

AN1
AN3
AN5
AN7

MUX

MUX

AN0/ANW/PQB0
AN1/ANX/PQB1
AN2/ANY/PQB2
AN3/ANZ/PQB3

Port QB

AN0
AN2
AN4
AN6

AN55/ETRIG1PQA3
AN56/ETRIG2/PQA4
AN16
AN18
AN20
AN22

AN17
AN19
AN21
AN23

Port QA

AN52/MA0/PQA0
AN53/MA1/PQA1

MUX

MUX

Figure 28-18. External Multiplexing Configuration

When externally multiplexed mode is selected, the QADC automatically drives the MA output signals
from the channel number in each CCW. The QADC also converts the proper input channel (ANW, ANX,
ANY, and ANZ) by interpreting the CCW channel number. As a result, up to 16 externally multiplexed
channels appear to the conversion queues as directly connected signals. User software simply puts the
channel number of externally multiplexed channels into CCWs.
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
28-32

Freescale Semiconductor

Functional Description

Figure 28-18 shows that the two MA signals may also be analog input signals. When external multiplexing
is selected, none of the MA signals can be used for analog or digital inputs. They become multiplexed
address outputs and are unaffected by DDRQA[1:0].

28.7.2.2

Module Version Options

The number of available analog channels varies, depending on whether external multiplexing is used. A
maximum of eight analog channels are supported by the internal multiplexing circuitry of the converter.
Table 28-21 shows the total number of analog input channels supported with 0 to 4 external multiplexer
chips.
Table 28-21. Analog Input Channels
Number of Analog Input Channels Available
Directly Connected + External Multiplexed = Total Channels1, 2
No External Mux

One External
Mux

Two External
Muxes

Three External
Muxes

Four External
Muxes

5+4=9

4 + 8 = 12

3 + 12 = 15

2 + 16 = 18

1
2

28.7.3

The external trigger inputs are not shared with two analog input signals.
When external multiplexing is used, two input channels are configured as multiplexed address
outputs, and for each external multiplexer chip, one input channel is a multiplexed analog input.

Analog Subsystem

This section describes the QADC analog subsystem, which includes the front-end analog multiplexer and
analog-to-digital converter.

28.7.3.1

Analog-to-Digital Converter Operation

The analog subsystem consists of the path from the input signals to the A/D converter block. Signals from
the queue control logic are fed to the multiplexer and state machine. The end-of-conversion (EOC) signal
and the successive approximation register (SAR) reflect the result of the conversion. Figure 28-19 shows
a block diagram of the QADC analog subsystem.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-33

Queued Analog-to-Digital Converter (QADC)


16

PQA4

4
Chan. Decode & MUX
16:1

CHAN[5:0]
6

PQA0

10-bit A/D Converter

Input
Bias Circuit

Internal
Channel
Decode

Sample
Buffer

PQB0

PowerDown

State Machine & Logic


CSAMP

VRH
VRL

VSSA

SAR Timing

10

Analog
Power

Comparator

QCLK
IST
Start Conv
End OF Conv

SAR[9:0]
10

VDDA

STOP
RST

10

Signals From/to Queue Control Logic

PQB3

Successive
Approximation
Register

Figure 28-19. QADC Analog Subsystem Block Diagram

28.7.3.2

Conversion Cycle Times

Total conversion time is made up of initial sample time, final sample time, and resolution time. Initial
sample time refers to the time during which the selected input channel is coupled through the sample buffer
amplifier to the sample capacitor. The sample buffer is used to quickly reproduce its input signal on the
sample capacitor and minimize charge sharing errors. During the final sampling period the amplifier is
bypassed, and the multiplexer input charges the sample capacitor array directly for improved accuracy.
During the resolution period, the voltage in the sample capacitor is converted to a digital value and stored
in the SAR as shown in Figure 28-20.
Initial sample time is fixed at two QCLK cycles. Final sample time can be 2, 4, 8, or 16 QCLK cycles,
depending on the value of the IST field in the CCW. Resolution time is 10 QCLK cycles.
A conversion requires a minimum of 14 QCLK cycles (7 s with a 2.0-MHz QCLK). If the maximum final
sample time period of 16 QCLKs is selected, the total conversion time is 28 QCLKs or 14 s (with a
2.0-MHz QCLK).

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-34

Freescale Semiconductor

Functional Description

Buffer
Sample
Time:
2 Cycles

Final
Sample
Time:
n Cycles
(2,4,8,16)

Resolution
Time:
10 Cycles

QCLK
Sample Time

Successive Approximation Resolution Sequence

Figure 28-20. Conversion Timing

If the amplifier bypass mode is enabled for a conversion by setting the amplifier bypass (BYP) field in the
CCW, the timing changes to that shown in Figure 28-21. See Section 28.6.7, Conversion Command Word
Table (CCW) for more information on the BYP field. The initial sample time is eliminated, reducing the
potential conversion time by two QCLKs. When using the bypass mode, the external circuit should be of
low source impedance (typically less than 10 k). Also, the loading effects on the external circuitry of the
QADC need to be considered, because the benefits of the sample amplifier are not present.
NOTE
Because of internal RC time constants, use of a two QCLK sample time in
bypass mode will cause serious errors when operating the QADC at high
frequencies.
Sample
Time:
n CYCLES
(2,4,8,16)

Resolution
Time:
10 Cycles

Sample Time

Successive Approximation Resolution Sequence

QCLK

Figure 28-21. Bypass Mode Conversion Timing

28.7.3.3

Channel Decode and Multiplexer

The internal multiplexer selects one of the eight analog input signals for conversion. The selected input is
connected to the sample buffer amplifier or to the sample capacitor. The multiplexer also includes positive
and negative stress protection circuitry, which prevents deselected channels from affecting the selected
channel when current is injected into the deselected channels.

28.7.3.4

Sample Buffer

The sample buffer is used to raise the effective input impedance of the A/D converter, so that external
factors (higher bandwidth or higher impedance) are less critical to accuracy. The input voltage is buffered
onto the sample capacitor to reduce crosstalk between channels.

28.7.3.5

Comparator

The comparator output feeds into the SAR, which accumulates the A/D conversion result sequentially,
beginning with the MSB.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-35

Queued Analog-to-Digital Converter (QADC)

28.7.3.6

Bias

The bias circuit is controlled by the STOP signal to power-up and power-down all the analog circuits.

28.7.3.7

Successive Approximation Register (SAR)

The input of the SAR is connected to the comparator output. The SAR sequentially receives the conversion
value one bit at a time, starting with the MSB. After accumulating the 10 bits of the conversion result, the
SAR data is transferred to the appropriate result location, where it may be read by user software.

28.7.3.8

State Machine

The state machine generates all timing to perform an A/D conversion. An internal start-conversion signal
indicates to the A/D converter that the desired channel has been sent to the MUX. CCW[IST[1:0]] denotes
the desired sample time. CCW[BYP] determines whether to bypass the sample amplifier. Once the end of
conversion has been reached a signal is sent to the queue control logic indicating that a result is available
for storage in the result RAM.

28.8

Digital Control Subsystem

The digital control subsystem includes the control logic to sequence the conversion activity, the system
clock and periodic/interval timer, control and status registers, the conversion command word table RAM,
and the result word table RAM.
The central element for control of QADC conversions is the 64-entry conversion command word (CCW)
table. Each CCW specifies the conversion of one input channel. Depending on the application, one or two
queues can be established in the CCW table. A queue is a scan sequence of one or more input channels.
By using a pause mechanism, subqueues can be created in the two queues. Each queue can be operated
using one of several different scan modes. The scan modes for queue 1 and queue 2 are programmed in
control registers QACR1 and QACR2. Once a queue has been started by a trigger event (any of the ways
to cause the QADC to begin executing the CCWs in a queue or subqueue), the QADC performs a sequence
of conversions and places the results in the result word table.

28.8.1

Queue Priority Timing Examples

This subsection describes the QADC priority scheme when trigger events on two queues overlap or
conflict.

28.8.1.1

Queue Priority

Queue 1 has priority over queue 2 execution. These cases show the conditions under which queue 1 asserts
its priority:
When a queue is not active, a trigger event for queue 1 or queue 2 causes the corresponding queue
execution to begin.
When queue 1 is active and a trigger event occurs for queue 2, queue 2 cannot begin execution until
queue 1 reaches completion or the paused state. The status register records the trigger event by
reporting the queue 2 status as trigger pending. Additional trigger events for queue 2, which occur
before execution can begin, are flagged as trigger overruns.
When queue 2 is active and a trigger event occurs for queue 1, the current queue 2 conversion is
aborted. The status register reports the queue 2 status as suspended. Any trigger events occurring
for queue 2 while it is suspended are flagged as trigger overruns. Once queue 1 reaches the
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
28-36

Freescale Semiconductor

Digital Control Subsystem

completion or the paused state, queue 2 begins executing again. The programming of the RESUME
bit in QACR2 determines which CCW is executed in queue 2.
When simultaneous trigger events occur for queue 1 and queue 2, queue 1 begins execution and
the queue 2 status is changed to trigger pending.
When subqueues are paused

The pause feature can be used to divide queue 1 and/or queue 2 into multiple subqueues. A subqueue is
defined by setting the pause bit in the last CCW of the subqueue.
Figure 28-22 shows the CCW format and an example of using pause to create subqueues. Queue 1 is
shown with four CCWs in each subqueue and queue 2 has two CCWs in each subqueue.
The operating mode selected for queue 1 determines what type of trigger event causes the execution of
each of the subqueues within queue 1. Similarly, the operating mode for queue 2 determines the type of
trigger event required to execute each of the subqueues within queue 2.
For example, when the external trigger rising edge continuous-scan mode is selected for queue 1, and there
are six subqueues within queue 1, a separate rising edge is required on the external trigger signal after
every pause to begin the execution of each subqueue (refer to Figure 28-22).
The choice of single-scan or continuous-scan applies to the full queue, and is not applied to each subqueue.
Once a subqueue is initiated, each CCW is executed sequentially until the last CCW in the subqueue is
executed and the pause state is entered. Execution can only continue with the next CCW, which is the
beginning of the next subqueue. A subqueue cannot be executed a second time before the overall queue
execution has been completed.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-37

Queued Analog-to-Digital Converter (QADC)

Conversion Command
Word (CCW) Table

Result Word Table

P
00

Beginning of Queue 1

00

0
0
1

Pause

0
0
0
1

Pause

0
0
BQ2 0
1

End of Queue 1

Channel Select,
Sample, Hold,
A/D Conversion

Beginning of Queue 2
Pause

0
1

Pause

0
1

Pause

63

Pause

End of Queue 2

63

Figure 28-22. QADC Queue Operation with Pause

Trigger events which occur during the execution of a subqueue are ignored, but the trigger overrun flag is
set. When a continuous-scan mode is selected, a trigger event occurring after the completion of the last
subqueue (after the queue completion flag is set), causes the execution to continue with the first subqueue,
starting with the first CCW in the queue.
When the QADC encounters a CCW with the pause bit set, the queue enters the paused state after
completing the conversion specified in the CCW with the pause bit. The pause flag is set in QASR0, and
a pause interrupt may be requested. The status of the queue is shown to be paused, indicating completion
of a subqueue. The QADC then waits for another trigger event to again begin execution of the next
subqueue.

28.8.1.2

Queue Priority Schemes

Because there are two conversion command queues and only one A/D converter, a priority scheme
determines which conversion occurs. Each queue has a variety of trigger events that are intended to initiate
conversions, and they can occur asynchronously in relation to each other and other conversions in
progress. For example, a queue can be idle awaiting a trigger event; a trigger event can have occurred, but
the first conversion has not started; a conversion can be in progress; a pause condition can exist awaiting
another trigger event to continue the queue; and so on.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-38

Freescale Semiconductor

Digital Control Subsystem

The following paragraphs and figures outline the prioritizing criteria used to determine which conversion
occurs in each overlap situation.
NOTE
Each situation in Figure 28-23 through Figure 28-33 is labeled S1 through
S19. In each diagram, time is shown increasing from left to right. The
execution of queue 1 and queue 2 (Q1 and Q2) is shown as a string of
rectangles representing the execution time of each CCW in the queue. In
most of the situations, there are four CCWs (labeled C1 to C4) in both queue
1 and queue 2. In some of the situations, CCW C2 is presumed to have the
pause bit set, to show the similarities of pause and end-of-queue as
terminations of queue execution.
Trigger events are described in Table 28-22.
Table 28-22. Trigger Events
Trigger

Events

T1

Events that trigger queue 1 execution (external trigger, software-initiated single-scan


enable bit, or completion of the previous continuous loop)

T2

Events that trigger queue 2 execution (external trigger, software-initiated single-scan


enable bit, timer period/interval expired, or completion of the previous continuous
loop)

When a trigger event causes a CCW execution in progress to be aborted, the aborted conversion is shown
as a ragged end of a shortened CCW rectangle.
The situation diagrams also show when key status bits are set.
Table 28-23 describes the status bits.
Table 28-23. Status Bits
Bit

Function

CF flag

Set when the end of the queue is reached

PF flag

Set when a queue completes execution up through a pause bit

Trigger overrun
error (TOR)

Set when a new trigger event occurs before the queue is finished
servicing the previous trigger event

Below the queue execution flows are three sets of blocks that show the status information that is made
available to the user. The first two rows of status blocks show the condition of each queue as:
Idle
Active
Pause
Suspended (queue 2 only)
Trigger pending
The third row of status blocks shows the 4-bit QS status register field that encodes the condition of the two
queues. Two transition status cases, QS = 0011 and QS = 0111, are not shown because they exist only very
briefly between stable status conditions.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-39

Queued Analog-to-Digital Converter (QADC)

The first three examples in Figure 28-23 through Figure 28-25 (S1, S2, and S3) show what happens when
a new trigger event is recognized before the queue has completed servicing the previous trigger event on
the same queue.
In situation S1 (Figure 28-23), one trigger event is being recognized on each queue while that queue is still
working on the previously recognized trigger event. The trigger overrun error status bit is set, and the
premature trigger event is otherwise ignored. A trigger event that occurs before the servicing of the
previous trigger event is through does not disturb the queue execution in progress.
T1
Q1:

T1
C1

C2

C3

C4
T2

TOR1

T2

CF1
Q2:

C1

C2

C3
TOR2

IDLE

Q1:

IDLE

0000

QS:

CF2

IDLE

ACTIVE

Q2:

C4

IDLE

ACTIVE

1000

0000

0000

0010

Figure 28-23. CCW Priority Situation 1

In situation S2 (Figure 28-24), more than one trigger event is recognized before servicing of a previous
trigger event is complete. The trigger overrun bit is again set, but the additional trigger events are otherwise
ignored. After the queue is complete, the first newly detected trigger event causes queue execution to begin
again. When the trigger event rate is high, a new trigger event can be seen very soon after completion of
the previous queue, leaving little time to retrieve the previous results. Also, when trigger events are
occurring at a high rate for queue 1, the lower priority queue 2 channels may not get serviced at all.
T1

T1

T1

T1

T1
T2

Q1:

C1

C2

C3

C4

C1

C2

C3

Q2:
TOR1 TOR1 TOR1

CF1

T2

T2

C2

C3

C4
C1

TOR2 TOR2
Q1:

IDLE

ACTIVE

1000

1000

CF2

IDLE

ACTIVE

IDLE

Q2:

QS:

IDLE

C4

CF1

0000

ACTIVE

IDLE

0010

0000

Figure 28-24. CCW Priority Situation 2

Situation S3 (Figure 28-25) shows that when the pause feature is used, the trigger overrun error status bit
is set the same way and that queue execution continues unchanged.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-40

Freescale Semiconductor

Digital Control Subsystem


T1
Q1:

T1

T1

C1

C2

C3
T2

TOR1

T2
TOR1

C1

ACTIVE

QS:

PF2

PAUSE

1001

0101

CF2

IDLE

ACTIVE

0110

0100

C4

TOR2

ACTIVE

1000

0000

C3

PAUSE

IDLE

Q2:

T2

CF1

C2

TOR2
IDLE

C4

T2

PF1
Q2:

Q1:

T1

0001

ACTIVE

IDLE

0010

0000

Figure 28-25. CCW Priority Situation 3

The next two situations consider trigger events that occur for the lower priority queue 2, while queue 1 is
actively being serviced.
Situation S4 (Figure 28-26) shows that a queue 2 trigger event is recognized while queue 1 is active is
saved, and as soon as queue 1 is finished, queue 2 servicing begins.
T1
Q1:

C1

C2

C3

C4
CF1

T2

C1

C2

C3

C4

Q2:
CF2
Q1:

IDLE

QS:

TRIGGERED

IDLE

Q2:

0000

IDLE

ACTIVE

1000

1011

ACTIVE

IDLE

0010

0000

Figure 28-26. CCW Priority Situation 4

Situation S5 (Figure 28-27) shows that when multiple queue 2 trigger events are detected while queue 1 is
busy, the trigger overrun error bit is set, but queue 1 execution is not disturbed. Situation S5 also shows
that the effect of queue 2 trigger events during queue 1 execution is the same when the pause feature is
used for either queue.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-41

Queued Analog-to-Digital Converter (QADC)

T1
Q1:

T1
C1

C2
T2 T2

C3

T2 T2

PF1

Q2:

C1

Q2:

QS:

IDLE

0110

CF2
IDLE

ACTIVE
ACTIVE

ACTIVE

1000 1011

0000

C4

TOR2

PAUSE

TRIG

IDLE

C3
PF2

ACTIVE

CF1

C2

TOR2
Q1:

C4

PAUSE

TRIG

ACTIVE

IDLE

0010

0000

0101 1001 1011

Figure 28-27. CCW Priority Situation 5

The remaining situations, S6 through S11, show the impact of a queue 1 trigger event occurring during
queue 2 execution. Because queue 1 has higher priority, the conversion taking place in queue 2 is aborted
so that there is no variable latency time in responding to queue 1 trigger events.
In situation 6 (Figure 28-28), the conversion initiated by the second CCW in queue 2 is aborted just before
the conversion is complete, so that queue 1 execution can begin. Queue 2 is considered suspended. After
queue 1 is finished, queue 2 starts over with the first CCW, when the RESUME control bit is set to 0.
Situation S7 (Figure 28-29) shows that when pause operation is not used with queue 2, queue 2 suspension
works the same way.
T1
Q1:

T1
C1

C2

C3

C4

RESUME = 0

T2
PF1
Q2:

CF1
C1

C1

C2

C2

C3

C4
CF2

Q1:

Q2:

QS

IDLE

ACTIVE

PAUSE

IDLE

0000

1000

0100

ACTIVE
ACTIVE

IDLE

ACTIVE

SUSPEND

ACTIVE

0110

1010

0010

IDLE

0000

Figure 28-28. CCW Priority Situation 6

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-42

Freescale Semiconductor

Digital Control Subsystem


.

T1
Q1:

T1
C1

C2

T2
Q2:

C3

PF1
C1
C1

C4

T2
C1

CF1

C3

C2

C3

C4
CF2

PF2
IDLE

Q1:

ACTIVE

Q2:

IDLE

ACTIVE

QS:

0000

0010

SUSPEND

PAUSE

ACTIVE

ACTIVE PAUSE ACT

0101 0110

0110

1010

SUSPEND

1010

IDLE

ACTIVE

IDLE

0010

0000

Figure 28-29. CCW Priority Situation 7

Situations S8 and S9 (Figure 28-30 and Figure 28-31) repeat the same two situations with the RESUME
bit set to a 1. When the RESUME bit is set, following suspension, queue 2 resumes execution with the
aborted CCW, not the first CCW, in the queue.
T1
Q1:

T1
C1

C2

C3

C4

T2
PF1
Q2:

CF1
C1

C2

C2

C3

RESUME=1

C4
CF2

Q1:

IDLE

Q2:

QS:

ACTIVE

PAUSE

IDLE

0000

1000

0100

ACTIVE
ACTIVE

IDLE

ACTIVE

SUSPEND

ACTIVE

IDLE

0110

1010

0010

0000

Figure 28-30. CCW Priority Situation 8

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-43

Queued Analog-to-Digital Converter (QADC)

T1
Q1:

T1
C1

C2

T2
Q2:

C3

PF1
C1
C1

C2

C4

T2

CF1
C4

C3

C2

C4
CF2

PF2
ACTIVE

IDLE

Q1:

Q2:

IDLE

ACTIVE

QS:

0000

0010

PAUSE

ACTIVE

SUSPEND ACT PAUSE ACTIVE

1010

RESUME=1

0110 0101

IDLE

IDLE

SUSPEND ACT

0110

1010

0000

0010

Figure 28-31. CCW Priority Situation 9

Situations S10 and S11 (Figure 28-32 and Figure 28-33) show that when an additional trigger event is
detected for queue 2 while the queue is suspended, the trigger overrun error bit is set, the same as if queue
2 were being executed when a new trigger event occurs. Trigger overrun on queue 2 thus allows the user
to know that queue 1 is taking up so much QADC time that queue 2 trigger events are being lost.
T1
Q1:
T2
Q2:

T1
C1

C2

T2
C1

C3

PF1

T2
C1

C2

C2

TOR2

Q2:

IDLE

QS:

0000

ACTIVE

0010

SUSPEND

1010

T2

CF1
C3

C3
PF2

ACTIVE

IDLE

Q1:

C4

PAUSE

ACTIVE

PAUSE ACT

0110

0101 0110

C4
CF2

TOR2
ACTIVE

SUSPEND

1010

RESUME = 0

IDLE

ACTIVE

IDLE

0010

0000

Figure 28-32. CCW Priority Situation 10

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-44

Freescale Semiconductor

Digital Control Subsystem

T1
C1

Q1:
T2
Q2:

T1
C2

T2
C1

PF1

C2

IDLE

QS:

0000

ACTIVE

C3

C4

PAUSE

RESUME = 1

C4
CF2

ACTIVE

ACTIVE

0110 0101

1010

CF1

TOR2

SUSPEND ACT PAUSE

0010

C4

T2

PF2

ACTIVE

IDLE

Q2:

T2
C2

TOR2
Q1:

C3

0110

IDLE

SUSPEND ACT

1010

0010

IDLE

0000

Figure 28-33. CCW Priority Situation 11

The previous situations cover normal overlap conditions that arise with asynchronous trigger events on the
two queues. An additional conflict to consider is that the freeze condition can arise while the QADC is
actively executing CCWs. The conventional use for the debug mode is for software/hardware debugging.
When the CPU enters background debug mode, peripheral modules can cease operation. When freeze is
detected, the QADC completes the conversion in progress, unlike the abort that occurs when queue 1
suspends queue 2. After the freeze condition is removed, the QADC continues queue execution with the
next CCW in sequence.
Trigger events that occur during freeze are not captured. When a trigger event is pending for queue 2 before
freeze begins, that trigger event is remembered when the freeze is passed. Similarly, when freeze occurs
while queue 2 is suspended, after freeze, queue 2 resumes execution as soon as queue 1 is finished.
Situations 12 through 19 (Figure 28-34 to Figure 28-41) show examples of all of the freeze situations.
FREEZE
T1
Q1:

C1

C2

C3

C4
CF1

Figure 28-34. CCW Freeze Situation 12

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-45

Queued Analog-to-Digital Converter (QADC)

FREEZE
T2
Q2:

C1

C2

C3

C4
CF2

Figure 28-35. CCW Freeze Situation 13


TRIGGERS IGNORED
FREEZE

T1
Q1:

T1 T1
C1

C2

C3

C4

T2 T2
CF1

Figure 28-36. CCW Freeze Situation 14


TRIGGERS IGNORED
FREEZE

T2
Q2:

T2 T2
C1

C2

C3

C4

T1 T1
CF2

Figure 28-37. . CCW Freeze Situation 15


TRIGGERS IGNORED
FREEZE

T1
Q1:

T1
C1

C2

T1
C3

PF1

C4
CF1

Figure 28-38. CCW Freeze Situation 16

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-46

Freescale Semiconductor

Digital Control Subsystem

TRIGGERS IGNORED
FREEZE

T2

T2
Q2:

C1

T2

C2

C3

C4

PF2

CF2

Figure 28-39. CCW Freeze Situation 17


FREEZE
T1
Q1:

C1

C2

C3

C4

T2

CF1

Q2:
TRIGGER CAPTURED, RESPONSE DELAYED AFTER FREEZE

C1

C2

C3

C4
CF2

Figure 28-40. CCW Freeze Situation 18


FREEZE
T1
Q1:

C1

C2

C3

C4

T2
Q2:

CF1
C1

C2

C3

C4

C4
CF2

Figure 28-41. CCW Freeze Situation 19

28.8.2

Boundary Conditions

The queue operation boundary conditions are:


The first CCW in a queue specifies channel 63, the end-of-queue (EOQ) code. The queue becomes
active and the first CCW is read. The end-of-queue is recognized, the completion flag is set, and
the queue becomes idle. A conversion is not performed.
BQ2 (beginning of queue 2) is set at the end of the CCW table (63) and a trigger event occurs on
queue 2. The end-of-queue condition is recognized, a conversion is performed, the completion flag
is set, and the queue becomes idle.
BQ2 is set to CCW0 and a trigger event occurs on queue 1. After reading CCW0, the end-of-queue
condition is recognized, the completion flag is set, and the queue becomes idle. A conversion is not
performed.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-47

Queued Analog-to-Digital Converter (QADC)

BQ2 (beginning of queue 2) is set beyond the end of the CCW table (64127) and a trigger event
occurs on queue 2. The end-of-queue condition is recognized immediately, the completion flag is
set, and the queue becomes idle. A conversion is not performed.
NOTE
Multiple end-of-queue conditions may be recognized simultaneously,
although there is no change in QADC behavior. For example, if BQ2 is set
to CCW0, CCW0 contains the EOQ code, and a trigger event occurs on
queue 1, the QADC reads CCW0 and detects both end-of-queue conditions.
The completion flag is set and queue 1 becomes idle.

Boundary conditions also exist for combinations of pause and end-of-queue. One case is when a pause bit
is in one CCW and an end-of-queue condition is in the next CCW. The conversion specified by the CCW
with the pause bit set completes normally. The pause flag is set. However, because the end-of-queue
condition is recognized, the completion flag is also set and the queue status becomes idle, not paused.
Examples of this situation include:
The pause bit is set in CCW5 and the channel 63 (EOQ) code is in CCW6.
The pause is in CCW63.
During queue 1 operation, the pause bit is set in CCW20 and BQ2 points to CCW21.
Another pause and end-of-queue boundary condition occurs when the pause and an end-of-queue
condition occur in the same CCW. Both the pause and end-of-queue conditions are recognized
simultaneously. The end-of-queue condition has precedence so a conversion is not performed for the CCW
and the pause flag is not set. The QADC sets the completion flag and the queue status becomes idle.
Examples of this situation are:
The pause bit is set in CCW10 and EOQ is programmed into CCW10.
During queue 1 operation, the pause bit set in CCW32, which is also BQ2.

28.8.3

Scan Modes

The QADC queuing mechanism allows application software to utilize different requirements for
automatically scanning input channels.
In single-scan mode, a single pass through a sequence of conversions defined by a queue is performed. In
continuous-scan mode, multiple passes through a sequence of conversions defined by a queue are
executed.
The possible modes are:
Disabled mode and reserved mode
Software-initiated single-scan mode
Externally triggered single-scan mode
Externally gated single-scan mode
Interval timer single-scan mode
Software-initiated continuous-scan mode
Externally triggered continuous-scan mode
Externally gated continuous-scan mode
Periodic timer continuous-scan mode
The following paragraphs describe single-scan and continuous-scan operations.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-48

Freescale Semiconductor

Digital Control Subsystem

28.8.4

Disabled Mode

When disabled mode is selected, the queue is not active. Trigger events cannot initiate queue execution.
When both queue 1 and queue 2 are disabled, there is no possibility of encountering wait states when
accessing CCW table and result RAM. When both queues are disabled, it is safe to change the QCLK
prescaler values.

28.8.5

Reserved Mode

Reserved mode is available for future mode definitions. When reserved mode is selected, the queue is not
active. The behavior is the same as disabled mode.

28.8.6

Single-Scan Modes

A single-scan queue operating mode is used to execute a single pass through a sequence of conversions
defined by a queue. By programming the MQ1 field in QACR1 or the MQ2 field in QACR2, these modes
can be selected:
Software-initiated single-scan mode
Externally triggered single-scan mode
Externally gated single-scan mode
Interval timer single-scan mode
NOTE
Queue 2 cannot be programmed for externally gated single-scan mode.
In all single-scan queue operating modes, queue execution is enabled by writing the single-scan enable bit
to a 1 in the queues control register. The single-scan enable bits, SSE1 and SSE2, are provided for queue
1 and queue 2, respectively.
Until a queues single-scan enable bit is set, any trigger events for that queue are ignored. The single-scan
enable bit may be set to a 1 during the same write cycle that selects the single-scan queue operating mode.
The single-scan enable bit can be written only to 1, but will always read 0. Once set, writing the single-scan
enable bit to 0 has no effect. Only the QADC can clear the single-scan enable bit. The completion flag,
completion interrupt, or queue status is used to determine when the queue has completed.
After the single-scan enable bit is set, a trigger event causes the QADC to begin execution with the first
CCW in the queue. The single-scan enable bit remains set until the queue is completed. After the queue
reaches completion, the QADC resets the single-scan enable bit to 0. Writing the single-scan enable bit to
a 1 or a 0 before the queue scan is complete has no effect; however, if the queue operating mode is changed,
the new queue operating mode and the value of the single-scan enable bit are recognized immediately. The
conversion in progress is aborted, and the new queue operating mode takes effect.
In software-initiated single-scan mode, writing a 1 to the single-scan enable bit causes the QADC to
generate a trigger event internally, and queue execution begins immediately. In the other single-scan queue
operating modes, once the single-scan enable bit is written, the selected trigger event must occur before
the queue can start. The single-scan enable bit allows the entire queue to be scanned once. A trigger
overrun is captured if a trigger event occurs during queue execution in an edge-sensitive external trigger
mode or a periodic/interval timer mode.
In the interval timer single-scan mode, the next expiration of the timer is the trigger event for the queue.
After queue execution is complete, the queue status is shown as idle. The queue can be restarted by setting
the single-scan enable bit to 1. Queue execution begins with the first CCW in the queue.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-49

Queued Analog-to-Digital Converter (QADC)

28.8.6.1

Software-Initiated Single-Scan Mode

Software can initiate the execution of a scan sequence for queue 1 or 2 by selecting software-initiated
single-scan mode and writing the single-scan enable bit in QACR1 or QACR2. A trigger event is generated
internally and the QADC immediately begins execution of the first CCW in the queue. If a pause occurs,
another trigger event is generated internally, and then execution continues without pausing.
The QADC automatically performs the conversions in the queue until an end-of-queue condition is
encountered. The queue remains idle until the single-scan enable bit is again set. While the time to
internally generate and act on a trigger event is very short, the queue status field can be read as
momentarily indicating that the queue is paused. The trigger overrun flag is never set while in
software-initiated single-scan mode.
The software-initiated single-scan mode is useful when:
Complete control of queue execution is required
There is a need to easily alternate between several queue sequences

28.8.6.2

Externally Triggered Single-Scan Mode

The externally triggered single-scan mode is available on both queue 1 and queue 2. Both rising and falling
edge triggered modes are available. A scan must be enabled by setting the single-scan enable bit for the
queue.
The first external trigger edge causes the queue to be executed one time. Each CCW is read and the
indicated conversions are performed until an end-of-queue condition is encountered. After the queue is
completed, the QADC clears the single-scan enable bit. The single-scan enable bit can be written again to
allow another scan of the queue to be initiated by the next external trigger edge.
The externally triggered single-scan mode is useful when the input trigger rate can exceed the queue
execution rate. Analog samples can be taken in sync with an external event, even though application
software does not require data taken from every edge. Externally triggered single-scan mode can be
enabled to get one set of data and, at a later time, be enabled again for the next set of samples.
When a pause bit is encountered during externally triggered single-scan mode, another trigger event is
required for queue execution to continue. Software involvement is not required for queue execution to
continue from the paused state.

28.8.6.3

Externally Gated Single-Scan Mode

The QADC provides external gating for queue 1 only. When externally gated single-scan mode is selected,
the input level on the associated external trigger signal enables and disables queue execution. The polarity
of the external gate signal is fixed so that only a high level opens the gate and a low level closes the gate.
Once the gate is open, each CCW is read and the indicated conversions are performed until the gate is
closed. Queue scan must be enabled by setting the single-scan enable bit for queue 1. If a pause is
encountered, the pause flag does not set, and execution continues without pausing.
While the gate is open, queue 1 executes one time. Each CCW is read and the indicated conversions are
performed until an end-of-queue condition is encountered. When queue 1 completes, the QADC sets the
completion flag (CF1) and clears the single-scan enable bit. Set the single-scan enable bit again to allow
another scan of queue 1 to be initiated during the next open gate.
If the gate closes before queue 1 completes execution, the current CCW completes, execution of queue 1
stops, the single-scan enable bit is cleared, and the PF1 bit is set. The CWPQ1 field can be read to
determine the last valid conversion in the queue. The single-scan enable bit must be set again and the PF1

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


28-50

Freescale Semiconductor

Digital Control Subsystem

bit should be cleared before another scan of queue 1 is initiated during the next open gate. The start of
queue 1 is always the first CCW in the CCW table.
Because the gate level is only sampled after each conversion during queue execution, closing the gate for
a period less than a conversion time interval does not guarantee the closure will be captured.

28.8.6.4

Interval Timer Single-Scan Mode

Both queues can use the periodic/interval timer in a single-scan queue operating mode. The timer interval
can range from 27 to 217 QCLK cycles in binary multiples. When the interval timer single-scan mode is
selected and the single-scan enable bit is set in QACR1 or QACR2, the timer begins counting. When the
time interval elapses, an internal trigger event is generated to start the queue and the QADC begins
execution with the first CCW.
The QADC automatically performs the conversions in the queue until a pause or an end-of-queue
condition is encountered. When a pause occurs, queue execution stops until the timer interval elapses
again, and queue execution continues. When queue execution reaches an end-of-queue situation, the
single-scan enable bit is cleared. Set the single-scan enable bit again to allow another scan of the queue to
be initiated by the interval timer.
The interval timer generates a trigger event whenever the time interval elapses. The trigger event may
cause queue execution to continue following a pause or may be considered a trigger overrun. Once queue
execution is completed, the single-scan enable bit must be set again to allow the timer to count again.
Normally, only one queue is enabled for interval timer single-scan mode, and the timer will reset at the
end-of-queue. However, if both queues are enabled for either single-scan or continuous interval timer
mode, the end-of-queue condition will not reset the timer while the other queue is active. In this case, the
timer will reset when both queues have reached end-of-queue. See Section 28.8.9, Periodic/Interval
Timer for a definition of interval timer reset conditions.
The interval timer single-scan mode can be used in applications that need coherent results. For example:
When it is necessary that all samples are guaranteed to be taken during the same scan of the analog
signals
When the interrupt rate in the periodic timer continuous-scan mode would be too high
In sensitive battery applications, where the interval timer single-scan mode uses less power than
the software-initiated continuous-scan mode

28.8.7

Continuous-Scan Modes

A continuous-scan queue operating mode is used to execute multiple passes through a sequence of
conversions defined by a queue. By programming the MQ1 field in QACR1 or the MQ2 field in QACR2,
these modes can be selected:
Software-initiated continuous-scan mode
Externally triggered continuous-scan mode
Externally gated continuous-scan mode
Periodic timer continuous-scan mode
NOTE
Queue 2 cannot be programmed for externally gated continuous-scan mode.
When a queue is programmed for a continuous-scan mode, the single-scan enable bit in the queue control
register does not have any meaning or effect. As soon as the queue operating mode is programmed, the
selected trigger event can initiate queue execution.
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
Freescale Semiconductor

28-51

Queued Analog-to-Digital Converter (QADC)

In the case of software-initiated continuous-scan mode, the trigger event is generated internally and queue
execution begins immediately. In the other continuous-scan queue operating modes, the selected trigger
event must occur before the queue can start. A trigger overrun is captured if a trigger event occurs during
queue execution in the externally triggered continuous-scan mode or the periodic timer continuous-scan
mode.
After queue execution is complete, the queue status is shown as idle. Because the continuous-scan queue
operating modes allow the entire queue to be scanned multiple times, software involvement is not needed
for queue execution to continue from the idle state. The next trigger event causes queue execution to begin
again, starting with the first CCW in the queue.
NOTE
In continuous-scan modes, all samples are guaranteed to be taken during
one pass through the queue (coherently), except when a queue 1 trigger
event halts queue 2 execution. The time between consecutive conversions
has been designed to be consistent. However, for queues that end with a
CCW containing the EOQ code (channel 63), the time between the last
queue conversion and the first queue conversion requires one additional
CCW fetch cycle. Continuous samples are not coherent at this boundary.
In addition, the time from trigger to first conversion cannot be guaranteed,
because it is a function of clock synchronization, programmable trigger
events, queue priorities, and so on.

28.8.7.1

Software-Initiated Continuous-Scan Mode

When software-initiated continuous-scan mode is selected, the trigger event is generated automatically by
the QADC. Queue execution begins immediately. If a pause is encountered, another trigger event is
generated internally, and execution continues without pausing. When the end-of-queue is reached, another
internal trigger event is generated and queue execution restarts at the beginning of the queue.
While the time to internally generate and act on a trigger event is very short, the queue status field can be
read as momentarily indicating that the queue is idle. The trigger overrun flag is never set while in
software-initiated continuous-scan mode.
The software-initiated continuous-scan mode keeps the result registers updated more frequently than any
of the other queue operating modes. The result table can always be read to get the latest converted value
for each channel. The channels scanned are kept up to date by the QADC without software involvement.
The software-initiated continuous-scan mode may be chosen for either queue, but is normally used only
with queue 2. When software-initiated continuous-scan mode is chosen for queue 1, that queue operates
continuously and queue 2, being lower in priority, never gets executed. The short interval of time between
a queue 1 completion and the subsequent trigger event is not sufficient to allow queue 2 execution to begin.
The software-initiated continuous-scan mode is a useful choice with queue 2 for converting channels that
do not need to be synchronized to anything or for slow-to-change analog channels. Interrupts are normally
not used with the software-initiated continuous-scan mode. Rather, the latest conversion results can be read
from the result table at any time. Once initiated, software action is not needed to sustain conversions of
channel.

28.8.7.2

Externally Triggered Continuous-Scan Mode

The QADC provides external trigger signals for both queues. When externally triggered continuous-scan
mode is selected, a transition on the associated external trigger signal initiates queue execution. The
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
28-52

Freescale Semiconductor

Digital Control Subsystem

polarity of the external trigger signal is programmable, so that a mode which begins queue execution on
the rising or falling edge can be selected. Each CCW is read and the indicated conversions are performed
until an end-of-queue condition is encountered. When the next external trigger edge is detected, queue
execution begins again automatically. Software involvement is not needed between trigger events.
When a pause bit is encountered in externally triggered continuous-scan mode, another trigger event is
required for queue execution to continue. Software involvement is not needed for queue execution to
continue from the paused state.
Some applications need to synchronize the sampling of analog channels to external events. There are cases
when it is not possible to use software initiation of the queue scan sequence, because interrupt response
times vary. Externally triggered continuous-scan mode is useful in these cases.

28.8.7.3

Externally Gated Continuous-Scan Mode

The QADC provides external gating for queue 1 only. When externally gated continuous-scan mode is
selected, the input level on the associated external trigger signal enables and disables queue execution. The
polarity of the external gate signal is fixed so that a high level opens the gate and a low level closes the
gate. Once the gate is open, each CCW is read and the indicated conversions are performed until the gate
is closed. When the gate opens again, queue execution automatically restarts at the beginning of the queue.
Software involvement is not needed between trigger events. If a pause in a CCW is encountered, the pause
flag does not set, and execution continues without pausing.
The purpose of externally gated continuous-scan mode is to continuously collect digitized samples while
the gate is open and to have the most recent samples available. It is up to the programmer to ensure that
the gate is not opened so long that an end-of-queue is reached.
In the event that the queue completes before the gate closes, the CF1 flag will set, and the queue will roll
over to the beginning and continue conversions until the gate closes. If the gate remains open and the CF1
flag is not cleared, when the queue completes a second time the TOR1 flag will set and the queue will
roll-over again. The queue will continue to execute until the gate closes or the mode is disabled.
If the gate closes before queue 1 completes execution, the QADC stops and sets the PF1 bit to indicate an
incomplete queue. The CWPQ1 field can be read to determine the last valid conversion in the queue. If the
gate opens again, execution of queue 1 restarts. The start of queue 1 is always the first CCW in the CCW
table. The condition of the gate is only sampled after each conversion during queue execution, so closing
the gate for a period less than a conversion time interval does not guarantee the closure will be captured.

28.8.7.4

Periodic Timer Continuous-Scan Mode

The QADC includes a dedicated periodic timer for initiating a scan sequence on queue 1 and/or queue 2.
A programmable timer interval ranging from 27 to 217 times the QCLK period in binary multiples can be
selected. The QCLK period is prescaled down from the MCU clock.
When a periodic timer continuous-scan mode is selected, the timer begins counting. After the programmed
interval elapses, the timer generated trigger event starts the appropriate queue. The QADC automatically
performs the conversions in the queue until an end-of-queue condition or a pause is encountered. When a
pause occurs, the QADC waits for the periodic interval to expire again, then continues with the queue.
Once EOQ has been detected, the next trigger event causes queue execution to restart with the first CCW
in the queue.
The periodic timer generates a trigger event whenever the time interval elapses. The trigger event may
cause queue execution to continue following a pause or queue completion or may be considered a trigger
overrun. As with all continuous-scan queue operating modes, software action is not needed between

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-53

Queued Analog-to-Digital Converter (QADC)

trigger events. Because both queues may be triggered by the periodic/interval timer, see Section 28.8.9,
Periodic/Interval Timer for a summary of periodic/interval timer reset conditions.

28.8.8

QADC Clock (QCLK) Generation

Figure 28-42 is a block diagram of the QCLK subsystem. The QCLK provides the timing for the A/D
converter state machine which controls the timing of the conversion. The QCLK is also the input to a
17-stage binary divider which implements the periodic/interval timer. To retain the specified analog
conversion accuracy, the QCLK frequency (fQCLK) must be within the tolerance specified in MCF5282
Electrical Characteristics.
Before using the QADC, the prescaler must be initialized with values that put the QCLK within the
specified range. Though most applications initialize the prescaler once and do not change it, write
operations to the prescaler fields are permitted.
QPR[6:0]
System Clock

Divide
by 2

Prescaler

SAR Control

Input Sample Time


from CCW
2

ATD Converter
State Machine

SAR

10

Binary Counter
27 28 29 210 211 212 213 214 215 216 217
Queue 1 and Queue 2 Timer
Mode Rate Selection

Periodic Timer/Interval Timer


Select

Periodic/Interval Trigger
Event for Q1 and Q2

Figure 28-42. QADC Clock Subsystem Functions

CAUTION
A change in the prescaler value while a conversion is in progress is likely to
corrupt the result. Therefore, any prescaler write operation should be done
only when both queues are in the disabled modes.
To accommodate the wide range of the system clock frequency, QCLK is generated by a programmable
prescaler which divides the system clock. To allow the A/D conversion time to be maximized across the
spectrum of system clock frequencies, the QADC prescaler permits the QCLK frequency to be software
selectable. The frequency of QCLK is set with the QPR field in QACR0.

28.8.9

Periodic/Interval Timer

The QADC periodic/interval timer can be used to generate trigger events at a programmable interval,
initiating execution of queue 1 and/or queue 2. The periodic/interval timer stays reset under these
conditions:
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
28-54

Freescale Semiconductor

Digital Control Subsystem

Both queue 1 and queue 2 are programmed to any mode which does not use the periodic/interval
timer.
System reset is asserted.
Stop mode is enabled.
Debug mode is enabled.
NOTE
Interval timer single-scan mode does not start the periodic/interval timer
until the single-scan enable bit is set.

These conditions will cause a pulsed reset of the periodic/interval timer during use:
A queue 1 operating mode change to a mode which uses the periodic/interval timer, even if queue
2 is already using the timer
A queue 2 operating mode change to a mode which uses the periodic/interval timer, provided queue
1 is not in a mode which uses the periodic/interval timer
Roll over of the timer
During stop mode, the periodic/interval timer is held in reset. Because stop mode causes QACR1 and
QACR2 to be reset to 0, a valid periodic or interval timer mode must be written after leaving stop mode to
release the timer from reset.
When QADC debug mode is entered and a periodic or interval timer mode is selected, the timer counter
is reset after the conversion in progress completes. When the periodic or interval timer mode has been
enabled (the timer is counting), but a trigger event has not been issued, debug mode takes effect
immediately, and the timer is held in reset. Removal of the QADC debug condition restarts the counter
from the beginning. Refer to Section 28.3.1, Debug Mode for more information.

28.8.10 Conversion Command Word Table


The conversion command word (CCW) table is 64 half-word (128 byte) long RAM with 10 bits of each
entry implemented. The CCW table is written by the user and is not modified by the QADC. Each CCW
requests the conversion of one analog channel to a digital result. The CCW specifies the analog channel
number, the input sample time, and whether the queue is to pause after the current CCW. The 10
implemented bits of the CCW can be read and written. The remaining six bits are unimplemented and read
as 0s; write operations have no effect. Each location in the CCW table corresponds to a location in the
result word table. When a conversion is completed for a CCW entry, the 10-bit result is written in the
corresponding result word entry.
The beginning of queue 1 is the first location in the CCW table. The first location of queue 2 is specified
by the beginning of queue 2 pointer field (BQ2) in QACR2. To dedicate the entire CCW table to queue 1,
place queue 2 in disabled mode and write BQ2 to 64 or greater. To dedicate the entire CCW table to queue
2, place queue 1 in disabled mode and set BQ2 to the first location in the CCW table (CCW0).
Figure 28-43 illustrates the operation of the queue structure.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-55

Queued Analog-to-Digital Converter (QADC)

Conversion Command
Word (CCW) Table
00

Result Word Table

Beginning of Queue 1

00

Channel Select,
Sample, Hold,
A/D Conversion

End of Queue 1
Beginning of Queue 2

63

63

End of Queue 2

10-bit Conversion Command


Word Format

10-bit Result, Readable in


Three 16-BIT Formats

[7:6]

[5:0]

15 14 13 12 11 10

[9:0]

BYP

IST

CHAN

0 0 0 0 0 0

RESULT

Right-Justified, Unsigned Result


P Pause after Conversion
until Next Trigger
BYP Bypass Buffer Amplifier
IST Input Sample Time
CHAN Channel Number and
End-of-Queue Code

[15:6]
S

RESULT

[5:0]
0 0 0 0 0 0

Left-Justified, Signed Result


[15:6]

[5:0]

RESULT

0 0 0 0 0 0

Left-Justified, Unsigned Result

Figure 28-43. QADC Conversion Queue Operation

To prepare the QADC for a scan sequence, write to the CCW table to specify the desired channel
conversions. The criteria for queue execution is established by selecting the queue operating mode. The
queue operating mode determines what type of trigger event starts queue execution. A trigger event refers
to any of the ways that cause the QADC to begin executing the CCWs in a queue or subqueue. An external
trigger is only one of the possible trigger events.
A scan sequence may be initiated by:
A software command
Expiration of the periodic/interval timer
An external trigger signal
An external gated signal (queue 1 only)
The queue can be scanned in single pass or continuous fashion. When a single-scan mode is selected, the
scan must be engaged by setting the single-scan enable bit. When a continuous-scan mode is selected, the
queue remains active in the selected queue operating mode after the QADC completes each queue scan
sequence.
During queue execution, the QADC reads each CCW from the active queue and executes conversions in
three stages:
Initial sample
Final sample
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
28-56

Freescale Semiconductor

Digital Control Subsystem

Resolution

During initial sample, a buffered version of the selected input channel is connected to the sample capacitor
at the input of the sample buffer amplifier.
During the final sample period, the sample buffer amplifier is bypassed, and the multiplexer input charges
the sample capacitor directly. Each CCW specifies a final input sample time of 2, 4, 8, or 16 QCLK cycles.
When an analog-to-digital conversion is complete, the result is written to the corresponding location in the
result word table. The QADC continues to sequentially execute each CCW in the queue until the end of
the queue is detected or a pause bit is found in a CCW.
When the pause bit is set in the current CCW, the QADC stops execution of the queue until a new trigger
event occurs. The pause status flag bit is set, and an interrupt may optionally be requested. After the trigger
event occurs, the paused state ends, and the QADC continues to execute each CCW in the queue until
another pause is encountered or the end of the queue is detected.
An end-of-queue condition occurs when:
The CCW channel field is programmed with 63 to specify the end of the queue.
The end-of-queue 1 is implied by the beginning of queue 2, which is specified by the BQ2 field in
QACR2.
The physical end of the queue RAM space defines the end of either queue.
When any of the end-of-queue conditions is recognized, a queue completion flag is set, and if enabled, an
interrupt is requested. These situations prematurely terminate queue execution:
Queue 1 is higher in priority than queue 2. When a trigger event occurs on queue 1 during queue 2
execution, the execution of queue 2 is suspended by aborting the execution of the CCW in progress,
and queue 1 execution begins. When queue 1 execution is complete, queue 2 conversions restart
with the first CCW entry in queue 2 or the first CCW of the queue 2 subqueue being executed when
queue 2 was suspended. Alternately, conversions can restart with the aborted queue 2 CCW entry.
The RESUME bit in QACR2 selects where queue 2 begins after suspension. By choosing to
re-execute all of the suspended queue 2 CCWs (RESUME = 0), all of the samples are guaranteed
to have been taken during the same scan pass. However, a high trigger event rate for queue 1 can
prevent completion of queue 2. If this occurs, execution of queue 2 can begin with the aborted
CCW entry (RESUME = 1).
Any conversion in progress for a queue is aborted when that queues operating mode is changed to
disabled. Putting a queue into the disabled mode does not power down the converter.
Changing a queues operating mode to another valid mode aborts any conversion in progress. The
queue restarts at its beginning once an appropriate trigger event occurs.
For low-power operation, the stop bit can be set to prepare the module for a loss of clocks. The
QADC aborts any conversion in progress when stop mode is entered.
When the QADC debug bit is set and the CPU enters background debug mode, the QADC freezes
at the end of the conversion in progress. After leaving debug mode, the QADC resumes queue
execution beginning with the next CCW entry. Refer to Section 28.3.1, Debug Mode for more
information.

28.8.11 Result Word Table


The result word table is a 64 half-word (128 byte) long by 10-bit wide RAM. An entry is written by the
QADC after completing an analog conversion specified by the corresponding CCW table entry. The result
word table can be read or written, but in normal operation is only read to obtain analog conversions from
the QADC. Unimplemented bits read as 0s and writes have no effect.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

28-57

Chapter 33
Electrical Characteristics
This chapter contains electrical specification tables and reference timing diagrams for the MCF5282
microcontroller unit. This section contains detailed information on power considerations, DC/AC
electrical characteristics, and AC timing specifications of MCF5282.
The electrical specifications are preliminary and are from previous designs or design simulations. These
specifications may not be fully tested or guaranteed at this early stage of the product life cycle; however,
these specifications will be met for production silicon. Finalized specifications will be published after
complete characterization and device qualifications have been completed.
NOTE
The parameters specified in this MCU document supersede any values
found in the module specifications.

33.1

Maximum Ratings
Table 33-1. Absolute Maximum Ratings1, 2
Rating

Symbol

Value

Unit

VDD

0.3 to +4.0

Clock Synthesizer Supply Voltage

VDDPLL

0.3 to +4.0

RAM Memory Standby Supply Voltage

VSTBY

0.3 to + 4.0

Flash Memory Supply Voltage

VDDF

0.3 to +4.0

Flash Memory Program / Erase Supply Voltage

VPP

0.3 to + 6.0

Analog Supply Voltage

VDDA

0.3 to +6.0

Analog Reference Supply Voltage

VRH

0.3 to +6.0

Analog ESD Protection Voltage

VDDH

0.3 to +6.0

Supply Voltage

Digital Input Voltage

VIN

0.3 to + 6.0

VAIN

0.3 to + 6.0

EXTAL pin voltage

VEXTAL

0 to 3.3

XTAL pin voltage

Analog Input Voltage

VXTAL

0 to 3.3

Instantaneous Maximum Current


Single pin limit (applies to all pins) 3, 4, 5

ID

25

mA

Maximum Power Supply Current 5

IDD

300

mA

Operating Temperature Range (Packaged)

TA

40 to 85

Tstg

65 to 150

Tj

105

oC

HBM

2000

Storage Temperature Range


Maximum operating junction temperature
ESD Target for Human Body
1

Model6

Functional operating conditions are given in DC Electrical Specifications. Absolute Maximum


Ratings are stress ratings only, and functional operation at the maxima is not guaranteed.
Stress beyond those listed may affect device reliability or cause permanent damage to the
device.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

33-1

Electrical Characteristics
2

4
5

33.2

This device contains circuitry protecting against damage due to high static voltage or electrical
fields; however, it is advised that normal precautions be taken to avoid application of any
voltages higher than maximum-rated voltages to this high-impedance circuit. Reliability of
operation is enhanced if unused inputs are tied to an appropriate logic voltage level (e.g., either
VSS or VDD).
Input must be current limited to the value specified. To determine the value of the required
current-limiting resistor, calculate resistance values for positive and negative clamp voltages,
then use the larger of the two values. 6.0V voltage excludes XTAL and EXTAL pads.
All functional non-supply pins are internally clamped to VSS and VDD.
Power supply must maintain regulation within operating VDD range during instantaneous and
operating maximum current conditions. If positive injection current (Vin > VDD) is greater than
IDD, the injection current may flow out of VDD and could result in external power supply going
out of regulation. Insure external VDD load will shunt current greater than maximum injection
current. This will be the greatest risk when the MCU is not consuming power (ex; no
clock).Power supply must maintain regulation within operating VDD range during instantaneous
and operating maximum current conditions.
All ESD testing methodology is in conformity with CDF-AEC-Q100 Stress Test Qualification for
Automotive Grade Integrated Circuits.

Thermal Characteristics

Table 33-2 lists thermal resistance values.


Table 33-2. Thermal Characteristics
Characteristic

2
3
4
5

Value

Unit

Junction to ambient, natural convection

Four layer board (2s2p)

JMA

261,2

C/W

Junction to ambient (@200 ft/min)

Four layer board (2s2p)

JMA

231,2

C/W

Junction to board

JB

153

C/W

Junction to case

JC

104

C/W

jt

21,5

C/W

Junction to top of package


1

Symbol

Natural convection

JMA and jt parameters are simulated in accordance with EIA/JESD Standard 51-2 for natural convection.
Freescale recommends the use of JA and power dissipation specifications in the system design to prevent device
junction temperatures from exceeding the rated specification. System designers should be aware that device
junction temperatures can be significantly influenced by board layout and surrounding devices. Conformance to the
device junction temperature specification can be verified by physical measurement in the customers system using
the jt parameter, the device power dissipation, and the method described in EIA/JESD Standard 51-2.
Per JEDEC JESD51-6 with the board horizontal.
Thermal resistance between the die and the printed circuit board per JEDEC JESD51-8. Board temperature is
measured on the top surface of the board near the package.
Thermal resistance between the die and the case top surface as measured by the cold plate method (MIL SPEC-883
Method 1012.1).
Thermal characterization parameter indicating the temperature difference between package top and the junction
temperature per JEDEC JESD51-2. When Greek letters are not available, the thermal characterization parameter is
written as Psi-JT.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


33-2

Freescale Semiconductor

DC Electrical Specifications

The average chip-junction temperature (TJ) in C can be obtained from:


T J = T A + ( P D JMA ) (1)

Where:
TA= Ambient Temperature, C
QJMA= Package Thermal Resistance, Junction-to-Ambient, C/W
PD= PINT + PI/O
PINT= IDD VDD, Watts - Chip Internal Power
PI/O= Power Dissipation on Input and Output Pins User Determined
For most applications PI/O < PINT and can be neglected. An approximate relationship between
PD and TJ (if PI/O is neglected) is:
P D = K ( T J + 273C ) (2)

Solving equations 1 and 2 for K gives:


K = PD (TA + 273 C) + QJMA PD 2 (3)

where K is a constant pertaining to the particular part. K can be determined from equation (3)
by measuring PD (at equilibrium) for a known TA. Using this value of K, the values of PD and
TJ can be obtained by solving equations (1) and (2) iteratively for any value of TA.

33.3

DC Electrical Specifications
Table 33-3. DC Electrical Specifications1
(VSS = VSSPLL= VSSF = VSSA= 0 VDC)
Characteristic

Symbol

Min

Max

Unit

Input High Voltage

VIH

0.7 x VDD

5.25

Input Low Voltage

VIL

VSS 0.3 0.35 x VDD

Input Hysteresis

VHYS

0.06 x
VDD

mV

Input Leakage Current


Vin = VDD or VSS, Input-only pins

Iin

-1.0

1.0

High Impedance (Off-State) Leakage Current


Vin = VDD or VSS, All input/output and output pins

IOZ

-1.0

1.0

Output High Voltage (All input/output and all output pins)


IOH = 2.0 mA

VOH

VDD - 0.5

__

Output Low Voltage (All input/output and all output pins)


IOL = 2.0mA

VOL

__

0.5

Weak Internal Pull Up Device Current, tested at VIL Max.

IAPU

-10

-130

7
7

Input Capacitance
All input-only pins
All input/output (three-state) pins

Cin

pF

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

33-3

Electrical Characteristics

Table 33-3. DC Electrical Specifications1 (continued)


(VSS = VSSPLL= VSSF = VSSA= 0 VDC)
Characteristic

Symbol

Load Capacitance3
(50% Partial Drive)
(100% Full Drive)

Min

Max

Unit
pF

CL

Supply Voltage (includes core modules and pads)


RAM Memory Standby Supply Voltage
Normal Operation: VDD > VSTBY - 0.3 V
Standby Mode: VDD < VSTBY - 0.3 V

VDD

25
50
2.7

3.6

0.0
1.8

3.6
3.6

2.7

3.6

V
V

VSTBY

Flash Memory Supply Voltage


VDDF
1

Refer to Table 33-8 through Table 33-12 for additional PLLQADC, and Flash specifications.
This parameter is characterized before qualification rather than 100% tested.
3
Refer to the chip configuration section for more information. Drivers for the SDRAM pins are at 25pF
drive strength.Drivers for the QADC pins are at 50pF drive strength.
2

33.4

Power Consumption Specifications


Table 33-4. STOP Mode Current Consumption Specifications
Symbol

Typical
Master Mode

Typical
Single Chip
Mode1

Max2

Unit

System clocks disabled (LPCR[STPMD] = 00)

IDD

25

7.9

mA

System clocks and CLKOUT disabled (LPCR[STPMD] =


01)

IDD

7.3

5.6

mA

System clocks, CLKOUT, and PLL disabled


(LPCR[STPMD] = 10)

IDD

4.5

4.7

mA

System clocks, CLKOUT, PLL, and OSC disabled


(LPCR[STPMD] = 11)

IDD

400

750

1000

Characteristic

Single chip mode current measured with all pins in general purpose input mode except for the UART0 and FEC pins that are enabled
for their module functionality.
2 Maximum values can vary depending on the systems state and signal loading.

Figure 33-1 shows typical WAIT/DOZE and RUN mode power consumption for both master and single
chip mode as measured on an M5282EVB.
For master mode the RUN mode current was measured executing a continuous loop that performs no
operation while running from the on-chip SRAM.
For WAIT/DOZE mode measurements the peripherals on the device are in their default power savings
mode, so the WAIT and DOZE power consumption are the same. Some modules can be programmed to
shutdown in WAIT and/or DOZE modes. Refer to module chapters for more information.
All single chip mode measurements were taken with all pins in general purpose input mode except for the
UART0 and FEC pins that are enabled for their module functionality; however, neither module is being
accessed at the time of the current measurement. Single chip RUN mode current was measured executing
a continuous loop that performs no operation while running from the on-chip Flash.
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3
33-4

Freescale Semiconductor

Power Consumption Specifications

250

Idd (mA)

200

Master mode - RUN

150

Master mode - WAIT

Single chip - RUN


100

Single chip - WAIT

50

0
8

16

24

32

40

48

56

64

72

80

Frequency (MHz)

Figure 33-1. Typical WAIT/DOZE Mode Current Consumption

Table 33-5 lists the estimated power consumption for individual modules. The current consumption is for
the module itself and does not include power for I/O.
Table 33-5. Estimated Module Power Consumption
Module

Estimated Power

Unit

EIM

20

A/MHz

SDRAMC

30

A/MHz

FEC

60

A/MHz

Watchdog

1.5

A/MHz

PIT

A/MHz

FlexCAN

15

A/MHz

QSPI, UART, I2C, and


Timers

75

A/MHz

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

33-5

Electrical Characteristics

Table 33-6. Typical Application Power Consumption


Application

Current
181.6 mA

Dhrystone benchmark running from cache and


on-chip SRAM (running at 64 MHz fsys)
dBUG ROM monitor running from external flash and
SDRAM (running at 64 MHz fsys)

155 mA

Table 33-7 lists the maximum power consumption specifications.


Table 33-7. Maximum Power Consumption Specifications
Characteristic
Operating Supply Current 1
Master Mode
66 MHz
80 MHz
Single Chip Mode
WAIT/DOZE
66 MHz
80 MHz

Symbol

Typical

Max

Unit

200
240
150

mA
mA
mA

125
150

mA
mA

4
2
1
10

mA
mA
mA
A

10
7
20

A
mA
A

16.53
254
1.64
0.2

30
64
20
10

mA
mA
mA
A

5.0
10.0

mA
A

IDD

Clock Synthesizer Supply Current


Normal Operation 8.25 MHz crystal, VCO on, Max fsys
STOP (OSC and PLL enabled)
STOP (OSC enable, PLL disabled)
STOP (OSC and PLL disabled)

IDDPLL

RAM Memory Standby Supply Current


Normal Operation: VDD > VSTBY - 0.3 V
Transient Condition: VSTBY - 0.3 V > VDD > VSS + 0.5 V
Standby Operation: VDD < VSS + 0.5 V

ISTBY

Flash Memory Supply Current


Read
Program or Erase2
Idle
STOP

IDDF

Analog Supply Current


Normal Operation
Low-Power Stop

IDDA

Current measured at maximum system clock frequency, all modules active, and default drive
strength with matching load.
2 Programming and erasing all 8 blocks of the Flash.
3 Measured with f
sys of 64 MHz.
4 Measured with f
sys of 32 MHz and fclk of 187.5 kHz.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


33-6

Freescale Semiconductor

Phase Lock Loop Electrical Specifications

33.5

Phase Lock Loop Electrical Specifications


Table 33-8. PLL Electrical Specifications
(VDD and VDDPLL = 2.7 to 3.6 V, VSS = VSSPLL = 0 V)
Characteristic

PLL Reference Frequency Range


Crystal reference
External reference
1:1 Mode
System Frequency 1
External Clock Mode
On-Chip PLL Frequency

Min

Max

fref_crystal
fref_ext
fref_1:1

2
2
33.33

10.0
10.0
80

Self Clocked Mode Frequency

3, 4

4, 5

0
fref / 32

80
80

fLOR

100

1000

kHz

fSCM

MHz

tcst

10

ms

VDD- 1.0
2.0

VDD
VDD

VSS
VSS

1.0
0.8

VDD- 1.0

0.5

pF

500

10.5
500

ms
s

EXTAL Input High Voltage


Crystal Mode
All other modes (1:1, Bypass, External)

VIHEXT

EXTAL Input Low Voltage


Crystal Mode
All other modes (1:1, Bypass, External)

VILEXT

XTAL Output High Voltage


IOH = 1.0 mA

VOL

XTAL Output Low Voltage


IOL = 1.0 mA

VOL

XTAL Load Capacitance6


4,7

tlpll

PLL Lock Time

4, 5,8

Unit
MHz

fsys

Loss of Reference Frequency 2, 4

Crystal Start-up Time

Symbol

MHz

V
V

Power-up To Lock Time


With Crystal Reference
Without Crystal Reference

tlplk

1:1 Clock Skew (between CLKOUT and EXTAL) 9

tskew

-2

ns

tdc

40

60

% fsys

fUL

- 1.5

1.5

% fsys

fLCK

- 0.75

0.75

% % fsys

10
.01

% fsys

Duty Cycle of

reference 4

Frequency un-LOCK Range


Frequency LOCK Range
4, 5, 7, 10,11 ,

CLKOUT Period Jitter


Measured at fSYS Max
Peak-to-peak Jitter (Clock edge to clock edge)
Long Term Jitter (Averaged over 2 ms interval)
1
2
3
4
5
6
7

Cjitter

All internal registers retain data at 0 Hz.


Loss of Reference Frequency is the reference frequency detected internally, which transitions the PLL into
self clocked mode.
Self clocked mode frequency is the frequency that the PLL operates at when the reference frequency falls
below fLOR with default MFD/RFD settings.
This parameter is characterized before qualification rather than 100% tested.
Proper PC board layout procedures must be followed to achieve specifications.
Load Capacitance determined from crystal manufacturer specifications and will include circuit board parasitics.
This specification applies to the period required for the PLL to relock after changing the MFD frequency control bits
in the synthesizer control register (SYNCR).
MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3

Freescale Semiconductor

33-7

Electrical Characteristics
8

Assuming a reference is available at power up, lock time is measured from the time VDD and VDDPLL are valid
to RSTO negating. If the crystal oscillator is being used as the reference for the PLL, then the crystal start up
time must be added to the PLL lock time to determine the total start-up time.
9
PLL is operating in 1:1 PLL mode.
10
Jitter is the average deviation from the programmed frequency measured over the specified interval at maximum
fsys. Measurements are made with the device powered by filtered supplies and clocked by a stable external clock
signal. Noise injected into the PLL circuitry via VDDPLL and VSSPLL and variation in crystal oscillator frequency
increase the Cjitter percentage for a given interval
11
Based on slow system clock of 40 MHz measured at fsys max.

33.6

QADC Electrical Characteristics


Table 33-9. QADC Absolute Maximum Ratings
Parameter

Symbol

Min

Max

Unit

VDDA

0.3

6.0

VDD

0.3

4.0

VRH

0.3

6.0

VSS Differential Voltage

VSS VSSA

0.1

0.1

VDD Differential Voltage 2

VDD VDDA

6.0

4.0

VREF Differential Voltage

VRH VRL

0.3

6.0

VRH to VDDA Differential Voltage 3

VRH VDDA

6.0

6.0

VRL to VSSA Differential Voltage

VRL VSSA

0.3

0.3

VDDH VDDA

1.0

1.0

IMA

25

25

mA

Analog Supply, with reference to VSSA


Internal Digital Supply

1,

with reference to VSS

Reference Supply, with reference to VRL

VDDH to VDDA Differential Voltage


Maximum Input Current
1
2
3
4
5

4, 5, 6

For internal digital supply of VDD = 3.3V typical.


Refers to allowed random sequencing of power supplies.
Refers to allowed random sequencing of power supplies.
Transitions within the limit do not affect device reliability or cause permanent damage. Exceeding limit may cause
permanent conversion error on stressed channels and on unstressed channels.
Input must be current limited to the value specified. To determine the value of the required current-limiting resistor,
calculate resistance values using VPOSCLAMP = VDDA + 0.3V and VNEGCLAMP = 0.3 V, then use the larger of the
calculated values.
Condition applies to one pin at a time.

Table 33-10. QADC Electrical Specifications (Operating) 1


(VDDH and VDDA = 5.0 Vdc 0.5V, VDD = 2.7-3.6V, VSS and VSSA = 0 Vdc, FQCLK = 2.0 MHz, TA within operating temperature
range)
Parameter
Analog Supply
VSS Differential Voltage

Symbol

Min

Max

Unit

VDDA

3.3

5.5

VSS VSSA

-100

100

mV

VRL

VSSA

VSSA + 0.1

Reference Voltage High 2

VRH

VDDA 0.1

VDDA

VREF Differential Voltage

VRH VRL

3.3

5.5

Reference Voltage Low

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


33-8

Freescale Semiconductor

QADC Electrical Characteristics

Table 33-10. QADC Electrical Specifications (Operating) 1 (continued)


(VDDH and VDDA = 5.0 Vdc 0.5V, VDD = 2.7-3.6V, VSS and VSSA = 0 Vdc, FQCLK = 2.0 MHz, TA within operating temperature
range)
Parameter

Symbol

Min

Max

Unit

VINDC

VSSA0.3

VDDA + 0.3

Input High Voltage, PQA and PQB

VIH

0.7 (VDDA)

VDDA + 0.3

Input Low Voltage, PQA and PQB

VIL

VSSA 0.3

0.4(VDDA)

Input Hysteresis, PQA, PQB 3

VHYS

0.5

Output High Voltage, PQA/PQB 3


IOH = TBD

VOH

VDDH-0.8

Analog Supply Current


Normal Operation 4
Low-Power Stop

IDDA

5.0
10.0

mA
A

Reference Supply Current, DC


Reference Supply Current, Transient

IREF
IREF

250
2.0

A
mA

CL

50

pF

IOFF

-200

200

nA

15
10

Input Voltage

Load Capacitance, PQA/PQB


Input Current, Channel Off 5
Capacitance 6

Total Input
PQA Not Sampling
PQB Not Sampling
Incremental Capacitance added during sampling
1
2
3

4
5
6

CIN

pF

QADC converter specifications are only guaranteed for VDDH and VDDA = 5.0V +/- 0.5V. VDDH and VDDA may be
powered down to 2.7V with only GPIO functions supported.
To obtain full-scale, full-range results, VSSA VRL VINDC VRH VDDA
Parameter applies to the following pins:
Port A: PQA[4:3]/AN[56:55]/ETRIG[2:1], PQA[1:0]/AN[53:52]/MA[1:0]
Port B: PQB[3:0]/AN[3:0]/AN[Z:W]
Current measured at maximum system clock frequency with QADC active.
Maximum leakage occurs at maximum operating temperature. Current decreases by approximately one-half for each 8
to 12 C, in the ambient temperature range of 50 to 125 C.
This parameter is characterized before qualification rather than 100% tested.

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


Freescale Semiconductor

33-9

Electrical Characteristics

Table 33-11. QADC Conversion Specifications (Operating)


(VDDH and VDDA = 5.0 Vdc 0.5V, VDD= 2.7-3.6V, VSS and VSSA= 0 Vdc, VRH VRL = 5 Vdc 0.5V, TA within operating
temperature range, fsys = 16 MHz)
Num

Parameter
QADC Clock (QCLK) Frequency1

Symbol

Min

Max

Unit

FQCLK

0.5

2.1

MHz

CC

14

28

QCLK
cycles

TCONV

7.0

14.0

TSR

10

mV

-2

Counts

-3

Counts

Conversion Cycles

Conversion Time
FQCLK = 2.0 MHz1
Min = CCW/IST =%00
Max = CCW/IST =%11

Stop Mode Recovery Time

Resolution2

Absolute (total unadjusted) error 3, 4, 5


FQCLK = 2.0 MHz 2, 2 clock input sample time

AE

error 3, 4, 5

Absolute (total unadjusted)


FQCLK = 2.0 MHz 2, 2 clock input sample time

7
1

2
3
4

Conversion characteristics vary with FQCLK rate. Reduced conversion accuracy occurs at max FQCLK rate. Using the
QADC pins as GPIO functions during conversions may result in degraded results. Best QADC conversion accuracy is
achieved at a frequency of 2 MHz.
At VRH VRL = 5.12 V, one count = 5 mV
Accuracy tested and guaranteed at VRH VRL = 5.0V 0.5V
Current Coupling Ratio, K, is defined as the ratio of the output current, Iout, measured on the pin under test to the
injection current, Iinj, when both adjacent pins are overstressed with the specified injection current. K = Iout/Iinj. The
input voltage error on the channel under test is calculated as Verr = Iinj * K * RS.
Performance expected with production silicon.

33.7

Flash Memory Characteristics

The Flash memory characteristics are shown in Table 33-12 and Table 33-13.
Table 33-12. SGFM Flash Program and Erase Characteristics
(VDDF = 2.7 to 3.6 V)
Parameter
System clock (read only)
System clock (program/erase)
1

Symbol

Min

Typ

Max

Unit

fsys(R)

80

MHz

fsys(P/E)

0.15

80

MHz

Refer to the Flash section for more information

Table 33-13. SGFM Flash Module Life Characteristics


(VDDF = 2.7 to 3.6 V)
Parameter
Maximum number of guaranteed program/erase cycles1 before failure
Data retention at average operating temperature of 85C

Symbol

Value

Unit

P/E

10,0002

Cycles

Retention

10

Years

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


33-10

Freescale Semiconductor

Electrical Characteristics

* The timings are also valid for inputs sampled on the negative clock edge.
1.5V

CLKOUT(66.67 MHz)
TSETUP

Input Setup And Hold

Invalid

1.5V Valid 1.5V

Vh = VIH

Input Rise Time

Invalid

trise = 1.5 ns

Vl = VIL

Vh = VIH

Input Fall Time

CLKOUT

THOLD

tfall = 1.5 ns

Vl = VIL

B4

B5

Inputs

Figure 33-2. General Input Timing Requirements

33.9

Processor Bus Output Timing Specifications

Table 33-14 lists processor bus output timings.


Table 33-15. External Bus Output Timing Specifications
Name

Characteristic

Symbol

Min

Max

Unit

tCHCV

0.5tCYC +10

ns

tCHBV

0.5tCYC +10

ns

Control Outputs
B6a

CLKOUT high to chip selects valid 1


valid2

B6b

CLKOUT high to byte enables (BS[3:0])

B6c

CLKOUT high to output enable (OE) valid3

tCHOV

0.5tCYC +10

ns

B7

CLKOUT high to control output (BS[3:0], OE) invalid

tCHCOI

0.5tCYC + 2

ns

B7a

CLKOUT high to chip selects invalid

tCHCI

0.5tCYC + 2

ns

Address and Attribute Outputs

MCF5282 Coldfire Microcontroller Users Manual, Rev. 2.3


33-12

Freescale Semiconductor

ANEXO 4

NMRA Electrical Standards for Digital


Command Control, July 2004.

NMRA STANDARD

Electrical Standards

This Standard received approval from the NMRA


membership and Board of Trustees in January
1994, July 2002 and July 2004.

For Digital Command Control,


All Scales
Adopted July 2004

S 9.1

10

Communication from a Digital Command Station to a Digital Decoder is accomplished by transmitting a


series of bits that convey instructions. A bit is a signal which represents one of two conditions, which we
will call "1" and "0". This portion of the standard covers the electrical characteristics of the digital
command control signal that encodes these bits.

A: Technique For Encoding Bits

15

20

25

30

The NMRA baseline digital command control signal consists of a stream of transitions between two equal
voltage levels that have opposite polarity1. Alternate transitions separate one bit from the next. The
remaining transitions divide each bit into a first part and a last part. Digital Command Stations shall
encode bits within this digital command control stream of transitions by varying the duration of the parts of
the bits, or frequency of the transitions.
In a "1" bit, the first and last part of a bit shall have the same duration, and that duration shall nominally be
58 microseconds2, giving the bit a total duration of 116 microseconds. Digital Command Station
components shall transmit "1" bits with the first and last parts each having a duration of between 55 and 61
microseconds. A Digital Decoder must accept bits whose first and last parts have a duration of between 52
and 64 microseconds, as a valid bit with the value of "1".
In a "0" bit, the duration of the first and last parts of each transition shall nominally be greater than or
equal to 100 microseconds. To keep the DC component of the total signal at zero as with the "1" bits, the
first and last part of the "0" bit are normally equal to one another. Digital Command Station components
shall transmit "0" bits with each part of the bit having a duration of between 95 and 9900 microseconds
with the total bit duration of the "0" bit not exceeding 12000 microseconds. A Digital Decoder must accept
bits whose first or last parts have a duration of between 90 and 10000 microseconds as a valid bit with the
value of "0". Figure 1 provides an example of bits encoded using this technique.

Figure 1: Bit Encoding


35

Digital Decoders must accept one bits whose positive and negative components differ by as much as 6
microseconds.

1 Note

that since a locomotive or piece of rolling stock can be placed upon a given section of track facing in
either direction, it is impossible to define, from the point of view of a Digital Decoder, whether the first or
last part of a bit will have the "positive" voltage polarity.
2 All

timing measurements are done between zero volt crossings.

2001,2004 by the National Model Railroad Association, Inc.


S-9.1 Electrical Standards for DCC
Page 1 of 3

Printed: July 2004

40

One Bit Timing


For Power Station Output under Load:
Relationship for One Bits
Period A < 55 Sec or Period A > 61 Sec
Period A = Period B
|Period A Period B| <= 3 Sec
|Period A Period B| > 3 Sec

Result
Bad
OK
OK
Bad

Decoders must accept:


Relationship for One Bits
Period A >= 52Sec and Period A <= 64 Sec
Period A = Period B
|Period A Period B| <= 6 Sec

Result
OK
OK
OK

B: Command Control Signal Shape


45

The NMRA digital signal applied to the track by any Digital Command Control system, as measured at the
power station output, shall have the following characteristics, as measured under conditions ranging from
no load to the maximum continuous load permitted by the power source. Transitions that cross the region
between -4 volts and +4 volts3 shall occur at 2.5 volts per microsecond or faster. This signal may contain
non-monotonic distortion at the zero-crossing transitions, provided that this distortion shall have an
amplitude of no greater than +/- 2 volts4.

50

55

Digital Decoders shall be designed to correctly decode signals with transitions whose slope is 2.0 volts per
microsecond or faster across the voltage range from -4 volts to +4 volts. A Digital Decoder shall correctly
decode at least 95% of properly addressed baseline packets, as defined in S-9.2, in the presence of noise
(and/or other types of signals) above 100 kHz with a total peak-to-peak amplitude of less than one fourth of
the peak-to-peak amplitude of the NMRA digital signal5.
The exact shape of the NMRA digital signal shall be designed to minimize electromagnetic radiation such
that a large layout operated using this standard can meet applicable United States Federal Communications
Commission electromagnetic interference requirements6.

30

volts is the mid point of the differential voltage.

4 This

standard specifically permits super-imposing non-NMRA signals upon the rails for other purposes,
provided that the NMRA Digital Decoder can reject these signals.
5 This

measurement is made with the Digital Decoder electrically connected to a track or accessory bus.

6 All

components of a NMRA compliant digital system shall meet all applicable FCC and/or CE
requirements.
2001,2004 by the National Model Railroad Association, Inc.
S-9.1 Electrical Standards for DCC
Page 2 of 3

Printed: July 2004

25

25
POWER STATION MAXIMUM

20

20

15

TYP. O/S/HO-SCALE SIGNAL


TYP. N-SCALE SIGNAL

10

VOLTAGE

TYP. LARGE-SCALE SIGNAL

POWER STATION MINIMUM

TYP. LARGE-SCALE SIGNAL

15

TYP. O/S/HO-SCALE SIGNAL


TYP. N-SCALE SIGNAL

10

0
ZERO-CROSSING

+5uS

+10uS

ZERO-CROSSING

+5uS

+10uS

Maximum Voltage for Power Stations

Minimum Voltage for Power Stations

NON N-SCALE DECODER MAXIMUM


25

25

20

TYP. LARGE-SCALE SIGNAL

15

TYP. O/S/HO-SCALE SIGNAL


TYP. N-SCALE SIGNAL

10

N-SCALE DECODER MAXIMUM

20

VOLTAGE

70

The baseline method for providing the power to operate locomotives and accessories, which shall be
supported by all Digital Command Stations and Digital Decoders, is by full-wave rectification of the
bipolar NMRA digital signal within the Digital Decoder7. In order to maintain power to the Digital
Decoders, gaps in bit transmission are only allowed at specified times (see S-9.2, Section C). The RMS
value of NMRA digital signal, measured at the track, shall not exceed by more than 2 volts8 the voltage
specified in standard S9 for the applicable scale9. In no case should the peak amplitude of the command
control signal exceed +/- 22 volts. The minimum peak value of the NMRA digital signal needed to provide
power to the decoder shall be +/-7 volts measured at the track. Digital Decoders intended for "N" and
smaller scales shall be designed to withstand a DC voltage of at least 24 volts as measured at the track.
Digital Decoders intended for scales larger than "N" shall be designed to withstand a DC voltage of at
least 27 volts as measured at the track.

VOLTAGE

65

C: Power Transmission and Voltage Limits For Transmitting


Power Through the Rails

VOLTAGE

60

TYP. LARGE-SCALE SIGNAL

15

TYP. O/S/HO-SCALE SIGNAL


TYP. N-SCALE SIGNAL

10
DECODER MINIMUM

ZERO-CROSSING

+5uS

+10uS

ZERO-CROSSING

Minimum Voltage for Decoders

+5uS

+10uS

Maximum Voltage for Decoders

7 Alternate

means for supplying power are acceptable, provided that Digital Command Station power units
are capable of producing the baseline track signal, and Digital Decoders are capable of operation from the
baseline track signal as described by this standard.
8 The

additional voltage is to compensate for voltage drop in the Digital Decoder, to ensure that the
maximum voltage as specified in the NMRA Electrical Standard (S-9) is available at the motor brushes.
9

Care should be taken to ensure that any motors exposed directly to the digital signal for extended periods
have a stall rating that exceeds the amplitude of the signal, or sufficiently high impedance at 4-9 kHz to
reduce the current to normal operating level. This appears to only be a concern for high-precision core-less
can motors, which present a low impedance load, or for layouts using an NMRA digital signal with an
amplitude in excess of +-18 volts.
2001,2004 by the National Model Railroad Association, Inc.
S-9.1 Electrical Standards for DCC
Page 3 of 3

Printed: July 2004

ANEXO 5

NMRA Communications Standards for Digital


Command Control, July 2004.

NMRA STANDARD
5
This Standard received approval from the NMRA
Membership and the Board of Trustees in January
1994, July 2002 and July 2004.

Communications Standards
For Digital Command Control,
All Scales
Adopted July 2004

10

15

S 9.2

This standard covers the format of the information sent via Digital Command Stations to Digital Decoders. A
Digital Command Station transmits this information to Digital Decoders by sending a series of bits using the
NMRA digital signal described in S-9.1. This sequence of bits, termed a packet, is used to encode one of a set of
instructions that the Digital Decoder operates upon. Packets must be precisely defined to ensure that the intended
instructions can be properly encoded and decoded.

A. General Packet Format


The following sequence of bits defines a valid NMRA packet. Any sequence of bits not meeting the full
specifications of this general packet format is not, for the purpose of this standard, a "packet". Digital decoders
should not act on any instructions that are not contained within a valid packet while in the NMRA digital mode of
operation1. Note, portions within square [ ] brackets must occur one or more times.

20

Preamble:

The preamble to a packet consists of a sequence of "1" bits. A digital decoder must not
accept as a valid, any preamble that has less then 10 complete one bits, or require for
proper reception of a packet with more than 12 complete one bits. A command station
must send a minimum of 14 full preamble bits.

Packet Start Bit:

The packet start bit is the first bit with a value of "0" that follows a valid preamble. The
Packet Start Bit terminates the preamble and indicates that the next bits are an address
data byte.

Address Data Byte:

The first data byte of the packet normally contains eight bits of address information2.
The first transmitted address bit shall be defined to be the most significant bit of the
address data byte. Address Data Bytes with values 00000000, 11111110, and 11111111
are reserved for special operations and must not be transmitted except as provided in this
Standard or associated Recommended Practices.

[ Data Byte Start Bit:

This bit precedes a data byte and has the value of "0".

Data Byte:

Each data byte contains eight bits of information used for address, instruction, data, or
error detection purposes. The first transmitted data bit of each data byte shall be defined
to be the most significant bit of the data byte. ]

Packet End Bit:

This bit marks the termination of the packet and has a value of "1"3.

It is permissible for Digital Decoders to accept formats in addition to the NMRA General Packet Format. See
Section C for details.
2

The first byte can also be used in special cases to indicate instructions. See the Service Mode Recommended
Practice (RP-9.2.3) for an example of this dual use.
3

The Packet End Bit may count as one of the preamble bits of the subsequent packet if there are no inter-packet bits
from an alternative command control protocol. The DCC bitstream must continue for an additional 26 S
(minimum) after the packet end bit.
2001-2004, by the National Model Railroad Association, Inc.
S-9.2 Communications Standards for DCC
Page 1 of 4

Printed: July 2004

Figure 1 provides an example of an acceptable command control packet that uses three data bytes: one address data
byte, one instruction data byte and one error detection data byte.

1 11 1 1 1 11 1 1 11 0
Preamble
Packet Start Bit

0 0 11 0 111 0
Address Data Byte
Data Byte Start Bit

0 11 1 0 1 0 0 0 0 1 0 0 0 0 11 1
Instruction Data Byte Error Detection Data Byte
Data Byte Start Bit

Packet End Bit

25

Figure 1 Example of a Transmitted Packet

B: Baseline Packets
30

The Baseline Packets are included to provide the minimum interoperability between different systems. More
complex packet formats that support different types of decoders, additional functions, addresses and speeds are
provided in the Extended Packet Format Recommended Practice (RP-9.2.1). It is the intention of this Standard
that, in order to conform: a Command Station must encode operator control input in conformance with the Baseline
Packet semantics; and a Digital Decoder must recognize and provide suitable locomotive control electrical output in
conformance with the Baseline Packet semantics. Digital Decoder Idle Packets and Digital Decoder Broadcast Stop
Packets4 (defined below) are optional for Command Stations, and required for decoders.

35

Speed and Direction Packet For Locomotive Decoders


111111111111 0
Preamble

0AAAAAAA 0 01DCSSSS 0
Byte One
Byte Two

EEEEEEEE 1
Byte Three (Error Detection Data Byte)

40

45

50

55

Byte One: Address Data Byte = 0AAAAAAA The address data byte contains the address of the intended recipient
of the packet. Every Digital Decoder shall be capable of retaining and recognizing its own address for
purposes of responding to Baseline Packets. Locomotive Digital Decoders shall support the full range of
baseline addresses in such a manner that this address is easily configurable by the user5. It is acceptable
for Digital Command Stations to restrict the number of valid addresses supported so long as this
restriction is clearly and plainly labeled on the package and in the instructions.
Byte Two: Instruction Data Byte = 01DCSSSS The instruction data byte is a data byte used to transmit speed and
direction information to the locomotive Digital Decoder. Bits 0-36 provides 4 bits for speed (S) with bit
0 being the least significant speed bit. Bit four of byte 2 (C) by default shall contain one additional speed
bit, which is the least significant speed bit. For backward compatibility, this bit may instead be used to
control the headlight. This optional use is defined in RP-9.2.1. Bit 5 provides one bit for direction (D).
When the direction bit (D) has a value of "1" the locomotive should move in the forward direction7. A
direction bit with the value of "0" should cause the locomotive to go in the reverse direction. Bits 7 and 6
contain the bit sequence "01"8 which are used to indicate that this instruction data byte is for speed and
direction.
4 Broadcast Stop Packet requirement for decoders, effective 1-Aug-2002.
5

The Service Mode Recommended Practice (RP-9.2.3) contains one example of an acceptable method for user address
configuration.
6

Bits within a byte are numbered right to left with bit 0 (the right most bit) being the least significant bit and bit 7
(the left most bit) being the most significant bit.
7

Forward in this case is in the direction of the front of the locomotive, as observed from the engineer's position
within the locomotive.
8

Other bit patterns in bits 7 and 6 are reserved for other types of instruction data, and are defined in the Extended
Packet Format Recommended Practice (RP-9.2.1).
2001-2004, by the National Model Railroad Association, Inc.
S-9.2 Communications Standards for DCC
Page 2 of 4

Printed: July 2004

CS3S 2S 1S 0

Speed

CS3S 2S 1S 0

Speed

CS3S 2S 1S 0

Speed

CS3S 2S 1S 0

Speed

00000
10000
00001
10001
00010
10010
00011
10011

Stop
Stop (I)
E-Stop*
E-Stop* (I)
Step 1
Step 2
Step 3
Step 4

00100
10100
00101
10101
00110
10110
00111
10111

Step 5
Step 6
Step 7
Step 8
Step 9
Step 10
Step 11
Step 12

01000
11000
01001
11001
01010
11010
01011
11011

Step 13
Step 14
Step 15
Step 16
Step 17
Step 18
Step 19
Step 20

01100
11100
01101
11101
01110
11110
01111
11111

Step 21
Step 22
Step 23
Step 24
Step 25
Step 26
Step 27
Step 28

60

65

*Digital Decoders shall immediately stop delivering power to the motor.


(I) Direction bit may be ignored for directional sensitive functions. (Optional)
Figure 2 Speed Table for Baseline Packet

Byte Three: Error Detection Data Byte = EEEEEEEE The error detection data byte is a data byte used to detect the
presence of transmission errors. The contents of the Error Detection Data Byte shall be the bitwise
exclusive OR of the contents of the Address Data Byte and the Instruction Data Byte in the packet
concerned. (e.g. the exclusive OR of bit 0 of the address data byte and bit 0 of the instruction data byte
will be placed in bit 0 of the error detection data byte...) Digital Decoders receiving a Baseline Packet
shall compare the received error detection data byte with the bitwise exclusive OR of the received address
and instruction data bytes and ignore the contents of the packet if this comparison is not identical.

70

The example packet shown in figure 1 illustrates a baseline packet with the instruction to locomotive 55 to proceed
in the forward direction at speed step 6.

Digital Decoder Reset Packet For All Decoders


75

111111111111 000000000 0
Preamble
Byte One
80

85

00000000 0
Byte Two

00000000 1
Byte Three (Error Detection Data Byte)

A three byte packet, where all eight bits within each of the three bytes contains the value of "0", is defined as a
Digital Decoder Reset Packet. When a Digital Decoder receives a Digital Decoder Reset Packet, it shall erase all
volatile memory (including any speed and direction data), and return to its normal power-up state. If the Digital
Decoder is operating a locomotive at a non-zero speed when it receives a Digital Decoder Reset, it shall bring the
locomotive to an immediate stop.
Following a Digital Decoder Reset Packet, a Command Station shall not send any packets with an address data byte
between the range "01100100" and "01111111" inclusive within 20 milliseconds, unless it is the intent to enter
service mode9.

Digital Decoder Idle Packet For All Decoders


90

111111111111 0
11111111 0
00000000 0
11111111 1
Preamble
Byte One
Byte Two
Byte Three (Error Detection Data Byte)
95

A three byte packet, whose first byte contains eight "1"s, whose second byte contains eight "0"s and whose third
and final byte contains eight "1"s, is defined as a Digital Decoder Idle Packet. Upon receiving this packet, Digital
Decoders shall perform no new action, but shall act upon this packet as if it were a normal digital packet addressed
to some other decoder.

Digital Decoders can have their configurations altered immediately after a digital decoder reset packet. See the
Service Mode Recommended Practice(RP-9.2.3) for details.
2001-2004, by the National Model Railroad Association, Inc.
S-9.2 Communications Standards for DCC
Page 3 of 4

Printed: July 2004

Digital Decoder Broadcast Stop Packets For All Decoders10


100

111111111111 0 00000000 0 01DC000S 0 EEEEEEEE 1


Preamble

105

110

Byte One

Byte Two

Byte Three (Error Detection Data Byte)

A three byte packet, whose first byte contains eight "0"s, whose second byte contains a specific stop command and
whose third and final byte contains an error byte that is identical to the second byte of the packet, is defined as a
Digital Decoder Broadcast Stop Packet. Upon receiving this packet where bit zero of byte two (S) contains a value
of "0", digital decoders intended to control a locomotive's motor shall bring the locomotive to a stop.
Upon receiving this packet where bit zero of byte two (S) contains a value of "1", digital decoders intended to
control a locomotive's motor shall stop delivering energy to the motor. If bit four of byte 2 (C) contains a value of
"1", the direction bit contained in bit five of byte 2 (D) may optionally be ignored for all direction sensitive
functions.

C: Frequency Of Packet Transmission


115

120

125

130

Packets sent to Digital Decoders should be repeated as frequently as possible, as a packet may have been lost due to
noise or poor electrical conductivity between wheels and rails. Power may also be removed from the rails between
the Packet End Bit and the Preamble of the next packet to allow for alternative command control formats. A Digital
Decoder shall be able to act upon multiple packets addressed to it, provided the time between the packet end bit of
the first packet and the packet start bit of the second packet are separated by at least 5 milliseconds11. If a decoder
receives a bit sequence with a missing or invalid data byte start bit, a missing or invalid packet end bit, or an
incorrect error detection byte, it must recognize the next valid preamble sequence as the beginning of a new packet.
Alternative command control formats are specifically allowed between the packet end bit and the start of the next
preamble.
Manufacturers of decoders are encouraged to provide automatic conversion for a variety of power signals and
command control formats in addition to the NMRA digital signal (per S-9.1), provided that automatic conversion
to these alternate power signals can be disabled. If automatic conversion is enabled, Digital Decoders must remain
in digital mode and not convert to using any alternate power signal so long as the time between Packet Start Bits is
less than or equal to 30 milliseconds in duration. If automatic conversion is disabled, Digital Decoders must
remain in digital mode regardless of the timing of Packet Start Bits. It shall be possible to configure Digital
Command Stations to transmit at least one complete packet every 30 milliseconds as measured from the time
between packet start bits12. 13

10Broadcast Stop Packet requirement for decoders, effective 1-Aug-2002.


11

Care must be taken to ensure that two packets with identical addresses are not are not transmitted within 5
milliseconds of each other for addresses in the range between 112-127 as older decoders may interpret these packets as
service mode packets (see RP-9.2.3).
12

Some DCC decoders manufactured prior to the NMRA standards require a valid baseline packet be received every
30 milliseconds to prevent analog power conversion.
13

Longer repetition rates may result in less than optimal decoder performance

2001-2004, by the National Model Railroad Association, Inc.


S-9.2 Communications Standards for DCC
Page 4 of 4

Printed: July 2004

ANEXO 6

Hojas de caractersticas (DataSheets)

Selective Photodiode

EPD-740-5

Spectral range

Type

Technology

Case

Infrared

EPD-740-5

AlGaAs/AlGaAs/GaAs

5 mm plastic lens

Description

Applications

Narrow response range (740 nm peak),


single heterostructure on the substrate

Optical communications,
safety equipment

7,1 - 0,6

2,54

5,3 - 0,3

0,8 - 0,4

Anode

1,7 - 0,1

6,2 - 0,5

1,1 - 0,1

2
10,6 - 0,6

16,5 - 2,0

0,7 - 0,4

Maximum Ratings
Parameter

Value

Unit

Storage Temperature

- 40...+90

Operating Temperature
Soldering Temperature

-40...+85
240

C
C

Optical and Electrical Characteristics


Tamb = 25C, unless otherwise specified
Parameter

Test conditions

Active area

Symbol

Min

Peak sensitivity

Smax

Spectral bandwidth at 50%

0,5

Acceptance angle at 50% S

Typ

Max

mm2

0.13
700

740

Unit

780

nm

60

nm

40

deg.

Responsivity at 740 nm

VR = 0 V

0.5

A/W

Short-circuit current*

VR = 0, Ee=1
mW/cm

ISC

Dark current

VR = 5 V, Ee=0

ID

40

Reverse voltage

IR = 10 A

VR

10

Junction capacitance

VR = 0, Ee=0

40

pF

Rise time

RL = 50

tr

15

Fall time

VR = 5 V

tf

30

200

Parameter
Test conditions Symbol
Min
Typ
Max
*Light source is an AlGaAs LED with a peak emission wavelength of 740 nm

pA

ns
Unit

rev.04/01

Small and Thin 5 g iMEMS Accelerometer


ADXL320
FEATURES

GENERAL DESCRIPTION

Small and thin


4 mm 4 mm 1.45 mm LFCSP package
2 mg resolution at 60 Hz
Wide supply voltage range: 2.4 V to 5.25 V
Low power: 350 A at VS = 2.4 V (typ)
Good zero g bias stability
Good sensitivity accuracy
X-axis and Y-axis aligned to within 0.1 (typ)
BW adjustment with a single capacitor
Single-supply operation
10,000 g shock survival
Compatible with Sn/Pb and Pb-free solder processes

The ADXL320 is a low cost, low power, complete dual-axis


accelerometer with signal conditioned voltage outputs, which is
all on a single monolithic IC. The product measures
acceleration with a full-scale range of 5 g (typical). It can also
measure both dynamic acceleration (vibration) and static
acceleration (gravity).
The ADXL320s typical noise floor is 250 g/Hz, allowing
signals below 2 mg to be resolved in tilt-sensing applications
using narrow bandwidths (<60 Hz).
The user selects the bandwidth of the accelerometer using
capacitors CX and CY at the XOUT and YOUT pins. Bandwidths of
0.5 Hz to 2.5 kHz may be selected to suit the application.

APPLICATIONS

The ADXL320 is available in a very thin 4 mm 4 mm


1.45 mm, 16-lead, plastic LFCSP.

Cost-sensitive motion- and tilt-sensing applications


Smart hand-held devices
Mobile phones
Sports and health-related devices
PC security and PC peripherals

FUNCTIONAL BLOCK DIAGRAM


+3V
VS

ADXL320
CDC

AC
AMP

DEMOD

OUTPUT
AMP

OUTPUT
AMP

SENSOR

COM

ST

RFILT
32k
YOUT
CY

XOUT
CX

04993-001

RFILT
32k

Figure 1.

Rev.0
Information furnished by Analog Devices is believed to be accurate and reliable.
However, no responsibility is assumed by Analog Devices for its use, nor for any
infringements of patents or other rights of third parties that may result from its use.
Specifications subject to change without notice. No license is granted by implication
or otherwise under any patent or patent rights of Analog Devices. Trademarks and
registered trademarks are the property of their respective owners.

One Technology Way, P.O. Box 9106, Norwood, MA 02062-9106, U.S.A.


Tel: 781.329.4700
www.analog.com
Fax: 781.326.8703
2007 Analog Devices, Inc. All rights reserved.

ADXL320

TABLE OF CONTENTS
Specifications..................................................................................... 3

Setting the Bandwidth Using CX and CY ................................. 12

Absolute Maximum Ratings............................................................ 4

Self-Test ....................................................................................... 12

ESD Caution.................................................................................. 4

Design Trade-Offs for Selecting Filter Characteristics: The


Noise/BW Trade-Off.................................................................. 12

Pin Configuration and Function Descriptions............................. 5


Typical Performance Characteristics (VS = 3.0 V) ....................... 7
Theory of Operation ...................................................................... 11
Performance ................................................................................ 11
Applications..................................................................................... 12

Use with Operating Voltages Other than 3 V............................. 13


Use as a Dual-Axis Tilt Sensor ................................................. 13
Outline Dimensions ....................................................................... 14
Ordering Guide .......................................................................... 14

Power Supply Decoupling ......................................................... 12

REVISION HISTORY
9/04Revision 0: Initial Version

Rev. 0 | Page 2 of 16

ADXL320
SPECIFICATIONS 1
TA = 25C, VS = 3 V, CX = CY = 0.1 F, Acceleration = 0 g, unless otherwise noted.

Table 1.
Parameter
SENSOR INPUT
Measurement Range
Nonlinearity
Package Alignment Error
Alignment Error
Cross Axis Sensitivity
SENSITIVITY (RATIOMETRIC) 2
Sensitivity at XOUT, YOUT
Sensitivity Change due to Temperature 3
ZERO g BIAS LEVEL (RATIOMETRIC)
0 g Voltage at XOUT, YOUT
0 g Offset Versus Temperature
NOISE PERFORMANCE
Noise Density
FREQUENCY RESPONSE 4
CX, CY Range 5
RFILT Tolerance
Sensor Resonant Frequency
SELF-TEST 6
Logic Input Low
Logic Input High
ST Input Resistance to Ground
Output Change at XOUT, YOUT
OUTPUT AMPLIFIER
Output Swing Low
Output Swing High
POWER SUPPLY
Operating Voltage Range
Quiescent Supply Current
Turn-On Time 7
TEMPERATURE
Operating Temperature Range

Conditions
Each axis

Min

Max

X sensor to Y sensor

Unit
g
%
Degrees
Degrees
%

5
0.2
1
0.1
2

% of full scale

Each axis
VS = 3 V
VS = 3 V
Each axis
VS = 3 V

Typ

156

174
0.01

192

mV/g
%/C

1.3

1.5
0.6

1.7

V
mg/C

@ 25C

250
0.002

g/Hz rms

32 15%
5.5

10

F
k
kHz

Self-test 0 to 1

0.6
2.4
50
55

V
V
k
mV

No load
No load

0.3
2.5

V
V

2.4

5.25

V
mA
ms

70

0.48
20
20

All minimum and maximum specifications are guaranteed. Typical specifications are not guaranteed.
Sensitivity is essentially ratiometric to VS. For VS = 2.7 V to 3.3 V, sensitivity is 154 mV/V/g to 194 mV/V/g typical.
3
Defined as the output change from ambient-to-maximum temperature or ambient-to-minimum temperature.
4
Actual frequency response controlled by user-supplied external capacitor (CX, CY).
5
Bandwidth = 1/(2 32 k C). For CX, CY = 0.002 F, bandwidth = 2500 Hz. For CX, CY = 10 F, bandwidth = 0.5 Hz. Minimum/maximum values are not tested.
6
Self-test response changes cubically with VS.
7
Larger values of CX, CY increase turn-on time. Turn-on time is approximately 160 CX or CY + 4 ms, where CX, CY are in F.
2

Rev. 0 | Page 3 of 16

ADXL320
ABSOLUTE MAXIMUM RATINGS
Table 2.
Parameter
Acceleration (Any Axis, Unpowered)
Acceleration (Any Axis, Powered)
VS
All Other Pins
Output Short-Circuit Duration
(Any Pin to Common)
Operating Temperature Range
Storage Temperature

Rating
10,000 g
10,000 g
0.3 V to +7.0 V
(COM 0.3 V) to
(VS + 0.3 V)
Indefinite
55C to +125C
65C to +150C

Stresses above those listed under Absolute Maximum Ratings


may cause permanent damage to the device. This is a stress
rating only; functional operation of the device at these or any
other conditions above those indicated in the operational
section of this specification is not implied. Exposure to absolute
maximum rating conditions for extended periods may affect
device reliability.

ESD CAUTION
ESD (electrostatic discharge) sensitive device. Electrostatic charges as high as 4000 V readily accumulate
on the human body and test equipment and can discharge without detection. Although this product features
proprietary ESD protection circuitry, permanent damage may occur on devices subjected to high energy
electrostatic discharges. Therefore, proper ESD precautions are recommended to avoid performance
degradation or loss of functionality.

Rev. 0 | Page 4 of 16

ADXL320
PIN CONFIGURATION AND FUNCTION DESCRIPTIONS

NC

VS

VS

NC

NC

XOUT

ST

ADXL320

NC

COM

TOP VIEW
(Not to Scale)

YOUT
NC

COM COM COM

NC

NC = NO CONNECT

04993-022

NC

Figure 2. Pin Configuration

Table 3. Pin Function Descriptions


Pin No.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Mnemonic
NC
ST
COM
NC
COM
COM
COM
NC
NC
YOUT
NC
XOUT
NC
VS
VS
NC

Description
Do Not Connect
Self-Test
Common
Do Not Connect
Common
Common
Common
Do Not Connect
Do Not Connect
Y Channel Output
Do Not Connect
X Channel Output
Do Not Connect
2.4 V to 5.25 V
2.4 V to 5.25 V
Do Not Connect

Rev. 0 | Page 5 of 16

ADXL320
CRITICAL ZONE
TL TO TP

tP

TP

TEMPERATURE

RAMP-UP
TL

tL

TSMAX
TSMIN

tS

RAMP-DOWN
04993-002

PREHEAT

t25C TO PEAK
TIME

Figure 3. Recommended Soldering Profile

Table 4. Recommended Soldering Profile


Profile Feature
Average Ramp Rate (TL to TP)
Preheat
Minimum Temperature (TSMIN)
Maximum Temperature (TSMAX)
Time (TSMIN to TSMAX), tS
TSMAX to TL
Ramp-Up Rate
Time Maintained Above Liquidous (TL)
Liquidous Temperature (TL)
Time (tL)
Peak Temperature (TP)
Time within 5C of Actual Peak Temperature (tP)
Ramp-Down Rate
Time 25C to Peak Temperature

Rev. 0 | Page 6 of 16

Sn63/Pb37
3C/second max

Pb-Free
3C/second max

100C
150C
60 120 seconds

150C
200C
60 150 seconds

3C/second

3C/second

183C
60 150 seconds
240C + 0C/5C
10 30 seconds
6C/second max
6 minutes max

217C
60 150 seconds
260C + 0C/5C
20 40 seconds
6C/second max
8 minutes max

ADXL320
25

25

20

20
% OF POPULATION

15

10

04993-006

1.40 1.42 1.44 1.46 1.48 1.50 1.52 1.54 1.56 1.58 1.60

1.40 1.42 1.44 1.46 1.48 1.50 1.52 1.54 1.56 1.58 1.60

OUTPUT (V)

OUTPUT (V)

Figure 4. X-Axis Zero g Bias Deviation from Ideal at 25C

Figure 7. Y-Axis Zero g Bias Deviation from Ideal at 25C

35

35

30

30

25

25
% OF POPULATION

% OF POPULATION

10

5
04993-003

15

20
15

10

0
2.82.4 2.0 1.61.2 0.8 0.4 0

15

10
5

04993-004

20

04993-007

% OF POPULATION

TYPICAL PERFORMANCE CHARACTERISTICS (VS = 3.0 V)

0.4 0.8 1.2 1.6 2.0 2.4 2.8

2.82.4 2.0 1.61.2 0.8 0.4 0

TEMPERATURE COEFFICIENT (mg/C)

0.4 0.8 1.2 1.6 2.0 2.4 2.8

TEMPERATURE COEFFICIENT (mg/C)

Figure 5. X-Axis Zero g Bias Temperature Coefficient

Figure 8. Y-Axis Zero g Bias Temperature Coefficient

90

70

80

60

70
% OF POPULATION

50
40
30

40
30

20

20
10
0
164

166

168

170

172

174

176

178

180

182

04993-008

10

04993-005

% OF POPULATION

50
60

0
164

184

SENSITIVITY (mV/g)

166

168

170

172

174

176

178

180

SENSITIVITY (mV/g)

Figure 6. X-Axis Sensitivity at 25C

Figure 9. Y-Axis Sensitivity at 25C

Rev. 0 | Page 7 of 16

182

184

ADXL320
1.54

0.180
0.179

1.53

0.177

SENSITIVITY (V/g)

1.51
1.50
1.49

0.176
0.175
0.174
0.173

1.48
0.172

1.46
30

04993-009

1.47

20

10

10

20

30

40

50

60

70

04993-012

OUTPUT (SCALE = 174mV/g)

0.178
1.52

0.171
0.170
30

80

20

10

10

TEMPERATURE (C)

20

30

40

50

60

70

80

TEMPERATURE (C)

Figure 10. Zero g Bias vs. TemperatureParts Soldered to PCB

Figure 13. Sensitivity vs. TemperatureParts Soldered to PCB

35

30

30

25

% OF POPULATION

20
15

10

20

15

10

5
04993-010

0
170

190

210

230

250

270

290

310

330

04993-013

% OF POPULATION

25

0
170

350

190

210

230

NOISE ug/ Hz

Figure 11. X-Axis Noise Density at 25C

270

290

310

330

350

Figure 14. Y-Axis Noise Density at 25C

25

30

25

% OF POPULATION

20

15

10

20

15

10

0
5

04993-014

5
04993-011

% OF POPULATION

250

NOISE ug/ Hz

0
5

PERCENT SENSITIVITY (%)

PERCENT SENSITIVITY (%)

Figure 12. Z vs. X Cross-Axis Sensitivity

Figure 15. Z vs. Y Cross-Axis Sensitivity

Rev. 0 | Page 8 of 16

60

60

50

50

% OF POPULATION

40

30

20

30

20

10
04993-015

10

40

0
35

40

45

50

55

60

65

70

04993-017

% OF POPULATION

ADXL320

75

35

SELF-TEST (mV)

40

45

50

55

60

65

70

75

SELF-TEST (mV)

Figure 16. X-Axis Self-Test Response at 25C

Figure 18. Y-Axis Self-Test Response at 25C

40
35

25
20
15

04993-020

10
04993-016

% OF POPULATION

30

0
420 430 440 450 460 470 480 490 500 510 520 530
CURRENT (A)

Figure 19. Turn-On TimeCX, CY = 0.1 F, Time Scale = 2 ms/DIV

Figure 17. Supply Current at 25C

Rev. 0 | Page 9 of 16

ADXL320

XL
320J
#1234
5678P

YOUT = 1.500V

XOUT = 1.500V
YOUT = 1.326V

XOUT = 1.674V
YOUT = 1.50V

XOUT = 1.500V
YOUT = 1.500V

EARTH'S SURFACE

Figure 20. Output Response vs. Orientation

Rev. 0 | Page 10 of 16

04993-018

YOUT = 1.674V

XOUT = 1.326V

XL
320J
#1234
5678P

XOUT = 1.500V

XL
320J
#1234
5678P

XL
320J
#1234
5678P

ADXL320
THEORY OF OPERATION
The ADXL320 is a complete acceleration measurement system
on a single monolithic IC. The ADXL320 has a measurement
range of 5 g. It contains a polysilicon surface-micromachined
sensor and signal conditioning circuitry to implement an openloop acceleration measurement architecture. The output signals
are analog voltages that are proportional to acceleration. The
accelerometer measures static acceleration forces, such as
gravity, which allows it to be used as a tilt sensor.
The sensor is a polysilicon surface-micromachined structure
built on top of a silicon wafer. Polysilicon springs suspend the
structure over the surface of the wafer and provide a resistance
against acceleration forces. Deflection of the structure is
measured using a differential capacitor that consists of
independent fixed plates and plates attached to the moving
mass. The fixed plates are driven by 180 out-of-phase square
waves. Acceleration deflects the beam and unbalances the
differential capacitor, resulting in an output square wave whose
amplitude is proportional to acceleration. Phase-sensitive
demodulation techniques are then used to rectify the signal and
determine the direction of the acceleration.

The demodulators output is amplified and brought off-chip


through a 32 k resistor. The user then sets the signal
bandwidth of the device by adding a capacitor. This filtering
improves measurement resolution and helps prevent aliasing.

PERFORMANCE
Rather than using additional temperature compensation
circuitry, innovative design techniques have been used to ensure
high performance is built-in. As a result, there is neither
quantization error nor nonmonotonic behavior, and
temperature hysteresis is very low (typically less than 3 mg over
the 20C to +70C temperature range).
Figure 10 shows the zero g output performance of eight parts
(X- and Y-axis) over a 20C to +70C temperature range.
Figure 13 demonstrates the typical sensitivity shift over
temperature for supply voltages of 3 V. This is typically better
than 1% over the 20C to +70C temperature range.

Rev. 0 | Page 11 of 16

ADXL320
APPLICATIONS
POWER SUPPLY DECOUPLING
For most applications, a single 0.1 F capacitor, CDC, adequately
decouples the accelerometer from noise on the power supply.
However, in some cases, particularly where noise is present at
the 140 kHz internal clock frequency (or any harmonic
thereof), noise on the supply may cause interference on the
ADXL320 output. If additional decoupling is needed, a 100
(or smaller) resistor or ferrite bead may be inserted in the
supply line. Additionally, a larger bulk bypass capacitor (in the
1 F to 4.7 F range) may be added in parallel to CDC.

SETTING THE BANDWIDTH USING CX AND CY


The ADXL320 has provisions for band-limiting the XOUT and
YOUT pins. Capacitors must be added at these pins to implement
low-pass filtering for antialiasing and noise reduction. The
equation for the 3 dB bandwidth is
F3 dB = 1/(2(32 k) C(X, Y))
or more simply,
F3 dB = 5 F/C(X, Y)
The tolerance of the internal resistor (RFILT) typically varies as
much as 15% of its nominal value (32 k), and the bandwidth
varies accordingly. A minimum capacitance of 2000 pF for CX
and CY is required in all cases.

DESIGN TRADE-OFFS FOR SELECTING FILTER


CHARACTERISTICS: THE NOISE/BW TRADE-OFF
The accelerometer bandwidth selected ultimately determines
the measurement resolution (smallest detectable acceleration).
Filtering can be used to lower the noise floor, which improves
the resolution of the accelerometer. Resolution is dependent on
the analog filter bandwidth at XOUT and YOUT.
The output of the ADXL320 has a typical bandwidth of 2.5 kHz.
The user must filter the signal at this point to limit aliasing
errors. The analog bandwidth must be no more than half the
A/D sampling frequency to minimize aliasing. The analog
bandwidth may be further decreased to reduce noise and
improve resolution.
The ADXL320 noise has the characteristics of white Gaussian
noise, which contributes equally at all frequencies and is
described in terms of g/Hz (the noise is proportional to the
square root of the accelerometers bandwidth). The user should
limit bandwidth to the lowest frequency needed by the
application in order to maximize the resolution and dynamic
range of the accelerometer.
With the single-pole, roll-off characteristic, the typical noise of
the ADXL320 is determined by

rmsNoise = (250 g/ Hz ) ( BW 1.6 )

Table 5. Filter Capacitor Selection, CX and CY


Bandwidth (Hz)
1
10
50
100
200
500

At 100 Hz bandwidth the noise will be

Capacitor (F)
4.7
0.47
0.10
0.05
0.027
0.01

rmsNoise = (250 g/ Hz ) ( 100 1.6 ) = 3.2 mg


Often, the peak value of the noise is desired. Peak-to-peak noise
can only be estimated by statistical methods. Table 6 is useful
for estimating the probabilities of exceeding various peak
values, given the rms value.
Table 6. Estimation of Peak-to-Peak Noise

SELF-TEST
The ST pin controls the self-test feature. When this pin is set to
VS, an electrostatic force is exerted on the accelerometer beam.
The resulting movement of the beam allows the user to test if
the accelerometer is functional. The typical change in output is
315 mg (corresponding to 55 mV). This pin may be left opencircuit or connected to common (COM) in normal use.

Peak-to-Peak Value
2 rms
4 rms
6 rms
8 rms

The ST pin should never be exposed to voltages greater than


VS + 0.3 V. If this cannot be guaranteed due to the system
design (for instance, if there are multiple supply voltages), then
a low VF clamping diode between ST and VS is recommended.

Rev. 0 | Page 12 of 16

% of Time That Noise Exceeds


Nominal Peak-to-Peak Value
32
4.6
0.27
0.006

ADXL320
Peak-to-peak noise values give the best estimate of the
uncertainty in a single measurement. Table 7 gives the typical
noise output of the ADXL320 for various CX and CY values.
Table 7. Filter Capacitor Selection (CX, CY)
Bandwidth
(Hz)
10
50
100
500

CX, CY
(F)
0.47
0.1
0.047
0.01

RMS Noise
(mg)
1.0
2.25
3.2
7.1

Peak-to-Peak Noise
Estimate (mg)
6
13.5
18.9
42.8

USE WITH OPERATING VOLTAGES OTHER THAN 3 V


The ADXL320 is tested and specified at VS = 3 V; however, it
can be powered with VS as low as 2.4 V or as high as 5.25 V.
Note that some performance parameters change as the supply
voltage is varied.
The ADXL320 output is ratiometric, so the output sensitivity
(or scale factor) varies proportionally to supply voltage. At VS =
5 V, the output sensitivity is typically 312 mV/g. At VS = 2.4 V,
the output sensitivity is typically 135 mV/g.
The zero g bias output is also ratiometric, so the zero g output is
nominally equal to VS/2 at all supply voltages.
The output noise is not ratiometric but is absolute in volts;
therefore, the noise density decreases as the supply voltage
increases. This is because the scale factor (mV/g) increases
while the noise voltage remains constant. At VS = 5 V, the noise
density is typically 150 g/Hz, while at VS = 2.4 V, the noise
density is typically 300 g/Hz,

USE AS A DUAL-AXIS TILT SENSOR


Tilt measurement is one of the ADXL320s most popular
applications. An accelerometer uses the force of gravity as an
input vector to determine the orientation of an object in space.
An accelerometer is most sensitive to tilt when its sensitive axis
is perpendicular to the force of gravity (that is, when it is
parallel to the earths surface). At this orientation, its sensitivity
to changes in tilt is highest. When the accelerometer is oriented
on axis to gravity (near its +1 g or 1 g reading), the change in
output acceleration per degree of tilt is negligible. When the
accelerometer is perpendicular to gravity, its output changes
nearly 17.5 mg per degree of tilt. At 45, its output changes at
only 12.2 mg per degree of tilt, and resolution declines.

Converting Acceleration to Tilt


When the accelerometer is oriented so both its X-axis and
Y-axis are parallel to the earths surface, it can be used as a 2axis tilt sensor with both a roll axis and pitch axis. Once the
output signal from the accelerometer has been converted to an
acceleration that varies between 1 g and +1 g, the output tilt in
degrees is calculated as
PITCH = ASIN(AX/1 g)
ROLL = ASIN(AY/1 g)
Be sure to account for overranges. It is possible for the
accelerometers to output a signal greater than 1 g due to
vibration, shock, or other accelerations.

Self-test response in g is roughly proportional to the square of


the supply voltage. However, when ratiometricity of sensitivity
is factored in with supply voltage, the self-test response in volts
is roughly proportional to the cube of the supply voltage. For
example, at VS = 5 V, the self-test response for the ADXL320 is
approximately 250 mV. At VS = 2.4 V, the self-test response is
approximately 25 mV.
The supply current decreases as the supply voltage decreases.
Typical current consumption at VS = 5 V is 750 A, and typical
current consumption at VS = 2.4 V is 350 A.

Rev. 0 | Page 13 of 16

ADXL320
OUTLINE DIMENSIONS
0.20 MIN

PIN 1
INDICATOR

0.20 MIN
13

PIN 1
INDICATOR

4.15
4.00 SQ
3.85
0.65 BSC

TOP
VIEW

16
1

12

2.43
1.75 SQ
1.08

BOTTOM
VIEW
9

4
8

0.55
0.50
0.45

1.95 BSC

0.05 MAX
0.02 NOM
SEATING
PLANE

0.35
0.30
0.25

COPLANARITY
0.05
072606-A

1.50
1.45
1.40

*STACKED DIE WITH GLASS SEAL.

Figure 21. 16-Lead Lead Frame Chip Scale Package [LFCSP_LQ]


4 mm 4 mm Body
(CP-16-5a*)
Dimensions shown in millimeters

ORDERING GUIDE
Model
ADXL320JCP 1
ADXL320JCPREEL1
ADXL320JCPREEL71
ADXL320EB

Measurement
Range
5 g
5 g
5 g

Specified
Voltage (V)
3
3
3

Temperature
Range
20C to +70C
20C to +70C
20C to +70C

Lead finishMatte tin.

Rev. 0 | Page 14 of 16

Package Description
16-Lead LFCSP_LQ
16-Lead LFCSP_LQ
16-Lead LFCSP_LQ
Evaluation Board

Package
Option
CP-16-5a
CP-16-5a
CP-16-5a

IL74
DUAL CHANNEL ILD74
QUAD CHANNEL ILQ74
SINGLE CHANNEL

PHOTOTRANSISTOR OPTOCOUPLER
FEATURES
7400 Series T2L Compatible
Transfer Ratio, 35% Typical
Coupling Capacitance, 0.5 pF
Single, Dual, & Quad Channel
Industry Standard DIP Package
Underwriters Lab File #E52744
V

VDE Approvals #0884


(Optional with Option 1, Add -X001 Suffix)

Dimensions in inches (mm)


Pin One ID.

The IL74 is an optically coupled pair with a Gallium Arsenide infrared LED and a silicon NPN
phototransistor. Signal information, including a
DC level, can be transmitted by the device while
maintaining a high degree of electrical isolation
between input and output. The IL74 is especially
designed for driving medium-speed logic, where
it may be used to eliminate troublesome gound
loop and noise problems. Also it can be used to
replace relays and transformers in many digital
interface applications, as well as analog applications such as CRT modulation.

1
6 Base

Anode 1
.248 (6.30)
.256 (6.50)

5 Collector

Cathode 2
4

4 Emitter

NC 3

.335 (8.50)
.343 (8.70)

D E

DESCRIPTION

.300 (7.62)
typ.

.039
(1.00)
min.

.130 (3.30)
.150 (3.81)

4
typ.

18 typ.
.020 (.051) min.
.031 (0.80)
.035 (0.90)

.018 (0.45)
.022 (0.55)

.300 (7.62)
.347 (8.82)

.100 (2.54) typ.

Pin One I.D.

.268 (6.81)
.255 (6.48)
5

The ILD74 has two isolated channels in a single


DIP package; the ILQ74 has four isolated channels per package.

.110 (2.79)
.150 (3.81)

.010 (.25)
.014 (.35)

Anode

8 Emitter

Cathode

7 Collector

Cathode

6 Collector

Anode

5 Emitter

.390 (9.91)
.379 (9.63)

.305 typ.
(7.75) typ.

.045 (1.14) .150 (3.81)


.030 (.76) .130 (3.30)

4
Typ.
.040 (1.02)
.030 (.76 )

.022 (.56)
.018 (.46)

39

10
Typ.

.135 (3.43)
.115 (2.92)

.012 (.30)
.008 (.20)

.100 (2.54) Typ.

Anode 1

.240 (6.10)
.260 (6.60)
9

10

11

12

13

14

15

.780 (19.81)
.800 (20.32)
.040 (1.02)
.050 (1.27)

.048 (1.22)
.052 (1.32)

51

Cathode 2

15 Collector

Cathode 3

14 Collector

pin one
ID. Anode 4

13 Emitter

Anode 5

12 Emitter

Cathode 6

11 Collector

Cathode

10 Collector

Anode 8

Emitter

.300 (7.62)
typ.

.034 (.86)
.130 (3.30)
.150 (3.81)

.280 (7.11)
.330 (8.38)
.014
(.35)
typ.

.016 (.41)
.020 (.51)

16

16 Emitter

.033 (.84)
typ.

.020 (.51)
.030 (.76)
.0255 (.65)
typ.
.100 (2.54) typ.

.130 (3.30)
.150 (3.81)
3 to 9
.008 (.20)
.012 (.31)

Maximum Ratings

Figure 1. Forward voltage versus forward current


1.4

VF - Forward Voltage - V

Emitter (each channel)


Peak Reverse Voltage .....................................3.0 V
Continuous Forward Current .........................60 mA
Power Dissipationat 25C...........................100 mW
Derate Linearly from 25C....................1.33 mW/C
Detector (each channel)
Collector-Emitter Breakdown Voltage ..............20 V
Emitter-Base Breakdown Voltage .......................5 V
Collector-Base Breakdown Voltage .................70 V
Power Dissipation at 25C..........................150 mW
Derate Linearly from 25C......................2.0 mW/C

1.0
0.9

Ta = 85C

0.8
0.7

NCTR - Normalized CTR

1.0

CTRce(sat) Vce = 0.4V

0.5
NCTR(SAT)
NCTR

VF

1.3

1.5

IF=20 mA

Reverse Current

IR

0.1

100

VR=3.0 V

Capacitance

CO

25

pF

VR=0

Emitter

Detector
50

Leakage Current,
Collector-Emitter

ICEO

5.0

Capacitance,
Collector-Emitter

CCE

10.0

500

NCTR - Normalized CTR

1.5

Condition

BVCEO

IC=1 mA

nA

VCE=5 V,
IF=0

pF

VCE=0,
F=1 MHz

1.0

100

Ta = 50C

0.5
NCTR(SAT)
NCTR
0.0
.1

DC Current Transfer Ratio

CTRDC

Saturation Voltage,
Collector-Emitter

VCEsat

0.3

Resistance, Input
to Output

RIO

100

Capacitance, Input
to Output

CIO

0.5

pF

Switching Times

tON,tOFF

3.0

0.5
V

IF=16 mA,
VCE=5 V
IC=2 mA,
IF=16 mA

100

Normalized to:
Vce = 10V, IF = 10mA
Ta = 25C

1.0

CTRce(sat) Vce = 0.4V

0.5
Ta = 70C
NCTR(SAT)
NCTR

0.0

RE=100 ,
VCE=10 V,
IC=2 mA

1
10
IF - LED Current - mA

Figure 4. Normalized non-saturated and saturated


CTR at TA=70C versus LED current
NCTR - Normalized CTR

35

1
10
IF - LED Current - mA

Normalized to:
Vce = 10V, IF = 10mA, Ta = 25C
CTRce(sat) Vce = 0.4V

1.5

Package
12.5

100

Figure 3. Normalized non-saturated and saturated


CTR at TA=50C versus LED current
Unit

Breakdown
Voltage,
Collector-Emitter

1
10
IF - Forward Current - mA

Normalized to:
Vce = 10V, IF = 10mA
Ta = 25C

0.0
.1

Max.

20

Ta = 25C

1.1

1.5

Typ.

Forward Voltage

1.2

Figure 2. Normalized non-saturated and saturated


CTR at TA=25C versus LED current

Electrical Characteristics (TA=25C)


Min.

Ta = -55C

.1

Package
Isolation Test Voltage (t=1 sec.) ........ 5300 VACRMS
Isolation Resistance
VIO=500 V, TA=25C ............................... 1012
VIO=500 V, TA=100C ............................. 1011
Total Package Dissipation
at 25C Ambient (LED Plus Detector)
IL74.........................................................200 mW
ILD74 ......................................................400 mW
IL74Q ......................................................500 mW
Derate Linearly from 25C
IL74.....................................................2.7 mW/C
ILD74 ................................................5.33 mW/C
ILQ74 ................................................6.67 mW/C
Creepage ............................................... 7 mm min.
Clearance............................................... 7 mm min.
Storage Temperature ...................55C to +150C
Operating Temperature ...............55C to +100C
Lead Soldering Time at 260C .................... 10 sec.

Symbol

1.3

.1

1
10
IF - LED Current - mA

100

IL/ILD/ILQ74

52

Figure 5. Normalized non-saturated and saturated CTR


at TA=85C versus LED current

Figure 9. Collector base photocurrent versus LED


current
1000

Normalized to:
Vce = 10V, IF = 10mA, Ta = 25C
CTRce(sat) Vce = 0.4V

1.0

0.5
Ta = 85C
NCTR(SAT)
NCTR

0.0
.1

1
10
IF - LED Current - mA

100

Icb = 1.0357 *IF ^1.3631

10
1
.1
.01

100

.1

100

1
10
IF - LED Current - mA

Figure 10. Normalized photocurrent versus If and


temperature

Figure 6. Collector-emitter current versus temperature


and LED current

10

35

Normalized to:

30
25

Normalized Photocurrent

Ice - Collector Current - mA

Ta = 25C

Icb - Collector Base


Photocurrent - A

NCTR - Normalized CTR

1.5

50C

20
15

70C

25C
85C

10
5
0
0

10
20
30
40
IF - LED Current - mA

50

If = 10ma, Ta = 25C
1

NIB-Ta=-20C

.1

NIb,Ta=25C
NIb,Ta=50C
NIb,Ta=70C

60
.01
.1

100

10

If LED Current mA

Figure 11. Normalized non-saturated HFE versus


base current and temperature

5
10
4
10
3
10
10 2
10
10

1.2
NHFE - Normalized HFE

Iceo - Collector-Emitter - nA

Figure 7. Collector-emitter leakage current versus


temperature
g
p

Vce = 10V

TYPICAL

10 -1
10 -2
-20

70C
50C
1.0

-20C

0.8
0.6
0.4
1

0
20
40
60
80
100
Ta - Ambient Temperature - C

10
100
Ib - Base Current - A

1000

Figure 12. Normalized saturated HFE versus base


current and temperature

Figure 8. Normalized CTRcb versus LED current


and temperature

1.5

1.5
Normalized to:
IF =10 mA
Vcb = 9.3 V
Ta = 25C

1.0

0.5

NHFE(sat) - Normalized
Saturated HFE

NCTRcb - Normalized CTRcb

25C

Normalized to:
Ib = 20A
Vce = 10 V
Ta = 25C

25C
50C
70C

0.0
.1

1
10
IF - LED Current - mA

100

70C
1.0

50C

25C

Normalized to:
Vce = 10V
Ib = 20A
Ta = 25C

-20C
0.5
Vce = 0.4V
0.0
1

10
100
Ib - Base Current - (A)

1000

IL/ILD/ILQ74

53

2.5

tpHL
100

2.0

1.5

10
tpLH
1

1.0
.1

10

1000
tpLH - Propagation Delay - s

Ta = 25C, IF = 10mA
Vcc = 5 V, Vth = 1.5 V

tpHL - Propagation Delay - s

tpLH - Propagation Delay - s

1000

Figure 14. Propagation delay versus collector load resistor

100

RL - Collector Load Resistor - K

2.5

Ta = 25C, IF = 10mA
Vcc = 5 V, Vth = 1.5 V
tpHL

100

2.0

1.5

10
tpLH
1

1.0
.1

1
10
RL - Collector Load Resistor - K

tpHL - Propagation Delay - s

Figure 13. Propagation delay versus collector load resistor

100

IL/ILD/ILQ74

54

L298

DUAL FULL-BRIDGE DRIVER

..
..
.

OPERATING SUPPLY VOLTAGE UP TO 46 V


TOTAL DC CURRENT UP TO 4 A
LOW SATURATION VOLTAGE
OVERTEMPERATURE PROTECTION
LOGICAL "0" INPUT VOLTAGE UP TO 1.5 V
(HIGH NOISE IMMUNITY)

DESCRIPTION
The L298 is an integrated monolithic circuit in a 15lead Multiwatt and PowerSO20 packages. It is a
high voltage, high current dual full-bridge driver designed to accept standard TTL logic levels and drive
inductive loads such as relays, solenoids, DC and
stepping motors. Two enable inputs are provided to
enable or disable the device independently of the input signals. The emitters of the lower transistors of
each bridge are connected together and the corresponding external terminal can be used for the con-

Multiwatt15

PowerSO20

ORDERING NUMBERS : L298N (Multiwatt Vert.)


L298HN (Multiwatt Horiz.)
L298P (PowerSO20)

nection of an external sensing resistor. An additional


supply input is provided so that the logic works at a
lower voltage.

BLOCK DIAGRAM

Jenuary 2000

1/13

L298
ABSOLUTE MAXIMUM RATINGS
Symbol
VS
VSS
VI,Ven
IO

Vsens

Value

Unit

Power Supply

Parameter

50

Logic Supply Voltage

0.3 to 7

3
2.5
2

A
A
A

Input and Enable Voltage


Peak Output Current (each Channel)
Non Repetitive (t = 100s)
Repetitive (80% on 20% off; ton = 10ms)
DC Operation
Sensing Voltage

1 to 2.3

25

Junction Operating Temperature

25 to 130

Storage and Junction Temperature

40 to 150

Ptot

Total Power Dissipation (Tcase = 75C)

Top
Tstg, Tj

PIN CONNECTIONS (top view)

Multiwatt15

15

CURRENT SENSING B

14

OUTPUT 4

13

OUTPUT 3

12

INPUT 4

11

ENABLE B

10

INPUT 3

LOGIC SUPPLY VOLTAGE VSS

GND

INPUT 2

ENABLE A

INPUT 1

SUPPLY VOLTAGE VS

OUTPUT 2

OUTPUT 1

CURRENT SENSING A

TAB CONNECTED TO PIN 8

D95IN240A

GND

20

GND

Sense A

19

Sense B

N.C.

18

N.C.

Out 1

Out 2

PowerSO20

17

Out 4

16

Out 3

VS

15

Input 4

Input 1

14

Enable B

Enable A

13

Input 3

Input 2

12

VSS

10

11

GND

GND

D95IN239

THERMAL DATA
Symbol

Parameter

PowerSO20

Multiwatt15

Unit

Rth j-case

Thermal Resistance Junction-case

Max.

C/W

Rth j-amb

Thermal Resistance Junction-ambient

Max.

13 (*)

35

C/W

(*) Mounted on aluminum substrate

2/13

L298
PIN FUNCTIONS (refer to the block diagram)
MW.15

PowerSO

Name

1;15

2;19

Sense A; Sense B

Function

2;3

4;5

Out 1; Out 2

VS

5;7

7;9

Input 1; Input 2

6;11

8;14

Enable A; Enable B

1,10,11,20

GND

12

VSS

10; 12

13;15

Input 3; Input 4

13; 14

16;17

Out 3; Out 4

3;18

N.C.

Between this pin and ground is connected the sense resistor to


control the current of the load.
Outputs of the Bridge A; the current that flows through the load
connected between these two pins is monitored at pin 1.
Supply Voltage for the Power Output Stages.
A non-inductive 100nF capacitor must be connected between this
pin and ground.
TTL Compatible Inputs of the Bridge A.
TTL Compatible Enable Input: the L state disables the bridge A
(enable A) and/or the bridge B (enable B).
Ground.
Supply Voltage for the Logic Blocks. A100nF capacitor must be
connected between this pin and ground.
TTL Compatible Inputs of the Bridge B.
Outputs of the Bridge B. The current that flows through the load
connected between these two pins is monitored at pin 15.
Not Connected

ELECTRICAL CHARACTERISTICS (VS = 42V; VSS = 5V, Tj = 25C; unless otherwise specified)
Symbol

Parameter

Test Conditions

Supply Voltage (pin 4)

Operative Condition

IS

Logic Supply Voltage (pin 9)


Quiescent Supply Current (pin 4)

Ven = H; IL = 0

ISS

Ven = L
Quiescent Current from VSS (pin 9) Ven = H; IL = 0

VS
VSS

ViH
IiL
IiH
Ven = L

Input Low Voltage


(pins 5, 7, 10, 12)
Input High Voltage
(pins 5, 7, 10, 12)
Low Voltage Input Current
(pins 5, 7, 10, 12)
High Voltage Input Current
(pins 5, 7, 10, 12)
Enable Low Voltage (pins 6, 11)

Ven = H
Ien = L

Enable High Voltage (pins 6, 11)


Low Voltage Enable Current
(pins 6, 11)

Ien = H

High Voltage Enable Current


(pins 6, 11)
Source Saturation Voltage

VCEsat (H)

VCEsat (L) Sink Saturation Voltage


VCEsat

Total Drop

Vsens

Sensing Voltage (pins 1, 15)

Max.

Unit

46

5
13
50

7
22
70

V
mA
mA

24
7

4
36
12

mA
mA
mA

0.3

6
1.5

mA
V

2.3

VSS

10

100

4.5

Ven = L
ViL

Min.

Typ.

VIH +2.5
Vi = L
Vi = H
Vi = X
Vi = L
Vi = H
Vi = X

Vi = L
Vi = H VSS 0.6V

30
0.3

1.5

2.3

VSS
10

V
A

30

100

1.35
2
1.2
1.7

1.7
2.7
1.6
2.3
3.2
4.9

V
V
V
V
V
V

Ven = L
Ven = H VSS 0.6V
IL = 1A
IL = 2A
IL = 1A
IL = 2A
IL = 1A
IL = 2A

0.95
(5)
(5)
(5)
(5)

0.85
1.80
1 (1)

3/13

L298
ELECTRICAL CHARACTERISTICS (continued)
Symbol

Parameter

Test Conditions

Min.

Typ.

Max.

Unit

(2); (4)

1.5

0.9 IL to 0.1 IL

(2); (4)

0.2

0.5 Vi to 0.1 IL

(2); (4)

Source Current Rise Time

0.1 IL to 0.9 IL

(2); (4)

0.7

T5 (Vi)

Sink Current Turn-off Delay

0.5 Vi to 0.9 IL

(3); (4)

0.7

T6 (Vi)

Sink Current Fall Time

0.9 IL to 0.1 IL

(3); (4)

0.25

T7 (Vi)

Sink Current Turn-on Delay

0.5 Vi to 0.9 IL

(3); (4)

1.6

T8 (Vi)

Sink Current Rise Time

0.1 IL to 0.9 IL

(3); (4)

0.2

T1 (Vi)

Source Current Turn-off Delay

0.5 Vi to 0.9 IL

T2 (Vi)

Source Current Fall Time

T3 (Vi)

Source Current Turn-on Delay

T4 (Vi)

Commutation Frequency

IL = 2A

T1 (Ven)

fc (Vi)

Source Current Turn-off Delay

0.5 Ven to 0.9 IL

25

T2 (Ven)

Source Current Fall Time

0.9 IL to 0.1 IL

T3 (Ven)

Source Current Turn-on Delay

0.5 Ven to 0.1 IL

T4 (Ven)

Source Current Rise Time

0.1 IL to 0.9 IL

T5 (Ven)

Sink Current Turn-off Delay

0.5 Ven to 0.9 IL

T6 (Ven)

Sink Current Fall Time

0.9 IL to 0.1 IL

T7 (Ven)

Sink Current Turn-on Delay

0.5 Ven to 0.9 IL

T8 (Ven)

Sink Current Rise Time

0.1 IL to 0.9 IL

(2); (4)
(2); (4)
(2); (4)
(2); (4)
(3); (4)
(3); (4)
(3); (4)
(3); (4)

40

0.3

0.4

2.2

0.35

0.25

0.1

1) 1)Sensing voltage can be 1 V for t 50 sec; in steady state Vsens min 0.5 V.
2) See fig. 2.
3) See fig. 4.
4) The load must be a pure resistor.

Figure 1 : Typical Saturation Voltage vs. Output


Current.

Figure 2 : Switching Times Test Circuits.

Note : For INPUT Switching, set EN = H


For ENABLE Switching, set IN = H

4/13

KHz

L298
Figure 3 : Source Current Delay Times vs. Input or Enable Switching.

Figure 4 : Switching Times Test Circuits.

Note : For INPUT Switching, set EN = H


For ENABLE Switching, set IN = L

5/13

L298
Figure 5 : Sink Current Delay Times vs. Input 0 V Enable Switching.

Figure 6 : Bidirectional DC Motor Control.

Inputs
Ven = H

Ven = L
L = Low

6/13

C=H;D=L
C=L;D=H
C=D
C=X;D=X
H = High

Function
Forward
Reverse
Fast Motor Stop
Free Running
Motor Stop
X = Dont care

L298
Figure 7 : For higher currents, outputs can be paralleled. Take care to parallel channel 1 with channel 4
and channel 2 with channel 3.

APPLICATION INFORMATION (Refer to the block diagram)


Each input must be connected to the source of the
1.1. POWER OUTPUT STAGE
driving signals by means of a very short path.
The L298 integrates two power output stages (A ; B).
Turn-On and Turn-Off : Before to Turn-ON the SupThe power output stage is a bridge configuration
ply Voltage and before to Turn it OFF, the Enable inand its outputs can drive an inductive load in comput must be driven to the Low state.
mon or differenzial mode, depending on the state of
the inputs. The current that flows through the load
3. APPLICATIONS
comes out from the bridge at the sense output : an
Fig 6 shows a bidirectional DC motor control Scheexternal resistor (RSA ; RSB.) allows to detect the inmatic Diagram for which only one bridge is needed.
tensity of this current.
The external bridge of diodes D1 to D4 is made by
1.2. INPUT STAGE
four fast recovery elements (trr 200 nsec) that
Each bridge is driven by means of four gates the inmust be chosen of a VF as low as possible at the
put of which are In1 ; In2 ; EnA and In3 ; In4 ; EnB.
worst case of the load current.
The In inputs set the bridge state when The En input
The sense output voltage can be used to control the
is high ; a low state of the En input inhibits the bridge.
current amplitude by chopping the inputs, or to proAll the inputs are TTL compatible.
vide overcurrent protection by switching low the enable input.
2. SUGGESTIONS
The brake function (Fast motor stop) requires that
A non inductive capacitor, usually of 100 nF, must
the Absolute Maximum Rating of 2 Amps must
be foreseen between both Vs and Vss, to ground,
never be overcome.
as near as possible to GND pin. When the large capacitor of the power supply is too far from the IC, a
When the repetitive peak current needed from the
second smaller one must be foreseen near the
load is higher than 2 Amps, a paralleled configuraL298.
tion can be chosen (See Fig.7).
The sense resistor, not of a wire wound type, must
An external bridge of diodes are required when inbe grounded near the negative pole of Vs that must
ductive loads are driven and when the inputs of the
be near the GND pin of the I.C.
IC are chopped ; Shottky diodes would be preferred.
7/13

L298
This solution can drive until 3 Amps In DC operation
and until 3.5 Amps of a repetitive peak current.
On Fig 8 it is shown the driving of a two phase bipolar
stepper motor ; the needed signals to drive the inputs of the L298 are generated, in this example,
from the IC L297.
Fig 9 shows an example of P.C.B. designed for the
application of Fig 8.

Fig 10 shows a second two phase bipolar stepper


motor control circuit where the current is controlled
by the I.C. L6506.

Figure 8 : Two Phase Bipolar Stepper Motor Circuit.


This circuit drives bipolar stepper motors with winding currents up to 2 A. The diodes are fast 2 A types.

RS1 = RS2 = 0.5


D1 to D8 = 2 A Fast diodes

8/13

VF 1.2 V @ I = 2 A
trr 200 ns

L298
Figure 9 : Suggested Printed Circuit Board Layout for the Circuit of fig. 8 (1:1 scale).

Figure 10 : Two Phase Bipolar Stepper Motor Control Circuit by Using the Current Controller L6506.

RR and Rsense depend from the load current

9/13

L298
mm

DIM.
MIN.

TYP.

inch
MAX.

MIN.

TYP.

MAX.

0.197

2.65

0.104

1.6

0.063

0.039

0.49

0.55

0.019

0.022

0.66

0.75

0.026

0.030

1.02

1.27

1.52

0.040

0.050

0.060

G1

17.53

17.78

18.03

0.690

0.700

0.710

H1

19.6

0.772

H2

20.2

0.795

21.9

22.2

22.5

0.862

0.874

0.886

L1

21.7

22.1

22.5

0.854

0.870

0.886

L2

17.65

18.1

0.695

L3

17.25

17.5

17.75

0.679

0.689

0.699

L4

10.3

10.7

10.9

0.406

0.421

0.429

L7

2.65

2.9

0.104

0.713

0.114

4.25

4.55

4.85

0.167

0.179

0.191

M1

4.63

5.08

5.53

0.182

0.200

0.218

1.9

2.6

0.075

S1

1.9

2.6

0.075

0.102

Dia1

3.65

3.85

0.144

0.152

10/13

OUTLINE AND
MECHANICAL DATA

0.102

Multiwatt15 V

L298
mm

DIM.
MIN.

TYP.

inch
MAX.

MIN.

TYP.

MAX.

0.197

2.65

0.104

1.6

0.063

0.49

0.55

0.019

0.022

0.66

0.75

0.026

0.030

1.14

1.27

1.4

0.045

0.050

0.055

G1

17.57

17.78

17.91

0.692

0.700

0.705

H1

19.6

0.772

H2

20.2

0.795

20.57

0.810

L1

18.03

0.710

L2

2.54

L3

17.25

L4

10.3

L5

0.100

17.5

17.75

0.679

0.689

0.699

10.7

10.9

0.406

0.421

0.429

5.28

L6

OUTLINE AND
MECHANICAL DATA

0.208

2.38

0.094

L7

2.65

2.9

0.104

0.114

1.9

2.6

0.075

0.102

S1

1.9

2.6

0.075

0.102

Dia1

3.65

3.85

0.144

0.152

Multiwatt15 H

11/13

L298

DIM.
A
a1
a2
a3
b
c
D (1)
D1
E
e
e3
E1 (1)
E2
E3
G
H
h
L
N
S
T

MIN.

mm
TYP.

0.1
0
0.4
0.23
15.8
9.4
13.9

MAX.
3.6
0.3
3.3
0.1
0.53
0.32
16
9.8
14.5

MIN.
0.004
0.000
0.016
0.009
0.622
0.370
0.547

1.27
11.43
10.9

inch
TYP.

0.050
0.450
11.1 0.429
2.9
6.2
0.228
0.1
0.000
15.9 0.610
1.1
1.1
0.031
10 (max.)
8 (max.)

5.8
0
15.5
0.8

OUTLINE AND
MECHANICAL DATA

MAX.
0.142
0.012
0.130
0.004
0.021
0.013
0.630
0.386
0.570

10

0.437
0.114
0.244
0.004
0.626
0.043
0.043

JEDEC MO-166

0.394

PowerSO20

(1) "D and F" do not include mold flash or protrusions.


- Mold flash or protrusions shall not exceed 0.15 mm (0.006").
- Critical dimensions: "E", "G" and "a3"

N
a2
b

DETAIL A

c
a1

DETAIL B

e3
H

DETAIL A

lead

slug

a3
DETAIL B
20

11

0.35
Gage Plane

-C-

SEATING PLANE

E2

E1

BOTTOM VIEW

T
E3
1

h x 45

12/13

10

PSO20MEC

(COPLANARITY)

D1

II.- PLANOS

PLANOS

II.- PLANOS

1. Lista de Planos

2. Esquemticos

3. Circuitos Impresos
3.1. Circuito Integrado
3.2. Mscara de soldadura
3.3. Serigrafa

PLANOS

1. Lista de Planos

Plano n1: esquema circuito 1. Etapa de potencia, medida de intensidad


por el motor, acondicionamiento microprocesador.

Plano n2: esquema circuito 2. Acondicionamiento del acelermetro.

Plano n3: esquema circuito 3. Balizas.

Plano n4: esquema circuito 4. Reguladores de tensin LM2736Y.

Plano n5: circuito impreso 1. Capa TOP.

Plano n6: circuito impreso 1. Capa BOTTOM.

Plano n7: circuito impreso 1. Capa GND.

Plano n8: circuito impreso 1. Capa INNER1.

Plano n9: circuito impreso 1. Capa INNER2.

Plano n10: circuito impreso 1. SERIGRAFA.

Plano n11: circuito impreso 1. PADS.

Plano n12: circuito impreso 2. Capa TOP.

Plano n13: circuito impreso 2. Capa BOTTOM.

Plano n14: circuito impreso 2. SERIGRAFA.

Plano n15: circuito impreso 2. PADS.

PLANOS

2. Esquemticos

PLANOS

3. Circuitos Impresos

III.- PLIEGO DE
CONDICIONES

CONDICIONES

III.- PLIEGO DE CONDICIONES

1. Generales y Econmicas
2. Tcnicas y particulares

CONDICIONES

Generales y econmicas

1. Generales y Econmicas
1.1. CONDICIONES GENERALES
Las condiciones y clusulas que se establecen en este documento
tratan de la contratacin, por parte de persona fsica o jurdica, del
hardware (tarjeta) y el software incorporado a la misma, que ha sido
desarrollado en este proyecto.

El cumplimiento de estas condiciones obliga a ambas partes, y son las


que a continuacin se exponen:

1.

Las dos partes se comprometen desde la fecha de la firma del


contrato, a cumplir todo lo que a continuacin se estipula.

2.

En el caso de reclamacin o discrepancia en lo concerniente al


cumplimiento por cualquiera de las dos partes, una vez agotada
la va del entendimiento, se tramitar el asunto por va legal.

3.

El suministrador se compromete a cumplir fielmente las


condiciones tcnicas, de diseo, fabricacin y capacidad que se
estipulen en los planos, listas de materiales y especificaciones
indicadas en el proyecto, a comprobar por el comprador desde
la recepcin del mismo.

4.

La conformidad de los inspectores del comprador no exime al


proveedor de la responsabilidad que le atae en los defectos de
diseo y construccin que se mostrasen con posterioridad. El
suministrador garantiza igualmente, que el suministro efectuado
est dotado de todas las medidas de seguridad exigidas por las
Condiciones Generales y Econmicas.

CONDICIONES
5.

Generales y econmicas
El plazo de entrega ser de tres semanas a partir de la fecha de
la firma del contrato.

6.

Si la entrega se retrasara ms de las tres semanas acordadas, el


comprador podr rescindir el contrato, sindole retribuidas
todas las cantidades abonadas.

7.

El equipo est garantizado por un ao a partir de la fecha de


puesta en servicio del mismo, cubriendo la reparacin de fallo
interno o defecto de fabricacin y excluyendo cualquier mal uso
que se haga del equipo.

8.

El plazo de puesta en servicio no ser superior a seis meses a


partir de la fecha de entrega del equipo.

9.

La garanta slo ser vlida siempre que se lleve a cabo una


correcta instalacin del equipo, as como un correcto uso del
mismo. La garanta cesa por manipulaciones efectuadas por
personal no autorizado expresamente por el suministrador.

10.

El suministrador no asumir ninguna responsabilidad superior a


las aqu definidas, y en ningn caso pagar indemnizaciones por
cualquier otro dao o perjuicio directo o indirecto a personas o
cosas por lucro cesante.

CONDICIONES

Generales y econmicas

1.2. CONDICIONES ECONMICAS

Los precios indicados en este proyecto son firmes y sin revisin por
ningn concepto, siempre y cuando se acepten dentro del perodo de
validez posteriormente indicado. El perodo de validez del presupuesto es
hasta el mes de Diciembre de 2008.

La forma de pago del presente proyecto ser:

5% a la recepcin del pedido.

15% a la entrega de planos y documentacin tcnica.

50% a la entrega del equipo.

30% a la puesta en marcha del sistema, siempre y cuando


este plazo no exceda los 100 das de la fecha de entrega del
equipo.

CONDICIONES

Tcnicas y particulares

2. Tcnicas y particulares
2.1. CIRCUITO IMPRESO
El tipo de soporte aislante usado ser de fibra de vidrio impregnada con resina
epoxi para dar rigidez. Se recomiendan las siguientes caractersticas para el
soporte aislante:

Para la fabricacin de la placa impresa se utilizar el mtodo sustractivo,


partiendo de una placa de doble cara y eliminando del soporte aislante las zonas
no representadas en el dibujo modelo.

Se realizar la soldadura por ola en cuanto a componentes de insercin, y por


horno de fusin en componentes SMD, y la limpieza por freno. El espesor de la
placa ha de ser de 1.6 mm., valor normalizado para circuitos impresos.

Las dimensiones de las placas debern permitir el alojamiento de las mismas


en una caja de 100x94 mm.

CONDICIONES

Tcnicas y particulares

2.2. TRAZADO DE LAS PISTAS


Para el correcto trazado de las pistas habr que tener en cuenta las siguientes
consideraciones en cuanto al grosor de las mismas:

El grosor de las pistas de alimentacin ser lo ms grande posible. Ay pistas


de alimentacin de 0,015 para lo que ha sido necesario disear convenientemente
el trazado, en funcin del consumo de cada zona.

2.3. DIAMETRO DE LOS PADS

Los dimetros recomendados para los pads de los distintos componentes son
los que se muestran a continuacin:

CONDICIONES

Tcnicas y particulares

2.4. DIMETRO DE LOS TALADROS

Los dimetros recomendados para los taladros son los que se muestran a
continuacin:

2.5. CONDICIONES DE MONTAJE

- Las placas de circuito llevarn capa de serigrafa.


- Los puestos de montaje dispondrn de proteccin antiesttica.

2.6. CONDICIONES AMBIENTALES

El sistema se disear para un funcionamiento correcto dentro de los


mrgenes siguientes:

Temperatura de almacenamiento..-30 C a +75 C.

Temperatura de trabajo.+0 C a +70 C.

Humedad relativa: 85% sin precipitacin y sin condensacin.

Vibracin: 2G entre 20 y 400Hz en cualquier plano y direccin.

Sock en operacin: 5G en cualquier plano y direccin.

Sock en transporte: 10G en cualquier plano y direccin.

CONDICIONES
2.7. OTROS CRITERIOS DE DISEO

Tcnicas y particulares

- Se deben evitar en lo posible los cableados, para lo que se utilizarn conexiones


mediante conectores enchufables, evitando la utilizacin del sistema cable plano.
No se puede evitar el cableado externo para la utilizacin del controlador.

- Se intentarn, en lo posible, utilizar componentes lo ms normalizados dentro


del mercado electrnico con existencia de segundas fuentes.

- Una vez montada y comprobada la tarjeta del circuito impreso, se aplicar sobre
ella una capa de barniz para efectuar la tropicalizacin de la misma, y evitar as
los defectos de una posible corrosin que se diera por inclemencias del medio
ambiente en el que pudiera instalarse el equipo.

- Se buscar en todo momento un sistema compacto y resistente a las vibraciones


que puedan producirse en los lugares donde se instale un equipo de estas
caractersticas.

- Se utilizarn componentes con alto margen de caractersticas climticas y para


funcionamiento en entorno industrial.

- Como estndar, el sistema se disear para obtener un funcionamiento ptimo,


dentro de los siguientes mrgenes:

- Con respecto a las caractersticas elctricas, la tensin de funcionamiento deber


ser capaz de variarse en un 20 % de su valor, sin que se aprecie en el equipo
ningn cambio de caractersticas de medida o funcionamiento.

CONDICIONES

Tcnicas y particulares

2.8. NORMATIVA
El equipo tendr que cumplir las normas citadas a continuacin:

IV.- PRESUPUESTO

PRESUPUESTO

IV.- PRESUPUESTO

1. Mediciones
2. Presupuestos parciales
3. Presupuesto total

PRESUPUESTO

1. Mediciones
1.1. Circuito 1: Etapa de potencia, medida de intensidad
por el motor, acondicionamiento microprocesador.
# COMPONENTE REFERENCIA #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

0.1UF
0.1UF
0.1UF
0.1UF
0.1UF
0
1NF
1NF
1NF
1NF
1NF
1
2N3904
2k
4.7K
4X 22
4X 22
5.6k
6.8k
10K
10K
10UF TANT.
10UF TANT.
10u
13k
43
68NF
68NF
68NF
68NF
68NF
68NF
68NF

C2
C3
C4
C5
C17
R1B
C6
C7
C8
C9
C14
R6
Q1
R7
R4
RP1
RP2
R3
R11
R12
R13
C1
C16
C3B
R8
R1
C18
C19
C20
C21
C22
C23
C24

34

68NF

C25

COMPONENTE

35
68NF
36
68NF
37
100N
38
100N
39
100PF
40
100PF
41
100PF
42
100PF
43
100PF
44
150k
45
200
46
270
47
7805/SIP
48
CARGA
49 Conector Acelermetro
50
DIODE BRIDGE
51 DIODE ZENER (3.3 V)
52 DIODE ZENER (3.3 V)
53
FUENTE
54
Flash Voltage Ref.
55
L298/MUTIV
56
MCF5282CVF66
57
OP-07
58
OP-07
59
OP-07
60
OP-07
61
SIPSOC-3
62
STANDBY SUPPLY
63
STANDBY SUPPLY
64
STANDBY SUPPLY
65
Voltage Ref. High
66
Voltage Ref. Low
67
ilq74

REFERENCIA
C26
C27
C1B
C2B
C10
C11
C12
C13
C15
R9
R2
R10
U9
J7
J10
D2
D1
D3
J8
JP1
U3
U1
U4
U5
U6
U7
J9
JP2
JP4
JP6
JP3
JP5
U2

PRESUPUESTO

1.2. Circuito 2: Acondicionamiento del acelermetro


# COMPONENTE REFERENCIA #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

1.5K
1.5K
1K
1K
1K
1K
1K
1K
1K
1K
1K
1K
3.3U
3.3U
5.6K
5.6K
100K

R8
R10
R2
R3
R4
R5
R6
R12
R13
R14
R15
R16
C1
C2
R7
R9
R1

COMPONENTE

18
100K
19
ADXL320
20
BYV28-150
21
BYV28-150
22
BYV28-150
23
BYV28-150
24 CONECTOR ACELERMETRO
25
FUENTE
26
FUENTE
27
FUENTE
28
OP-07
29
OP-07
30
OP-07
31
OP-07
32
OP-07
33
OP-07

REFERENCIA
R11
U1
D1
D2
D3
D4
J4
J1
J2
J3
U2
U3
U4
U5
U6
U7

1.3. Circuito 3: Balizas


# COMPONENTE REFERENCIA #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

0.33K
0.33K
0.47K
0.47K
1.5k
1K
1K
1K
1K
1K
1K
2N3904
2N3904
4.7k
70k
100K
100K
100K

R1
R6
R14
R15
R8
R2
R5
R9
R10
R16
R17
Q1
Q2
R4
R13
R3
R7
R11

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

COMPONENTE

REFERENCIA

100K
Conector Micro
DIODE ZENER (3.3V)
DUMMY
DUMMY
FUENTE
FUENTE
LED
LED
OP-07
OP-07
OP-07
OP-07
OP-07
OP-07
PHOTODIODE
PHOTODIODE

R12
J4
D7
D2
D4
J1
J2
D8
D9
U1
U2
U3
U4
U5
U6
D1
D3

PRESUPUESTO

2. Presupuestos parciales
2.1. Circuito 1: Etapa de potencia, medida de intensidad
por el motor, acondicionamiento microprocesador.

REFERENCIA
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

COMPONENTE

C1,C16
10uF TANT.
C1,C2
100n
C10,C11,C12,C13,C15
100pF
C18,C19,C20,C21,C22,C23,
68nF
C1B,C2B
100n
C2,C3,C4,C5,C17
0.1uF
C24,C25,C26,C27
C3
10u
C3B
10u
C6,C7,C8,C9,C14
1nF
D1,D3
DIODE ZENER (3V)
D1,D3
DIODE ZENER (3.3 V)
D2
DIODE BRIDGE
D2
DIODE BRIDGE
J10
Conector Acelermetro
J7
CARGA
J7
CARGA
J8
FUENTE
J8
FUENTE
J9
SIPSOC-3
J9
SIPSOC-3
JP1
Flash Voltage Ref.
JP2,JP4,JP6
Standby supply
JP3
Voltage Ref. High
JP5
Voltage Ref. Low
Q1
2N3904
Q1
2N3904
R1
43
R1
43
R10
270
R10
270
R11
6.8k
R11
6.8k
R12,R13
10k
R12,R13
10k

UDS.
2
2
5
10
2
5
1
1
5
2
2
1
1
1
1
1
1
1
1
1
1
3
1
1
1
1
1
1
1
1
1
1
2
2

PRECIO
UD.
1,60
0,01
0,01
0,01
0,01
0,01
0,01
0,01
0,01
0,01
0,03
0,03
0,15
0,15
0,20
0,20
0,20
0,20
0,20
0,20
0,20
0,15
0,15
0,15
0,15
0,03
0,03
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02

TOTAL
3,20
0,02
0,05
0,10
0,02
0,05
0,00
0,01
0,01
0,05
0,06
0,06
0,15
0,15
0,20
0,20
0,20
0,20
0,20
0,20
0,20
0,15
0,45
0,15
0,15
0,03
0,03
0,02
0,02
0,02
0,02
0,02
0,02
0,04
0,04

PRESUPUESTO
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

R1B
R2
R2
R3
R3
R4
R4
R6
R6
R7
R7
R8
R8
R9
R9
RP1,RP2
U1
U10
U2
U3
U4,U5,U6,U7
U9

0
200
200
5.6k
5.6k
4.7k
4.7k
1
1
2k
2k
13k
13k
150k
150k
4x 22
MCF5282CVF66
7803/SIP
ilq74
L298/MUTIV
OP-07
7805/SIP

1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
2
1
1
1
1
4
1

0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,70
47,29
0,53
2,77
4,45
0,04
0,53

TOTAL

0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,02
1,40
47,29
0,53
2,77
4,45
0,16
0,53
63,92

2.2. Circuito 2: Acondicionamiento del acelermetro

1
2
3
4
5
6
7
8
9
10

REFERENCIA

COMPONENTE

UDS.

PRECIO
UD.

C1,C2
D1,D2,D3,D4
J1,J2,J3
J4
R1,R11
R2,R3,R4,R5,R6,R12,R13,
R14,R15,R16
R7,R9
R8,R10
U1
U2,U3,U4,U5,U6,U7

3.3u
BYV28-150
FUENTE
Conector Acelermetro
100k
1k

2
4
3
1
2
10

0,01
0,02
0,20
0,20
0,02
0,02

5.6k
1.5k
ADXL320
OP-07

2
2
1
6

0,02
0,02
10,08
0,04

TOTAL

TOTAL
0,02
0,08
0,60
0,20
0,04
0,20
0,00
0,04
0,04
10,08
0,24
11,54

PRESUPUESTO

2.3. Circuito 3: Balizas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

REFERENCIA

COMPONENTE

UDS.

PRECIO
UD.

TOTAL

D1,D3
D2,D4
D7
D8,D9
J1,J2
J4
Q1,Q2
R1,R6
R2,R5,R9,R10,R16,R17
R3,R7,R11,R12
R4
R8
R13
R14,R15
U1,U2,U3,U4,U5,U6

PHOTODIODE
Dummy
DIODE ZENER (3.3V)
LED
FUENTE
Conector Micro
2N3904
0.33k
1k
100k
4.7k
1.5k
70k
0.47k
OP-07

2
2
1
2
2
1
2
2
6
4
1
1
1
2
6

10,44
10,44
0,03
0,44
0,20
0,20
0,03
0,02
0,02
0,02
0,02
0,02
0,02
0,02
0,03

20,88
20,88
0,03
0,88
0,40
0,20
0,06
0,04
0,12
0,08
0,02
0,02
0,02
0,04
0,18

TOTAL

43,85

2.4. Maqueta:

1
2
3

COMPONENTE

UDS.

PRECIO UD.

TOTAL

Maqueta tren elctrico


Va recta tren
Va curva tren

1
2
12

89,5
1,1
1,1

89,5
2,2
13,2

TOTAL

104,9

2.5. Recursos:
Concepto
Ordenador AMD Athlon 64
Licencia Matlab
Licencia Freescale Codewarrior
Licencia PSPICE
Licencia Microsoft Office
TOTAL

UDS.

PRECIO
UD.

TOTAL

1
1
1
1
1

1200.00
600.00
380.00
350.00
450.00

1200.00
600.00
380.00
350.00
450.00

3580.00

PRESUPUESTO

2.6. Diseo:
Concepto
Hora ingeniera
TOTAL

UDS.

PRECIO
UD.

TOTAL

1056

35.00

36960.00

36960.00

PRESUPUESTO

3. Presupuesto total

Concepto
Gastos de materiales
Gastos de recursos empleados
Gastos de ingeniera
TOTAL

TOTAL
224,21
3580
36960

40764,21

Fdo.: Fernando Moreno Prez


Madrid, 17 de Junio de 2010

También podría gustarte