Control Motor Tesis

350
Autorizada la entrega del proyecto: Diseño de un sistema de control de velocidad de un motor de corriente continua basado en acelerómetros Realizado por Fernando Moreno Pérez El director del Proyecto: _________ ________ D. Eduardo Santamaría Navarrete Fecha: ……/…………/……. Vº Bº del Coordinador de Proyectos _________ ________ D. Álvaro Sánchez Miralles Fecha: ……/…………/…….

Transcript of Control Motor Tesis

Page 1: Control Motor Tesis

Autorizada la entrega del proyecto:

Diseño de un sistema de control de velocidad de un motor de corriente continua basado en

acelerómetros

Realizado por

Fernando Moreno Pérez

El director del Proyecto:

_________ ________

D. Eduardo Santamaría Navarrete

Fecha: ……/…………/…….

Vº Bº del Coordinador de Proyectos

_________ ________

D. Álvaro Sánchez Miralles

Fecha: ……/…………/…….

Page 2: Control Motor Tesis

PROYECTO FIN DE CARRERA

DISEÑO DE UN SISTEMA DE CONTROL DE VELOCIDAD DE UN

MOTOR DE CORRIENTE CONTINUA BASADO EN ACELERÓMETROS

AUTOR: Fernando Moreno Pérez

MADRID, Junio 2010

UNIVERSIDAD PONTIFICIA COMILLAS

ESCUELA TÉCNICA SUPERIOR DE INGENIERÍA (ICAI)

INGENIERO INDUSTRIAL

Page 3: Control Motor Tesis

RESUMEN

DISEÑO DE UN SISTEMA DE CONTROL DE VELOCIDAD DE UN MOTOR DE

CORRIENTE CONTINUA BASADO EN ACELERÓMETROS

Autor: Moreno Pérez, Fernando.

Director: Santamaría Navarrete, Eduardo.

Entidad Colaboradora: ICAI – Universidad Pontificia Comillas

RESUMEN DEL PROYECTO

OBJETIVO

Se pretende diseñar un sistema de control que permita regular la velocidad de una maqueta de tren

eléctrico, accionado por un motor de corriente continua, en función de la aceleración normal que

experimente en cada instante. Dicho control será implantado en un microprocesador. Para ello, será

necesario realizar:

• La estimación de los parámetros físicos de la planta mediante ensayos.

• El modelado del sistema a partir de dichos parámetros.

• El diseño y construcción del hardware del sistema: etapa de potencia (que contendrá el driver

del motor), y circuitos de acondicionamiento de señales de medida (aceleración, intensidad que

recorrer el motor, etc.).

• El diseño del sistema de control, y su adecuación al tiempo discreto para su posterior desarrollo

software e implantación en el microprocesador.

• Programación del microprocesador basada en el SOTR FreeRTOS©.

DESARROLLO

1. Estimación de parámetros físicos y modelado del sistema

Antes de realizar el diseño del control, es necesario conocer y modelar los distintos parámetros

físicos que intervienen en el sistema a controlar. Esos parámetros 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

• Fricción viscosa

• Velocidad máxima

Una vez obtenidos dichos parámetros, se ha obtenido un modelo del sistema, a partir de cual

trabajar en el diseño del control, ya que, sin una modelización del sistema físico, habría sido

imposible realizar dicho diseño o las simulaciones pertinentes para comprobar la validez del mismo.

Una primera aproximación del modelo del sistema podría ser la que se observa en la figura

siguiente:

Page 4: Control Motor Tesis

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

señales de medida que intervienen en el control y del microprocesador.

La etapa de potencia es la encargada de adecuar la señal 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 señal cumplen la función de acondicionar las señales que se

desean medir para realimentar el control de manera que dicha medición se efectúe con la mayor

precisión y sensibilidad posibles, y sin perturbar a la señal original. Para ello se han utilizado

básicamente etapas basadas en amplificadores operacionales y los propios sensores.

3. Diseño e implantación del sistema de control

El diseño del sistema de control se puede dividir en dos partes: un sistema que genera una

referencia de velocidad, de acuerdo con los valores de aceleración 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 generación 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 parámetros

Page 5: Control Motor Tesis

RESUMEN

se fijaron a partir de distintos diseños, que se describen brevemente a continuación: en una primera

aproximación se diseñó aproximando los parámetros por simulación, para comprobar

posteriormente que este método de diseño no es el más acertado, y se procedió a diseñar aplicando

técnicas de respuesta en frecuencia: diseño por margen de fase y diseño por margen de ganancia.

Ante el comportamiento de la salida con los controles anteriores, se pensó que se podía mejorar

filtrando la corriente medida que va al microprocesador. Para ello se diseñaron dos filtros digitales:

un filtro paso bajo de primer orden, y un filtro FIR paso bajo. Después de haber rediseñado el

control para el sistema incluyendo esos filtros, se comprobó mediante simulación que no

mejoraban, sino que empeoraban la respuesta del sistema.

Una vez claro el regulador que se iba a utilizar (el diseñado por técnicas 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

más 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,

gestión de salidas mediante onda PWM, etc., sobre el sistema operativo en tiempo real FreeRTOS.

RESULTADOS Y CONCLUSIONES

Se muestra a continuación 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 régimen permanente:

Se puede observar una respuesta que se adapta con bastante precisión a la referencia, lo que induce

a pensar que el control ha sido diseñado de forma satisfactoria, tal y como demostraron los ensayos.

Page 6: Control Motor Tesis

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 system´s 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:

• Motor´s internal resistance

• System´s mass

• Motor´s inductance

• Constants associated to the motor´s torque

• Viscous friction

• Maximum speed

Once these parameters have been measured, a system´s 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:

Page 7: Control Motor Tesis

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 generation´s 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

Page 8: Control Motor Tesis

ABSTRACT

parameters by different simulations. This method didn´t 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 system´s 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 system´s 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.

Page 9: Control Motor Tesis

I.- MEMORIA

Page 10: Control Motor Tesis

MEMORIA Índice

1

ÍNDICE

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

ÍNDICE DE TABLAS .................................. ................................................. 9

CAPÍTULO 1: INTRODUCCIÓN .......................... ..................................... 10

1.1. Motivación ................................................................................................ 10

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

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

CAPÍTULO 2: ESTADO DEL ARTE ....................... .................................. 17

2.1. Introducción ............................................................................................. 17

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

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

CAPÍTULO 3: DESCRIPCIÓN Y MODELADO DEL SISTEMA .... ........... 27

3.1. Introducción ............................................................................................. 27

3.2. Descripción del sistema ............................................................................ 29

3.3. Estimación de parámetros físicos ............................................................ 33

3.2.1. Cálculo de la resistencia interna del motor ............................... 33

3.2.2. Cálculo de la inductancia del motor .......................................... 34

3.2.3. Cálculo de la constante asociada a la fuerza contraelectromotriz del motor (Ke) .............................. 37

3.2.4. Cálculo de la constante del par motor (Km) .............................. 38

3.2.5. Cálculo de la fricción viscosa ................................................... 39

3.2.6. Cálculo de la masa .................................................................... 40

3.2.7. Estimación de la velocidad máxima .......................................... 41

3.4. Obtención del modelo ............................................................................... 42

3.3.1. Modelo de la planta ................................................................... 42

3.3.2. Modelo del actuador (motor DC) .............................................. 43

3.5. Conclusiones ............................................................................................ 46

Page 11: Control Motor Tesis

MEMORIA Índice

2

CAPÍTULO 4: DISEÑO DEL HARDWARE ................... ........................... 47

4.1. Introducción ............................................................................................. 47

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

4.3. Reguladores de tensión ............................................................................ 61

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

4.5. Circuito de acondicionamiento de la señal del acelerómetro ................. 67

4.6. Diseño de las balizas ................................................................................ 72

4.7. Conclusiones ............................................................................................ 77

CAPÍTULO 5: SISTEMA DE CONTROL .................... .............................. 79

5.1. Introducción ............................................................................................. 79

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

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

5.4. Diseño del control .................................................................................... 86

5.4.1. Diseño mediante ajuste por simulación ..................................... 88

5.4.2. Diseño basado en técnicas de respuesta en frecuencia en lazo abierto con modelado de los efectos de retrasos de

actualización 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

CAPÍTULO 6: IMPLANTACIÓN EN EL MICROPROCESADOR .... ....... 129

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

6.2. Implantación: programación 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

Page 12: Control Motor Tesis

MEMORIA Índice

3

6.2.6. Programación del regulador PI discreto .................................. 142

6.3. Conclusiones .......................................................................................... 145

CAPÍTULO 7: RESULTADOS EXPERIMENTALES ............. ................. 146

7.1. Introducción ........................................................................................... 146

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

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

CAPÍTULO 8: CONCLUSIONES Y TRABAJO FUTURO ......... ............. 150

AGRADECIMIENTOS ................................... .......................................... 154

BIBLIOGRAFÍA ...................................... ................................................ 155

ANEXOS ................................................................................................. 157

Page 13: Control Motor Tesis

MEMORIA Índice

4

ÍNCIDE DE FIGURAS

Figura 1.1: Diagrama de bloques del sistema a diseñar .................................... 13

Figura 3.1: diagrama funcional de bloques de un sistema de control continuo tipo...... .................................................................................................................. 29

Figura 3.2: Primera aproximación del diagrama funcional de bloques del sistema completo ................................................................................................... 32

Figura 3.3: corriente que atraviesa el motor ...................................................... 35

Figura 3.4: Esquema eléctrico de un motor DC ................................................. 36

figura 3.5: fuerza contraelectromotriz en función de la velocidad del tren desarrollada en el experimento. ........................................................................... 38

figura 3.6: fuerza del par motor en función de la velocidad del tren desarrollada en el experimento. ........................................................................... 40

Figura 3.7: velocidad en función de tensión de alimentación. .......................... 41

Figura 3.8: representación mecánica 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: representación esquemática del funcionamiento de un puente en H …………………………………………………………………………..49

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

Figura 4.3: configuración 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: disposición 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: caída de tensión en el diodo en conducción directa, en función 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

Page 14: Control Motor Tesis

MEMORIA Índice

5

Figura 4.10: circuito de regulación de tensión de 14V a 3V .............................. 62

Figura 4.11: circuito de regulación de tensión de 14V a 5V .............................. 63

Figura 4.12: circuito de acondicionamiento de medida de la intensidad que atraviesa el motor ................................................................................................. 64

Figura 4.13A: situación del acelerómetro sobre la maqueta del tren ................ 67

Figura 4.13B: configuración de los pines del ADXL320 ................................... 68

Figura 4.14: circuito de acondicionamiento de la señal del acelerómetro ........ 70

Figura 4.15: característica del rectificador de precisión .................................... 72

Figura 4.16: Circuito de una baliza .................................................................... 73

Figura 4.17: sumador, inversor y protección del microprocesador ................... 77

Figura 5.1: discretización de una señal continua y efecto aliasing ................... 80

Figura 5.2: esquema genérico 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 aproximación 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: relación entre Ti y K para un amortiguamiento de 0.7 ................... 90

Figura 5.7: respuesta ante un escalón de la salida del lazo de corriente linealizado con distintos valores de K y Ti ........................................................... 91

Figura 5.8: respuesta ante un escalón 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: simulación del sistema con distintos valores de K ........................ 97

Figura 5.13: simulación del sistema con distintos valores de Ti ........................ 97

Page 15: Control Motor Tesis

MEMORIA Índice

6

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

Figura 5.15: respuesta del mando de tensión ..................................................... 98

Figura 5.16: respuesta del sistema en simulación con retardos de actualización de salidas y PWM modelados ............................................................................. 100

Figura 5.17: diagrama de bloques del sistema, incluyendo retardos de actualización 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, después de aplicar el primer diseño del control ............................................................................... 105

Figura 5.22: diagrama de Black del lazo de corriente abierto, después de aplicar el segundo diseño 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, después de aplicar diseño del control ............................................................................................... 107

Figura 5.25: respuesta de la simulación del sistema ....................................... 108

Figura 5.26: ampliación de la respuesta de la simulación 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

Page 16: Control Motor Tesis

MEMORIA Índice

7

Figura 5.31: respuesta del sistema en simulación ............................................ 114

Figura 5.32: diagrama de ceros y polos del filtro FIR diseñado ..................... 117

Figura 5.33: diagrama de Bode del filtro FIR diseñado .................................. 117

Figura 5.34: diagrama de bloques del filtro FIR diseñado .............................. 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, después 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 escalón ......................... 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 escalón de amplitud 0.1 m/s. ........................ 127

Figura 6.1: diagrama de bloques del microprocesador .................................... 130

Figura 6.2: características mecánicas del microprocesador MCF5282 .......... 131

Figura 6.3: asignación de pines (pinout) del microprocesador ....................... 131

Figura 6.4: diagrama de flujo de la función 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 interrupción IntGPTA0 ........................... 140

Figura 6.8: diagrama de flujo de la interrupción 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

Page 17: Control Motor Tesis

MEMORIA Índice

8

Figura 7.2 : generador de señales 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

Page 18: Control Motor Tesis

MEMORIA Índice

9

ÍNDICE DE TABLAS

Tabla 4.1: características eléctricas del circuito ILQ74 ..................................... 54

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

Tabla 4.3: características eléctricas más relevantes del L298N ......................... 60

Tabla 4.4: Características del acelerómetro ADXL320 ...................................... 68

Tabla 6.1: características eléctricas máximas del MCF5282 ........................... 132

Tabla 6.2: características eléctricas DC del MCF5282 .................................... 132

Tabla 6.3: características eléctricas DC del MCF5282 (continuación) ........... 133

Tabla 6.4: funciones asociadas a cada módulo ................................................ 136

Page 19: Control Motor Tesis

MEMORIA Introducción

10

Capítulo 1: Introducción

1.1. Motivación Los sistemas automáticos de control han desempeñado, y desempeñan, 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

diseño del reloj de agua, también conocido como Clepsydra, por parte de

Ktesibios. El primer uso del control automático en la industria parece haber sido

el regulador centrífugo de la máquina de vapor de Watt, en el año 1775, pero no

fue hasta 1868 cuando se comienza a estudiar la teoría del control por

realimentación, gracias a la explicación matemática del regulador centrífugo por

James Clerk Maxwell.

Hoy en día, el control de sistemas es una de las áreas de estudio más

interesantes y completas para el alumno de Ingeniería Electrónica, 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 (mecánica, teoría de fluidos, transmisión de calor… etc., dependiendo

del tipo de sistema), diseñar el actuador que actuará sobre la planta del sistema

(electrónica de potencia, funcionamiento de máquinas eléctricas…), o diseñar el

circuito de acondicionamiento de medida de señales (electrónica analógica,

instrumentación electrónica…).

Además, son muy amplias las aplicaciones que tiene el control de sistemas,

por lo cual el presente proyecto adquiere gran valor didáctico de cara a la

incorporación 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 señales discretas, la programación en

general, y la orientada a microprocesadores en particular.

Page 20: Control Motor Tesis

MEMORIA Introducción

11

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

fuese una pequeña maqueta de tren eléctrico. De esta forma se podrían observar

físicamente los efectos del control, en vez de tener que intuirlos a partir de

simulaciones por ordenador. Además, el sector del transporte ferroviario es un

campo de trabajo bastante atractivo, y que presumiblemente ganará aceptación

en el futuro frente a otros medios de transporte (avión, coche) de seguir como

hasta ahora las tendencias inflacionistas del precio del petróleo.

Además, se puede consultar en la bibliografía una relación de noticias de

accidentes ferroviarios por llevar una elevada velocidad al recorrer una curva.

Este tipo de accidentes se podrían haber evitado con un sistema automático de

control como el que propone el presente proyecto, aplicado a los sistemas

ferroviarios reales, en vez de a una maqueta.

Page 21: Control Motor Tesis

MEMORIA Introducción

12

1.2. Objetivos y fases del proyecto

El objetivo del presente proyecto es el diseño de un sistema de control de

velocidad de una maqueta de tren a escala, accionado por un motor de corriente

continua, basado en acelerómetros, que será implantado en un microprocesador.

Dicho control actuará sobre el motor de la maqueta, haciendo que el tren

desarrolle la máxima velocidad posible en cada tramo, dependiendo de la

aceleración normal que experimente en cada instante. Cuando el tren entre en

una curva, una baliza enviará una señal al microprocesador para que el tren

adopte una velocidad moderada, entonces, el tren comenzará a aumentar su

velocidad hasta alcanzar un máximo que vendrá dado por la aceleración normal,

la cual será proporcional a la velocidad y al radio de la curva, que experimente el

tren en dicha curva.

Se deberá diseñar tanto el circuito de potencia que permita actuar sobre el

motor del tren, como el circuito de acondicionamiento de señal que permita

medir las variables necesarias para efectuar el control. Además, se deberán

diseñar distintos controles, y realizar pruebas mediante simulación de los

mismos, para finalmente elegir el que mejor se adecúe 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

adaptación del control al tiempo discreto, y posteriormente programar el

microprocesador para que efectúe dicho control.

La figura 1.1 ilustra un esquema completo del sistema que se ha de diseñar.

Page 22: Control Motor Tesis

MEMORIA Introducción

13

Figura 1.1: Diagrama de bloques del sistema a diseñar

Page 23: Control Motor Tesis

MEMORIA Introducción

14

A continuación se hace referencia a los diferentes pasos a seguir para la

realización del proyecto:

1. Diseño del circuito de potencia

2. Estimación de los parámetros físicos del sistema

3. Diseño y simulación del control

4. Diseño de los circuitos de acondicionamiento de señal para la medida

5. Adaptación del control al microprocesador. Escalado.

6. Implantación del control en el microprocesador. Programación.

7. Elaboración del circuito completo (potencia, acondicionamiento, balizas)

8. Elaboración de la memoria.

Diagrama de Gantt de la planificación del proyecto

1

2

3

4

5

6

7

8

MAR ABR JUNMAYENE FEBDICSEPT OCT NOV

Page 24: Control Motor Tesis

MEMORIA Introducción

15

1.3. Estructura de la memoria

A continuación se comentan los capítulos de los que está compuesta la

memoria y el contenido de los mismos:

• Capítulo 2: Estado del arte. Abarca:

o Breve historia de la evolución de los mecanismos de control

ferroviario, hasta llegar a los sistemas de control actuales.

o Breve historia de la evolución de los mecanismos de control

de motores de corriente continua.

• Capítulo 3: Descripción y modelado del sistema. Abarca:

o Introducción a los sistemas de control continuo.

o Estimación de los parámetros físicos necesarios a la hora de

diseñar el control.

o Obtención de los modelos de la planta y del actuador del

sistema, así como una descripción del sistema completo.

• Capítulo 4: Diseño y construcción del hardware. Abarca:

o Diseño de la etapa de potencia del sistema.

o Elección de los reguladores de tensión.

o Diseño del circuito de acondicionamiento de medida de la

corriente que atraviesa el motor.

o Diseño del circuito de acondicionamiento de medida de la

aceleración.

o Diseño de las balizas.

• Capítulo 5: Sistema de control. Abarca:

o Introducción a los sistemas de control discreto.

o Diseños del control del sistema sin filtros.

o Diseños del control del sistema con filtros de primer orden y

filtros FIR.

Page 25: Control Motor Tesis

MEMORIA Introducción

16

o Escalado del problema a 16 bits.

• Capítulo 6: Implantación en el microprocesador. Abarca:

o Breve introducción al microprocesador ColdFire MCF5282 y

sus características más importantes para este proyecto.

o Programación del microprocesador, explicando las tareas y

funciones más relevantes.

• Capítulo 7: Resultados experimentales. Abarca:

o Pruebas del circuito de potencia

o Pruebas del prototipo

• Capítulo 8: Conclusiones y trabajo futuro. Abarca:

o Recopilación de las conclusiones que se han obtenido a lo

largo de todos los capítulos mencionados.

o Breve descripción del trabajo futuro que se podría desarrollar.

Page 26: Control Motor Tesis

MEMORIA Estado del arte

17

Capítulo 2: Estado del arte

2.1. Introducción En el presente capítulo se tratarán distintos aspectos del desarrollo

tecnológico aplicado hoy en día tanto a sistemas de control de trenes como a

control de velocidad de motores. También se expondrá brevemente la evolución

tecnológica a largo de la historia de dichas disciplinas.

2.2. Sistemas de control de trenes

Por razones históricas, la terminología ferroviaria mezcla a menudo dos

conceptos diferentes bajo el término "control de tren": la intervención

automática sobre el movimiento del tren (en los sistemas más simples

generalmente sólo bajo la forma de frenado de emergencia) y la señalización en

cabina (que no obligatoriamente controla la marcha del tren).

Los primeros elementos no visuales para apoyar la señalización lateral son

muy antiguos. Ya en 1842, E. A. Cowper patentó la primera señal acústica, el

"detonador", que era prácticamente un petardo unido al carril, que estallaba

cuando pasaba un tren por encima. Puesto que los petardos tenían que ser

colocados manualmente, el uso era limitado a las situaciones de emergencia.

El paso siguiente fue, en Gran Bretaña y los E.E.U.U. y a partir de 1850, la

automatización de señales acústicas, mediante contactos mecánicos entre las

señales y las locomotoras. Los primeros aparatos eran una señal acústica

(típicamente un gong) instalada lateralmente a la vía, p. e., en el soporte de la

señal. Si la señal indicaba parada una barra tocaba las ruedas y sonaba el gong.

Más adelante el gong fue instalado en la locomotora constituyendo, así, la forma

más temprana señalización en cabina.

Alrededor de 1872, se creó en Francia el "Crocodile", el sistema de control de

tren (al principio sólo repetición de señales laterales) con un ciclo de vida más

Page 27: Control Motor Tesis

MEMORIA Estado del arte

18

largo, pues todavía está en operación en las redes francesa y belga. El término

"Crocodile" deriva de la forma del dispositivo de la rampa colocada entre los

carriles, que se utiliza para establecer un contacto galvánico (electromecánico) y

transmitir información a la locomotora.

A partir de ese momento, la introducción del primer verdadero sistema de

control del tren estaba sólo a un paso. Alrededor de 1870, Axel Vogt, el jefe de

mecánicos del ferrocarril de Pennsylvania colocó un tubo de vidrio en la cabina,

conectado con el tubo del freno neumático. Si un tren sobrepasaba una señal de

parada, una palanca de la señal golpeaba y rompía el tubo de vidrio y se

aplicaban los frenos.

El primer sistema de control del tren utilizado a gran escala fue el ATC

(control automático del tren) de la compañía británica GWR, que fue introducido

en 1906. El ATC se basó en el sistema francés "Crocodile" pero, además de la

señal acústica, el ATC también tuvo desde el principio métodos de visualización

mecánica en la cabina y de accionamiento automático del freno de emergencia.

Aunque el ATC y los sistemas similares han experimentado varias

modificaciones, el principio de base es el mismo, y todavía 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 holandés. En vez de contactos

electromecánicos (y sus partes móviles posibles fuentes de averías), el CCS se

basa en un contacto inductivo entre circuitos cifrados en la vía y un receptor en

la locomotora. Desde el principio fueron utilizadas luces de colores para

anunciar en la cabina el aspecto de la próxima señal. El sistema original tenía

dispositivo de intervención automática del freno, pero fue desactivado más

adelante por algunas compañías. El CCS anunciaba las señales en la cabina tan

correctamente que algunas compañías ferroviarias americanas quitaron las

señales laterales para reducir gastos de explotación. Después de la primera

guerra mundial, CCS fue transferido a la Unión Soviética. En lo que se refiere a

longitud de líneas equipadas, CCS es el sistema mayoritario en el mundo.

Page 28: Control Motor Tesis

MEMORIA Estado del arte

19

Mientras, en Alemania, Siemens comenzaba el desarrollo de Indusi, el primer

sistema de control aplicado a gran escala que incorporó la supervisión de la

curva de frenado. De una forma semejante al CCS americano, también utiliza

inducción para transmitir la información, pero la transmisión tiene lugar

solamente en puntos discretos, mediante circuitos magnéticos en la locomotora y

en las señales. 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 más popular en buena parte de Europa (Alemania, Austria,

Polonia, la antigua Yugoeslavia, Rumania, Turquía).

La transmisión de información mediante transponders es más reciente y en

ella se basan los sistemas españoles ASFA y el sueco EBICAB (en España se

utiliza la versión EBICAB 900). Mas reciente aún es la transmisión 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 francés, el CCS

americano y el Indusi alemán, los tres sistemas de control han evolucionado

históricamente de maneras muy diferentes en las distintas compañías

ferroviarias. Los sistemas modernos incluyen el cálculo dinámico en tiempo real

del perfil de la velocidad. En 1990, había por lo menos 30 diversos sistemas de

control del tren en operación en la red europea de vía ancha. A pesar de los

antepasados comunes, casi todos los sistemas existentes son completamente

incompatibles. La creación de las eurobalizas y sobre todo de ERTMS, debe

terminar con esta "torre de Babel de estándares".

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

• Sistemas "auxiliares" (señalización lateral prominente, la

señalización en cabina repite la lateral, control de tren sólo en algunas

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

• Sistemas completos de señalización en cabina (señalización

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

Page 29: Control Motor Tesis

MEMORIA Estado del arte

20

en líneas de cercanías y metro con mucha densidad de tráfico. Los

sistemas mensajes que son evaluados en el computador central del

vehículo. El sistema supervisa continuamente la velocidad del tren, y

gobierna su marcha por medio de sistemas que controlan la tracción y el

frenado del vehículo (como por ejemplo el sistema ATF, Automatismo

de Tracción y Frenado, de las locomotoras de la serie 252 de Renfe. El

equipo del vehículo emite la posición del tren, velocidad, características

de frenado y otras informaciones al sistema central para su posterior

tratamiento y realimentación del sistema.

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

velocidad de trenes y señalización, entre los cuales, caben destacar los

siguientes:

• ATP (Protección Automática de Tren, del inglés “Automatic Train

Protection”) se puede encontrar implantado de distintas maneras:

- Doble señalización y ATP de una portadora

En los sistemas de doble señalización el tren siempre está protegido

por dos señales de control. Existe un cantón –tramo por el que un tren

está autorizado a circular– único entre señal y señal, que por lo general

se compone de uno o más circuitos de vía, conformando un cantón.

Cada circuito de vía tiene asignada una velocidad máxima de

seguridad (límite civil) a través del sistema de ATP, que es invariable

en función de los pasos por diagonales, radios de curva, las pendientes,

etc. (perfil de la vía). En caso de superar la velocidad asignada o rebasar

una señal de control el tren aplica freno de emergencia hasta su total

detención.

El sistema de ATP se comunica de forma continua con el tren por

medio de una señal que recorre los carriles y aporta un código con la

velocidad máxima en el circuito de vía. Este sistema consigue

Page 30: Control Motor Tesis

MEMORIA Estado del arte

21

intervalos teóricos de entre 2 min 20 seg y 2 min 50 seg dependiendo de

las configuraciones de la vía.

- Señalización Simple y ATP de dos portadoras

En este sistema las parejas de códigos (portadoras) indican la

“Velocidad Máxima de Seguridad” y la “Velocidad Objetivo”. Para un

tren que circula por una Línea con sistema de códigos de dos portadoras

el sistema “avisa” con antelación cual va a ser la velocidad máxima

permitida en el siguiente circuito de vía, de tal manera que si el tren

llegara a ese circuito de vía a una velocidad superior, se aplicaría freno

de emergencia hasta la completa detención del tren.

En los sistemas de ATP de dos portadoras existe una señal a la salida

de la estación 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 vía libre para los trenes conducidos con ATP – que indica

que la vía no está libre hasta la siguiente estación, por lo que el tren

debe posteriormente guiarse por los códigos de ATP existentes en la

vía.

Los tramos de vía con códigos de dos portadoras tienen una

velocidad máxima de seguridad (límite civil) que puede variar hacia una

velocidad menor en función de la proximidad del tren anterior o el

aspecto de las señales (por la posición de agujas, vueltas automáticas,

etc.)

Así mismo se imposibilita la aplicación de tracción cuando la

velocidad del tren es superior a la objetivo.

El ATP de dos portadoras consigue intervalos teóricos de entre 1 min

55 seg y 2 min 15 seg dependiendo de las configuraciones de la vía.

Page 31: Control Motor Tesis

MEMORIA Estado del arte

22

• ATO (Conducción Automática de Tren, del inglés “Automatic Train

Operation)

El sistema de conducción automática se compone de un conjunto de

equipos, que situados en vía y tren sustituyen la función del conductor,

excepto la apertura y cierre de puertas y la orden de arranque.

Este modo de conducción está bajo la supervisión del ATP que

indica al sistema las velocidades máximas para cada tramo, y

proporciona un menor tiempo de recorrido y un mejor confort de

marcha respecto a la conducción en “Manual” con ATP.

El tren puede recibir diferentes tipos de órdenes y en especial la de

velocidad de marcha por regulación de tráfico que se realiza desde el

Puesto Central a través del SIRAT.

También permite la maniobra de vuelta en terminales (autoshunt),

sin conductor en una de las cabinas (la de entrada al saco), siempre que

existan códigos de ATP.

Para la correcta parada de los trenes en las estaciones existen en la

vía una serie de balizas denominadas X1, X2 y X3. Por medio de ellas

es posible transmitir datos de geometría de vía al tren y desde el Puesto

Central órdenes como por ejemplo; el paso sin parada en la estación,

situación del punto de parada, velocidad en la interestación, perfil de

vía, autoshunt, etc.

• SIRAT (Sistema Integrado de Regulación Automática de Trenes)

Este sistema permite la regulación de trenes a intervalo y a horario

en horas de menor afluencia de viajeros. También realiza de una forma

gradual la incorporación o encierre de trenes de la línea y las

transiciones de circulación por intervalo a circulación con horario.

Page 32: Control Motor Tesis

MEMORIA Estado del arte

23

El Sistema Integrado de Regulación Automática de Trenes está

plenamente integrado en las líneas con circulación en ATO, este

sistema permite, por medio de una simulación 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 líneas no dotadas de ATO realiza la

regulación mediante el uso de las señales.

Como resultado de estos ajustes en la regulación se mejora la

capacidad de transporte de las líneas y se consiguen unos elevados

ahorros de energía derivados de la aplicación de marchas con menor

consumo de los trenes y evitando paradas por regulación en las

estaciones.

Otra de las prestaciones del sistema son los informes en tiempo real

en forma de gráficos de los índices de calidad de la regularidad.

• Distancia Objetivo

En este sistema el tren recibe de la instalación de vía no sólo la

velocidad máxima a la que el tren puede circular en el cantón por el que

circula, sino también que cantón precedente se encuentra ocupado por

otro tren. De esta forma, cada tren tiene información de la distancia que

le queda por recorrer hasta el cantón realmente ocupado por delante.

Con ello se posibilita un mayor acercamiento de cada tren a su

precedente, reduciéndose el intervalo entre trenes en la línea y

aumentando la capacidad de transporte de la misma.

• Cantón móvil

En este sistema el tren va informando vía radio permanentemente a

un sistema de control ubicado en la instalación fija de su situación. A su

vez, cada tren recibe información vía radio acerca de la situación del

Page 33: Control Motor Tesis

MEMORIA Estado del arte

24

tren anterior, de esta forma un tren puede aproximarse al máximo al

tren precedente según lo que su parábola o distancia de frenado le exija

(en función de su velocidad, el perfil de vía, 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 cantón ocupado, ya que

éste en función 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 máquina es una

de las más versátiles en la industria. Su fácil control de posición, par y velocidad

la han convertido en una de las mejores opciones en aplicaciones de control y

automatización de procesos. La principal característica del motor de corriente

continua es la posibilidad de regular la velocidad desde vacío a plena carga.

Una máquina de corriente continua (generador o motor) se compone

principalmente de dos partes, un estator que da soporte mecánico al aparato y

tiene un hueco en el centro generalmente de forma cilíndrica. En el estator

además se encuentran los polos, que pueden ser de imanes permanentes o

devanados con hilo de cobre sobre núcleo de hierro. El rotor es generalmente de

forma cilíndrica, también devanado y con núcleo, al que llega la corriente

mediante dos escobillas. También se construyen motores de CC con el rotor de

imanes permanentes para aplicaciones especiales.

En 1896 aparece el control Ward Leonard para variación de velocidad. De las

tres formas de variar la velocidad de un motor, la más eficaz es la del control de

voltaje de armadura, puesto que permite una amplia variación de la velocidad sin

afectar el par máximo del motor. La forma normal de variar el voltaje de

armadura de un motor de cc, era suministrándolo desde un generador de cc.

Page 34: Control Motor Tesis

MEMORIA Estado del arte

25

Un motor primo trifásico 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 versátil. 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 pequeño 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. Además permite también el cambio del sentido

de rotación, solamente cambiando la polaridad del voltaje de armadura, así es

posible obtener un rango muy amplio de variación de la velocidad en cualquier

sentido de rotación. Otra función es la de “regenerar” o retornar a las líneas de

alimentación la energía de movimiento de las máquinas. 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

energía requerida en el primer momento para alzar la carga puede recuperarse

reduciendo el costo total de operación de la máquina. La desventaja del sistemna

Ward-Leonard, es la de tener que comprar tres máquinas completas de valores

nominales esencialmente iguales, lo cual es muy costoso. Otra es que tres

máquinas son mucho menos eficientes que una, por ello han sido reemplazado

por circuitos controladores basados en SCRs , que resultan definitivamente más

barato que dos máquinas extra.

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

en el principio de Leblanc, este método difiere en que el transformador variable

va conectado a los anillos colectores del motor bobinado en vez de a la línea.

Como en el caso del sistema de Leblanc, la frecuencia del rotor bobinado es

también la frecuencia del voltaje en el conmutador. Decalando la posición 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 síncrona. Además el convertidor de frecuencia también actúa

Page 35: Control Motor Tesis

MEMORIA Estado del arte

26

como motor al convertir la potencia que se le suministra a través del

autotransformador en potencia mecánica 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

energía al sistema, además de las bajas pérdidas en línea del convertidor y el

autotransformador (el aparato eléctrico de mayor rendimiento desarrollado hasta

el momento), combinado con la ventaja de corrección 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 evolución del control de motores a partir de entonces va de la mano del

desarrollo de distintos dispositivos eléctricos y electrónicos. Durante los años 20

aparecen los primeros dispositivos electrónicos de arco (ignitron, tiratron,

válvula de mercurio). Durante los años 50 aparecen los semiconductores de

estado sólido (diodo y transistor). En la década del 60 aparece el tiristor, que es

considerado el dispositivo más importante para la Electrónica de potencia. En la

década de los 70 comienza a evolucionar la microelectrónica

En la década del 80 se desarrolla el microprocesador. Este hecho, junto con el

avance de la electrónica, ha hecho que los motores de corriente continua hayan

caído en desuso pues los motores de corriente alterna del tipo asíncrono, pueden

ser controlados de igual forma a precios más accesibles para el consumidor

medio de la industria. A pesar de esto el uso de motores de corriente continua

continúa y se usan en muchas aplicaciones de potencia (trenes y tranvías) o de

precisión (máquinas, micromotores, etc.)

En este proyecto se han utilizado técnicas de control por modulación de

ancho de pulso (PWM), las cuales se verán con mayor profundidad en el

capítulo cuarto.

Page 36: Control Motor Tesis

MEMORIA Modelado del sistema

27

Capítulo 3: Descripción y modelado del sistema

3.1. Introducción Se define sistema como un elemento o conjunto de elementos que da una

respuesta o salida ante una determinada excitación o entrada. Existen diversos

tipos de sistemas, clasificados atendiendo a distintas características o

propiedades de los mismos, pudiéndose clasificar el sistema que se va a tratar a

continuación como un sistema cuantitativo (se puede tratar siguiendo modelos

matemáticos), dinámico (su respuesta en un instante depende de valores

anteriores de la entrada, y no sólo del valor de la entrada para ese instante),

lineal (se cumple el principio de superposición 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 comúnmente “LTI”, del inglés linear time-invariant.

Un modelo es un conjunto de ecuaciones matemáticas que se emplean para

describir la relación 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 simulación (obtención de forma numérica o gráfica de la

respuesta de un sistema ante una excitación conocida), el control (regulación de

la salida de un sistema para que sea igual o parecida a una determinada entrada o

consgina) o la predicción (obtención 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.

Page 37: Control Motor Tesis

MEMORIA Modelado del sistema

28

De ahora en adelante, se utilizará el término señal para referirse a una

variable o magnitud que puede variar en el tiempo. La señal de entrada de un

sistema, o excitación, es la variable que normalmente controla o impone el

usuario. La respuesta de este sistema, o salida, es la variable de interés. Nótese

que las variables de salida son, en ocasiones, elegidas por el usuario. Además,

pueden existir otras variables o señales internas en el sistema, normalmente de

menor interés. La mayor parte de las señales estarán modeladas por funciones

sencillas. En otros casos la señal será una composición de estas funciones. El uso

de estas funciones sencillas está justificado por varios motivos:

· Se dan comúnmente en la práctica.

· Se usan, en algunos casos, como señales normalizadas.

· Son más fáciles de tratar analíticamente.

Se utilizará habitualmente la notación u(t) para la señal de entrada e y(t) para

la salida.

Cabe señalar que un sistema dinámico, lineal e invariante en el tiempo, está

representado por una ecuación diferencial lineal de coeficientes constantes, del

tipo:

( ) ( ) ( ) ( )

( ) ( ) ( ) ( )tybdt

tdyb

dt

tydb

dt

tydb

tyadt

tdya

dt

tyda

dt

tyda

m

m

mm

m

m

n

n

nn

n

n

011

1

1

011

1

1

...

...

++++=

=++++

[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:

( ) ( ) ττ τ dextxLsX s−∞

∫−

== ·)(0

[3.2]

Para más información acerca de la trasformación de Laplace y sus

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

Page 38: Control Motor Tesis

MEMORIA Modelado del sistema

29

más adelante, se puede consultar cualquier texto sobre ecuaciones diferenciales,

como por ejemplo las referencias bibliográficas número 6, 7 y 8.

3.2. Descripción del sistema

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

modelización:

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. Después de aplicar su acción proporcional-

integral, que se verá con más detalle en el capítulo de “Software y sistema de

control” , obtiene como salida un valor de corriente (el cual oscilará entre dos

valores, mínimo y máximo, que serán los valores de saturación, por encima de

los cuales, en valor absoluto, el motor podría sufrir daños), 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 acción proporcional-integral, y generar

una señal (mando), que, debidamente acondicionada, tras pasar por la etapa de

CONTROL CONVERTIDOR DE POTENCIA

SISTEMA A CONTROLAR

SENSOR

Ref. Salida

Perturbación

-

-

Page 39: Control Motor Tesis

MEMORIA Modelado del sistema

30

potencia, representa la tensión de alimentación 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 señal 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 tensión que se le procura al motor entre

los valores mencionados anteriormente. El proceso de acondicionamiento de la

señal efectuado en el circuito de potencia se encuentra detallado en el apartado

primero del capítulo cuarto, denominado “Etapa de potencia”.

El sistema a controlar se compone de dos partes:

• Actuador: modelo eléctrico del motor de corriente continua. Se

estimarán sus parámetros (inductancia y resistencia internas) como se

describe en el apartado de estimación de parámetros físicos, y se

modelizará de acuerdo a un modelo matemático, descrito con más

detalle en el apartado 3.4.

• Planta: modelo mecánico del motor y la maqueta del tren. Sus

parámetros (masa y fricción viscosa producto del rozamiento del tren

con las vías y de las holguras de los engranajes del motor) serán

estimados tal y como se describe en el apartado 3.3. Se tratará la

planta como un modelo matemático cuya obtención 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 diseñará 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 diseño como

implantación están detallados en el apartado 4.4, denominado “Diseño del

circuito de acondicionamiento”.

Page 40: Control Motor Tesis

MEMORIA Modelado del sistema

31

El diagrama de bloques del sistema completo, simplificando distintos

aspectos del mismo como la etapa de potencia o la discretización de las señales

de control es el que muestra la figura 3.2:

Page 41: Control Motor Tesis

MEMORIA Modelado del sistema

32

Figura 3.2: Primera aproximación del diagrama funcional de bloques del sistema completo

Page 42: Control Motor Tesis

MEMORIA Modelado del sistema

33

3.3. Estimación de parámetros físicos

3.2.1. Cálculo de la resistencia interna del motor

Para calcular la resistencia interna del motor, se mide con un polímetro la

resistencia que existe entre las dos bornas del motor. Como el control se va a

aplicar a una maqueta de tren eléctrico, cuyo motor es alimentado a través de las

vías metálicas sobre las que circula dicha maqueta, habrá que comprobar que la

resistencia de las vías es despreciable con respecto a la resistencia interna del

motor.

Se demuestra que la resistencia eléctrica de un conductor es directamente

proporcional a su longitud, e inversamente proporcional a su sección y a su

conductividad:

S

lR

·σ∆=∆ [3.3]

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

dlS

Rb

a

ba ·1

·1

),( ∫=σ [3.4]

Cuando el conductor tiene sección constante, como es este caso, la expresión

anterior puede simplificarse, obteniéndose así:

S

L

S

LR abab

ab ··1 ρσ

== [3.5]

Una vez demostrado, queda comprobar lo enunciado con anterioridad, esto es,

que la resistencia eléctrica que ofrecen las vías es despreciable respecto a la

resistencia interna del motor. Para ello se realizó un ensayo experimental, viendo

cómo cambiaba la resistencia del conjunto motor-vías conforme se desplazaba el

tren por las mismas de forma manual (esto es, sin aplicarle ninguna tensión al

motor). De este ensayo se sacó la conclusión de que la resistencia de las vías es

Page 43: Control Motor Tesis

MEMORIA Modelado del sistema

34

despreciable, ya que, a lo largo de todo el circuito, la resistencia del conjunto

variaba como máximo 1 Ω sobre 35 Ω.

3.2.2. Cálculo 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 tensión 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 precisión posible, se almacenan los

datos del osciloscopio en un fichero “.txt”, llamado “corriente.txt” , y desde

Matlab se efectúan las operaciones pertinentes mediante un fichero “.m”, llamado

“leer_datos.m” (ver anexo 2 para más información) con el fin de representar

dicha corriente, dando como resultado:

Page 44: Control Motor Tesis

MEMORIA Modelado del sistema

35

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 expresión analítica será del tipo:

τt

eIIItI−+ ∞−+∞= ·))()0(()()( [3.6]

Siendo τ la constante de tiempo de la exponencial.

Despejando τ de la ecuación anterior, queda:

∞−∞−

−=

+ )()0(()()(

II

ItILn

tτ [3.7]

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

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

Page 45: Control Motor Tesis

MEMORIA Modelado del sistema

36

“leer_datos.m”, se obtiene un valor para la constante de tiempo de la exponencial

de: s-510 · 5.6662=τ

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

la corriente, sólo hará falta hallar la relación entre la inductancia del motor y dicha

constante de tiempo para calcular la primera. A partir del esquema eléctrico del

motor de corriente continua, representado en la figura 3.4, se obtiene:

L

Rt

mm eL

eUti

sLR

eUsI

−=⇒+−= ·)(

·)( [3.8]

Figura 3.4: Esquema eléctrico de un motor DC Como se vio anteriormente, la corriente es una exponencial cuya expresión

analítica se define como: τt

eIIItI−+ ∞−+∞= ·))()0(()()( . Comparando estas dos

expresiones obtenidas, se deduce que:

R

L=τ [3.9]

Por lo tanto, mHL 2=

Page 46: Control Motor Tesis

MEMORIA Modelado del sistema

37

3.2.3. Cálculo de la constante asociada a la fuerza contraelectromotriz del motor (K e)

A partir del circuito eléctrico del actuador (motor DC), se concluye que:

mm

m KsLR

euKiFm ·

··

+−

== [3.10]

De lo que se deduce que, en régimen permanente:

mm

m KR

euKiFm ··)0()0(

−== [3.11]

La corriente, en régimen permanente se puede calcular como:

iRueR

eui m

m ·−=⇒−= [3.12]

Además, la fuerza contraelectromotriz del motor se puede expresar como:

vKe em ·= [3.13]

Para el cálculo de la fricción viscosa por rozamiento del tren con las vías, así

como para el cálculo 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,

también 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 régimen permanente.

Una vez obtenidos los distintos valores descritos anteriormente, se representa

gráficamente la fuerza contraelectromotriz en función de la velocidad, y se realiza

una regresión lineal simple, obteniéndose:

Page 47: Control Motor Tesis

MEMORIA Modelado del sistema

38

figura 3.5: fuerza contraelectromotriz en función 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 fácilmente que dicha constante asociada a la fuerza electromotriz será la

pendiente de la recta representada anteriormente.

Por tanto: V·s/m5.8347=eK

3.2.4. Cálculo de la constante del par motor (K m)

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: N·m/A75.834=mK

Page 48: Control Motor Tesis

MEMORIA Modelado del sistema

39

3.2.5. Cálculo de la fricción viscosa

Debido al rozamiento que se produce entre las ruedas del tren y las vías, y a

posibles holguras en los engranajes del motor, se produce un efecto de fricción

que se puede modelar como una fricción viscosa.

Como ya se explicará más adelante, la función de transferencia de la planta del

sistema es:

)·(1

1

)·(1

FfFms

D

MDFfFm

DMsv −

+=−

+= [3.14]

De lo que se deduce que, en régimen permanente (es decir, cuando ω=0):

FmFfvDFfFmj

D

MDvv js =+⇒−

+== == ·)·(

1

1

)0( 0,

ωωω [3.15]

Como se vio anteriormente:

mm

m KsLR

euKiFm ·

··

+−== [3.16]

De lo que se deduce que, en régimen permanente:

( ) ( )m

mm K

R

euKiFm ··)()(

∞−∞=∞=∞ [3.17]

Como Km es ya una constante conocida, así como em también lo es, se puede

representar la fuerza del par del motor (Fm) con respecto a la velocidad, y hacer

de nuevo una regresión lineal simple, lo cual se puede observar en la figura 3.6:

Page 49: Control Motor Tesis

MEMORIA Modelado del sistema

40

figura 3.6: fuerza del par motor en función 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 fricción viscosa y la velocidad, se puede afirmar que la

fricción viscosa asociada al rozamiento del tren con las vías será la pendiente de la

recta anteriormente representada.

Por tanto: Nm·s/rad0.6703=D

3.2.6. Cálculo de la masa

La medida de la masa se realizó con una balanza electrónica. De este ensayo se

concluyó que: kgM 7.0=

Page 50: Control Motor Tesis

MEMORIA Modelado del sistema

41

3.2.7. Estimación de la velocidad máxima

Por último, se trató de estimar la velocidad máxima que puede desarrollar el

tren cuando se alimenta su motor con una tensión máxima de 14V. Para ello se

representó es una gráfica los distintos datos de velocidad en función de la tensión

de alimentación. Se puede observar dicha representación en la figura 3.7:

Figura 3.7: velocidad en función de tensión de alimentación.

A partir de ella, y mediante interpolación, se obtuvo la velocidad que habría de

tener el tren cuando éste es alimentado a 14V. Se considera que el tren va a

conservar su tendencia lineal de velocidad en función de tensión de alimentación,

la cual se puede observar en la gráfica.

Se concluye pues que: m/s 1.12 m/s 1.1178max ≈=V

Page 51: Control Motor Tesis

MEMORIA Modelado del sistema

42

3.4. Obtención 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 mecánico de traslación, tal y como puede verse en la figura 3.8:

Figura 3.8: representación mecánica de la planta

Es un sistema dinámico, lineal e invariante, y la ecuación diferencial que rige

el comportamiento de la planta es la siguiente:

( ) ( ) ( ) ( )tvDdt

tdvMFfFm

dt

tdxD

dt

txdMFfFm ··

2

2

+=−⇒+=− [3.18]

Aplicando la transformada de Laplace, se obtiene:

( ) ( ) ( ) ( )sVDsMsFfsFm ·· +=− [3.19]

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

( ) ( ) ( )DsM

sFfsFmsV

+−=

· [3.20]

M

D Fm

v

x

Ffm

Page 52: Control Motor Tesis

MEMORIA Modelado del sistema

43

Como el sistema es lineal, si se supone nula la perturbación (Ff(s)), la ecuación

anterior queda:

( ) ( ) ( )( ) DsMsFm

sV

DsM

sFmsV

+=⇒

+=

·1

· [3.21]

La cual es la función de transferencia (función matemática que modela el

comportamiento de un sistema) de la planta.

Si dicha función de transferencia es traducida a un diagrama de bloques, en el

cual únicamente se utilizan ganancias e integradores (esto es así para poder

obtener información sobre las señales intermedias que actúan sobre la planta, y no

sólo 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 mT , se relaciona con la corriente de armadura i mediante una

constante mK :

Page 53: Control Motor Tesis

MEMORIA Modelado del sistema

44

iKT mm ·= [3.22]

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

motor ω, con constante de proporcionalidad eK :

ω·em Ke = [3.23]

Aplicando la 1º ley de Kirchoff al circuito eléctrico del motor, ya representado

en la figura 3.3, resulta:

ω··· eKViRdt

diL −=+

[3.24]

Donde:

=dt

diLV

L· [3.25]

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

Tomando transformadas de Laplace:

( ) ( ) ( )RsL

KVsIKVsIRsL e

e +−=⇒−=+·

····

ωω [3.26]

Por tanto, la función de transferencia:

( )( ) RsLsV

sI

+=

·

1 [3.27]

Por otra parte, la ecuación mecánica del motor es:

RmRmm TiKTTDdt

dJ −=−=+ ··· ωω

[3.28]

Donde:

J: es el momento de inercia del motor.

Dm: es la constante de fricción viscosa del motor.

ω: es la velocidad angular del eje del motor.

TR: es el par de carga del motor.

Page 54: Control Motor Tesis

MEMORIA Modelado del sistema

45

Como se puede observar, el modelo del motor trabaja con parámetros propios

de un sistema mecánico de rotación, sin embargo, en la planta se ha utilizado un

modelo de sistema mecánico de traslación. Tanto el momento de inercia como la

constante de fricción viscosa del motor están tenidos en cuenta en la masa y la

constante de fricción 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.

Además, 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 sección Estimación de parámetros físicos ya

tienen en cuenta ese efecto, y de ellas se obtiene directamente la relación 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

Page 55: Control Motor Tesis

MEMORIA Modelado del sistema

46

3.5. Conclusiones

A lo largo del capítulo se ha expuesto la metodología seguida para obtener los

distintos parámetros necesarios a la hora de diseñar el control, así como la base

teórica sobre la que se sustentan los cálculos realizados para dicha obtención de

los mencionados parámetros.

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

de cual trabajar en el diseño del control, ya que, sin una modelización del sistema

físico, sería imposible realizar dicho diseño o las simulaciones pertinentes para

comprobar la validez del mismo.

Page 56: Control Motor Tesis

MEMORIA Hardware

47

Capítulo 4: Diseño del hardware

4.1. Introducción

Se distinguirán distintas fases dentro del diseño del hardware:

• Diseño de la etapa de potencia: conlleva el acondicionamiento de la

señal de PWM generada en el microprocesador, entre 0V y 5V, para

convertirla en otra señal PWM entre -14V y 14V, márgenes 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.

• Diseño de los reguladores de tensión: como se verá más adelante,

para conseguir la señal PWM antes descrita entre -14V y 14V, será

necesario alimentar el circuito a 14V DC. Debido a esto, es necesario

utilizar dos reguladores de tensión para obtener 3.3V para la

alimentación del microprocesador y 5V para activar el puente en H de

la etapa de potencia. Desde el punto de vista de la eficiencia energética,

se descartan los reguladores lineales, ya que disipan mucha potencia en

forma de calor, lo cual, es altamente indeseable; por tanto, se emplearán

dos reguladores de tensión conmutados, cuyo diseño se detallará más

adelante.

• Diseño 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 diseñar

un circuito de acondicionamiento que permita medir dicha intensidad

con la mayor precisión y sensibilidad posibles.

Page 57: Control Motor Tesis

MEMORIA Hardware

48

• Diseño del circuito de acondicionamiento para medir la señal del

acelerómetro: se detallará más adelante el proceso de

acondicionamiento de señal de los acelerómetros, para llevarla hasta el

conversor analógico/digital del microprocesador. A grandes rasgos, el

circuito consistirá de un rectificador de precisión y una etapa de ajuste

de ganancia, que tomará como ganancia teórica máxima 4G.

• Diseño de las balizas: las balizas estarán colocadas al comienzo de

cada curva, y mandarán una señal al microprocesador cuando el tren

pase por su lado, con el fin de aminorar su velocidad antes de entrar a la

curva. Estarán 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 adecúa la señal PWM de salida

del microprocesador para que pueda ser utilizada en el motor. Como se puede

observar en la hoja de características del microprocesador utilizado (ver anexo 4),

la corriente máxima de salida que es capaz de suministrar entre todas sus patillas

es de 60mA. Experimentalmente, se midió la corriente máxima que requiere el

motor en su situación más desfavorable, esto es, cuando el tren está parado y se le

aplica la tensión máxima, que en este caso son 14V, obteniendo un pico máximo

de corriente de 390mA. Resulta evidente pues la necesidad de emplear una

circuitería adicional para poder alimentar al motor, lo cual se conseguirá gracias al

puente en H.

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

figura 4.1 se muestra una representación esquemática del circuito. Hay que tener

en cuenta que es una simplificación: faltan los diodos de libre circulación, la

circuitería de activación/desactivación de los transistores, etc. Para que el motor

gire, se activan dos de los transistores opuestos diagonalmente. En función del par

Page 58: Control Motor Tesis

MEMORIA Hardware

49

de transistores activados, la corriente fluye en uno u otro sentido, lo que permite

controlar el sentido de giro del motor.

Figura 4.1: representación esquemática 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 través del

motor por dos caminos distintos: desde Q1 a Q4 o desde Q3 a Q2. Según el

camino seleccionado, la corriente fluye a través 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 simultáneamente los transistores de la

misma rama de la “H”. Si eso ocurre la corriente fluiría desde el terminal positivo

de la fuente de alimentación de los motores al terminal negativo. Al no haber más

resistencia que la que ofrecen los propios transistores, la cantidad de corriente que

fluiría por el circuito sería máxima y estaría limitada por la propia fuente de

alimentación o por la autodestrucción 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 opción suele ser más cara, pero

mucho más cómoda y robusta. Los circuitos integrados que proporcionan puentes-

H 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

Page 59: Control Motor Tesis

MEMORIA Hardware

50

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 través 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 eléctrica. Si se conecta una

carga a los terminales del motor, entonces presentaría 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 señales de

dirección 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 estén conectados al terminal negativo de la fuente de

alimentación del motor (generalmente, tierra) a través de los transistores Q2 y Q4,

por lo que el motor tendrá sus dos terminales a una tensión de 0,4 V, determinada

Page 60: Control Motor Tesis

MEMORIA Hardware

51

por la caída de tensión de los transistores. En este caso, los transistores actúan

como un cable que une los dos terminales del mismo motor, produciéndose el

efecto comentado anteriormente de que el motor debe hacer frente a una carga

infinita. Como no puede, se para prácticamente en seco en el momento en que se

activa esta configuración.

Figura 4.3: configuración para frenado del motor utilizando el puente en H

La modulación por ancho de pulsos (pulse-width modulation o PWM) es una

técnica que se basa en la modificación del ciclo de trabajo de una señal periódica

(por ejemplo sinusoidal o cuadrada). El ciclo de trabajo de una señal periódica es

el ancho relativo de su parte positiva en relación al período.

Matemáticamente:

TDC

τ= [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 función es

positiva

T es el período de la función.

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 tensión de la señal de entrada, esto es,

Page 61: Control Motor Tesis

MEMORIA Hardware

52

el valor de tensión continua que tiene la entrada (esta afirmación sólo es cierta si

se está en régimen permanente).

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

( ) ( )∫=><T

dttxT

tx0

1 [4.2]

Para señales con forma sencilla, como la onda cuadrada que se ha empleado en

el presente PWM, se puede calcular su valor medio como:

( ) ( )( ) ( ) ( ) ( )txDtxTDTDT

tx cuadrada

∧∧−=−−=>< ·12··1··

1 [4.3]

En función de su ancho de pulso, la señal tendrá más o menos valor medio, lo

que hará que el motor aplique más o menos par.

Se puede observar en la figura 4.4 el esquema del circuito diseñado, el cual se explicará a continuación:

Page 62: Control Motor Tesis

MEMORIA Hardware

53

Figura 4.4: Esquema del circuito de la etapa de potencia

Optoacoplador

Inversor

Puente en H

Puente de diodos de libre circulación

43

Salida PWM

Page 63: Control Motor Tesis

MEMORIA Hardware

54

• La señal 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 saturación. El optoacoplador

utilizado ha sido el ILQ74. Se detallan a continuación las características más

relevantes de dicho circuito, así como la disposición de sus pines:

Tabla 4.1: características eléctricas del circuito ILQ74

Page 64: Control Motor Tesis

MEMORIA Hardware

55

Figura 4.5: disposición de los pines del ILQ74

• Se detallan a continuación los cálculos realizados para R1:

Se quiere que, cuando la señal de salida del microprocesador esté en

nivel alto (3V de valor típico), la corriente colector-emisor por el

fototransistor del optoacoplador sea de 25mA. Dicha corriente colector-

emisor viene dada por la gráfica de la figura 4.6, en función 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 caída de

tensión en el diodo será de 1.2V.

Page 65: Control Motor Tesis

MEMORIA Hardware

56

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

Figura 4.7: caída de tensión en el diodo en conducción directa, en función de la corriente que lo atraviesa

Por tanto, aplicando la ley de Ohm:

Page 66: Control Motor Tesis

MEMORIA Hardware

57

Ahora se recalcula la intensidad que circulará por R1:

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

optoacoplador es de 25mA cuando la señal de salida del microprocesador

tiene valor lógico alto, y 0 cuando tiene valor lógico bajo. La siguiente etapa

del circuito transforma esa señal en una similar, pero entre 0V y 5V, e

invertida respecto a la señal original del microprocesador. Para ello se

utiliza R2:

Cuando se tiene una corriente colector-emisor del fototransistor de

25mA, se verá más adelante que Q1 está en corte, luego por R3 no pasará

corriente. Entonces, esos 25mA pasarán íntegros por R2, por lo que, para

obtener la señal de la que se habló con anterioridad:

⇒Ω== 20025

52

mA

VR para ese valor de R2, el fototransistor estará

saturado, porque su tensión colector-emisor será menor que su tensión

colector-emisor de saturación, luego, en los instantes en los que la salida del

microprocesador esté en estado lógico alto, tendremos en el colector de

fototransistor una tensión de 0.2V (que equivale a la tensión colector-emisor

de saturación).

El fototransistor estará en corte cuando la salida del microprocesador esté

en valor lógico 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

Ω=⇒⇒Ω=−= 4314540

2.131 Ranormalizad

mA

VVR

mWVmAPRdepotenciamAVV

I RD 758.1·86.41186.4143

2.131 ==⇒⇒=

Ω−=

Page 67: Control Motor Tesis

MEMORIA Hardware

58

alcance una tensión lo más cercana posible a 5V en ese instante, de tal

forma, que entonces Q1 esté saturado:

Se selecciona una tensión de colector mayor que 4.8V, para la cual se

diseñará:

Ω=⇒⇒Ω>⇒+Ω

−=−kRanormalizadkR

R

VV

R

VV6.531.43

32.0

7.05

3

7.08.4

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

mAR

VVi 741.0

32.0

7.05 =+Ω

−=

Por tanto, la tensión en el colector del fototransistor será:

VkmAVVC 85.46.5·741.07.0 =Ω+=

Por último queda diseñar R4 para que ciertamente Q1 esté en estado de

saturación en las circunstancias anteriores:

Para que Q1 esté saturado:

Ω=⇒<==⇒=+

<⇒≈⇒>=

kRmAmAR

ViVRiV

mAitomandoi

mAi

ccCEsat

cC

B

1405.378.44

8.454·

05.3750741.0 ββ

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

del fototransistor y del transistor Q1 valores de tensión que pueden ser 0V ó

5V (en realidad oscilan alrededor de los 0,2V para valores lógicos bajos, y

los 4,85V para valores lógicos 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 lógico para estas señales, como ya se ha

mencionado, vienen dados por la señal PWM de salida del microprocesador.

Page 68: Control Motor Tesis

MEMORIA Hardware

59

• 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 continuación las características más relevantes del L298N:

Figura 4.8: esquema del puente en H L298N

Tabla 4.2: funciones de cada uno de los pines del L 298N

Page 69: Control Motor Tesis

MEMORIA Hardware

60

Tabla 4.3: características eléctricas más relevante s 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 señal entre 0V y 5V (valores típicos), y

por su entrada In2 esa misma señal 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á desempeñada vía software por el

microprocesador, y que será explicada con detalle en el capítulo 5. Por

último, indicar que tanto C1 como C2 cumplen una misión de filtro de las

posibles fluctuaciones de la tensión de alimentación.

Page 70: Control Motor Tesis

MEMORIA Hardware

61

4.3. Reguladores de tensión

Se eligió utilizar dos reguladores de tensión conmutados para obtener los 3V

DC de alimentación del microprocesador y los 5V DC del puente en H a partir de

los 14V DC de alimentación 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 aún con grandes variaciones de tensión en la entrada,

estando la primera aislada de la segunda. Además, se pueden lograr múltiples

tensiones de salida reguladas, de diferente polaridad. Por último, mencionar que

los elementos pasivos de un regulador de tensión conmutado son más pequeños,

que los utilizados en un regulador lineal, ya que el primero trabaja con frecuencias

de switching (conmutación de los transistores) bastante más altas.

A la hora de elegir el regulador conmutado adecuado para el diseño del

circuito, se encontraron dos tipos de reguladores, dependiendo de su nivel de

integración, 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

tensión, 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 sólo componente de tres pines (entrada, tierra y salida) en

el cual vienen integrados todos los elementos necesarios para realizar la

regulación de tensión, desde el circuito de control, hasta los componentes pasivos

como condensadores, bobina, resistencias y diodos. Esto hace que sea mucho más

fácil de manejar e implantar en un circuito, a pesar de su elevado precio. Como en

el presente proyecto se pretende diseñar y construir un prototipo, y no realizar una

fabricación en serie del circuito, se optó por los reguladores conmutados

integrados 78SR-3.3/2-C (para tensión de 3V) y 78SR-5/2-C (para tensión de 5V).

Page 71: Control Motor Tesis

MEMORIA Hardware

62

Se pueden consultar sus características en su hoja de características, incluida en

el anexo 4.

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

No obstante, si se desease realizar una fabricación en serie del equipo, se

propone el siguiente circuito para el regulador de tensión, 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 regulación de tensión de 14V a 3V

Page 72: Control Motor Tesis

MEMORIA Hardware

63

Figura 4.11: circuito de regulación de tensión 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 misión de adecuar la señal a medir (en este caso la intensidad que

recorre el motor) para que pueda ser medida con la mayor precisión y sensibilidad

posibles por el microprocesador, mediante su conversor analógico/digital.

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

perturbar la señal 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 continuación

Page 73: Control Motor Tesis

MEMORIA Hardware

64

Figura 4.12: circuito de acondicionamiento de medida de la intensidad que atraviesa el motor

Puente de diodos de libre circulación

Estimador del módulo de corriente

Estimador del signo de la corriente

Estimador analógico de la velocidad

Diodo de protección del micro

Diodo de protección del micro

Page 74: Control Motor Tesis

MEMORIA Hardware

65

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 señal (a través el

amplificador operacional U5), y otro encargado de medir el signo (a través del

amplificador operacional (U4). Será el microprocesador el encargado de unir estos

dos datos, y obtener la medida de la intensidad con signo.

La realimentación del amplificador operacional U5 ha sido calculada de modo

que para una intensidad de 0.4A por la carga (que coincide con la intensidad

máxima estimada), la salida del mismo sean 3.3V, que es la máxima tensión

admitida por el conversor analógico-digital del microprocesador, al haber

establecido la tensión de comparación a 3.3V. En J9 estará situada la resistencia

Rs, que será la resistencia de medida del módulo de la corriente. Se detalla a

continuación los cálculos realizados para Rs=1Ω:

Ω=Ω=

⇒=+⇒

+=kR

kR

A

V

R

R

R

RiRv MAXsMAXo 138

27

4.0

3.3

7

81

7

81··

Donde:

• vo MAX = tensión máxima de entrada del microprocesador

• iMAX = corriente máxima que atraviesa el motor

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

función de transferencia de la planta. De esta forma, la señal resultante que le

llega al microprocesador después de pasar por ellos es la velocidad a la que va el

tren en cada instante. Los cálculos realizados fueron los siguientes (para una

resistencia Rs de 1Ω):

DsM

iKv

R

R

sCRiR

R

R

sCRiRv m

sso +=

++

=

++

·;

10

111·

6.0·3·9·6.0

6.0·

10

111·

1·3·9

)

Page 75: Control Motor Tesis

MEMORIA Hardware

66

=≈

Ω==

⇒==

Ω=Ω=

⇒≈⇒==

+

67.06.0

1509

107.03·9·6.0

27010

8.61125

10

118347.5·

2.1

10

111·6.0

D

kR

FCMCR

R

kR

R

RK

v

v

R

RR m

MAX

MAXos

µ

)

Donde:

• vo = tensión 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 OUT1→OUT2 (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 lógico alto

cuando la señal esté alrededor de 5V, y en estado lógico bajo cuando la señal esté

en 0V. A partir de esta entrada, se multiplicará, o no, el valor del módulo de la

corriente, medido mediante U5, por -1, estableciendo así el signo a la misma.

Tanto U5, como U6 y U7 están alimentados a 5V. Esto es así para que si

saturan, los operacionales no pierdan rango dinámico de tensión. Teóricamente,

sus respectivas realimentaciones están calculadas para que con un valor máximo

en sus entradas, obtengan una salida de 3.3V, pero ante eventuales picos en los

valores de esas entradas, su tensión de salida sería mayor. Para evitar que esto

dañe al microprocesador, se han utilizado diodos zener como protección. Los

diodos zener que aparecen en el circuito tienen una tensión inversa de 3.3V, por lo

que impiden que en las entradas del microprocesador se alcancen valores de

tensión por encima de esos 3.3V, la cual es la tensión máxima admitida por el

Page 76: Control Motor Tesis

MEMORIA Hardware

67

mismo. De este modo, el microprocesador queda protegido ante eventuales picos

de tensión en sus entradas.

4.5. Circuito de acondicionamiento de la señal del acelerómetro

El acelerómetro irá situado en la parte superior del tren, tal y como muestra la

figura 4.13A. De esa forma, se podrá calcular la aceleración normal en cada

instante, la cual será proporcional a la velocidad instantánea del tren y al radio de

la curva por la que circule, según la fórmula:

Donde v es la velocidad instantánea, y ρ es el radio de curvatura.

Figura 4.13A: situación del acelerómetro sobre la maqueta del tren

El circuito de acondicionamiento de la señal del acelerómetro tiene por objeto

adecuar la señal que proporciona dicho componente, para poder ser medida con la

mayor precisión y sensibilidad posibles por el microprocesador, utilizando su

conversor analógico/digital.

El acelerómetro que se ha utilizado es el ADXL320, un acelerómetro de dos

ejes, cuyas características se detallan en la tabla 4.4:

Dirección del movimiento

Sensor N: Normal

Sensor T: Tangencial

Page 77: Control Motor Tesis

MEMORIA Hardware

68

Tabla 4.4: Características del acelerómetro ADXL320

La configuración de los pines del encapsulado se detalla en la figura 4.13B.

Figura 4.13B: configuración de los pines del ADXL320

El primer paso para diseñar el circuito de acondicionamiento del acelerómetro

es estimar la aceleración máxima 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:

Page 78: Control Motor Tesis

MEMORIA Hardware

69

• Aceleración de un monoplaza de F1 al girar: entorno a 4G.

• Aceleración de un monoplaza de F1 al frenar: entorno a 5G.

• Aceleración máxima en la montaña rusa Dragon Khan: 3.75G.

• Aceleración máxima del caza F-16 Falcon: 9G.

• Aceleración máxima del caza F-18 Hornet: 7.5G.

En base a estos datos, resulta lógico no esperar medir aceleraciones superiores

a los 4G. Por tanto, se seleccionará esa aceleración como cota superior de las

aceleraciones a medir, y se hará coincidir la máxima salida del circuito (5V) con

esa aceleración de 4G.

Se puede observar el circuito detallado en la figura 4.14.

Page 79: Control Motor Tesis

MEMORIA Hardware

70

Figura 4.14: circuito de acondicionamiento de la señal del acelerómetro

Filtro paso alto

Salida ADXL320

Etapa de ganancia

Rectificador de precisión

Page 80: Control Motor Tesis

MEMORIA Hardware

71

La primera etapa es un filtro paso alto a 0.5 Hz para eliminar la continua. Los

cálculos para el mismo han sido los siguientes:

Hzf

teconsiguienporuFCnormalizarAl

uFfR

C

fijadakR

c

c

48.0

:,3.31

18.3···2

11

1001

==

==

→Ω=

π

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

circuito para conseguir la máxima sensibilidad posible en la medida. Según la

hoja de características del acelerómetro, la sensibilidad típica cuando éste está

alimentado a 3.3V es de 174mV/G. Como se ha tomado como límite de

aceleración 4G, el sensor dará como máximo una salida de 174mV/G·4G =

696mV. Como el valor máximo 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:

==

⇒=+kR

kR

R

RR

5.18

6.5774.4

8

87

La última etapa se trata de un rectificador de precisión. Hasta esta etapa, el

circuito mide y amplifica la señal del acelerómetro con signo, sin embargo, sólo

es necesario medir el módulo de la aceleración, ya que el signo de la aceleración

sólo serviría para indicar en qué dirección se está tomando la curva en cuestión.

Además, el microprocesador no admite niveles de tensión negativos en sus

entradas. Por tanto, en esta etapa, se rectificarán las señales negativas, y se

transformarán en positivas. La característica del rectificador de precisión está

ilustrada en la figura 4.15:

Page 81: Control Motor Tesis

MEMORIA Hardware

72

Figura 4.15: característica del rectificador de precisión

Las resistencias están escogidas de modo que limitan la corriente para no dañar

los diodos. Como la tensión máxima que va a entrar al rectificador son 3.3V, y la

intensidad máxima que puede circular por los diodos es 25mA, si dividimos estas

dos cifras, obtenemos una resistencia mínima de 120 Ω. Para proteger mejor el

circuito, se han seleccionado resistencias de 1k.

4.6. Diseño de las balizas

Las balizas, como ya se ha comentado anteriormente, se colocarán al principio

de cada curva, y serán las encargadas de mandar una señal 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

acelerómetros. Estarán 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 características:

• 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

Vout

Vin

1

1 -1

Page 82: Control Motor Tesis

MEMORIA Hardware

73

Figura 4.16: Circuito de una baliza

Diodo LED

Acondicionamiento del fotodiodo

Inversor

Negador

Resistencia de entrada al sumador

Page 83: Control Motor Tesis

MEMORIA Hardware

74

Se quiere conseguir que cuando el tren cruce el haz de luz que emite el LED

hacia el fotodiodo, se envíe una señal de 3.3V al microprocesador, y que en caso

contrario, la señal permanezca por debajo de los 1.15V, que es el umbral para que

una señal se considere a nivel bajo. Para ello se ha diseñado el circuito de la figura

4.16, que se explica a continuación.

En primer lugar se ha diseñado el circuito que alimenta al diodo LED para que

esté siempre encendido. Según la hora de características del mismo, la corriente

que atraviesa el diodo cuando está polarizado directamente es de 7mA, y la caída

de tensión es de 1.8V. Según esto, y sabiendo que la tensión de alimentación es de

5V, se puede calcular R14:

kRkmA

VVR 47.01446.0

7

8.1514 =⇒=−=

Seguidamente se ha diseñado el circuito de acondicionamiento del fotodiodo.

Se sabe que la intensidad que recorre la rama donde está colocado el fotodiodo, en

sentido cátodo-ánodo, es I0+k·PL. 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 características constructivas del fotodiodo en cuestión. 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 más precisa posible, primero se requiere eliminar los efectos de la

“corriente oscura”. Para ello se coloca otro fotodiodo de las mismas características

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 cápsula 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+k·PL , sino por una intensidad igual a k·PL.

Page 84: Control Motor Tesis

MEMORIA Hardware

75

De forma empírica 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 debía ser de 0.33k.

Como, debido a la topografía del circuito de acondicionamiento del fotodiodo,

sólo se pueden obtener a su salida tensiones negativas, es necesario añadir a

continuación 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 señales

(previamente tratada) al micro. Este sistema funciona porque sólo 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 señal que entre al sumador valga

3.3V (o el equivalente al estado lógico 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

señal a la salida del inversor vale 2V y cuando se interrumpe, vale 0.5V. Se desea

pues que el transistor esté saturado para una tensión en su base de 2V, y en corte

para una tensión de 0.5V. Se realizan pues los siguientes cálculos:

==

⇒≥⇒≥⇒≤−−=kR

kR

R

RR

RR

RV

Saturación

C 1003

7.44037.0

3

48.44·

3

3.12.04·

3

7.025

:

ββ

Page 85: Control Motor Tesis

MEMORIA Hardware

76

Al ser 0.5 menor que 0.7, el corte se produce automáticamente cuando el haz

de luz que incide en el fotodiodo se corta. Para que la caída de tensión en R4 sea

la menor posible cuando se produce el corte, R11 tendrá que ser grande en

comparación con ésta, por ello se ha elegido un valor de 100k para ella, lo que

produce una caída 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 desearían, acarrea

consecuencias negativas, y es que como se sumarían las diferentes tensiones de

distintos fotodiodos, se podrían tener como máximo 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 límite

superior de la señal lógica en estado bajo para el microprocesador. Para optimizar

el número de fotodiodos que se pueden instalar, se puede ajustar la ganancia del

sumador. Como el nivel alto de la señal que entra al sumador es de 4.78V, y sólo

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 número de balizas, podría llevarse la señal 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

después del sumador, hay una etapa inversora de ganancia -1. Esto es así porque

la ganancia del sumador tiene fase 180º. Además, se ha colocado un diodo zener

de 3.3V para proteger al microprocesador frente a tensiones mayores de 3.3V.

Page 86: Control Motor Tesis

MEMORIA Hardware

77

Figura 4.17: sumador, inversor y protección del microprocesador

4.7. Conclusiones

Se ha expuesto en el presente capítulo 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 tensión que han sido utilizados, pasando por los

diferentes circuitos de acondicionamiento de señal.

En una primera sección se ha hablado de todo el diseño de la etapa de potencia,

exponiendo los cálculos, así como información detallada de todos los elementos

que la componen: optoacoplador, inversor y puente en H.

En la segunda sección se han presentado los distintos tipos de reguladores

existentes, y se argumenta la elección de uno de ellos sobre el resto. Además, se

han propuesto diseños alternativos de los reguladores para que, en caso de una

fabricación en serie del prototipo que se propone en el presente proyecto, los

gastos en componentes disminuyesen drásticamente en esta parte del circuito.

Sumador Inversor

Protección

Page 87: Control Motor Tesis

MEMORIA Hardware

78

En las siguientes tres secciones se han abordado los distintos circuitos de

acondicionamiento de señal: la medida de la corriente que atraviesa el motor, el

acondicionamiento de la señal del acelerómetro, y el diseño de las balizas. Como

ya se ha expuesto, estos circuitos cumplen la función de acondicionar las señales

que se desean medir para realimentar el control de manera que dicha medición se

efectúe con la mayor precisión y sensibilidad posibles, y sin perturbar a la señal

original. Para ello se han utilizado básicamente etapas basadas en amplificadores

operacionales, tanto en realimentación negativa como en bucle abierto, diodos

zener para la protección del microprocesador, y los propios elementos cuya señal

se había de acondicionar.

Page 88: Control Motor Tesis

MEMORIA Sistema de Control

79

Capítulo 5: Sistema de control

5.1. Introducción Se utiliza como sistema de control un regulador con acción proporcional-

diferencial (PI) discreto, que va programado en un microprocesador

MC9S08QG4/8. Para realizar el ajuste de los distintos parámetros del control se

han utilizado diferentes herramientas informáticas (Matlab® y Simulink®) para

simular la respuesta del sistema ante distintas entradas o hallar su respuesta en

frecuencia.

En el presente capítulo se tratarán, por este orden, los fundamentos teóricos

subyacentes de la teoría de control discreta, el diseño de distintos controles y la

elección del más conveniente al sistema a controlar, la implementación de filtros

para intentar mejorar la respuesta de los controles antes mencionados, el escalado

del problema a 8bits, el cual es el tamaño de los registros del microprocesador, se

introducirán brevemente algunas de las características 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 capítulo tercero el esquema general de un sistema de control

analógico o continuo. En él, las señales 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 señales, o al menos algunas de ellas, se representan como

secuencias discretas (ver figura 5.1(b)). Esas secuencias discretas son una serie

de números que provienen de tomar los valores instantáneos de señales analógicas

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

Page 89: Control Motor Tesis

MEMORIA Sistema de Control

80

su número de muestra k. En la figura 5.1(b) se observa una secuencia yk = y0, y1,

y2, . . ., que proviene de una señal analógica y(t) (figura 5.1(a)), con la relación

entre muestra k e instante de tiempo k·T. La elección del periodo de muestreo es

muy importante puesto que un valor demasiado grande hace que se pierda

información cuando se muestrean señales rápidas (figuras 5.1(c) y 5.1(d)), que en

el caso de tratarse de un problema de control provendrán de sistemas rápidos. Es

lo que se conoce como “efecto aliasing”.

Figura 5.1: discretización de una señal continua y efecto aliasing

Por tanto, el esquema genérico de un sistema de control digital es el mostrado

en la figura 5.2:

Page 90: Control Motor Tesis

MEMORIA Sistema de Control

81

Figura 5.2: esquema genérico de un sistema de control digital

Al igual que en los sistemas continuos se puede obtener la función de

transferencia a partir de la ecuación 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 función de transferencia a partir

de la ecuación en diferencias y por medio de la Transformada en Z, sin más que

tener en cuenta:

[5.3]

Con lo que se obtiene la función de transferencia discreta:

CONTROL POT

SISTEMA A CONTROLAR

SENSOR

Ref. Salida

Perturbación

-

-

T

Retenedor (Hold)

Muestreador (Sampler) Sistema Digital

Page 91: Control Motor Tesis

MEMORIA Sistema de Control

82

[5.4]

A la hora de realizar el diseño de los reguladores digitales, existen dos

enfoques:

- Diseñar directamente en “z”: trabajar con sistemas discretos y

metodologías aplicables a los mismos.

- Diseñar 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 continuación algunas técnicas de

discretización:

Para obtener la versión discreta de un sistema continuo se dispone, a grandes

rasgos, de dos posibilidades:

- Método exacto: tener en cuenta la relación z = e s·T

- Métodos aproximados: técnicas de simplificación para hacer más

sencilla la discretización. Se explicará a continuación uno de los

métodos utilizados en el presente texto a la hora de discretizar: el

“método de la derivada”:

El método 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:

Page 92: Control Motor Tesis

MEMORIA Sistema de Control

83

[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 función de transferencia las “s” por z 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 continuación algunas de las

características de dicho control en continuo, que pueden hacerse extensibles a su

versión discreta:

La función de transferencia del control es la siguiente:

[5.8]

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

servirá para obtener distintas conclusiones:

( )sT

sTK

sTKsC

i

i

i ·

·1·

·

11)(

+=

+=

Page 93: Control Motor Tesis

MEMORIA Sistema de Control

84

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 acción integral al control, retraso que se tratará de aminorar en la

medida de lo posible (se manejarán 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

dicha aproximación. Si se tiene una función ττ∫=t

duty0

)·()( y la señal )(τu es

1/Ti

20·log(K)

Page 94: Control Motor Tesis

MEMORIA Sistema de Control

85

una señal discreta, se puede demostrar que el valor de la función y en un instante

k es: [ ] [ ][ ]

[ ] [ ]( )[ ]

→−+

→−

+−=

Riemanndesuperiorintegral

ltrapezoidaregla12

1

Riemanndeinferiorintegral1

·1

ku

kuku

ku

tkyky s [5.9]

Por consiguiente, utilizando la regla trapezoidal como método de aproximación

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 ponderación de la referencia, no utilizada

en este texto)

Page 95: Control Motor Tesis

MEMORIA Sistema de Control

86

5.4. Diseño 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 función de dicha comparación, obtener una variable de error, a partir

de la cual generar un mando de corriente, dentro de unos límites de saturación que

no podrá superar, y que corresponden a los valores de corriente por encima, en el

caso del límite superior o por debajo, en el caso de límite inferior, de los cuales el

motor podría sufrir daños. 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.

Después de aplicar su acción 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

capítulo cuarto.

Las principales ventajas que se derivan de la implantación de dos bloques de

control en cascada son las siguientes:

- Protección del motor frente a sobreintensidades que pudieran dañarlo: al

generar el primer bloque de control un mando de corriente con límites de

saturación, el segundo bloque se encargará de generar el mando de

tensión adecuado (el cual también se encuentra entre dos límites de

saturación) para que la corriente del motor se encuentre entre esos

límites.

- Mayor precisión 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.

Page 96: Control Motor Tesis

MEMORIA Sistema de Control

87

Figura 3.2: Primera aproximación del diagrama funcional de bloques del sistema completo

Page 97: Control Motor Tesis

MEMORIA Sistema de Control

88

Los parámetros del control han sido diseñados varias veces, atendiendo a

distintos criterios, y utilizando distintas técnicas de diseño. Una vez obtenidos

todos los resultados, se ha elegido aquél que mejor satisface las necesidades del

sistema.

Todos los diseños se han realizado en base a una aproximación 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 diseñado, en una primera aproximación, se supuso el

sistema como continuo, a excepción 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 señal era lo suficientemente alta como para que los valores medios del

resto de las señales del sistema sólo se viesen afectados en un ligero rizado

alrededor de dicho valor medio). Más adelante, y ante respuestas del sistema

inesperadas, debidas al desprecio de efectos físicos no modelados, se fueron

añadiendo al modelo del sistema elementos que simulaban dichos efectos físicos,

tales como retrasos en la actualización de los valores, distintos tiempos de

muestreo para los distintos bloques de control, efectos de la señal de PWM, etc.

Todo ello se explica con detenimiento a continuación.

5.4.1. Diseño mediante ajuste por simulación

El primer control diseñado se realizó bajo la hipótesis de que los efectos de la

no continuidad de las señales del sistema, excepto en lo referente al control, eran

despreciables. No se tuvieron en cuenta pues retrasos de actualización 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

Page 98: Control Motor Tesis

MEMORIA Sistema de Control

89

tensión, sino como dicha tensión directamente1). Además, se trabajó con el mismo

tiempo de muestreo para los dos bloques de control, resultando éste demasiado

rápido para lo que el microprocesador puede ofrecer. El diagrama de bloques del

sistema completo se puede observar en la figura 3.2.

El diseño se realizó en dos partes: en primer lugar se ajustó el lazo de control

de corriente, ya que es considerablemente más rápido que el lazo de control del

sistema completo, para más 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 función de transferencia de segundo orden

entre su entrada y su salida. Se pueden modelar pues sus parámetros de forma

analítica, de modo que adquieran los valores que se desee.

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

Función de transferencia una vez cerrado el lazo:

( )( ) ( )

( )( )

1··

·1

·1··

·1)(

2 +++=

++++=

sK

TKRs

K

LTsT

sTKsLRsT

sTKsG

ii

i

ii

i [5.10]

1 Si se observa la función de transferencia de la planta:

DsM +·

1 , se puede apreciar que tiene el

aspecto de un filtro paso bajo, de frecuencia de corte: HzM

Dfc 152.0

··2=

π, por tanto, es de

esperar que filtre las fluctuaciones de velocidad que pudieran surgir debido a las conmutaciones de la onda PWM.

Page 99: Control Motor Tesis

MEMORIA Sistema de Control

90

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 más

la derivada de dicha respuesta. En lo que concierne al diseño, sólo se tendrá en

cuenta la respuesta del sistema de segundo orden:

( )

=

+=

=

++

=

1)0(·2

·

1··

1)(

2

GLK

TKR

LT

K

sK

TKRs

K

LTsG i

in

ii

ζ

ω

[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 pulsación natural lo mayor

posible. Para dichos valores, se obtuvo la siguiente expresión que relaciona Ti con

K:

[5.12]

Se puede observar en la siguiente gráfica la relación entre Ti y K:

Figura 5.6: relación entre Ti y K para un amortiguamiento de 0.7

KK

Ti

++=

50625

00392.0

Page 100: Control Motor Tesis

MEMORIA Sistema de Control

91

Teniendo en cuenta la relación anterior, se ensayó la respuesta del lazo de

corriente linealizado frente a un escalón 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 escalón de la salida del lazo de corriente

linealizado con distintos valores de K y Ti

Page 101: Control Motor Tesis

MEMORIA Sistema de Control

92

Figura 5.8: respuesta ante un escalón del mando de corriente

con distintos valores de K y Ti

Los valores de K y Ti elegidos después de comparar las distintas respuestas

fueron los del ensayo 3. Una vez fijados esos valores, se procedió a diseñar el

regulador del lazo de control del sistema completo.

El diseño del lazo de control del sistema completo se realizó a partir de

distintos ensayos de la respuesta ante un escalón del sistema linealizado,

utilizando un método de aproximación para ajustar los parámetros del control.

Una vez fueron obtenidas respuestas más o menos aceptables, se realizó un ajuste

más fino con parámetros cercanos a aquellos que habían dado esas respuestas.

A continuación se muestran distintas gráficas de los resultados obtenidos en el

diseño:

Ajuste de la parte proporcional del control:

Page 102: Control Motor Tesis

MEMORIA Sistema de Control

93

- 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 rápido, a los ojos del regulador del lazo de

control del sistema completo es como si sólo tuviese que actuar sobre la planta, la

cual, es un sistema de primer orden. Al aplicarle únicamente la acción

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 físico

realmente no es un sistema de primer orden, ya que hay efectos físicos que

siempre se van a despreciar a la hora de hacer un modelo (de lo contrario, modelar

un sistema resultaría imposible), una K demasiado alta haría al sistema oscilante,

aunque no se reflejase así en la simulación. Para prevenir esto, se ha elegido el

valor de K del ensayo 4.

Ajuste de la parte integral del control:

Page 103: Control Motor Tesis

MEMORIA Sistema de Control

94

- 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 simulación 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 régimen permanente, y una vez estabilizado, otro de amplitud 0.1m/s, para

comprobar la respuesta del sistema ante pequeñas 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

Page 104: Control Motor Tesis

MEMORIA Sistema de Control

95

valor de Ti. Las figuras 5.13 y 5.14 son distintas respuestas del mando de corriente

y del mando de tensión en función de los distintos valores de Ti. Los valores de

los parámetros utilizados en cada ensayo se detallan a continuación de las

gráficas. En la figura 5.10 se observa el diagrama de bloques del sistema

simulado:

Page 105: Control Motor Tesis

MEMORIA Sistema de Control

96

Figura 5.11: diagrama de bloques del sistema simulado

Page 106: Control Motor Tesis

MEMORIA Sistema de Control

97

Figura 5.12: simulación del sistema con distintos valores de K

Figura 5.13: simulación del sistema con distintos valores de Ti

Page 107: Control Motor Tesis

MEMORIA Sistema de Control

98

Figura 5.14: respuesta del mando de corriente

Figura 5.15: respuesta del mando de tensión

Page 108: Control Motor Tesis

MEMORIA Sistema de Control

99

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. Diseño basado en técnicas de respuesta en fr ecuencia en lazo abierto con modelado de los efectos de retrasos de actualización de valores y PWM

Con el fin de comprobar que el control diseñado anteriormente funcionaría

correctamente implantado en el sistema real, se decidió modelar el efecto de los

retrasos en la actualización de los valores de salida del control, así como el efecto

que tiene el que el mando de tensión no sea una tensión continua sino una señal

PWM. El diagrama de bloques del sistema, una vez modelados dichos efectos,

queda como se muestra en la figura 5.17.

Page 109: Control Motor Tesis

MEMORIA Sistema de Control

100

Al realizar la simulación del sistema con los parámetros del control

seleccionados anteriormente, se obtuvo la siguiente respuesta:

Figura 5.16: respuesta del sistema en simulación con retardos de actualización de salidas y PWM modelados

Como dicha respuesta no es demasiado buena, se optó por realizar un segundo

diseño del sistema de control, esta vez teniendo en cuenta los efectos de los

retardos y del PWM. Además, para este segundo diseño, se aplicaron técnicas de

diseño por respuesta en frecuencia en lazo abierto, como son el diseño por margen

de ganancia y el diseño por margen de fase (para más información acerca de las

técnicas de diseño de controles por respuesta en frecuencia, ver las referencias

bibliográficas número 9 y 10).

Page 110: Control Motor Tesis

MEMORIA Sistema de Control

101

Figura 5.17: diagrama de bloques del sistema, incluyendo retardos de actualización de salidas y efecto del PWM

Retardo en la actualización

del mando

Modulación PWM

Page 111: Control Motor Tesis

MEMORIA Sistema de Control

102

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

Retardo en la actualización del mando

y retardo por el retenedor de orden cero

PI 2

PI 1

Page 112: Control Motor Tesis

MEMORIA Sistema de Control

103

Figura 5.19: diagrama de bloques del lazo de control de corriente abierto, en tiempo continuo

Como se comenta al principio de la sección, los diseños no se realizan sobre el

modelo propio del sistema, sino sobre una linealización del sistema, una vez

pasado a continuo. Para ello, se han de sustituir los bloques de control discreto por

sus equivalentes en continuo (ver sección 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 actualización 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:

stse ··5.1− [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 información necesaria para

diseñar el control. Como ya se hizo en el primer diseño, se comienza con el lazo

de control de corriente.

Se diseña en primer lugar por margen de ganancia:

( )( )

−==⇒=+=∠

−==Φ

dBjG

sradjG

dBc

m

7.17

/10·57.3º1320º60º1260

º10

º50

0

300

ωωω

ϕ [5.14]

PI 2

Retardo en la actualización del mando

y retardo por el retenedor de orden cero

Page 113: Control Motor Tesis

MEMORIA Sistema de Control

104

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

( ) ( ) 6736.7107.17 20

7.17

00 ==⇒= ωω jCdBjCdB

( ) 3

00 10·6.1

º80tanº10·º90 −==⇒−=+−=

ωωϕ iic TTarctg

( ) ( )56.76736.7

·

·1

0

20

0 =⇒=+

= KT

TKjC

i

i

ωω

ω [5.15]

Donde:

(Nomenclatura extensiva a todos los diseños por respuesta en frecuencia)

• Φm = margen de fase

• Am = margen de ganancia

• ω0 = pulsación de cruce

• ωu = pulsación de oscilación

• G = función de transferencia del sistema a controlar en lazo abierto

• C = función de transferencia del control

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

• Ti y K = ver sección 5.2 de la memoria

Page 114: Control Motor Tesis

MEMORIA Sistema de Control

105

Como se puede observar en la figura 5.21, el control diseñado resulta en un

margen de fase adecuado, sin embargo el margen de ganancia, que debería estar

por encima de los 8 dB, se hace demasiado pequeño.

Figura 5.21: diagrama de Black del lazo de corriente abierto, después de aplicar el primer diseño del control

Entonces, se decide diseñar por margen de ganancia:

( )( )

−==⇒=+=∠

−==

dBjG

sradjGdBA

dBc

m

8.17

/10·5º1270º10º1260

º10

8

0

300

ωωω

ϕ

( ) ( ) 1.3108.987.17 20

8.9

00 ==⇒=−= ωω jCdBdBdBjCdB

( ) 33

00 1010·134.1

º80tanº10·º90 −− ≈==⇒−=+−=

ωωϕ iic TTarctg

( ) ( )305.31.3

·

·1

0

20

0 ≈=⇒=+

= KT

TKjC

i

i

ωω

ω [5.16]

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

Page 115: Control Motor Tesis

MEMORIA Sistema de Control

106

Figura 5.22: diagrama de Black del lazo de corriente abierto, después de aplicar el segundo diseño 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

diseñar el regulador que lo controle por margen de fase:

Page 116: Control Motor Tesis

MEMORIA Sistema de Control

107

( )( )

−==⇒=+=∠

−==Φ

dBjG

sradjG

dBc

m

8.33

/300º1320º60º1260

º10

º50

0

00

ωωω

ϕ

Una vez obtenidos los puntos característicos del sistema en lazo abierto, se

procede a diseñar el control:

( ) ( ) 978.48108.33 20

8.33

00 ==⇒= ωω jCdBjCdB

( ) 22

00 10·210·89.1

º80tanº10·º90 −− ≈==⇒−=+−=

ωωϕ iic TTarctg

( ) ( )50234.48978.78

·

·1

0

20

0 ≈=⇒=+

= KT

TKjC

i

i

ωω

ω [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, después de aplicar diseño del control

Una vez implantado el control con los valores diseñados, se simula el sistema

tomando como referencia dos escalones: el primero, de 0 a 0.5m/s, para estabilizar

el sistema en régimen permanente, y el segundo de 0.1m/s de amplitud, para

Page 117: Control Motor Tesis

MEMORIA Sistema de Control

108

observar la reacción del sistema ante pequeñas variaciones, una vez está

estabilizado en régimen permanente. Se obtiene como respuesta:

Figura 5.25: respuesta de la simulación 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: ampliación de la respuesta de la simulación del sistema

Page 118: Control Motor Tesis

MEMORIA Sistema de Control

109

5.5. Filtros digitales: filtro de primer orden y f iltro 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 analógicos (los valores de los filtros digitales se

pueden cambiar mediante software en cualquier momento, mientras que los filtros

analógicos una vez implantados no se pueden modificar), se decide diseñar 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 diseñar un filtro digital paso bajo de primer orden, se diseñará en primer

lugar el filtro paso bajo en tiempo continuo, y más tarde, utilizando las técnicas

expuestas en la sección 5.1 de la memoria, se discretizará.

La función de transferencia de un filtro paso bajo tiene la forma:

ssF

·1

1)(

τ+= , donde

τπ ··2

1 es la frecuencia de corte..

Se aplica la aproximación de la integral superior de Riemann para hallar la

transformada “z” de la función de transferencia del filtro. Para ello, se sustituye

“s” por sT

z 11 −−, quedando pues:

1·)( −−+

=zT

TzF

s

s

ττ. Por tanto, su ecuación en

diferencias será:

[ ] [ ] [ ]τ

τ+

−+=

s

s

T

kykuTky

1·· [5.18]

Page 119: Control Motor Tesis

MEMORIA Sistema de Control

110

Figura 5.27: diagrama de bloques del filtro de primer orden

Page 120: Control Motor Tesis

MEMORIA Sistema de Control

111

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 diseñado el filtro, se procede a diseñar el control del lazo de corriente.

Después de observar el diagrama de black en lazo abierto, se decide diseñar por

margen de ganancia:

( )( )

−==⇒=+=∠

−==

dBjG

sradjGdBA

dBc

m

82

/10·5º1270º10º1260

º10

10

0

300

ωωω

ϕ

( ) ( ) 398110721082 20

72

00 ==⇒=−= ωω jCdBdBdBjCdB

( ) 3

00 10·38.3

º80tanº10·º90 −==⇒−=+−=

ωωϕ iic TTarctg

( ) ( )5.39203981

·

·1

0

20

0 =⇒=+

= KT

TKjC

i

i

ωω

ω [5.19]

Page 121: Control Motor Tesis

MEMORIA Sistema de Control

112

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

Page 122: Control Motor Tesis

MEMORIA Sistema de Control

113

A la hora de diseñar 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 diseñar por margen de fase. Se especifican

los cálculos a continuación:

( )( )

==⇒−=+−=∠

−==Φ

dBjG

sradjG

dBc

m

87.3

/1.2º130º50º180

º5

º45

0

00

ωωω

ϕ

( ) ( ) 65.01087.3 20

87.3

00 ==⇒−=−

ωω jCdBjCdB

( ) 4.5º85tan

º5·º900

0 ==⇒−=+−=ω

ωϕ iic TTarctg

( ) ( )65.065.0

·

·1

0

20

0 =⇒=+

= KT

TKjC

i

i

ωω

ω [5.20]

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

Page 123: Control Motor Tesis

MEMORIA Sistema de Control

114

Figura 5.30: diagrama de Black del lazo completo, con control aplicado

Sin embargo, se observa una respuesta del sistema más lenta y fluctuante que

con controles anteriores:

Figura 5.31: respuesta del sistema en simulación

Page 124: Control Motor Tesis

MEMORIA Sistema de Control

115

5.5.2. Filtro paso bajo FIR

Ante la mala respuesta del sistema con el filtro paso bajo de primer orden, se

decide diseñar un filtro FIR, que tiene la ventaja de ofrecer una gran atenuación e

incluso completa eliminación 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 número 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 más información sobre la teoría que rodea a los filtros FIR

(aspecto en el cual no se va a ahondar más en el presente texto) se puede consultar

cualquier libro de tratamiento de señales discretas, como por ejemplo los

enunciados en las referencias bibliográficas 1, 2 y 3.

Los filtros FIR se diseñan en función de las frecuencias que se desean eliminar.

A partir de la transformada “z” del filtro, se hallan los ceros de la función. Éstos

serán complejos, que, en forma módulo-argumental tendrán por módulo la unidad,

y por argumento la pulsación normalizada (pulsación / pulsación de muestreo) que

elimine ese cero. Si se diseña dicha transformada para que tenga ceros en ciertas

frecuencias normalizadas (pulsación normalizada / 2π), que, multiplicadas por la

frecuencia de muestreo dan como resultado las frecuencias que se quieren

eliminar, éstas resultarán eliminadas (se vuelve a hacer hincapié en que el presente

texto no pretende ahondar en los aspectos teóricos de los filtros FIR y los

teoremas de muestreo. Se puede consultar las referencias bibliográficas 1, 2 y 3

para más información). Como se quiere diseñar un filtro paso bajo, se hará de tal

Page 125: Control Motor Tesis

MEMORIA Sistema de Control

116

forma que elimine frecuencias equidistantes a partir de una pulsación normalizada

de π/2 hasta una pulsación normalizada de 3π/2.

Idealmente, se querrían tener tantos ceros entre esas dos frecuencias como

fuese posible, para eliminar el mayor número posible de altas frecuencias, pero

cuantos más ceros se introduzcan en la función, más carga de trabajo tendrá que

soportar el microprocesador, y más altos (y, por consiguiente, difíciles de escalar

en 8 bits, que es el tamaño de los registros del microprocesador utilizado)

resultarán los coeficientes que acompañan a las “z-n” en la transformada “z” del

filtro, los cuales son los mismos coeficientes que acompañan a las “x[n-k]” en la

ecuación en diferencias del filtro.

Se decidió que cinco ceros, en e±jπ/2, e±j3π/4 y ejπ , conforman un filtro que

cumple las características necesarias para la función que ha de desempeñar en el

diseño. Una vez redondeados los coeficientes, para su posterior implantación en el

microprocesador con enteros de 8 bits, queda la siguiente ecuación en diferencias

del filtro:

[ ]6

23456

z

2 + z 7 + z 12 + z 14 + z 12 + z 7 + z 2=ny [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:

Page 126: Control Motor Tesis

MEMORIA Sistema de Control

117

Figura 5.32: diagrama de ceros y polos del filtro FIR diseñado

Figura 5.33: diagrama de Bode del filtro FIR diseñado

Page 127: Control Motor Tesis

MEMORIA Sistema de Control

118

Figura 5.34: diagrama de bloques del filtro FIR diseñado

Como en el filtro de primer orden, una vez diseñado el filtro FIR, se procede a

diseñar el control mediante técnicas de respuesta en frecuencia en lazo abierto.

Se comienza, como en anteriores diseños, por el diseño del regulador del lazo

de control de corriente:

( )( )

==⇒=+=∠

−==

dBjG

sradjGdBA

dBc

m

8.16

/10·24.4º190º10º180

º10

8

0

300

ωωω

ϕ

( ) ( ) 058.0108.2488.16 20

8.24

00 ==⇒−=−−=−

ωω jCdBdBdBjCdB

( ) 3

00 10·34.1

º80tanº10·º90 −==⇒−=+−=

ωωϕ iic TTarctg

( ) ( )057.0058.0

·

·1

0

20

0 =⇒=+

= KT

TKjC

i

i

ωω

ω [5.22]

Page 128: Control Motor Tesis

MEMORIA Sistema de Control

119

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, después de aplicar el control

Page 129: Control Motor Tesis

MEMORIA Sistema de Control

120

Después de diseñar el regulador del lazo de control de corriente, se realiza el

diseño del regulador del lazo de control completo:

( )( )

==⇒=+=∠

−==Φ

dBjG

sradjG

dBc

m

6.33

/99.6º600º60º540

º10

º50

0

00

ωωω

ϕ

( ) ( ) 02.0106.33 20

6.33

00 ==⇒−=−

ωω jCdBjCdB

( ) 81.0º80tan

º10·º900

0 ==⇒−=+−=ω

ωϕ iic TTarctg

( ) ( )02.002.0

·

·1

0

20

0 =⇒=+

= KT

TKjC

i

i

ωω

ω [5.23]

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

Page 130: Control Motor Tesis

MEMORIA Sistema de Control

121

Figura 5.38: diagrama de Black del lazo completo abierto, una vez aplicado el

control

Una vez diseñados los dos reguladores en tiempo continuo, se procede a

efectuar la simulación de la respuesta del sistema en tiempo discreto ante un

escalón, dando como resultado la gráfica de la figura 5.39.

Si se comparan todas las gráficas obtenidas de la simulación de la respuesta del

sistema con y sin filtros, se puede determinar que el sistema ofrece una mejor

respuesta (al menos en simulación) sin filtrar la medida de corriente que le llega al

microprocesador. Por ello, se elige el mencionado diseño para desarrollar el

software pertinente en base a él, e implantarlo en el sistema físico.

Page 131: Control Motor Tesis

MEMORIA Sistema de Control

122

Figura 5.39: respuesta simulada del sistema ante un escalón

Page 132: Control Motor Tesis

MEMORIA Sistema de Control

123

5.6. Escalado del problema

Al realizar los diseños y simularlos en el ordenador, se ha trabajado siempre

con variables codificadas en formato de coma flotante y doble precisión. 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 más pequeño dentro de un

rango aceptable de resultados para trabajar con él.

El escalado se efectúa multiplicando las variables del sistema que están 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 número a multiplicar, y dicha operación de desplazamiento se efectúa de forma

muy rápida. Mediante estas operaciones se consigue que las variables estén 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 también los diferentes tiempos de

muestreo del sistema mediante distintos colores, así como el tipo de dato de todas

las señales 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

simulación se puede observar en la figura 5.43.

Page 133: Control Motor Tesis

MEMORIA Sistema de Control

124

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

Page 134: Control Motor Tesis

MEMORIA Sistema de Control

125

Figura 5.41: bloque PI3 escalado a 8 bits

Page 135: Control Motor Tesis

MEMORIA Sistema de Control

126

Figura 5.42: bloque PI4 escalado a 8 bits

Page 136: Control Motor Tesis

MEMORIA Sistema de Control

127

Figura 5.43: respuesta del sistema en coma flotante y del sistema escalado a enteros de 8,16 y 32 bits ante un escalón de amplitud 0.1 m/s.

Existe en el ensayo realizado con las variables escaladas a enteros de 8 bits un

pequeño error en régimen permanente, producido por dos causas: la primera de

ellas es el error que se introduce con la perdida de sensibilidad al realizar la

conversión A/D, en la cual, se pasa de valores continuos a valores discretos con

una sensibilidad igual al cociente entre el valor de tensión máximo de entrada al

conversor, y la n-ésima potencia de dos, siendo n el número de bits del conversor

A/D; la segunda causa es la pérdida de precisión 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

pérdida de información debida al desprecio de cifras decimales. En el escalado a

constantes de 16 y 32 bits no se aprecia prácticamente diferencia con las variables

en coma flotante y doble precisión. Se elige pues trabajar con el escalado a 16

bits.

Page 137: Control Motor Tesis

MEMORIA Sistema de Control

128

5.7. Conclusiones

Se presenta en este capítulo toda la información relativa al diseño del control

del sistema, desde los fundamentos teóricos básicos para comprender el

funcionamiento de los sistemas de control discreto y sus posibles métodos de

diseño, hasta el programa que se implantará en el microprocesador para realizar el

control del sistema.

Se ha tratado con bastante profundidad el diseño de los reguladores PI. En una

primera aproximación se diseñan aproximando los parámetros por simulación,

para comprobar posteriormente que este método de diseño no es el más acertado,

y se procede a diseñar aplicando técnicas de respuesta en frecuencia: diseño por

margen de fase y diseño 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 diseñan dos filtros digitales: un filtro paso bajo de

primer orden, y un filtro FIR paso bajo. Después de rediseñar el control para el

sistema incluyendo esos filtros, se comprueba mediante simulación que no

mejoran, sino que empeoran la respuesta del sistema.

Una vez claro el regulador que se va a utilizar (el diseñado por técnicas 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 precisión, que

disminuirían notablemente el rendimiento del microprocesador. Después de haber

realizado el escalado con los tres tipos de variables, se elige trabajar con enteros

de 16 bits, ya que son la variable más pequeña que ofrece una calidad aceptable en

las simulaciones.

Page 138: Control Motor Tesis

MEMORIA Implantación

129

Capítulo 6: Implantación 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 propósito general de 32 bits y una

memoria RAM estática de 64kB. En la figura 6.1 se puede observar un diagrama

de bloques con los distintos periféricos y funciones.

El soporte físico del microprocesador es un encapsulado MAPBGA de 256

pines. En la figura 6.2 se pueden observar las características mecánicas del

microprocesador.

La asignación de pines del microprocesador viene ilustrada en la figura 6.3, y

las características eléctricas se pueden observar en las tablas 6.1, 6.2 y 6.3.

El MCF5282 posee un conversor analógico/digital de 10 bits gestionado por

colas, que será fundamental para la medición de las diversas señales del circuito

(aceleración, intensidad por el motor, velocidad). Además, posee una salida PWM

configurable por software, y diversos timers y entradas/salidas de propósito

general, que serán utilizados en el proyecto.

Page 139: Control Motor Tesis

MEMORIA Implantación

130

Figura 6.1: diagrama de bloques del microprocesador

Page 140: Control Motor Tesis

MEMORIA Implantación

131

Figura 6.2: características mecánicas del microprocesador MCF5282

Figura 6.3: asignación de pines (pinout) del microprocesador

Page 141: Control Motor Tesis

MEMORIA Implantación

132

Tabla 6.1: características eléctricas máximas del M CF5282

Tabla 6.2: características eléctricas DC del MCF528 2

Page 142: Control Motor Tesis

MEMORIA Implantación

133

Tabla 6.3: características eléctricas DC del MCF528 2 (continuación)

Page 143: Control Motor Tesis

MEMORIA Implantación

134

6.2. Implantación: programación del microprocesador

La última fase del diseño del control es implantar éste en el microprocesador.

Para ello, se programarán en lenguaje C las instrucciones necesarias para tal fin,

con ayuda del compilador Freescale CodeWarrior©, el cual también se usará para

grabar el programa en el microprocesador.

Para llevar a cabo la implantación se usará el sistema operativo en tiempo real

(de ahora en adelante “SOTR”) FreeRTOS©. El SOTR FreeRTOS es un sistema

desarrollado en código abierto, por lo que, además 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 señal analógica de salida del circuito de acondicionamiento del

acelerómetro es pasada a digital en el conversor A/D.

2. Se ajusta el mando para alcanzar el valor de aceleración normal máxima

programada (a_max). Si el tren está en una recta, ese valor será imposible de

alcanzar, luego el tren desarrollará su máxima velocidad. Por el contrario, si

circula por una curva, se ajustará su velocidad para que mantenga la

aceleración normal cercana a la máxima dentro de unos márgenes.

3. Si se detecta una baliza, salta una interrupción que pone la referencia de

velocidad a un valor moderado (la mitad de la velocidad máxima 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

Page 144: Control Motor Tesis

MEMORIA Implantación

135

en función de la aceleración normal que se mida en cada instante, pasando de

nuevo al punto 1.

El programa se ha desarrollado en 3 módulos distintos: main.c, control.c y

configuración.c. Además, se han creado los archivos “.h” control.h,

configuración.h y constantes.h.

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

módulo, y a continuación se dará una explicación más detallada de las funciones

más relevantes.

Page 145: Control Motor Tesis

MEMORIA Implantación

136

Tabla 6.4: funciones asociadas a cada módulo

MÓDULO FUNCIÓN TAREA

Main.c Main Inicialización, creación de tareas y arranque

del planificador.

Configuración

.c

InitM5282Lite_ES Inicialización

InitPWM Inicialización PWM.

SetPWM Fija un Duty Cycle en el PWM.

Control.c

InitControl Inicialización.

ADCTask

(TAREA)

Tarea que realiza conversiones en el conversor

A/D.

Control (TAREA)

Tarea que realiza las gestiones para modificar

la referencia de velocidad del tren de acuerdo

a la aceleración normal leída en cada instante.

CopiaRef

CopiaEnRef

Funciones de copia de datos para proteger

zonas críticas.

PI1 y PI2

Funciones que realizan el control PI discreto

en el lazo de corriente y el lazo de velocidad

del control.

QadcInit Inicialización del conversor A/D.

ArrancaConversion Arranca la conversión en AN0-AN3.

Convirtiendo

Función de encuesta que devuelve 1 si el

conversor A/D está ejecutando una conversión

en ese momento.

LeeAN0, 1, 2 y 3 Lee el valor digital convertido en el conversor

analógico para las 4 entradas.

Interrupts

(en Control.c)

IntGPTA0 Salta cuando hay flanco de subida en GPTA0.

Detección de baliza. Modera la referencia.

IntPIT0

Salta cada 0.5ms (tiempo de muestreo).

Realiza el control del lazo de corriente y

velocidad.

Page 146: Control Motor Tesis

MEMORIA Implantación

137

6.2.1. Main

En la función main se realizan todas las inicializaciones pertinentes para el

correcto funcionamiento del programa. Desde esta función se llamará a

InitM5282Lite_ES, InitPWM, QadcInit e InitControl. Acontinuación se crearán

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 función:

Figura 6.4: diagrama de flujo de la función main

Page 147: Control Motor Tesis

MEMORIA Implantación

138

6.2.2. Control

La tarea de control se ejecuta cada 20 ms, y realiza los cálculos necesarios para

la gestión de la referencia de velocidad del tren, en función de la aceleración

normal medida. La figura 6.5 muestra su diagrama de flujo.

Figura 6.5: diagrama de flujo de la tarea de control

Page 148: Control Motor Tesis

MEMORIA Implantación

139

6.2.3. ADCTask

La tarea ADCTask realiza las conversiones de analógico 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

Page 149: Control Motor Tesis

MEMORIA Implantación

140

6.2.4. IntGPTA0

IntGPTA0 es la interrupción 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 interrupción IntGPTA0

6.2.5. IntPIT0

La interrupción 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 interrupción 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 más rápido que el de velocidad).

Page 150: Control Motor Tesis

MEMORIA Implantación

141

La figura 6.8 presenta su diagrama de bloques:

Figura 6.8: diagrama de flujo de la interrupción PIT0

Page 151: Control Motor Tesis

MEMORIA Implantación

142

6.2.6. Programación del regulador PI discreto

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 sección 5.2, queda:

sTkeke

kIekeI

kmedidakreferenciake

·2

]1[][]1[][

][][][

−++−=

−= [5.24]

Donde:

• e[k] = error en el instante k

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

stkeke

kIekIe

kekeke

·2

]1[][][][

]1[][][

−++=∆

−−=∆ [5.25]

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

∆+∆=∆ ][

1][·][ kIe

TkeKkm

i

[5.26]

Y el mando en un instante k:

]1[][][ −+∆= kmkmkm [5.27]

Page 152: Control Motor Tesis

MEMORIA Implantación

143

Luego, si se programa una subrutina llamada “PI” que efectúe 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 = K * (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 debía realizar el microprocesador han sido

implementadas con éxito.

Page 153: Control Motor Tesis

MEMORIA Implantación

144

Figura 6.9: diagrama de flujo del sistema completo

Page 154: Control Motor Tesis

MEMORIA Implantación

145

6.3. Conclusiones El presente capítulo comienza con una recopilación de datos útiles sobre el

microprocesador Motorola ColdFire MCF5282, tales como sus características

eléctricas y mecánicas, o aquellas de sus funcionalidades que van a ser útiles en el

proyecto.

A continuación, 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, gestión de salidas mediante onda

PWM… Se hace un repaso general de todas las funciones que se utilizarán a lo

largo del programa, y se profundiza en aquellas funciones y tareas que son de más

relevancia para la comprensión del funcionamiento del programa.

El capítulo concluye con el desarrollo de la programación de los módulos 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.

Page 155: Control Motor Tesis

MEMORIA Resultados

146

Capítulo 7: Resultados experimentales

7.1. Introducción

Se tratarán en este capítulo 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

señal Thandar TG501. Se realizaron medidas con un osciloscopio Tektroniks TDS

1002B en distintos puntos del circuito, para verificar que su tensión se hallaba

dentro de los límites esperados.

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

Page 156: Control Motor Tesis

MEMORIA Resultados

147

Figura 7.2 : generador de señales Thandar TG501

Figura 7.3: osciloscopio Tektroniks TDS 1002B

Page 157: Control Motor Tesis

MEMORIA Resultados

148

Se pueden observar a continuación 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

Page 158: Control Motor Tesis

MEMORIA Resultados

149

7.3. Pruebas del prototipo

Se realizaron pruebas con un prototipo para cerciorarse de que el sistema, a

falta de la implantación de los acelerómetros, funcionaba correctamente:

Figura 7.6: prototipo final

A través del sistema de control se fue variando a placer la velocidad de la

maqueta de tren, cuyo motor es alimentado a través de las vías, quedando así

constancia de la efectividad del diseño.

Page 159: Control Motor Tesis

MEMORIA Conclusiones

150

Capítulo 8: Conclusiones y trabajo futuro

Antes de realizar el diseño del control, es necesario conocer y modelar los

distintos parámetros físicos que intervienen en el sistema a controlar. La

metodología seguida para obtener los distintos parámetros necesarios a la hora de

diseñar el control, así como la base teórica sobre la que se sustentan los cálculos

realizados para dicha obtención de los mencionados parámetros se encuentra

desarrollada en el capítulo segundo.

Una vez obtenidos dichos parámetros, se ha procedido a obtener un modelo del

sistema, a partir de cual trabajar en el diseño del control, ya que, sin una

modelización del sistema físico, sería imposible realizar dicho diseño o las

simulaciones pertinentes para comprobar la validez del mismo.

El control ha de ir implantado sobre un hardware. Se ha expuesto en el capítulo

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 tensión que han sido utilizados.

En una primera sección se ha hablado de todo el diseño de la etapa de potencia,

exponiendo los cálculos, así como información detallada de todos los elementos

que la componen: optoacoplador, inversor y puente en H.

En la segunda sección se han presentado los distintos tipos de reguladores

existentes, y se ha argumentado la elección de uno de ellos sobre el resto.

Además, se han propuesto diseños alternativos de los reguladores para que, en

caso de una fabricación en serie del prototipo que se propone en el presente

proyecto, los gastos en componentes disminuyan drásticamente en esta parte del

circuito.

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

señal que se han utilizado. Éstos cumplen la función de acondicionar las señales

que se desean medir para realimentar el control de manera que dicha medición se

Page 160: Control Motor Tesis

MEMORIA Conclusiones

151

efectúe con la mayor precisión y sensibilidad posibles, y sin perturbar a la señal

original. Para ello se han utilizado básicamente etapas basadas en amplificadores

operacionales, tanto en realimentación negativa como en bucle abierto, diodos

zener para la protección del microprocesador, y los propios elementos cuya señal

se había de acondicionar.

La última etapa de diseño es la relativa al diseño del control del sistema. Se han

presentado pues en el capítulo quinto, desde los fundamentos teóricos básicos para

comprender el funcionamiento de los sistemas de control discreto y sus posibles

métodos de diseño, hasta el programa que se ha implantado en el microprocesador

para realizar el control del sistema.

Se ha tratado con bastante profundidad el diseño de los reguladores PI. En una

primera aproximación se diseñan aproximando los parámetros por simulación,

para comprobar posteriormente que este método de diseño no es el más acertado,

y se procede a diseñar aplicando técnicas de respuesta en frecuencia: diseño por

margen de fase y diseño 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 diseñan dos filtros digitales: un filtro paso bajo de

primer orden, y un filtro FIR paso bajo. Después de rediseñar el control para el

sistema incluyendo esos filtros, se ha comprobado mediante simulación que no

mejoran, sino que empeoran la respuesta del sistema.

Una vez claro el regulador que se va a utilizar (el diseñado por técnicas 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 precisión, tal y como se trabaja en las simulaciones). Después 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

Page 161: Control Motor Tesis

MEMORIA Conclusiones

152

que el tipo de variable más 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, gestión

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 diseño, se deben realizar las pruebas pertinentes sobre un

prototipo para verificar que el sistema funciona correctamente. Desde un principio

se concibió el diseño 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 diseño de éste no presentaba ninguna

problemática.

Cabe destacar que, a medida que se fueron realizando los diversos avances en

el diseño, éstos se fueron acompañando de la documentación necesaria para la

elaboración de la presente memoria. Además, también se fueron diseñando 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 sección de planos, a

continuación de la presente memoria. Para este fin se utilizaron los programas

OrCAD Capture® y OrCAD LayOut®.

Como trabajo futuro, sería muy interesante la implantación de un sistema de

transmisión de todas las señales que maneja el sistema cumpliendo los estándares

eléctricos 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

transmisión de señales de acuerdo a estos estándares se realiza por medio de

Page 162: Control Motor Tesis

MEMORIA Conclusiones

153

pulsos eléctricos transmitidos por medio de las vías del tren, y en el presente

proyecto se utiliza una señal PWM que se transmite también por las mismas vías

para llegar al motor del tren, sería complicado distinguir entre los pulsos de la

señal de comunicación y los pulsos generados por el ruido de la onda PWM, o la

propia onda PWM. Éste problema se podría solucionar por medio de filtrado, pues

la frecuencia de la onda PWM es conocida, y la frecuencia de las ondas de pulsos

de comunicación también lo sería, el problema radica en que el ruido generado

por el PWM podría distorsionar distintas frecuencias, incluida aquélla en la que se

transmite la onda de pulsos de comunicación.

Page 163: Control Motor Tesis

MEMORIA Agradecimientos

154

Agradecimientos

Una vez terminado el proyecto, sólo queda mirar atrás con una expresión de

satisfacción en el rostro, y agradecer a todas esas personas que han hecho

posible la realización del mismo:

En primer lugar, he de darles las gracias a mis padres, por toda la paciencia

que a lo largo de todos estos años han tenido conmigo, y porque sin su ayuda y

apoyo, nada habría sido posible.

He de agradecer también 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 gustaría darle las gracias profundamente a mi director de proyecto, D.

Eduardo Santamaría, por haber confiado en mí, y haberme dado la oportunidad

de trabajar con él desde la lejana y árida Arizona, cuando no había ningún

precedente de dirección de proyecto a distancia.

Por último, y aunque prácticamente no han tenido nada que ver de una forma

directa con este proyecto, por ser éste el punto final de mis cincos últimos años de

estudios, me gustaría mencionar a D. Félix Alonso y a D. Santiago Canales, por

haberme sabido inculcar allá en primer curso valores tan importantes como el

trabajo y el esfuerzo.

Page 164: Control Motor Tesis

MEMORIA Bibliografía

155

Bibliografía

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 modelación.” Ed. Oxford University Press, 2002

7. [MARC90] MARCELLÁN, F.-CASASUS, L.-ZARZO, A . “Ecuaciones

diferenciales” Ed. McGraw-Hill, 1990

8. [GARC06] GARCÍA, A.-GARCÍA, F.- LÓPEZ, A.- RODRÍGUE Z, G.-

ROMERO, S.- VILLA, A de la . “Ecuaciones diferenciales ordinarias.

Teoría y problemas. Métodos exactos. Métodos numéricos. Estudio

cualitativo” Ed. CLAGSA, 2006

9. [PAGO06] PAGOLA, LUIS. “Regulación Automática” Ed. Universidad

Pontificia Comillas, 2006

10. [NISE04] NISE. “Control Systems Engineering” Ed. Wiley, 2004

11. [MUÑO09] MUÑOZ FRÍAS, JOSÉ DANIEL. “Sistemas Empotrados en

Tiempo Real” Creative Commons. Febrero 2009

Page 165: Control Motor Tesis

MEMORIA Bibliografía

156

Relación de páginas web consultadas, agrupadas por temática:

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/maquinista-

tren-descarrilado-parres-20090225.html

• http://www.tribuna.net/noticia/27502/CASTILLA-Y-LEÓN/seis-muertos-

heridos-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-tren-

provincia-palencia/sernotnac/20060821csrcsrnac_10/Tes

ARTÍCULO 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

Page 166: Control Motor Tesis

Fdo.: Fernando Moreno Pérez

Madrid, 17 de Junio de 2010

Page 167: Control Motor Tesis

MEMORIA Anexos

157

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. Capítulo 10: Interrupt Controller Modules

- Anexo 3.2. Capítulo19: Programmable Interrupt Timer Modules

(PIT0-PIT3)

- Anexo 3.3. Capítulo 20: General Purpose Timer Modules (GPTA and

GPTB)

- Anexo 3.4. Capítulo 28: Queued Analog-to-Digital Converter (QADC)

- Anexo 3.5.Capítulo 33: Características Eléctricas

• 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 características (Datasheets)

- Anexo 6.1. Fotodiodo selectivo EPD-740-5

- Anexo 6.2. Acelerómetro ADXL320

- Anexo 6.3. Optoacoplador ILQ74

- Anexo 6.4. Puente en H L298

Page 168: Control Motor Tesis

ANEXO 1

Programa completo en lenguaje C

Page 169: Control Motor Tesis

MEMORIA Anexo I

/*Main.c * Autor: Fernando Moreno * Última modificación: 6/Jun/2010 */ #include "Constantes.h" int main() InitM5282Lite_ES(); //Inicializa los perifericos del M5282 InitPWM(); //Inicializa el PWM con una resolución de PWM_RESOLUTION unidades. QadcInit(); //Inicializa el conversor AD InitControl(); //Inicializa registros y variables utilizadas por el control //Creación 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(); //Arranca el planificador (scheduler)

Page 170: Control Motor Tesis

MEMORIA Anexo I

/*Control.c * Autor: Fernando Moreno * Última modificación: 6/Jun/2010 */ #include Control.h static int16 duty_cycle_variation; static int16 periodo; static int16 referencia_velocidad; //L a referencia de velocidad en unidades físicas (m/s) v a 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) //Configuración interrupciones puerto GPTA MCF_GPTA_GPTCTL2=0x55; //Interrumpe en flanco de su bida a cada uno de los canales MCF_GPTA_GPTIE=0x0F; //Habilita interrupciones de l os 4 canales de GPTA. MCF_GPTA_GPTSCR1=0x80; MCF_INTC0_ICR44 = 0x08; /* Nivel 1 Prioridad 0 */ MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK44; /* Tim er Channel 0 Desenmascarada */ *(void **)(0x20000000 +(64+44)*4) = (void *)IntGPTA 0; MCF_INTC0_ICR45 = 0x08; /* Nivel 1 Prioridad 1 */ MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK45; // Tim er Channel 1 Desenmascarada *(void **)(0x20000000 +(64+45)*4) = (void *)IntGPTA 1; MCF_INTC0_ICR46 = 0x08; /* Nivel 1 Prioridad 2 */ MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK46; /* Tim er Channel 2 Desenmascarada */ *(void **)(0x20000000 +(64+46)*4) = (void *)IntGPTA 2; MCF_INTC0_ICR47 = 0x08; /* Nivel 1 Prioridad 3 */ MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK47; /* Tim er Channel 3 Desenmascarada */ *(void **)(0x20000000 +(64+47)*4) = (void *)IntGPTA 3;

Page 171: Control Motor Tesis

MEMORIA Anexo I

//Confguración interrupciones PIT0 MCF_INTC0_ICR55 = 0x08; /* Nivel 1 Prioridad 4 */ MCF_INTC0_IMRH &= ~MCF_INTC_IMRH_INT_MASK55; /* Tim er Channel 0 Desenmascarada */ *(void **)(0x20000000 +(64+55)*4) = (void *)IntPIT0 ; //Configuración PIT0 para que salte con un periodo de 500us MCF_PIT0_PCSR = 0x51B; //prescalado de 64, DOZE, HA LTED 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. //Configuración 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))//Equivaldría a 2G menos un error, puesto que el conversor AD da 1024 para 4G, según cálculos del circuito de acondicionamiento. ref_vel = ref_vel + INC_REF; else if(acel>(SAT_AD/2))

Page 172: Control Motor Tesis

MEMORIA Anexo I

ref_vel = ref_vel - INC_REF; CopiaEnRef(ref_vel); 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;

Page 173: Control Motor Tesis

MEMORIA Anexo I

Ie_act = *pIe_ant + (e_act + *pe_ant) * 3; inc_mando = 3 * (((e_act-(*pe_ant))*16) + (((Ie_a ct-(*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 d e dos colas en las

Page 174: Control Motor Tesis

MEMORIA Anexo I

* que se pueden programar la realización de una se rie de conversiones * automáticas de una serie de canales, de forma qu e se interrumpa al * micro (o se active el bit de final de conversión si usamos * encuesta) cuando finalice la secuencia de conversiones. * * En esta librería simple se usa una sola cola pa ra convertir los * canales 0, 1, 2 y 3 (entradas AN0, AN1, AN2 y AN 3). La conversión 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 * función ArrancaConversion(). Por último, el bit 15 del registro de * estado de la cola QASR0 se pone a 1 cuando final iza la secuencia de * conversiones. La función Convirtiendo() comprueb a este bit y * devuelve un 1 si la conversión aún está en march a o un cero si ha * terminado. */ void QadcInit(void) MCF_QADC_QADCMCR = 0; /* Arranca el módulo del conversor AD. Accesible en modo usuario */ MCF_QADC_DDRQA = 0; /* los pines se definen como entrada pues si por algo están configurados como */ MCF_QADC_DDRQB = 0; /* salida digital el converso r no funcionará */ MCF_QADC_QACR0 = 7; /* Mux interno, división 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*/

Page 175: Control Motor Tesis

MEMORIA Anexo I

MCF_QADC_QACR2 = 0x7f; /* No se usa la cola 2. BQ 2 = 7f (>64) para indicarlo) */ MCF_QADC_CCW(0) = 0; /* Primera conversión: AN0 */ MCF_QADC_CCW(1) = 1; /* Segunda conversión: AN1 */ MCF_QADC_CCW(2) = 2; /* Tercera conversión: AN2 */ MCF_QADC_CCW(3) = 3; /* Cuarta conversión: AN3 * / MCF_QADC_CCW(4) = 63; /* Fin de la cola */ vSemaphoreCreateBinary(sem_AD); //Crea el semáfor o 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 aún */ 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);

Page 176: Control Motor Tesis

MEMORIA Anexo I

__declspec(interrupt) IntGPTA0(void) //Interrupción: Detección baliza MCF_GPTA_GPTFLG1|=(0x1<<0);//Baja el flag //Si salta interrupcion, hay flanco de subida en GP TA0 -> 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) //Interrupción: Tiempo de muestreo MCF_PIT0_PIF&=(0x1); // Clear flag by writting 1 to it medida_i = LeeAN3; if(!(MCF_GPIO_SETA&1)) //La condición se cumple s i 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 analógico; 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);

Page 177: Control Motor Tesis

MEMORIA Anexo I

/*Control.h * Autor: Fernando Moreno * Última modificación: 1/Jun/2010 */ #ifndef Control_h #define Control_h #include "Constantes.h" /* Función: InitControl * * Inicializa las interrupciones en el puerto GPTA, para * que salte una interrupción con la detección de u na baliza. * y configura el PIT0 y el GPIO. * Versión: 0.0 */ void InitControl(void); /* Función: ADCTask * * Tarea que realiza las conversiones A/D, * controlada por el planificador. * * Versión: 0.0 */ void ADCTask(void *pvParameters) /* Función: Control * * Tarea que realiza el control de la referencia de velocidad cada 20ms * * Versión: 0.0 */ void Control(void *pvParameters); /* Función: CopiaRef * * Copia la referencia de velocidad * * Versión: 0.0 */ uint16 CopiaRef(void); /* Función: CopiaEnRef *

Page 178: Control Motor Tesis

MEMORIA Anexo I

* Copia la referencia de velocidad calculada en la tarea de Control. * * Versión: 0.0 */ uint16 CopiaEnRef(void); /* Función: PI1 * * Realiza un control PI incremental en tiempo disc reto a partir * de los parámetros de entrada * * Versión: 0.0 */ int PI1(int referencia,int salida, int* pe_ant, int * pIe_ant, int K, int Ti); /* Función: PI2 * * Realiza un control PI incremental en tiempo disc reto a partir * de los parámetros de entrada * * Versión: 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*/ /* Función: QadcInit * * Inicializa en conversor AD para medir las entrad as AN0, AN1, AN2 y AN3. El final de * la conversión se realizará por encuesta mediante la función Convirtiendo(). * * Versión: 0.0 */ void QadcInit(void); /* Función: ArrancaConversion * * Arranca una conversión. Se convertirán los canal es * AN0, AN1, AN2 y AN3. * * Versión: 0.0 */

Page 179: Control Motor Tesis

MEMORIA Anexo I

void ArrancaConversion(void); /* Función: Convirtiendo * * Consulta el registro de estado del conversor A/D y devuelve un 1 si se está * realizando la conversión o un cero si ésta ha terminado. * * Versión: 0.0 */ int Convirtiendo(); /* Función: LeeAN0 * * Devuelve el resultado de la conversión A/D del c anal AN0 * El valor es de 10 bits, de forma que 0V se tradu cen en el valor 0 y 3.3 V * en 1023. Los bits 10 a 15 estarán siempre a 0. * * Versión: 0.0 */ uint16 LeeAN0(void); /* Función: LeeAN1 * * Idem LeeAN0 pero para el canal AN1 * * Versión: 0.0 */ uint16 LeeAN1(void); /* Función: LeeAN2 * * Idem LeeAN0 pero para el canal AN2 * * Versión: 0.0 */ uint16 LeeAN2(void); /* Función: LeeAN3 * * Idem LeeAN0 pero para el canal AN3 * * Versión: 0.0 */ uint16 LeeAN3(void);

Page 180: Control Motor Tesis

MEMORIA Anexo I

/*Interrupciones*/ /* Interrupción: IntGPTA0 * * Interrupción de detección de baliza * * Versión: 0.0 */ __declspec(interrupt) IntGPTA0(void) /* Interrupción: IntPIT0 * * Interrupción para realizar el control cada tiemp o de muestreo. * * Versión: 0.0 */ __declspec(interrupt) IntPIT0(void) #endif

Page 181: Control Motor Tesis

MEMORIA Anexo I

/* Funciones para el manejo del conversor AD y el P WM */ #include "Configuracion.h" /*Puerto salida PWM*/ /* Inicialización 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 o ff */ sim.gpt[GPT_NUM].ios=0x0f; /* Turn on output compar e 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 wi th 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 initia l compare values */ sim.gpt[GPT_NUM].c3=PWM_RESOLUTION;

Page 182: Control Motor Tesis

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_RESOLU TION;

Page 183: Control Motor Tesis

MEMORIA Anexo I

/* Funciones para el manejo del conversor A/D y el * modulador de ancho de pulso. * * Autor: Modificado: Fernando Moreno Pérez * * Versión: 0.1 */ #ifndef Configuracion_h #define Configuracion_h #include "Constantes.h" /* Función: InitM5282Lite_ES * * Inicializa el generador de Chip Select del ColdF ire para direccionar la * CPLD de la tarjeta M5282Lite-ES. * Es necesario llamar a esta función antes de usar los interruptores/LEDS * o el teclado. * * Versión: 0.0 */ void InitM5282Lite_ES(void); /* Funciones para el manejo del generador PWM*/ /* Función: InitPWM * * Inicializa la señal PWM en el pin GPTA0 del microprocesador, con *un DUTY_CYCLE del 50%, y una resolución igual al parámetro *definido como PWM_RESOLUTION (ha de ser 1000 para que la *frecuencia del PWM sea de 32kHz). * * Versión: 0.0 */ void InitPWM(void) /* Función: SetPWM * * Cambia el valor de comparación del PWM por el * valor del parámetro p0. * * Versión: 0.0 */ void SetPWM(int p0)

Page 184: Control Motor Tesis

MEMORIA Anexo I

#endif

Page 185: Control Motor Tesis

MEMORIA Anexo I

/*Constantes.h * Autor: Fernando Moreno * Última modificación: 6/Jun/2010 */ //Archivo .h que engloba todos los defines y los includes utilizados. #ifndef CONSTANTES_H #define CONSTANTES_H #include "mcf5282.h" #include "M5282Lite-ES.h" //Includes del kernel #include "FreeRTOS.h" #include "semphr.h" #include "task.h" #include "queue.h" #include "semphr.h" //defines #define SAT 32768 //16 bits #define SAT_AD 1020 //10 bits #define MAN_SAT1 32768 #define MAN_SAT2 32768 #define MEDIR_VEL 1 #define INC_REF 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 //G´s -> vienen dadas por el circuito de acondicionamiento #define PER_CTRL 8 //Para que el periodo de la tarea control sea 20 ms #endi

Page 186: Control Motor Tesis

ANEXO 2

Archivos “.m” utilizados en Matlab

Page 187: Control Motor Tesis

Inicializacion_PWM_con_filtro.m%Inicializacion Parametros Proyecto Control de Velocidad por Microprocesadors=tf('s');

% ----- SIN SIMULACION ----- %

%PARAMETROS NUMERICOSKe=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 microts=tiempo_muestreo;

%PARAMETROS DE CONTROL%PI1K_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;%PI2K_pi2 = 3920.5; %OKTi_pi2 = 3.38e-3; %OKb_pi2 = 1; %OK ts_pi2 = tiempo_muestreo;sat_sup_man_pi2 = 3; %1;sat_inf_man_pi2 = -3; %-1;OK=1

Page 1

Page 188: Control Motor Tesis

ANEXO 3

Manual del microprocesador

Page 189: Control Motor Tesis

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 10-1

Chapter 10 Interrupt Controller ModulesThis section details the functionality for the MCF5282 interrupt controllers (INTC0, INTC1). The generalfeatures 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 controllerson the MCF5282 handle the complete set of interrupt sources from all of the modules on the device. Thissection describes how the interrupt sources are mapped to the interrupt controller logic and how interruptsare serviced.

10.1 68K/ColdFire Interrupt Architecture OverviewBefore continuing with the specifics of the MCF5282 interrupt controllers, a brief review of the interruptarchitecture 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-bitencoded interrupt priority level sent from the interrupt controller to the core, providing 7 levels of interruptrequests. Level 7 represents the highest priority interrupt level, while level 1 is the lowest priority. Theprocessor samples for active interrupt requests once per instruction by comparing the encoded prioritylevel against a 3-bit interrupt mask value (I) contained in bits 10:8 of the machine’s status register (SR). Ifthe priority level is greater than the SR[I] field at the sample point, the processor suspends normalinstruction execution and initiates interrupt exception processing. Level 7 interrupts are treated asnon-maskable and edge-sensitive within the processor, while levels 1-6 are treated as level-sensitive andmay 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 thenfetches an 8-bit vector from the interrupt controller. This byte-sized operand fetch is known as the interruptacknowledge (IACK) cycle with the ColdFire implementation using a special encoding of the transfer typeand transfer modifier attributes to distinguish this data fetch from a “normal” memory access. The fetcheddata provides an index into the exception vector table which contains 256 addresses, each pointing to thebeginning of a specific exception service routine. In particular, vectors 64 - 255 of the exception vectortable are reserved for user interrupt service routines. The first 64 exception vectors are reserved for theprocessor to handle reset, error conditions (access, address), arithmetic faults, system calls, etc. Once theinterrupt 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 statusregister data, along with the 32-bit program counter value of the instruction that was interrupted (seeSection 2.6, “Exception Stack Frame Definition” for more information on the stack frame format). Afterthe exception stack frame is stored in memory, the processor accesses the 32-bit pointer from the exceptionvector table using the vector number as the offset, and then jumps to that address to begin execution of the

Page 190: Control Motor Tesis

Interrupt Controller Modules

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

10-2 Freescale Semiconductor

service routine. After the status register is stored in the exception stack frame, the SR[I] mask field is setto the level of the interrupt being acknowledged, effectively masking that level and all lower values whilein the service routine. For many peripheral devices, the processing of the IACK cycle directly negates theinterrupt request, while other devices require that request to be explicitly negated during the processing ofthe service routine. For the MCF5282, the processing of the interrupt acknowledge cycle is fundamentally different thanprevious 68K/ColdFire cores. In the new approach, all IACK cycles are directly handled by the interruptcontroller, so the requesting peripheral device is not accessed during the IACK. As a result, the interruptrequest must be explicitly cleared in the peripheral during the interrupt service routine. For moreinformation, see Section 10.1.1.3, “Interrupt Vector Determination.”Unlike the M68000 family, all ColdFire processors guarantee that the first instruction of the service routineis 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 peripheralto negate the interrupt request. For more information on exception processing, see the ColdFire Programmer’s Reference Manual athttp://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 interruptsources are organized as 7 levels, with each level supporting up to 9 prioritized requests. Consider thepriority structure within a single interrupt level (from highest to lowest priority) as shown in Table 10-1.

The level and priority is fully programmable for all sources except interrupt sources 1–7. Interrupt source1–7 (from the Edgeport module) are fixed at the corresponding level’s midpoint priority. Thus, a maximumof 8 fully-programmable interrupt sources are mapped into a single interrupt level. The “fixed” interruptsource is hardwired to the given level, and represents the mid-point of the priority within the level. For thefully-programmable interrupt sources, the 3-bit level and the 3-bit priority within the level are defined inthe 8-bit interrupt control register (ICRnx).The operation of the interrupt controller can be broadly partitioned into three activities:

Table 10-1. Interrupt Priority Within a Level

ICR[2:0] PriorityInterrupt Sources

111 7 (Highest) 8-63

110 6 8-63

101 5 8-63

100 4 8-63

— Fixed Midpoint Priority 1-7

011 3 8-63

010 2 8-63

001 1 8-63

000 0 (Lowest) 8-63

Page 191: Control Motor Tesis

68K/ColdFire Interrupt Architecture Overview

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 10-3

• 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 todetermine 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-bitdecoded priority level (IRQ[7:1]) is driven out of the interrupt controller. The decoded priority levels fromall the interrupt controllers are logically summed together and the highest enabled interrupt request is thenencoded 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 generatesan interrupt acknowledge cycle (IACK). The IACK transfer is treated as a memory-mapped byte read bythe processor, and routed to the appropriate interrupt controller. Next, the interrupt controller extracts thelevel being acknowledged from address bits[4:2], and then determines the highest priority interrupt requestactive for that level, and returns the 8-bit interrupt vector for that request to complete the cycle. The 8-bitinterrupt 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, thefollowing 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 vectornumber.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 errorsituation.Note this protocol implies the interrupting peripheral is not accessed during the acknowledge cycle sincethe interrupt controller completely services the acknowledge. This means the interrupt source must beexplicitly disabled in the interrupt service routine. This design provides unique vector capability for allinterrupt requests, regardless of the “complexity” of the peripheral device.

Page 192: Control Motor Tesis

Interrupt Controller Modules

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

10-4 Freescale Semiconductor

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

10.2 Memory MapThe register programming model for the interrupt controllers is memory-mapped to a 256-byte space. Inthe following discussion, there are a number of program-visible registers greater than 32 bits in size. Forthese control fields, the physical register is partitioned into two 32-bit values: a register “high” (the upperlongword) and a register “low” (the lower longword). The nomenclature <reg_name>H and <reg_name>Lis used to reference these values.The registers and their locations are defined in Table 10-3. The offsets listed start from the base addressfor 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 IPSBAR + 0xD00

Global IACK Registers Space1

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

IPSBAR + 0xF00

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] Reserved

0x1c - 0x3c 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

Page 193: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 10-5

10.3 Register Descriptions

10.3.1 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 bitmap 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 clearedby reset. The IPRn is a read-only register, so any attempted write to this register is ignored. Bit 0 is notimplemented and reads as a zero.

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 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

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

Module Offset Bits[31:24] Bits[23:16] Bits[15:8] Bits[7:0]

Page 194: Control Motor Tesis

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 19-1

Chapter 19 Programmable Interrupt Timer Modules (PIT0–PIT3)

19.1 OverviewThe programmable interrupt timer (PIT) is a 16-bit timer that provides precise interrupts at regularintervals with minimal processor intervention. The timer can either count down from the value written inthe modulus register, or it can be a free-running down-counter. This device has four programmableinterrupt timers, PIT0–PIT3.

19.2 Block Diagram

Figure 19-1. PIT Block Diagram

16-bit PMR

16-bit PIT CounterCOUNT = 0

SystemClock

IPBUS

16-bit PCNTR

IPBUS

ENOVW

DOZE

HALTED

Prescaler

PRE[3:0] RLD

PIF

PIE

LoadCounter

To InterruptController

Divideby 2

Page 195: Control Motor Tesis

Programmable Interrupt Timer Modules (PIT0–PIT3)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

19-2 Freescale Semiconductor

19.3 Low-Power Mode OperationThis subsection describes the operation of the PIT modules in low-power modes and halted mode ofoperation. Low-power modes are described in the Power Management Module. Table 19-1 shows the PITmodule operation in low-power modes, and how it can exit from each mode.

NOTEThe low-power interrupt control register (LPICR) in the System ControlModule specifies the interrupt level at or above which the device can bebrought out of a low-power mode.

Table 19-1. PIT Module Operation in Low-power Modes

In wait mode, the PIT module continues to operate as in run mode and can be configured to exit thelow-power mode by generating an interrupt request. In doze mode with the PCSR[DOZE] bit set, PITmodule operation stops. In doze mode with the PCSR[DOZE] bit cleared, doze mode does not affect PIToperation. 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 thePCSR[HALTED] bit cleared, halted mode does not affect PIT operation. When halted mode is exited, thePIT continues to operate in its pre-halted mode state, but any updates made in halted mode remain.

19.4 SignalsThe PIT module has no off-chip signals.

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 No

Halted Normal if PCR[HALTED] cleared, stopped otherwise

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

Page 196: Control Motor Tesis

Memory Map and Registers

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 19-3

19.5 Memory Map and RegistersThis subsection describes the memory map and register structure for PIT0–PIT3.

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 addresslocations for each timer.PIT0: 0x0015_0000PIT1: 0x0016_0000PIT2: 0x0017_0000PIT3: 0x0018_0000

19.5.2 Registers

The PIT programming model consists of these registers: • The PIT control and status register (PCSR) configures the timer’s operation.• The PIT modulus register (PMR) determines the timer modulus reload value.• The PIT count register (PCNTR) provides visibility to the counter value.

Table 19-2. Programmable Interrupt Timer Modules Memory Map

IPSBAR Offset for PITxAddress

Bits 15–8 Bits 7–0 Access1

1 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.

0x001x_0000 PIT Control and Status Register (PCSR) S

0x001x_0002 PIT Modulus Register (PMR) S

0x001x_0004 PIT Count Register (PCNTR) S/U

0x001x_0006 Unimplemented2

2 Accesses to unimplemented address locations have no effect and result in a cycle termination transfer error.

Page 197: Control Motor Tesis

Programmable Interrupt Timer Modules (PIT0–PIT3)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

19-4 Freescale Semiconductor

19.5.2.1 PIT Control and Status Register (PCSR)

15 12 11 10 9 8

Field — PRE3 PRE2 PRE1 PRE0

Reset 0000_0000

R/W R R/W

7 6 5 4 3 2 1 0

Field — DOZE HALTED OVW PIE PIF RLD EN

Reset 0000_0000

R/W R R/W

Address 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 Description

15–12 — Reserved, should be cleared.

11–8 PRE 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.

7 — Reserved.

PRE System Clock Divisor PRE System Clock Divisor

0000 2 1000 512

0001 4 1001 1,024

0010 8 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

Page 198: Control Motor Tesis

Memory Map and Registers

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 19-5

19.5.2.2 PIT Modulus Register (PMR)

The 16-bit read/write PMR contains the timer modulus value that is loaded into the PIT counter when thecount 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 loadedinto the PIT counter. The prescaler counter is reset anytime a new value is loaded into the PIT counter andalso during reset. Reading the PMR returns the value written in the modulus latch. Reset initializes PMRto 0xFFFF.

6 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 mode1 PIT function stopped in doze modeWhen doze mode is exited, timer operation continues from the state it was in before entering doze mode.

5 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 mode1 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.

4 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.

3 PIE PIT interrupt enable. This read/write bit enables the PIF flag to generate interrupt requests.0 PIF interrupt requests disabled1 PIF interrupt requests enabled

2 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.

1 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 0x00001 Counter reloaded from PMR on count of 0x0000

0 EN 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 disabled1 PIT enabled

Table 19-3. PCSR Field Descriptions (continued)

Bit(s) Name Description

Page 199: Control Motor Tesis

Programmable Interrupt Timer Modules (PIT0–PIT3)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

19-6 Freescale Semiconductor

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 readsis not guaranteed to be coherent. Writing to PCNTR has no effect, and write cycles are terminatednormally.

19.6 Functional DescriptionThis 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 modulusregister is loaded into the counter, and the counter begins decrementing toward 0x0000. If the PIE bit isset in PCSR, the PIF flag issues an interrupt request to the CPU.

15 14 13 12 11 10 9 8

Field PM15 PM14 PM13 PM12 PM11 PM10 PM9 PM8

Reset 1111_1111

R/W R/W

7 6 5 4 3 2 1 0

Field 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)

15 14 13 12 11 10 9 8

Field PC15 PC14 PC13 PC12 PC11 PC10 PC9 PC8

Reset 1111_1111

R/W R

7 6 5 4 3 2 1 0

Field PC7 PC6 PC5 PC4 PC3 PC2 PC1 PC0

Reset 1111_1111

R/W R

Address 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)

Page 200: Control Motor Tesis

Interrupt Operation

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 19-7

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

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 overfrom 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, thePIF 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 withouthaving to wait for the count to reach 0x0000.

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 systemclock as selected by the PRE[3:0] bits in PCSR. The PM[15:0] bits in PMR select the timeout period.

19.7 Interrupt OperationTable 19-4 shows the interrupt request generated by the PIT.

0x0002 0x0001 0x0000 0x0005

0x0005

PIT CLOCK

COUNTER

MODULUS

PIF

0x0002 0x0001 0x0000 0xFFFF

0x0005

PIT CLOCK

COUNTER

MODULUS

PIF

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

---------------------------------------------------------------------------=

Page 201: Control Motor Tesis

Programmable Interrupt Timer Modules (PIT0–PIT3)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

19-8 Freescale Semiconductor

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

Table 19-4. PIT Interrupt Requests

Interrupt Request Flag Enable Bit

Timeout PIF PIE

Page 202: Control Motor Tesis

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 20-1

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 a16-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-bitrange of the counter. Each of the four timer channels can be configured for input capture, which cancapture the time of a selected transition edge, or for output compare, which can generate output waveformsand timer software delays. These functions allow simultaneous input waveform measurements and outputwaveform generation.Additionally, one of the channels, channel 3, can be configured as a 16-bit pulse accumulator that canoperate as a simple event counter or as a gated time accumulator. The pulse accumulator uses the GPTchannel 3 input/output pin in either event mode or gated time accumulation mode.

20.1 FeaturesFeatures 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)

Page 203: Control Motor Tesis

General Purpose Timer Modules (GPTA and GPTB)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

20-2 Freescale Semiconductor

20.2 Block Diagram

Figure 20-1. GPT Block Diagram

Prescaler

Channel 0

PT0

16-Bit Counter

System

LOGIC

PR[2:0]

Divide-by-64

GPTC0H:GPTC0L

EDGEDETECTGPTPACNTH:GPTPACNTLPAOVF

PEDGE

PAOVI

PAMOD

PAE

16-Bit Comparator

GPTCNTH:GPTCNTL

16-Bit Latch

CHANNEL 1

GPTC1H:GPTC1L

16-Bit Comparator

16-Bit Latch

16-Bit Counter

InterruptLogic

TOF

TOI

C0F

C1F

EdgeDetect

PT1LOGIC

EdgeDetect

CxF

Channel 2

Channel3

GPTC3H:GPTC3L

16-Bit Comparator

16-Bit Latch

C3F

PT3LOGIC

EdgeDetect

IOS0

IOS1

IOS3

OM:OL0

TOV0

OM:OL1

TOV1

OM:OL3

TOV3

EDG1A

EDG1B

EDG3A

EDG3B

EDG0A

EDG0B

TCRE

Channel 3 Output Compare

PAIF

Clear Counter

PAIF

PAI

InterruptLogic

CxI

InterruptRequest

InterruptRequest

PAOVF

CH. 3 Compare

CH.3 Capture

CH. 1 Capture

MUX

CLK[1:0]

PACLKPACLK/256

PACLK/65536

PACLKPACLK/256

PACLK/65536

TE

Clock

CH. 1 Compare

CH. 0 Compare

CH. 0 Capture

PA Input

MUX

GPTx0Pin

GPTx1Pin

GPTx3Pin

X

SYNCx

Pin

Divideby 2

Divideby 2

SystemClock

Page 204: Control Motor Tesis

Low-Power Mode Operation

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 20-3

20.3 Low-Power Mode OperationThis subsection describes the operation of the general purpose time module in low-power modes andhalted mode of operation. Low-power modes are described in the Power Management Module. Table 3-1shows the general purpose timer module operation in the low-power modes, and shows how this modulemay facilitate exit from each mode.

Table 20-1. Watchdog Module Operation in Low-power Modes

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

20.4 Signal DescriptionTable 20-2 provides an overview of the signal properties.

NOTEThroughout this section, an “n” in the pin name, as in “GPTn0,” designatesGPTA or GPTB.

20.4.1 GPTn[2:0]

The GPTn[2:0] pins are for channel 2–0 input capture and output compare functions. These pins areavailable 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 accumulatorinput. This pin is available for general-purpose I/O when not configured for timer functions.

Low-power Mode Watchdog Operation Mode Exit

Wait Normal No

Doze Normal No

Stop Stopped No

Halted Normal No

Table 20-2. Signal Properties

PinName

GPTPORT Register Bit

Function Reset State Pull-up

GPTn0 PORTTn0 GPTn channel 0 IC/OC pin Input Active

GPTn1 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

1 SYNCA is available on either PORTE3 or PORTE1; SYNCB is available on either PORTE2 or PORTE0.

GPTn counter synchronization Input Active

Page 205: Control Motor Tesis

General Purpose Timer Modules (GPTA and GPTB)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

20-4 Freescale Semiconductor

20.4.3 SYNCn

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

20.5 Memory Map and RegistersSee 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.

NOTEReading reserved or unimplemented locations returns zeroes. Writing toreserved or unimplemented locations has no effect.

Table 20-3. GPT Modules Memory Map

IPSBAR OffsetBits 7–0 Access1

GPTA GPTB

0x1A_0000 0x1B_0000 GPT IC/OC Select Register (GPTIOS) S

0x1A_0001 0x1B_0001 GPT Compare Force Register (GPTCFORC) S

0x1A_0002 0x1B_0002 GPT Output Compare 3 Mask Register (GPTOC3M) S

0x1A_0003 0x1B_0003 GPT Output Compare 3 Data Register (GPTOC3D) S

0x1A_0004 0x1B_0004 GPT Counter Register (GPTCNT) S

0x1A_0006 0x1B_0006 GPT System Control Register 1 (GPTSCR1) S

0x1A_0007 0x1B_0007 Reserved2 —

0x1A_0008 0x1B_0008 GPT Toggle-on-Overflow Register (GPTTOV) S

0x1A_0009 0x1B_0009 GPT Control Register 1 (GPTCTL1) S

0x1A_000A 0x1B_000a Reserved(2) —

0x1A_000B 0x1B_000b GPT Control Register 2 (GPTCTL2) S

0x1A_000C 0x1B_000c GPT Interrupt Enable Register (GPTIE) S

0x1A_000D 0x1B_000d GPT System Control Register 2 (GPTSCR2) S

0x1A_000E 0x1B_000e GPT Flag Register 1 (GPTFLG1) S

0x1A_000F 0x1B_000f GPT Flag Register 2 (GPTFLG2) S

0x1A_0010 0x1B_0010 GPT Channel 0 Register High (GPTC0H) S

0x1A_0011 0x1Bb_0011 GPT Channel 0 Register Low (GPTC0L) S

0x1A_0012 0x1B_0012 GPT Channel 1 Register High (GPTC1H) S

0x1A_0013 0x1B_0013 GPT Channel 1 Register Low (GPTC1L) S

0x1A_0014 0x1B_0014 GPT Channel 2 Register High (GPTC2H) S

0x1A_0015 0x1B_0015 GPT Channel 2 Register Low (GPTC2L) S

0x1A_0016 0x1B_0016 GPT Channel 3 Register High (GPTC3H) S

Page 206: Control Motor Tesis

Memory Map and Registers

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 20-5

20.5.1 GPT Input Capture/Output Compare Select Register (GPTIOS)

0x1A_0017 0x1B_0017 GPT Channel 3 Register Low (GPTC3L) S

0x1A_0018 0x1B_0018 Pulse Accumulator Control Register (GPTPACTL) S

0x1A_0019 0x1B_0019 Pulse Accumulator Flag Register (GPTPAFLG) S

0x1A_001A 0x1B_001A Pulse Accumulator Counter Register High (GPTPACNTH) S

0x1A_001B 0x1B_001B Pulse Accumulator Counter Register Low (GPTPACNTL) S

0x1A_001C 0x1B_001C Reserved(2) —

0x1A_001D 0x1B_001D GPT Port Data Register (GPTPORT) S

0x1A_001E 0x1B_001E GPT Port Data Direction Register (GPTDDR) S

0x1A_001F 0x1B_001F GPT Test Register (GPTTST) S

1 S = CPU supervisor mode access only. 2 Writes have no effect, reads return 0s, and the access terminates without a transfer error exception.

7 4 3 0

Field — IOS

Reset 0000_0000

R/W R/W

Address 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 Description

7–4 — Reserved, should be cleared.

3–0 IOS 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 enabled0 Input capture enabled

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

IPSBAR OffsetBits 7–0 Access1

GPTA GPTB

Page 207: Control Motor Tesis

General Purpose Timer Modules (GPTA and GPTB)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

20-6 Freescale Semiconductor

20.5.2 GPT Compare Force Register (GPCFORC)

NOTEA successful channel 3 output compare overrides any compare on channels2:0. For each OC3M bit that is set, the output compare action reflects thecorresponding OC3D bit.

20.5.3 GPT Output Compare 3 Mask Register (GPTOC3M)

7 4 3 0

Field — FOC

Reset 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 Description

7–4 — Reserved, should be cleared.

3–0 FOC 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 compare0 No effect

7 4 3 0

Field — OC3M

Reset 0000_0000

R/W R/W

Address IPSBAR + 0x1A_0002, 0x1B_0002

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

Page 208: Control Motor Tesis

Memory Map and Registers

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 20-7

20.5.4 GPT Output Compare 3 Data Register (GPTOC3D)

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

20.5.5 GPT Counter Register (GPTCNT)

Table 20-6. GPTOC3M Field Descriptions

Bit(s) Name Description

7–4 — Reserved, should be cleared.

3–0 OC3M 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 output0 No effect

7 4 3 0

Field — OC3D

Reset 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 Description

7–4 — Reserved, should be cleared.

3–0 OC3D 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.

15 0

Field CNTR

Reset 0000_0000_0000_0000

R/W Read only

Address IPSBAR + 0x1A_0004, 0x1B_0004

Figure 20-6. GPT Counter Register (GPTCNT)

Page 209: Control Motor Tesis

General Purpose Timer Modules (GPTA and GPTB)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

20-8 Freescale Semiconductor

20.5.6 GPT System Control Register 1 (GPTSCR1)

Table 20-8. GPTCNT Field Descriptions

Bit(s) Name Description

15–0 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.

7 6 5 4 3 0

Field GPTEN — TFFCA —

Reset 0000_0000

R/W R/W

Address IPSBAR + 0x1A_0006, 0x1B_0006

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

Table 20-9. GPTSCR1 Field Descriptions

Bit(s) Name Description

7 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 enabled0 GPT and GPT counter disabled

6–5 — Reserved, should be cleared.

4 TFFCA 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 clearing0 Normal flag clearing

3–0 — Reserved, should be cleared.

Page 210: Control Motor Tesis

Memory Map and Registers

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 20-9

Figure 20-8. Fast Clear Flag Logic

20.5.7 GPT Toggle-On-Overflow Register (GPTTOV)

20.5.8 GPT Control Register 1 (GPTCTL1)

7 6 5 4 3 0

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 Description

7–4 — Reserved, should be cleared.

3–0 TOV 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 enabled0 Toggle output compare pin on overflow feature disabled

7 6 5 4 3 2 1 0

Field OM3 OL3 OM2 OL2 OM1 OL1 OM0 OL0

Reset 0000_0000

R/W R/W

Address IPSBAR + 0x1A_0009, 0x1B_0009

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

Clear

Write GPTCn Registers

Read GPTCn Registers

TFFCA

Data Bit nWrite GPTFLG1 Register

CnF

CnF Flag

Page 211: Control Motor Tesis

General Purpose Timer Modules (GPTA and GPTB)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

20-10 Freescale Semiconductor

20.5.9 GPT Control Register 2 (GPTCTL2)

20.5.10 GPT Interrupt Enable Register (GPTIE)

Table 20-11. GPTCL1 Field Descriptions

Bit(s) Name Description

7–0 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 lineNote: 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.

7 6 5 4 3 2 1 0

Field EDG3B EDG3A EDG2B EDG2A EDG1B EDG1A EDG0B EDG0A

Reset 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 Description

7–0 EDGn[B:A] Input capture edge control. Configures the input capture edge detector circuits for each channel. These bits are read anytime, write anytime.00 Input capture disabled01 Input capture on rising edges only10 Input capture on falling edges only11 Input capture on any edge (rising or falling)

7 6 5 4 3 0

Field — CI

Reset 0000_0000

R/W R/W

Address IPSBAR + 0x1A_000C, 0x1B_000C

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

Page 212: Control Motor Tesis

Memory Map and Registers

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 20-11

20.5.11 GPT System Control Register 2 (GPTSCR2)

Table 20-13. GPTIE Field Descriptions

Bit(s) Name Description

7–4 — Reserved, should be cleared.

3–0 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 enabled0 Corresponding channel interrupt requests disabled

7 6 5 4 3 2 0

Field TOI — PUPT RDPT TCRE PR

Reset 0000_0000

R/W R/W

Address IPSBAR + 0x1A_000D, 0x1B_000D

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

Table 20-14. GPTSCR2 Field Descriptions

Bit(s) Name Description

7 TOI Enables timer overflow interrupt requests.1 Overflow interrupt requests enabled0 Overflow interrupt requests disabled

6 — Reserved, should be cleared.

5 PUPT Enables pull-up resistors on the GPT ports when the ports are configured as inputs.1 Pull-up resistors enabled0 Pull-up resistors disabled

4 RDPT GPT drive reduction. Reduces the output driver size.1 Output drive reduction enabled0 Output drive reduction disabled

3 TCRE Enables a counter reset after a channel 3 compare.1 Counter reset enabled0 Counter reset disabledNote: 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.

Page 213: Control Motor Tesis

General Purpose Timer Modules (GPTA and GPTB)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

20-12 Freescale Semiconductor

20.5.12 GPT Flag Register 1 (GPTFLG1)

20.5.13 GPT Flag Register 2 (GPTFLG2)

2–0 PRn Prescaler bits. Select the prescaler divisor for the GPT counter.000 Prescaler divisor 1001 Prescaler divisor 2010 Prescaler divisor 4011 Prescaler divisor 8100 Prescaler divisor 16101 Prescaler divisor 32110 Prescaler divisor 64111 Prescaler divisor 128Note: 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.)

7 6 5 4 3 0

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 Description

7–4 — Reserved, should be cleared.

3–0 CnF 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.

7 6 5 4 3 0

Field TOF — CF

Reset 0000_0000

R/W R/W

Address IPSBAR + 0x1A_000F, 0x1B_000F

Figure 20-15. GPT Flag Register 2 (GPTFLG2)

Table 20-14. GPTSCR2 Field Descriptions (continued)

Bit(s) Name Description

Page 214: Control Motor Tesis

Memory Map and Registers

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 20-13

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)

Table 20-16. GPTFLG2 Field Descriptions

Bit(s) Name Description

7 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 overflow0 No timer overflowNote: 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.

6–4 — Reserved, should be cleared.

3–0 CnF 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).

15 0

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

15–0 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.

Page 215: Control Motor Tesis

General Purpose Timer Modules (GPTA and GPTB)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

20-14 Freescale Semiconductor

20.5.15 Pulse Accumulator Control Register (GPTPACTL)

7 6 5 4 3 0

Field — PAE PAMOD PEDGE CLK PAOVI PAI

Reset 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

7 — Reserved, should be cleared.

6 PAE Enables the pulse accumulator.1 Pulse accumulator enabled0 Pulse accumulator disabledNote: The pulse accumulator can operate in event mode even when the GPT enable bit, GPTEN, is clear.

5 PAMOD Pulse accumulator mode. Selects event counter mode or gated time accumulation mode.1 Gated time accumulation mode0 Event counter mode

4 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 counter0 Falling PAI edge increments counterIn 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.

3–2 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 PACLK10 PACLK/25611 PACLK/65536

Page 216: Control Motor Tesis

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-1

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 inputchannels 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 includesinput pins, an analog multiplexer, and sample and hold analog circuits.The digital control section contains queue control logic to sequence the conversion process and interruptgeneration logic. Also included are the periodic/interval timer, control and status registers, the conversioncommand 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 theanalog-to-digital converter and queue mechanism, and present formatted conversion results.

28.1 FeaturesFeatures 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.

Page 217: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-2 Freescale Semiconductor

28.2 Block Diagram

Figure 28-1. QADC Block Diagram

28.3 Modes of OperationThis subsection describes the two modes of operation in which the QADC does not perform conversionsin 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 whenthe CPU enters background debug mode. When QDBG is clear, the QADC operates normally and isunaffected 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 inprogress and then freezes. This is QADC debug mode. Depending on when debug mode is entered, thethree 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.

Digital

External

External

Reference

Analog Power

64-Entry Queue

Control

of 10-bitConversion

Command Words

IPBUSInterface

10-bitAnalog-to-Digital

Converter

Analog Input MUXand Digital

Signal Functions

64-Entry Tableof 10-bit

10-bit to 16-bitResult Alignment

(18 with External MUXing)MUX Address

Triggers Inputs

Inputs

(CCWs)Results

8 Analog Channels

Page 218: Control Motor Tesis

Signals

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-3

• 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 queuepointer 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 QADCto execute a different CCW by reconfiguring the QADC. When the QADC exits debug mode, it looks atthe queue operating modes, the current queue pointer, and any pending trigger events to decide whichCCW 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 stopmode.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 somerecovery time (tSR) to stabilize the analog circuits.

28.4 SignalsThe QADC uses the external signals shown in Figure 28-2. There are eight channel/port signals that cansupport up to 18 channels when external multiplexing is used (including internal channels). All of thechannel 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 analoginput 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.

Page 219: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-4 Freescale Semiconductor

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].

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/outputport. 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 asgeneral-purpose digital inputs when the applied voltages meet high-voltage input (VIH) and low-voltageinput (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) whenDDRQA specifies that the signals are inputs. The digital data in PORTQA is driven onto the port QAsignals when the corresponding bits in DDRQA specify output. See Section 28.6.4, “Port QA and QB DataDirection 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].

AN52/MA0/PQA0AN53/MA1/PQA1

AN55/ETRIG1/PQA3AN56/ETRIG2/PQA4

AN0/ANW/PQB0AN1/ANX/PQB1AN2/ANY/PQB2AN3/ANZ/PQB3

DigitalAnalog

VSSI

Analog Power and Ground

Internal Digital Power

PO

RT

QB

ConverterResults

andControl

AnalogMux and

Port QB Analog InputsExternal MUX Inputs

Digital Inputs

Port QA Analog InputsExternal Trigger Inputs

External MUX Address Outputs

VDDI

VSSAVDDA

VRHVRL

Analog References

Shared with Other Modules

Digital I/O

Port Logic

PO

RT

QA

Page 220: Control Motor Tesis

Signals

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-5

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 tofunctioning as analog input signals, the port QB signals are also connected to the input of a synchronizerduring reads and may be used as general-purpose digital inputs when the applied voltages meet VIH andVIL 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) whenDDRQB specifies that the signals are inputs. The digital data in PORTQB is driven onto the port QBsignals when the corresponding bits in DDRQB specify output. See Section 28.6.4, “Port QA and QB DataDirection Register (DDRQA & DDRQB).

28.4.3 External Trigger Input Signals

The QADC has two external trigger signals, ETRIG2 and ETRIG1. Each external trigger input isassociated with one of the scan queues, queue 1 or queue 2. The assignment of ETRIG[2:1] to a queue ismade by the TRG bit in QADC control register 0 (QACR0). When TRG = 0, ETRIG1 triggers queue 1 andETRIG2 triggers queue 2. When TRG = 1, ETRIG1 triggers queue 2 and ETRIG2 triggers queue 1. SeeSection 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 whichroutes the analog signals into the internal A/D converter.In externally multiplexed mode, the QADC allows automatic channel selection through up to four external4-to-1 multiplexer chips. The QADC provides a 2-bit multiplexed address output to the externalmultiplexer chips to allow selection of one of four inputs. The multiplexed address output signals, MA1and MA0, can be used as multiplexed address output bits or as general-purpose I/O when externalmultiplexed 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 inDDRQA 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 analoginput channels. See Table 28-1.

Table 28-1. Multiplexed Analog Input Channels

MultiplexedAnalog 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

Page 221: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-6 Freescale Semiconductor

28.4.6 Voltage Reference Signals

VRH and VRL are the dedicated input signals for the high and low reference voltages. Separating thereference inputs from the power supply signals allows for additional external filtering, which increasesreference voltage precision and stability, and subsequently contributes to a higher degree of conversionaccuracy.

NOTEVRH and VRL must be set to VDDA and VSSA potential, respectively. Formore information, refer to Section 28.9, “Signal ConnectionConsiderations.

28.4.7 Dedicated Analog Supply Signals

The VDDA and VSSA signals supply power to the analog subsystems of the QADC module. Dedicatedpower is required to isolate the sensitive analog circuitry from the normal levels of noise present on thedigital 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 thosesignals to tolerate 5 volts when configured as inputs and drive 5 volts when configured as outputs.

28.5 Memory MapThe QADC occupies 1 Kbyte, or 512 half-word (16-bit) entries, of address space. Ten half-word registersare control, port, and status registers, 64 half-word entries are the CCW table, and 64 half-word entries arethe result table which occupies 192 half-word address locations because the result data is readable in threedata alignment formats. Table 28-2 is the QADC memory map.

Table 28-2. QADC Memory Map

IPSBAR +Offset

MSB LSB Access1

0x19_0000 QADC Module Configuration Register (QADCMCR) S

0x19_0002 QADC Test Register (QADCTEST)2 S

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

Page 222: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-7

28.6 Register DescriptionsThis 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 levelrequired to access most registers.

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

1 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.

15 14 13 8

Field QSTOP QDBG —

Reset 0000_0000

R/W: R/W R

7 6 0

Field SUPV —

Reset 1000_0000

R/W: R/W R

Address IPSBAR + 0x19_0000, 0x19_0001

Figure 28-3. QADC Module Configuration Register (QADCMCR)

Table 28-2. QADC Memory Map (continued)

IPSBAR +Offset

MSB LSB Access1

Page 223: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-8 Freescale Semiconductor

28.6.2 QADC Test Register (QADCTEST)

The QADCTEST is a reserved register. Attempts to access this register outside of factory test mode willresult 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. PortQA can also be used for analog inputs (AN[56:55, 53:52]), external trigger inputs (ETRIG[2:1]), andexternal 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 alsobe used for non-multiplexed (AN[3:0]) and multiplexed (ANZ, ANY, ANX, ANW) analog inputs.PORTQA and PORTQB are not initialized by reset.

Table 28-3. QADCMCR Field Descriptions

Bit(s) Name Description

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 mode0 QADC operates normally.

13–8 — Reserved, should be cleared.

7 SUPV 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

6–0 — Reserved, should be cleared.

7 6 5 4 3 2 1 0

Field — PQA4(AN56)

(ETRIG2)

PQA3(AN55)

(ETRIG1)

— PQA1(AN53)(MA1)

PQA0(AN52)(MA0)

Reset 000 See Note 0 See Note

R/W: R R/W R R/W

Address IPSBAR + 0x19_0006

Figure 28-4. QADC Port QA Data Register (PORTQA)

Page 224: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-9

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 theseregisters configures the corresponding signal as an output. Clearing a bit in these registers configures thecorresponding signal as an input. During QADC initialization, port QA and QB signals that will be usedas 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, thevoltage 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 areignored 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 themultiplexed address outputs are driven. The data returned during a port data register read is the value ofthe MA[1:0] signals, regardless of their data direction setting.Similarly, when the external trigger signals are assigned to port signals and external trigger queueoperating 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 returnedduring a port data register read is the value of the ETRIG[2:1] signals, regardless of their data directionsetting.

NOTEUse caution when mixing digital and analog inputs. They should be isolatedas much as possible. Rise and fall times should be as large as possible tominimize ac coupling effects.

7 6 5 4 3 2 1 0

Field — PQB3(AN3)(ANZ)

PQB2(AN2)(ANY)

PQA1(AN1)(ANX)

PQA0(AN0)(ANW)

Reset 0000 See Note

R/W: R R/W

Address IPSBAR + 0x19_0007

Figure 28-5. QADC Port QB Data Register (PORTQB)

7 6 5 4 3 2 1 0

Field — DDQA4 DDQA3 — DDQA1 DDQA0

Reset 0000_0000

R/W: R R/W R R/W

Address IPSBAR + 0x19_0008

Figure 28-6. QADC Port QA Data Direction Register (DDRQA)

Page 225: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-10 Freescale Semiconductor

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 defineswhether external multiplexing is enabled. Typically, these bits are written once when the QADC isinitialized and not changed thereafter. The bits in this register are read anytime, write anytime (exceptduring stop mode).

7 6 5 4 3 2 1 0

Field — DDQB3 DDQB2 DDQB1 DDQB0

Reset 0000_0000

R/W R

Address IPSBAR + 0x19_0009

Figure 28-7. Port QB Data Direction Register (DDRQB)

Page 226: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-11

15 14 13 12 11 8

Field MUX — TRG —

Reset 0000_0000

R/W: R/W R R/W R

7 6 5 4 3 2 1 0

Field — QPR6 QPR5 QPR4 QPR3 QPR2 QPR1 QPR0

Reset 0001_0011

R/W: 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 channels0 Internally multiplexed, up to 8 possible channels

14–13 — Reserved, should be cleared.

12 TRG 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.

11–7 — Reserved, should be cleared.

6–0 QPR 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:

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.

fQCLK =fSYS

2(QPR[6:0] + 1)

Page 227: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-12 Freescale Semiconductor

Table 28-5. Prescaler fSYS Divide-by Values

QPR[6:0]fSYS

DivisorQPR[6:0]

fSYSDivisor

QPR[6:0]fSYS

DivisorQPR[6:0]

fSYSDivisor

0000000 4 0100000 66 1000000 130 1100000 194

0000001 4 0100001 68 1000001 132 1100001 196

0000010 6 0100010 70 1000010 134 1100010 198

0000011 8 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

Page 228: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-13

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 useof completion and/or pause interrupts. Typically, these bits are written once when the QADC is initializedand are not changed thereafter.Stop mode resets this register.

15 14 13 12 11 10 9 8

Field CIE1 PIE1 SSE1 MQ112 MQ111 MQ110 MQ19 MQ18

Reset 0000_0000

R/W: R/W

7 0

Field —

Reset 0000_0000

R/W: R

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.

12–8 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.

7–0 — Reserved, should be cleared.

Page 229: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-14 Freescale Semiconductor

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

Page 230: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-15

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 useof completion and/or pause interrupts. Typically, these bits are written once when the QADC is initializedand not changed thereafter.QACR2 also includes a resume feature that selects the resumption point for queue 2 after its operation issuspended by a queue 1 trigger event. The primary reason for selecting re-execution of the entire queue orsubqueue 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 withthe 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 toreport 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 queue2 completion. If the rate of queue 1 execution is too high, it is best for queue 2 execution to continue withthe CCW that was being converted when queue 2 was suspended. This allows queue 2 to eventuallycomplete execution.The beginning of queue 2 is defined by programming the BQ2 field in QACR2. BQ2 is usually set beforeor at the same time as the queue operating mode for queue 2 is selected. If BQ2[6:0] ≥ 64, queue 2 has noentries, 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 selectedfor 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. Achange in BQ2 after queue 2 has begun or when queue 2 has a trigger pending does not affect queue 2 untilit is started again. For example, two scan sequences could be defined as follows: The first sequence startsat CCW10, with a pause after CCW11 and an end of queue (EOQ) programmed in CCW15; the secondsequence 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 thepause is encountered in CCW11, an interrupt service routine can retarget BQ2[6:0] to CCW16. When theend-of-queue is recognized in CCW15, an internal retrigger event is generated and execution restarts atCCW16. When the pause software interrupt occurs again, BQ2 can be changed back to CCW10. After theend-of-queue is recognized in CCW39, an internal retrigger event is created and execution now restarts atCCW10.If BQ2[6:0] is changed while queue 1 is active, the effect of BQ2[6:0] as an end-of-queue indication forqueue 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.

NOTEIf 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] takeseffect.

Each time a CCW is read for queue 1, the CCW location is compared with the current value of theBQ2[6:0] pointer to detect a possible end-of-queue condition. For example, if BQ2[6:0] is changed toCCW3 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

Page 231: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-16 Freescale Semiconductor

recognize a BQ2[6:0] end-of-queue condition until queue 1 execution reached CCW1 again, presumablyon the next pass through the queue.Stop mode resets this register (0x007f)

15 14 13 12 11 10 9 8

Field CIE2 PIE2 SSE2 MQ212 MQ211 MQ210 MQ29 MQ28

Reset 0000_0000

R/W: R/W

7 6 5 4 3 2 1 0

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)

Page 232: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-17

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.

12–8 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.

7 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.

6–0 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

Page 233: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-18 Freescale Semiconductor

28.6.6 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 inthis 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

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

Table 28-9. Queue 2 Operating Modes (continued)

MQ2[12:8] Operating Modes

Page 234: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-19

• 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 executionto continue. However, a special case occurs when the CCW with the pause bit set is the last CCW in aqueue; queue execution is complete. The queue status becomes idle, not paused, and both the pause andcompletion flags are set. Another special case occurs when the queue is operating in software-initiated single-scan orcontinuous-scan mode and a CCW pause bit is set. The QADC will set PFn and will also automaticallygenerate 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. Whenthe gate closes before the end of the queue is reached, PFn is set to indicate that an incomplete scan hasoccurred. In single-scan mode, a resultant interrupt can be used to determine if the queue should be enabledagain. In either externally gated mode, setting PFn indicates that the results for the queue have not beencollected during one scan (coherently).

NOTE:If a set CCW pause bit is encountered in either externally gated mode, thepause flag will not set, and execution continues without pausing. This hasallowed for the modified behavior of PF1 in the externally gated modes.

PFn is maintained by the QADC regardless of whether the correspondinginterrupt is enabled. PFn may be polled to determine if the QADC hasreached a pause in scanning a queue.

A trigger event generated by a transition on the external trigger signal or by the periodic/interval timer maybe captured as a trigger overrun. TORn cannot be set when the software-initiated single-scan mode or thesoftware-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 completedor 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, additionalqueue 1 trigger events are not retained. Such trigger events are considered unexpected, and the QADC setsthe 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 thequeue reaches an end-of-queue condition for the second time during an open gate, TORn is set. This isconsidered an overrun condition. In this case, CF1 has been set for the first end-of-queue condition andTORn sets for the second end-of-queue condition. For TOR1 to set, CF2 must not be cleared before thesecond 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 ina valid queue operating mode awaiting a trigger event to initiate queue execution. One or both queues maybe in the idle state. When a queue is idle, CCWs are not being executed for that queue, the queue is not inthe pause state, and no trigger is pending.

Page 235: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-20 Freescale Semiconductor

A queue is in the active state when a valid queue operating mode is selected, when the selected triggerevent 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 fromthat queue had the pause bit set. The QADC does not execute any CCWs from the paused queue until atrigger 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 isexecuting, the current queue 2 conversion is aborted and the queue 2 status is reported as suspended. Queue2 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 ofqueue 2 is changed to trigger pending when a trigger event occurs for queue 2 while queue 1 is active. Inthe opposite case, when a trigger event occurs for queue 1 while queue 2 is active, queue 2 is aborted andthe status is reported as queue 1 active, queue 2 suspended. So due to the priority scheme, only queue 2can 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 theactive state. When queue 1 is active and there is a trigger pending on queue 2, after queue 1 completes orpauses, queue 2 continues to be in the trigger pending state for a few clock cycles. The fleeting statusconditions 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 fromqueue 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, theCWP value is maintained until a trigger event occurs on either queue. Usually, the CWP is updated a fewclock cycles before the queue status field shows that the queue has become active. For example, a read ofCWP may point to a CCW in queue 2, while the queue status field shows queue 1 paused and queue 2trigger pending.When the QADC finishes a queue scan, the CWP points to the CCW where the end-of-queue conditionwas detected. Therefore, when the end-of-queue condition is a CCW with the EOQ code (channel 63), theCWP 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 EOQcode, 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 CWPpoints to the same CCW as BQ2.

15 14 13 12 11 10 9 8

Field CF1 PF1 CF2 PF2 TOR1 TOR2 QS9 QS8

Reset 0000_0000

R/W: R/W R

Page 236: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-21

7 6 5 4 3 2 1 0

Field QS7 QS6 CWP5 CWP4 CWP3 CWP2 CWP1 CWP0

Reset 0000_0000

R/W: R

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.

11–10 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.

Page 237: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-22 Freescale Semiconductor

9–6 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.

5–0 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

Table 28-10. QASR0 Field Descriptions (continued)

Bit(s) Name Description

Page 238: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-23

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

Table 28-12. Queue Status (continued)

QS[9:6] Queue 1/Queue 2 States

Page 239: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-24 Freescale Semiconductor

Figure 28-12. Queue Status Transition

Q1 Idle/Q2 Active

Q1 Idle/Q2 Idle

Q1 Active/Q2 Idle

Q1 Paused/Q2 Idle

Q1 Active/Q2 Suspended

Q1 Active/Q2 Paused

Q1 Paused/Q2 Active

Q1 Idle/Q2 Paused

Q1 Paused/Q2 Paused

Q1 Active/Q2 TriggerPending

Q1 Paused/Q2 TriggerPending

(Temporary)

Q2 Complete

Delayed Transition

Q1 Pause Bit Set

Q2 Trigger Event

Q1 Trigger Event

Q1 Pause Bit Set

Q1 Complete

Q1 Trigger Event

Q1 Complete

Delayed Transition

Q1 Complete

Q1 Pause Bit Set

Q1 Trigger Event

Q2 Complete

Q2 Pause Bit Set

Q2 Trigger Event

Q1 Trigger Event

Q1 Complete

Q1 Trigger Event

Q1 Pause Bit Set

Q2 Pause Bit Set

Q2 Trigger Event

Q1 Idle/Q2 TriggerPending

(Temporary)Q1 Trigger Event

Q2 Trigger Event

Page 240: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-25

28.6.6.2 QADC Status Register 1 (QASR1)

Stop mode resets this register .

28.6.7 Conversion Command Word Table (CCW)

The CCW table is 64 half-word (128 byte) long RAM with 10 bits of each entry implemented. The CCWtable is written by the user and is not modified by the QADC. Each CCW requests the conversion of oneanalog channel to a digital result. The CCW specifies the analog channel number, the input sample time,

15 14 13 12 11 10 9 8

Field — CWPQ15 CWPQ14 CWPQ13 CWPQ12 CWPQ11 CWPQ10

Reset 0011_1111

R/W: R

7 6 5 4 3 2 1 0

Field — CWPQ25 CWPQ24 CWPQ23 CWPQ22 CWPQ21 CWPQ20

Reset 0011_1111

R/W: R

Address IPSBAR + 0x19_0012, 0x19_0013

Figure 28-13. QADC Status Register 1 (QASR1)

Table 28-13. QASR1 Field Descriptions

Bit(s) Name Description

15–14 — Reserved, should be cleared.

13–8 CWPQ1 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.

7–6 — Reserved, should be cleared.

5–0 CWPQ 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.

Page 241: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-26 Freescale Semiconductor

and whether the queue is to pause after the current CCW. The bits in this register are read anytime (exceptduring stop mode), write anytime (except during stop mode).

15 10 9 8

Field — P BYP

Reset 0000_00 Unaffected

R/W: R R/W

7 6 5 4 3 2 1 0

Field IST1 IST0 CHAN5 CHAN4 CHAN3 CHAN2 CHAN1 CHAN0

Reset Undefined

R/W: R

Address IPSBAR + 0x19_0200, 0x19_027e

Figure 28-14. Conversion Command Word Table (CCW)

Table 28-14. CCW Field Descriptions

Bit(s) Name Description

15–10 — Reserved, should be cleared.

9 P 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.

8 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 enabled0 Amplifier bypass mode disabledNOTE: BYP is maintained for software compatibility but has no functional benefit on this version of the QADC.

Page 242: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-27

7–6 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.

5–0 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 (VRH–VRL)/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

Non-Multiplexed Input SignalsChannel Number1

in CCW CHAN Field

Port Signal Name Analog Signal NameOther

FunctionsSignal Type Binary Decimal

PQB0PQB1PQB2PQB3

AN0AN1AN2AN3

————

InputInputInputInput

000000000001000010000011

0123

PQA0PQA1

AN52AN53

——

Input/OutputInput/Output

110100110101

5253

PQA3PQA4

AN55AN56

ETRIG1ETRIG2

Input/OutputInput/Output

110111111000

5556

VRL

VRH—

Low referenceHigh reference

——

(VRH–VRL)/2

InputInput

111100111101111110

606162

— — End-of-Queue Code — 111111 63

Table 28-14. CCW Field Descriptions (continued)

Bit(s) Name Description

Page 243: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-28 Freescale Semiconductor

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 theQADC after completing an analog conversion specified by the corresponding CCW table entry.

28.6.8.1 Right-Justified Unsigned Result Register (RJURR)

1 All channels not listed are reserved or unimplemented and return undefined results.

Table 28-17. Multiplexed Channel Assignments and Signal Designations

Multiplexed Input SignalsChannel Number1

in CCW CHAN Field

1 All channels not listed are reserved or unimplemented and return undefined results.

Port Signal Name

Analog Signal Name

Other Functions

Signal Type Binary Decimal

PQB0PQB1PQB2PQB3

ANWANXANYANZ

————

InputInputInputInput

000XX0000XX1010XX0010XX1

0, 2, 4, 61, 3, 5, 7

16, 18, 20, 2217, 19, 21, 23

PQA0PQA1

——

MA0MA1

OutputOutput

— 5253

PQA3PQA4

AN55AN56

ETRIG1ETRIG2

Input/OutputInput/Output

110111111000

5556

VRLVRH—

Low ReferenceHigh Reference

——

(VRH–VRL)/2

InputInput

111100111101111110

606162

— — End-of-Queue Code — 111111 63

15 10 9 8

Field — RESULT

Reset 0000_00 Undefined

R/W: R R/W

7 0

Field RESULT

Reset Undefined

R/W: R/W

Address IPSBAR + 0x19_0280, 0x19_02fe

Figure 28-15. Right-Justified Unsigned Result Register (RJURR)

Page 244: Control Motor Tesis

Register Descriptions

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-29

28.6.8.2 Left-Justified Signed Result Register (LJSRR)

28.6.8.3 Left-Justified Unsigned Result Register (LJURR)

Table 28-18. RJURR Field Descriptions

Bit(s) Name Description

15–10 — Reserved, should be cleared.

9–0 RESULT The conversion result is unsigned, right-justified data.

15 14 8

Field S RESULT

Reset Undefined

R/W: R/W

7 0

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 S The left justified, signed format corresponds to a half-scale, offset binary, two’s 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 two’s complement value representing –512.

14–6 RESULT The conversion result is signed, left-justified data.

5–0 — Reserved, should be cleared.

15 8

Field RESULT

Reset Undefined

R/W: R/W

Page 245: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-30 Freescale Semiconductor

28.7 Functional DescriptionThis 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 conversionresults are stored in half-word registers, and the QADC does not allow more than one result register to beread 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 fromone read to the next. Simply initiating a read of one result register will not prevent another from beingupdated with a new conversion result.Thus, to read any given number of result registers coherently, the queue or queues capable of modifyingthese registers must be inactive. This can be guaranteed by system operating conditions (such as, knowncompletion of a software-initiated queue single-scan or no possibility of an externally triggered/gatedqueue 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 usefulfor 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 thenumber of analog signals that need to be shielded due to the proximity of noisy high speed digital signalsat the microcontroller chip.For example, four 4-input multiplexer chips can be put at the connector where the analog signals firstarrive on the printed circuit board. As a result, only four analog signals need to be shielded from noise asthey approach the microcontroller chip, rather than having to protect 16 analog signals. However, externalmultiplexer chips may introduce additional noise and errors if not properly utilized. Therefore, it isnecessary to maintain low “on” resistance (the impedance of an analog switch when active within amultiplexed chip) and insert a low pass filter (R/C) on the input side of the multiplexed chip.

7 6 5 0

Field RESULT —

Reset Undefined

R/W: R/W R

Address IPSBAR + 0x19_0380, 0x19_03fe

Figure 28-17. Left-Justified Unsigned Result Register (LJURR)

Table 28-20. LJURR Field Descriptions

Bit(s) Name Description

15–6 RESULT The conversion result is unsigned, left-justified data.

5–0 — Reserved, should be cleared.

Page 246: Control Motor Tesis

Functional Description

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-31

28.7.2.1 External Multiplexing Operation

The QADC can use from one to four external multiplexer chips to expand the number of analog signalsthat 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, thesame as internally multiplexed channels. The QADC is configured for the externally multiplexed mode bysetting the MUX bit in control register 0 (QACR0).Figure 28-18 shows the maximum configuration of four external multiplexer chips connected to theQADC. 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], toselect one of four inputs. These inputs are connected to all four external multiplexer chips. The analogoutput of the four multiplexer chips are each connected to separate QADC inputs (ANW, ANX, ANY, andANZ) as shown in Figure 28-18

Page 247: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-32 Freescale Semiconductor

Figure 28-18. External Multiplexing Configuration

When externally multiplexed mode is selected, the QADC automatically drives the MA output signalsfrom 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 multiplexedchannels appear to the conversion queues as directly connected signals. User software simply puts thechannel number of externally multiplexed channels into CCWs.

AN52/MA0/PQA0AN53/MA1/PQA1

AN55/ETRIG1PQA3AN56/ETRIG2/PQA4

AN0/ANW/PQB0AN1/ANX/PQB1AN2/ANY/PQB2AN3/ANZ/PQB3

Por

t QB

Por

t QA

AN0AN2AN4AN6

AN1AN3AN5AN7

AN16AN18AN20AN22

AN17AN19AN21AN23

MUX

MUX

MUX

MUX

Page 248: Control Motor Tesis

Functional Description

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-33

Figure 28-18 shows that the two MA signals may also be analog input signals. When external multiplexingis selected, none of the MA signals can be used for analog or digital inputs. They become multiplexedaddress 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. Amaximum 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 multiplexerchips.

28.7.3 Analog Subsystem

This section describes the QADC analog subsystem, which includes the front-end analog multiplexer andanalog-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 fromthe queue control logic are fed to the multiplexer and state machine. The end-of-conversion (EOC) signaland the successive approximation register (SAR) reflect the result of the conversion. Figure 28-19 showsa block diagram of the QADC analog subsystem.

Table 28-21. Analog Input Channels

Number of Analog Input Channels AvailableDirectly Connected + External Multiplexed = Total Channels1, 2

1 The external trigger inputs are not shared with two analog input signals.2 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.

No External MuxOne External

MuxTwo External

MuxesThree External

MuxesFour External

Muxes

8 5 + 4 = 9 4 + 8 = 12 3 + 12 = 15 2 + 16 = 18

Page 249: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-34 Freescale Semiconductor

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. Initialsample time refers to the time during which the selected input channel is coupled through the sample bufferamplifier to the sample capacitor. The sample buffer is used to quickly reproduce its input signal on thesample capacitor and minimize charge sharing errors. During the final sampling period the amplifier isbypassed, 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 storedin 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 finalsample time period of 16 QCLKs is selected, the total conversion time is 28 QCLKs or 14 µs (with a2.0-MHz QCLK).

PQA4

PQA0

PQB3

PQB0

VDDA

VSSA

VRH

VRL

QCLK

Start ConvEnd OF Conv

RSTSTOP

SAR[9:0]

10-bit A/D Converter Input

AnalogPower

2IST

Sample

Compar-Successive

ator

Bias Circuit

ApproximationRegister

Buffer

1010

CHAN[5:0]

CSAMP

10

Chan. Decode & MUX16:1

Sig

nals

Fro

m/to

Que

ue C

ontr

ol L

ogic

16

State Machine & Logic

Power-Down

InternalChannelDecode

SAR Timing

4

6

Page 250: Control Motor Tesis

Functional Description

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-35

Figure 28-20. Conversion Timing

If the amplifier bypass mode is enabled for a conversion by setting the amplifier bypass (BYP) field in theCCW, the timing changes to that shown in Figure 28-21. See Section 28.6.7, “Conversion Command WordTable (CCW) for more information on the BYP field. The initial sample time is eliminated, reducing thepotential conversion time by two QCLKs. When using the bypass mode, the external circuit should be oflow source impedance (typically less than 10 kΩ). Also, the loading effects on the external circuitry of theQADC need to be considered, because the benefits of the sample amplifier are not present.

NOTEBecause of internal RC time constants, use of a two QCLK sample time inbypass mode will cause serious errors when operating the QADC at highfrequencies.

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 isconnected to the sample buffer amplifier or to the sample capacitor. The multiplexer also includes positiveand negative stress protection circuitry, which prevents deselected channels from affecting the selectedchannel 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 externalfactors (higher bandwidth or higher impedance) are less critical to accuracy. The input voltage is bufferedonto 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.

Sample Time Successive Approximation Resolution Sequence

QCLK

BufferSampleTime:

2 Cycles

FinalSampleTime:

n Cycles(2,4,8,16)

ResolutionTime:

10 Cycles

Sample Time Successive Approximation Resolution Sequence

QCLK

SampleTime:

n CYCLES(2,4,8,16)

ResolutionTime:

10 Cycles

Page 251: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-36 Freescale Semiconductor

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 conversionvalue one bit at a time, starting with the MSB. After accumulating the 10 bits of the conversion result, theSAR 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 signalindicates to the A/D converter that the desired channel has been sent to the MUX. CCW[IST[1:0]] denotesthe desired sample time. CCW[BYP] determines whether to bypass the sample amplifier. Once the end ofconversion has been reached a signal is sent to the queue control logic indicating that a result is availablefor storage in the result RAM.

28.8 Digital Control SubsystemThe digital control subsystem includes the control logic to sequence the conversion activity, the systemclock 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 twoqueues 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 operatedusing one of several different scan modes. The scan modes for queue 1 and queue 2 are programmed incontrol registers QACR1 and QACR2. Once a queue has been started by a trigger event (any of the waysto cause the QADC to begin executing the CCWs in a queue or subqueue), the QADC performs a sequenceof 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 orconflict.

28.8.1.1 Queue Priority

Queue 1 has priority over queue 2 execution. These cases show the conditions under which queue 1 assertsits 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

Page 252: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-37

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 pausedThe pause feature can be used to divide queue 1 and/or queue 2 into multiple subqueues. A subqueue isdefined 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 isshown 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 ofeach of the subqueues within queue 1. Similarly, the operating mode for queue 2 determines the type oftrigger 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 thereare six subqueues within queue 1, a separate rising edge is required on the external trigger signal afterevery 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 isexecuted and the pause state is entered. Execution can only continue with the next CCW, which is thebeginning of the next subqueue. A subqueue cannot be executed a second time before the overall queueexecution has been completed.

Page 253: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-38 Freescale Semiconductor

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 isset. When a continuous-scan mode is selected, a trigger event occurring after the completion of the lastsubqueue (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 aftercompleting the conversion specified in the CCW with the pause bit. The pause flag is set in QASR0, anda pause interrupt may be requested. The status of the queue is shown to be paused, indicating completionof a subqueue. The QADC then waits for another trigger event to again begin execution of the nextsubqueue.

28.8.1.2 Queue Priority Schemes

Because there are two conversion command queues and only one A/D converter, a priority schemedetermines which conversion occurs. Each queue has a variety of trigger events that are intended to initiateconversions, and they can occur asynchronously in relation to each other and other conversions inprogress. For example, a queue can be idle awaiting a trigger event; a trigger event can have occurred, butthe first conversion has not started; a conversion can be in progress; a pause condition can exist awaitinganother trigger event to continue the queue; and so on.

Beginning of Queue 1 00

Channel Select,Sample, Hold, A/D Conversion

Conversion CommandResult Word Table

0

Pause

Word (CCW) Table

0

0

1

0

0

0

1

0

Pause

00

P

0

Pause

0

0

1

0

1

0

1

0

Pause

P

End of Queue 1

Beginning of Queue 2BQ2

Pause

Pause

End of Queue 2

P

1

063 63

Page 254: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-39

The following paragraphs and figures outline the prioritizing criteria used to determine which conversionoccurs in each overlap situation.

NOTEEach situation in Figure 28-23 through Figure 28-33 is labeled S1 throughS19. In each diagram, time is shown increasing from left to right. Theexecution of queue 1 and queue 2 (Q1 and Q2) is shown as a string ofrectangles representing the execution time of each CCW in the queue. Inmost of the situations, there are four CCWs (labeled C1 to C4) in both queue1 and queue 2. In some of the situations, CCW C2 is presumed to have thepause bit set, to show the similarities of pause and end-of-queue asterminations of queue execution.

Trigger events are described in Table 28-22.

When a trigger event causes a CCW execution in progress to be aborted, the aborted conversion is shownas 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.

Below the queue execution flows are three sets of blocks that show the status information that is madeavailable 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 twoqueues. Two transition status cases, QS = 0011 and QS = 0111, are not shown because they exist only verybriefly between stable status conditions.

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)

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 overrunerror (TOR)

Set when a new trigger event occurs before the queue is finished servicing the previous trigger event

Page 255: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-40 Freescale Semiconductor

The first three examples in Figure 28-23 through Figure 28-25 (S1, S2, and S3) show what happens whena new trigger event is recognized before the queue has completed servicing the previous trigger event onthe same queue.In situation S1 (Figure 28-23), one trigger event is being recognized on each queue while that queue is stillworking on the previously recognized trigger event. The trigger overrun error status bit is set, and thepremature trigger event is otherwise ignored. A trigger event that occurs before the servicing of theprevious trigger event is through does not disturb the queue execution in progress.

Figure 28-23. CCW Priority Situation 1

In situation S2 (Figure 28-24), more than one trigger event is recognized before servicing of a previoustrigger event is complete. The trigger overrun bit is again set, but the additional trigger events are otherwiseignored. After the queue is complete, the first newly detected trigger event causes queue execution to beginagain. When the trigger event rate is high, a new trigger event can be seen very soon after completion ofthe previous queue, leaving little time to retrieve the previous results. Also, when trigger events areoccurring at a high rate for queue 1, the lower priority queue 2 channels may not get serviced at all.

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 bitis set the same way and that queue execution continues unchanged.

Q1:

Q2:

QS:

IDLE

IDLE ACTIVE IDLE

0000 1000 0000 0010 0000

TOR1

T1 T1

Q1: C1 C2 C3 C4

CF1C1 C2 C3 C4

TOR2

T2 T2

Q2:

CF2

IDLE ACTIVE

T1

ACTIVE IDLEQ1:

Q2:

QS:

IDLE ACTIVE

IDLE ACTIVE IDLE

1000 1000 0000 0010 0000

C1 C2 C3 C4

TOR2

T2 T2

Q2:

CF2

IDLE

C1 C2 C3 C4

T1

CF1

C1 C2 C3 C4

TOR1

T1

Q1:

CF1TOR1

T1

TOR1

T1

TOR2

T2

Page 256: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-41

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 isactively being serviced.Situation S4 (Figure 28-26) shows that a queue 2 trigger event is recognized while queue 1 is active issaved, and as soon as queue 1 is finished, queue 2 servicing begins.

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 isbusy, the trigger overrun error bit is set, but queue 1 execution is not disturbed. Situation S5 also showsthat the effect of queue 2 trigger events during queue 1 execution is the same when the pause feature isused for either queue.

PAUSE Q1:

Q2:

QS:

IDLE ACTIVE

IDLE ACTIVE IDLE

1000 0110 0001 0010

ACTIVE

0000

IDLE

C1 C2

T1 T1

Q1:

TOR1 PF1

C1 C2

0000

Q2:

0100

TOR2 PF2

T2 T2

0101

C3 C4

T1 T1

TOR1 CF1

ACTIVE

PAUSE

1001

C3 C4

CF2

T2 T2

TOR2

Q1:

Q2:

QS:

IDLE

IDLE ACTIVE IDLE

0000 1000 0010

ACTIVE

0000

C1 C2 C3 C4

T1

Q1:

CF1

Q2:C1 C2 C3 C4

T2

CF2

IDLE

1011

TRIGGERED

Page 257: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-42 Freescale Semiconductor

Figure 28-27. CCW Priority Situation 5

The remaining situations, S6 through S11, show the impact of a queue 1 trigger event occurring duringqueue 2 execution. Because queue 1 has higher priority, the conversion taking place in queue 2 is abortedso 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 beforethe conversion is complete, so that queue 1 execution can begin. Queue 2 is considered suspended. Afterqueue 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 suspensionworks the same way.

Figure 28-28. CCW Priority Situation 6

Q1:

Q2:

QS:

IDLE

IDLE IDLE

0000 1000 0010

ACTIVE

0000

C1 C2

T1

Q1:

C1 C2

PF2

C3 C4

C3 C4

CF2

IDLE

1011

TRIG

Q2:

T2T2PF1

PAUSE

ACTIVE PAUSE

TOR2

T2T2CF1

TOR2

T1

ACTIVE

TRIG

0110

ACTIVE

ACTIVE

0101 1001 1011

IDLE

Q1:

Q2:

QS

IDLE

IDLE

0000 1000

ACTIVE

C1 C2

T1

Q1:

C1

C3 C4

IDLE

Q2:

PF1

PAUSE

ACTIVE

CF1

T1

ACTIVE

SUSPEND

0100

ACTIVE

ACTIVE

0110 1010

C1 C2 C3 C4

CF2

T2

0010 0000

RESUME = 0

C2

Page 258: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-43

.

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 RESUMEbit set to a 1. When the RESUME bit is set, following suspension, queue 2 resumes execution with theaborted CCW, not the first CCW, in the queue.

Figure 28-30. CCW Priority Situation 8

T1

PAUSE Q1:

Q2:

QS:

IDLE ACTIVE

IDLE ACTIVE IDLE

0010 0110 1010 0010

ACTIVE

0000

IDLE

Q1:

PF1

C1 C2

0000 1010

ACTIVE

0110

C1Q2:

T2

C1

PF2

T1

C3 C4

CF1

C3

CF2

SUSPEND PAUSE SUSPEND

T2

C1 C3C2

ACTIVE ACT

0101

C4

IDLE

Q1:

Q2:

QS:

IDLE

IDLE

0000 1000 0010

ACTIVE

C1 C2

T1

Q1:

C1

C3 C4

IDLE

Q2:

PF1

PAUSE

ACTIVE

CF1

T1

ACTIVE

SUSPEND

0100

ACTIVE

ACTIVE

0110 1010

C2 C3 C4

CF2

T2

0000

RESUME=1C2

Page 259: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-44 Freescale Semiconductor

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 isdetected for queue 2 while the queue is suspended, the trigger overrun error bit is set, the same as if queue2 were being executed when a new trigger event occurs. Trigger overrun on queue 2 thus allows the userto know that queue 1 is taking up so much QADC time that queue 2 trigger events are being lost.

Figure 28-32. CCW Priority Situation 10

T1

PAUSE Q1:

Q2:

QS:

IDLE ACTIVE

IDLE ACT IDLE

0010 0110 1010 0010

ACTIVE

0000

IDLE

Q1:

PF1

C1 C2

0000 1010 0101

ACTIVE

PAUSE

0110

C1Q2:

T2

C2

PF2

T1

C3 C4

CF1

C4

CF2

SUSPEND ACT ACTIVE SUSPEND

T2

C3C1 RESUME=1C2 C4

T1 T1

PAUSE Q1:

Q2:

QS:

IDLE ACTIVE

IDLE ACTIVE IDLE

0010 0110 1010 0010

ACTIVE

0000

IDLE

Q1:

PF1

C1 C2

0000 1010 0101

ACTIVE

PAUSE

0110

Q2:

T2

PF2

C1 C2

C3 C4

CF1

C3 C4

CF2

T2

C3

SUSPEND ACTIVE

C1

ACT SUSPEND

T2

TOR2

T2

TOR2

RESUME = 0C2

Page 260: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-45

Figure 28-33. CCW Priority Situation 11

The previous situations cover normal overlap conditions that arise with asynchronous trigger events on thetwo queues. An additional conflict to consider is that the freeze condition can arise while the QADC isactively 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 isdetected, the QADC completes the conversion in progress, unlike the abort that occurs when queue 1suspends queue 2. After the freeze condition is removed, the QADC continues queue execution with thenext CCW in sequence.Trigger events that occur during freeze are not captured. When a trigger event is pending for queue 2 beforefreeze begins, that trigger event is remembered when the freeze is passed. Similarly, when freeze occurswhile 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.

Figure 28-34. CCW Freeze Situation 12

T1 T1

C3 C4

CF1

PAUSE Q1:

Q2:

QS:

IDLE ACTIVE

IDLE ACT IDLE

0010 0110 1010 0010

ACTIVE

0000

IDLE

Q1:

PF1

C1 C2

0000 1010 0101

ACTIVE

PAUSE

0110

Q2:

T2

SUSPEND ACT

C1

ACTIVE SUSPEND

T2

TOR2

T2

TOR2

C2

PF2

C4

CF2

T2

C3C2 C4 RESUME = 1

C3 C4

CF1

C1 C2

T1

Q1:

FREEZE

Page 261: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-46 Freescale Semiconductor

Figure 28-35. CCW Freeze Situation 13

Figure 28-36. CCW Freeze Situation 14

Figure 28-37. . CCW Freeze Situation 15

Figure 28-38. CCW Freeze Situation 16

C1 C2

T2

Q2:

CF2

C3 C4

FREEZE

C1 C2

T1

Q1:

CF1

C3 C4

FREEZE

T1 T1

T2 T2

TRIGGERS IGNORED

C1 C2

T2

Q2:

CF2

C3 C4

FREEZE

T2 T2

T1 T1

TRIGGERS IGNORED

C1 C2

T1

Q1:

CF1

C3 C4

FREEZE

T1 T1

PF1

TRIGGERS IGNORED

Page 262: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-47

Figure 28-39. CCW Freeze Situation 17

Figure 28-40. CCW Freeze Situation 18

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.

C1 C2

T2

Q2:

CF2

C3 C4

FREEZE

T2 T2

PF2

TRIGGERS IGNORED

C1 C2

T1

Q1:

CF1

C3 C4

FREEZE

T2

C1 C2Q2: C3

CF2

C4TRIGGER CAPTURED, RESPONSE DELAYED AFTER FREEZE

C1 C2

T1

Q1:

CF1

C4

FREEZE

CF2

C4C1 C2

T2

Q2: C3

C3

C4

Page 263: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-48 Freescale Semiconductor

• BQ2 (beginning of queue 2) is set beyond the end of the CCW table (64–127) 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.

NOTEMultiple end-of-queue conditions may be recognized simultaneously,although there is no change in QADC behavior. For example, if BQ2 is setto CCW0, CCW0 contains the EOQ code, and a trigger event occurs onqueue 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 bitis in one CCW and an end-of-queue condition is in the next CCW. The conversion specified by the CCWwith the pause bit set completes normally. The pause flag is set. However, because the end-of-queuecondition 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-queuecondition occur in the same CCW. Both the pause and end-of-queue conditions are recognizedsimultaneously. The end-of-queue condition has precedence so a conversion is not performed for the CCWand 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 forautomatically scanning input channels.In single-scan mode, a single pass through a sequence of conversions defined by a queue is performed. Incontinuous-scan mode, multiple passes through a sequence of conversions defined by a queue areexecuted. 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.

Page 264: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-49

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 whenaccessing CCW table and result RAM. When both queues are disabled, it is safe to change the QCLKprescaler values.

28.8.5 Reserved Mode

Reserved mode is available for future mode definitions. When reserved mode is selected, the queue is notactive. 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 conversionsdefined by a queue. By programming the MQ1 field in QACR1 or the MQ2 field in QACR2, these modescan be selected:

• Software-initiated single-scan mode• Externally triggered single-scan mode• Externally gated single-scan mode• Interval timer single-scan mode

NOTEQueue 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 bitto a 1 in the queue’s control register. The single-scan enable bits, SSE1 and SSE2, are provided for queue1 and queue 2, respectively.Until a queue’s single-scan enable bit is set, any trigger events for that queue are ignored. The single-scanenable 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-scanenable 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 firstCCW in the queue. The single-scan enable bit remains set until the queue is completed. After the queuereaches completion, the QADC resets the single-scan enable bit to 0. Writing the single-scan enable bit toa 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. Theconversion 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 togenerate a trigger event internally, and queue execution begins immediately. In the other single-scan queueoperating modes, once the single-scan enable bit is written, the selected trigger event must occur beforethe queue can start. The single-scan enable bit allows the entire queue to be scanned once. A triggeroverrun is captured if a trigger event occurs during queue execution in an edge-sensitive external triggermode 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 settingthe single-scan enable bit to 1. Queue execution begins with the first CCW in the queue.

Page 265: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-50 Freescale Semiconductor

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-initiatedsingle-scan mode and writing the single-scan enable bit in QACR1 or QACR2. A trigger event is generatedinternally 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 isencountered. The queue remains idle until the single-scan enable bit is again set. While the time tointernally generate and act on a trigger event is very short, the queue status field can be read asmomentarily indicating that the queue is paused. The trigger overrun flag is never set while insoftware-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 fallingedge triggered modes are available. A scan must be enabled by setting the single-scan enable bit for thequeue.The first external trigger edge causes the queue to be executed one time. Each CCW is read and theindicated conversions are performed until an end-of-queue condition is encountered. After the queue iscompleted, the QADC clears the single-scan enable bit. The single-scan enable bit can be written again toallow 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 queueexecution rate. Analog samples can be taken in sync with an external event, even though applicationsoftware does not require data taken from every edge. Externally triggered single-scan mode can beenabled 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 isrequired for queue execution to continue. Software involvement is not required for queue execution tocontinue 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 polarityof 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 isclosed. Queue scan must be enabled by setting the single-scan enable bit for queue 1. If a pause isencountered, 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 areperformed until an end-of-queue condition is encountered. When queue 1 completes, the QADC sets thecompletion flag (CF1) and clears the single-scan enable bit. Set the single-scan enable bit again to allowanother 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 1stops, the single-scan enable bit is cleared, and the PF1 bit is set. The CWPQ1 field can be read todetermine the last valid conversion in the queue. The single-scan enable bit must be set again and the PF1

Page 266: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-51

bit should be cleared before another scan of queue 1 is initiated during the next open gate. The start ofqueue 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 fora 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 intervalcan range from 27 to 217 QCLK cycles in binary multiples. When the interval timer single-scan mode isselected and the single-scan enable bit is set in QACR1 or QACR2, the timer begins counting. When thetime interval elapses, an internal trigger event is generated to start the queue and the QADC beginsexecution with the first CCW.The QADC automatically performs the conversions in the queue until a pause or an end-of-queuecondition is encountered. When a pause occurs, queue execution stops until the timer interval elapsesagain, and queue execution continues. When queue execution reaches an end-of-queue situation, thesingle-scan enable bit is cleared. Set the single-scan enable bit again to allow another scan of the queue tobe initiated by the interval timer.The interval timer generates a trigger event whenever the time interval elapses. The trigger event maycause queue execution to continue following a pause or may be considered a trigger overrun. Once queueexecution 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 theend-of-queue. However, if both queues are enabled for either single-scan or continuous interval timermode, the end-of-queue condition will not reset the timer while the other queue is active. In this case, thetimer will reset when both queues have reached end-of-queue. See Section 28.8.9, “Periodic/IntervalTimer 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 ofconversions 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

NOTEQueue 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 controlregister does not have any meaning or effect. As soon as the queue operating mode is programmed, theselected trigger event can initiate queue execution.

Page 267: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-52 Freescale Semiconductor

In the case of software-initiated continuous-scan mode, the trigger event is generated internally and queueexecution begins immediately. In the other continuous-scan queue operating modes, the selected triggerevent must occur before the queue can start. A trigger overrun is captured if a trigger event occurs duringqueue execution in the externally triggered continuous-scan mode or the periodic timer continuous-scanmode.After queue execution is complete, the queue status is shown as idle. Because the continuous-scan queueoperating modes allow the entire queue to be scanned multiple times, software involvement is not neededfor queue execution to continue from the idle state. The next trigger event causes queue execution to beginagain, starting with the first CCW in the queue.

NOTEIn continuous-scan modes, all samples are guaranteed to be taken duringone pass through the queue (coherently), except when a queue 1 triggerevent halts queue 2 execution. The time between consecutive conversionshas been designed to be consistent. However, for queues that end with aCCW containing the EOQ code (channel 63), the time between the lastqueue conversion and the first queue conversion requires one additionalCCW 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 triggerevents, 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 bythe QADC. Queue execution begins immediately. If a pause is encountered, another trigger event isgenerated internally, and execution continues without pausing. When the end-of-queue is reached, anotherinternal 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 beread as momentarily indicating that the queue is idle. The trigger overrun flag is never set while insoftware-initiated continuous-scan mode.The software-initiated continuous-scan mode keeps the result registers updated more frequently than anyof the other queue operating modes. The result table can always be read to get the latest converted valuefor 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 onlywith queue 2. When software-initiated continuous-scan mode is chosen for queue 1, that queue operatescontinuously and queue 2, being lower in priority, never gets executed. The short interval of time betweena 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 thatdo not need to be synchronized to anything or for slow-to-change analog channels. Interrupts are normallynot used with the software-initiated continuous-scan mode. Rather, the latest conversion results can be readfrom the result table at any time. Once initiated, software action is not needed to sustain conversions ofchannel.

28.8.7.2 Externally Triggered Continuous-Scan Mode

The QADC provides external trigger signals for both queues. When externally triggered continuous-scanmode is selected, a transition on the associated external trigger signal initiates queue execution. The

Page 268: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-53

polarity of the external trigger signal is programmable, so that a mode which begins queue execution onthe rising or falling edge can be selected. Each CCW is read and the indicated conversions are performeduntil an end-of-queue condition is encountered. When the next external trigger edge is detected, queueexecution 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 isrequired for queue execution to continue. Software involvement is not needed for queue execution tocontinue from the paused state.Some applications need to synchronize the sampling of analog channels to external events. There are caseswhen it is not possible to use software initiation of the queue scan sequence, because interrupt responsetimes 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 isselected, the input level on the associated external trigger signal enables and disables queue execution. Thepolarity of the external gate signal is fixed so that a high level opens the gate and a low level closes thegate. Once the gate is open, each CCW is read and the indicated conversions are performed until the gateis 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 pauseflag does not set, and execution continues without pausing.The purpose of externally gated continuous-scan mode is to continuously collect digitized samples whilethe gate is open and to have the most recent samples available. It is up to the programmer to ensure thatthe 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 rollover to the beginning and continue conversions until the gate closes. If the gate remains open and the CF1flag is not cleared, when the queue completes a second time the TOR1 flag will set and the queue willroll-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 anincomplete queue. The CWPQ1 field can be read to determine the last valid conversion in the queue. If thegate opens again, execution of queue 1 restarts. The start of queue 1 is always the first CCW in the CCWtable. The condition of the gate is only sampled after each conversion during queue execution, so closingthe 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 beselected. 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 programmedinterval elapses, the timer generated trigger event starts the appropriate queue. The QADC automaticallyperforms the conversions in the queue until an end-of-queue condition or a pause is encountered. When apause 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 CCWin the queue.The periodic timer generates a trigger event whenever the time interval elapses. The trigger event maycause queue execution to continue following a pause or queue completion or may be considered a triggeroverrun. As with all continuous-scan queue operating modes, software action is not needed between

Page 269: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-54 Freescale Semiconductor

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/Dconverter state machine which controls the timing of the conversion. The QCLK is also the input to a17-stage binary divider which implements the periodic/interval timer. To retain the specified analogconversion accuracy, the QCLK frequency (fQCLK) must be within the tolerance specified in MCF5282Electrical Characteristics.Before using the QADC, the prescaler must be initialized with values that put the QCLK within thespecified range. Though most applications initialize the prescaler once and do not change it, writeoperations to the prescaler fields are permitted.

Figure 28-42. QADC Clock Subsystem Functions

CAUTIONA change in the prescaler value while a conversion is in progress is likely tocorrupt the result. Therefore, any prescaler write operation should be doneonly when both queues are in the disabled modes.

To accommodate the wide range of the system clock frequency, QCLK is generated by a programmableprescaler which divides the system clock. To allow the A/D conversion time to be maximized across thespectrum of system clock frequencies, the QADC prescaler permits the QCLK frequency to be softwareselectable. 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 theseconditions:

ATD ConverterState Machine

27 28 29 210 211 212 213 214 215 216 217

Periodic Timer/Interval TimerSelect

Binary Counter

Queue 1 and Queue 2 TimerMode Rate Selection

Input Sample Timefrom CCW SAR

SAR Control

Periodic/Interval TriggerEvent for Q1 and Q2

Prescaler

System Clock

2

8

10

2

QPR[6:0]

Divideby 2

Page 270: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-55

• 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.

NOTEInterval timer single-scan mode does not start the periodic/interval timeruntil 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 andQACR2 to be reset to 0, a valid periodic or interval timer mode must be written after leaving stop mode torelease the timer from reset.When QADC debug mode is entered and a periodic or interval timer mode is selected, the timer counteris reset after the conversion in progress completes. When the periodic or interval timer mode has beenenabled (the timer is counting), but a trigger event has not been issued, debug mode takes effectimmediately, and the timer is held in reset. Removal of the QADC debug condition restarts the counterfrom 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 eachentry implemented. The CCW table is written by the user and is not modified by the QADC. Each CCWrequests the conversion of one analog channel to a digital result. The CCW specifies the analog channelnumber, the input sample time, and whether the queue is to pause after the current CCW. The 10implemented bits of the CCW can be read and written. The remaining six bits are unimplemented and readas 0s; write operations have no effect. Each location in the CCW table corresponds to a location in theresult word table. When a conversion is completed for a CCW entry, the 10-bit result is written in thecorresponding result word entry. The beginning of queue 1 is the first location in the CCW table. The first location of queue 2 is specifiedby 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 queue2, 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.

Page 271: Control Motor Tesis

Queued Analog-to-Digital Converter (QADC)

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

28-56 Freescale Semiconductor

Figure 28-43. QADC Conversion Queue Operation

To prepare the QADC for a scan sequence, write to the CCW table to specify the desired channelconversions. The criteria for queue execution is established by selecting the queue operating mode. Thequeue operating mode determines what type of trigger event starts queue execution. A trigger event refersto any of the ways that cause the QADC to begin executing the CCWs in a queue or subqueue. An externaltrigger 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, thescan must be engaged by setting the single-scan enable bit. When a continuous-scan mode is selected, thequeue remains active in the selected queue operating mode after the QADC completes each queue scansequence.During queue execution, the QADC reads each CCW from the active queue and executes conversions inthree stages:

• Initial sample• Final sample

Beginning of Queue 1 00

Channel Select,Sample, Hold, A/D Conversion

Conversion CommandResult Word Table Word (CCW) Table

00

End of Queue 1

Beginning of Queue 2

End of Queue 263 63

BYPP IST CHAN

89 [7:6] [5:0]

P — Pause after Conversionuntil Next Trigger

BYP — Bypass Buffer AmplifierIST — Input Sample TimeCHAN — Channel Number and

End-of-Queue Code

10-bit Conversion CommandWord Format

0 RESULT

[9:0]

10-bit Result, Readable inThree 16-BIT Formats

0 0 0 0 0

15 14 13 12 11 10

0RESULT 0 0 0 0 0

Right-Justified, Unsigned Result

Left-Justified, Unsigned Result

Left-Justified, Signed Result

0RESULT 0 0 0 0 0S

[5:0]

[5:0]

[15:6]

[15:6]

Page 272: Control Motor Tesis

Digital Control Subsystem

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 28-57

• ResolutionDuring initial sample, a buffered version of the selected input channel is connected to the sample capacitorat the input of the sample buffer amplifier.During the final sample period, the sample buffer amplifier is bypassed, and the multiplexer input chargesthe 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 theresult word table. The QADC continues to sequentially execute each CCW in the queue until the end ofthe 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 triggerevent occurs. The pause status flag bit is set, and an interrupt may optionally be requested. After the triggerevent occurs, the paused state ends, and the QADC continues to execute each CCW in the queue untilanother 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, aninterrupt 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 queue’s operating mode is changed to disabled. Putting a queue into the disabled mode does not power down the converter.

• Changing a queue’s 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 theQADC after completing an analog conversion specified by the corresponding CCW table entry. The resultword table can be read or written, but in normal operation is only read to obtain analog conversions fromthe QADC. Unimplemented bits read as 0s and writes have no effect.

Page 273: Control Motor Tesis

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 33-1

Chapter 33 Electrical CharacteristicsThis chapter contains electrical specification tables and reference timing diagrams for the MCF5282microcontroller unit. This section contains detailed information on power considerations, DC/ACelectrical characteristics, and AC timing specifications of MCF5282.The electrical specifications are preliminary and are from previous designs or design simulations. Thesespecifications 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 aftercomplete characterization and device qualifications have been completed.

NOTEThe parameters specified in this MCU document supersede any valuesfound in the module specifications.

33.1 Maximum RatingsTable 33-1. Absolute Maximum Ratings1, 2

1 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.

Rating Symbol Value Unit

Supply Voltage VDD – 0.3 to +4.0 V

Clock Synthesizer Supply Voltage VDDPLL – 0.3 to +4.0 V

RAM Memory Standby Supply Voltage VSTBY – 0.3 to + 4.0 V

Flash Memory Supply Voltage VDDF – 0.3 to +4.0 V

Flash Memory Program / Erase Supply Voltage VPP – 0.3 to + 6.0 V

Analog Supply Voltage VDDA – 0.3 to +6.0 V

Analog Reference Supply Voltage VRH – 0.3 to +6.0 V

Analog ESD Protection Voltage VDDH – 0.3 to +6.0 V

Digital Input Voltage 3 VIN – 0.3 to + 6.0 V

Analog Input Voltage VAIN – 0.3 to + 6.0 V

EXTAL pin voltage VEXTAL 0 to 3.3 V

XTAL pin voltage VXTAL 0 to 3.3 V

Instantaneous Maximum CurrentSingle 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 °C

Storage Temperature Range Tstg – 65 to 150 °C

Maximum operating junction temperature Tj 105 oC

ESD Target for Human Body Model6 HBM 2000 V

Page 274: Control Motor Tesis

Electrical Characteristics

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

33-2 Freescale Semiconductor

33.2 Thermal CharacteristicsTable 33-2 lists thermal resistance values.

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).

3 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.

4 All functional non-supply pins are internally clamped to VSS and VDD.5 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.

6 All ESD testing methodology is in conformity with CDF-AEC-Q100 Stress Test Qualification for Automotive Grade Integrated Circuits.

Table 33-2. Thermal Characteristics

Characteristic Symbol Value Unit

Junction to ambient, natural convection Four layer board (2s2p) θJMA 261,2

1 θ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 customer’s system using the Ψjt parameter, the device power dissipation, and the method described in EIA/JESD Standard 51-2.

2 Per JEDEC JESD51-6 with the board horizontal.

°C/W

Junction to ambient (@200 ft/min) Four layer board (2s2p) θJMA 231,2 °C/W

Junction to board θJB 153

3 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.

°C/W

Junction to case θJC 104

4 Thermal resistance between the die and the case top surface as measured by the cold plate method (MIL SPEC-883 Method 1012.1).

°C/W

Junction to top of package Natural convection Ψjt 21,5

5 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.

°C/W

Page 275: Control Motor Tesis

DC Electrical Specifications

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 33-3

33.3 DC Electrical Specifications

The average chip-junction temperature (TJ) in °C can be obtained from:(1)

Where:TA= Ambient Temperature, ×CQJMA= Package Thermal Resistance, Junction-to-Ambient, ×C/WPD= PINT + PI/OPINT= IDD ¥ VDD, Watts - Chip Internal PowerPI/O= Power Dissipation on Input and Output Pins — User Determined

For most applications PI/O < PINT and can be neglected. An approximate relationship betweenPD and TJ (if PI/O is neglected) is:

(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 andTJ can be obtained by solving equations (1) and (2) iteratively for any value of TA.

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 V

Input Low Voltage VIL VSS – 0.3 0.35 x VDD V

Input Hysteresis VHYS 0.06 x VDD

— mV

Input Leakage CurrentVin = VDD or VSS, Input-only pins

Iin -1.0 1.0 µA

High Impedance (Off-State) Leakage CurrentVin = VDD or VSS, All input/output and output pins

IOZ -1.0 1.0 µA

Output High Voltage (All input/output and all output pins)IOH = –2.0 mA

VOH VDD - 0.5 __ V

Output Low Voltage (All input/output and all output pins)IOL = 2.0mA

VOL __ 0.5 V

Weak Internal Pull Up Device Current, tested at VIL Max. IAPU -10 -130 µA

Input Capacitance 2

All input-only pinsAll input/output (three-state) pins

Cin——

77

pF

TJ TA PD ΘJMA×( )+=

PD K TJ 273°C+( )÷=

Page 276: Control Motor Tesis

Electrical Characteristics

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

33-4 Freescale Semiconductor

33.4 Power Consumption Specifications

Figure 33-1 shows typical WAIT/DOZE and RUN mode power consumption for both master and singlechip mode as measured on an M5282EVB.For master mode the RUN mode current was measured executing a continuous loop that performs nooperation while running from the on-chip SRAM.For WAIT/DOZE mode measurements the peripherals on the device are in their default power savingsmode, so the WAIT and DOZE power consumption are the same. Some modules can be programmed toshutdown 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 theUART0 and FEC pins that are enabled for their module functionality; however, neither module is beingaccessed at the time of the current measurement. Single chip RUN mode current was measured executinga continuous loop that performs no operation while running from the on-chip Flash.

Load Capacitance3

(50% Partial Drive)(100% Full Drive)

CL 2550

pF

Supply Voltage (includes core modules and pads) VDD 2.7 3.6 V

RAM Memory Standby Supply Voltage Normal Operation: VDD > VSTBY - 0.3 V Standby Mode: VDD < VSTBY - 0.3 V

VSTBY0.01.8

3.63.6

V

Flash Memory Supply VoltageVDDF 2.7 3.6

V

1 Refer to Table 33-8 through Table 33-12 for additional PLLQADC, and Flash specifications.2 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.

Table 33-4. STOP Mode Current Consumption Specifications

Characteristic SymbolTypical–

Master Mode

Typical–Single Chip

Mode1

1 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.

Max2

2 Maximum values can vary depending on the system’s state and signal loading.

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 µA

Table 33-3. DC Electrical Specifications1 (continued)

(VSS = VSSPLL= VSSF = VSSA= 0 VDC)

Characteristic Symbol Min Max Unit

Page 277: Control Motor Tesis

Power Consumption Specifications

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 33-5

Figure 33-1. Typical WAIT/DOZE Mode Current Consumption

Table 33-5 lists the estimated power consumption for individual modules. The current consumption is forthe 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 1 µA/MHz

FlexCAN 15 µA/MHz

QSPI, UART, I2C, and Timers

75 µA/MHz

0

50

100

150

200

250

8 16 24 32 40 48 56 64 72 80

Frequency (MHz)

Idd

(mA

) Master mode - RUNMaster mode - WAITSingle chip - RUNSingle chip - WAIT

Page 278: Control Motor Tesis

Electrical Characteristics

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

33-6 Freescale Semiconductor

Table 33-7 lists the maximum power consumption specifications.

Table 33-6. Typical Application Power Consumption

Application Current

Dhrystone benchmark running from cache and on-chip SRAM (running at 64 MHz fsys)

181.6 mA

dBUG ROM monitor running from external flash and SDRAM (running at 64 MHz fsys)

155 mA

Table 33-7. Maximum Power Consumption Specifications

Characteristic Symbol Typical Max Unit

Operating Supply Current 1

Master Mode• 66 MHz• 80 MHzSingle Chip ModeWAIT/DOZE• 66 MHz• 80 MHz

1 Current measured at maximum system clock frequency, all modules active, and default drive strength with matching load.

IDD

——————

200240150

125150

mAmAmA

mAmA

Clock Synthesizer Supply CurrentNormal 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————

42110

mAmAmAµA

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———

10720

µAmAµA

Flash Memory Supply Current Read Program or Erase2

Idle STOP

2 Programming and erasing all 8 blocks of the Flash.

IDDF16.53

254

1.64

0.2

3 Measured with fsys of 64 MHz.4 Measured with fsys of 32 MHz and fclk of 187.5 kHz.

30642010

mAmAmAµA

Analog Supply CurrentNormal OperationLow-Power Stop

IDDA——

5.010.0

mAµA

Page 279: Control Motor Tesis

Phase Lock Loop Electrical Specifications

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 33-7

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 Symbol Min Max Unit

PLL Reference Frequency Range Crystal reference External reference1:1 Mode

fref_crystalfref_extfref_1:1

22

33.33

10.010.080

MHz

System Frequency 1

External Clock ModeOn-Chip PLL Frequency

1 All internal registers retain data at 0 Hz.

fsys0

fref / 328080

MHz

Loss of Reference Frequency 2, 4

2 “Loss of Reference Frequency” is the reference frequency detected internally, which transitions the PLL into self clocked mode.

fLOR 100 1000 kHz

Self Clocked Mode Frequency 3, 4

3 Self clocked mode frequency is the frequency that the PLL operates at when the reference frequency falls below fLOR with default MFD/RFD settings.

fSCM 1 5 MHz

Crystal Start-up Time 4, 5

4 This parameter is characterized before qualification rather than 100% tested.5 Proper PC board layout procedures must be followed to achieve specifications.

tcst — 10 ms

EXTAL Input High VoltageCrystal ModeAll other modes (1:1, Bypass, External)

VIHEXTVDD- 1.0

2.0VDDVDD

V

EXTAL Input Low VoltageCrystal ModeAll other modes (1:1, Bypass, External)

VILEXTVSSVSS

1.00.8

V

XTAL Output High VoltageIOH = 1.0 mA

VOLVDD- 1.0 —

V

XTAL Output Low VoltageIOL = 1.0 mA

VOL— 0.5

V

XTAL Load Capacitance6

6 Load Capacitance determined from crystal manufacturer specifications and will include circuit board parasitics.

— — pF

PLL Lock Time4,7

7 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).

tlpll — 500 µs

Power-up To Lock Time 4, 5,8

With Crystal ReferenceWithout Crystal Reference

tlplk——

10.5500

msµs

1:1 Clock Skew (between CLKOUT and EXTAL) 9 tskew -2 2 ns

Duty Cycle of reference 4 tdc 40 60 % fsys

Frequency un-LOCK Range fUL - 1.5 1.5 % fsys

Frequency LOCK Range fLCK - 0.75 0.75 % % fsys

CLKOUT Period Jitter 4, 5, 7, 10,11 , Measured at fSYS MaxPeak-to-peak Jitter (Clock edge to clock edge)Long Term Jitter (Averaged over 2 ms interval)

Cjitter——

10.01

% fsys

Page 280: Control Motor Tesis

Electrical Characteristics

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

33-8 Freescale Semiconductor

33.6 QADC 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.

Table 33-9. QADC Absolute Maximum Ratings

Parameter Symbol Min Max Unit

Analog Supply, with reference to VSSA VDDA –0.3 6.0 V

Internal Digital Supply 1, with reference to VSS

1 For internal digital supply of VDD = 3.3V typical.

VDD –0.3 4.0 V

Reference Supply, with reference to VRL VRH –0.3 6.0 V

VSS Differential Voltage VSS – VSSA –0.1 0.1 V

VDD Differential Voltage 2

2 Refers to allowed random sequencing of power supplies.

VDD – VDDA –6.0 4.0 V

VREF Differential Voltage VRH – VRL –0.3 6.0 V

VRH to VDDA Differential Voltage 3

3 Refers to allowed random sequencing of power supplies.

VRH – VDDA –6.0 6.0 V

VRL to VSSA Differential Voltage VRL – VSSA –0.3 0.3 V

VDDH to VDDA Differential Voltage VDDH – VDDA –1.0 1.0 V

Maximum Input Current 4, 5, 6

4 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.

5 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.

6 Condition applies to one pin at a time.

IMA –25 25 mA

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 Symbol Min Max Unit

Analog Supply VDDA 3.3 5.5 V

VSS Differential Voltage VSS – VSSA -100 100 mV

Reference Voltage Low 2 VRL VSSA VSSA + 0.1 V

Reference Voltage High 2 VRH VDDA – 0.1 VDDA V

VREF Differential Voltage VRH – VRL 3.3 5.5 V

Page 281: Control Motor Tesis

QADC Electrical Characteristics

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

Freescale Semiconductor 33-9

Input Voltage VINDC VSSA–0.3 VDDA + 0.3 V

Input High Voltage, PQA and PQB VIH 0.7 (VDDA) VDDA + 0.3 V

Input Low Voltage, PQA and PQB VIL VSSA – 0.3 0.4(VDDA) V

Input Hysteresis, PQA, PQB 3 VHYS 0.5 — V

Output High Voltage, PQA/PQB 3IOH = TBD

VOHVDDH-0.8 —

V

Analog Supply CurrentNormal Operation 4

Low-Power Stop

IDDA——

5.010.0

mAµA

Reference Supply Current, DCReference Supply Current, Transient

IREFIREF

——

2502.0

µAmA

Load Capacitance, PQA/PQB CL — 50 pF

Input Current, Channel Off 5 IOFF -200 200 nA

Total Input Capacitance 6

PQA Not SamplingPQB Not Sampling

Incremental Capacitance added during sampling

CIN——

1510

5

pF

1 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.

2 To obtain full-scale, full-range results, VSSA ≤ VRL ≤ VINDC ≤ VRH ≤ VDDA3 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]

4 Current measured at maximum system clock frequency with QADC active.5 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.6 This parameter is characterized before qualification rather than 100% tested.

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

Page 282: Control Motor Tesis

Electrical Characteristics

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

33-10 Freescale Semiconductor

33.7 Flash Memory CharacteristicsThe Flash memory characteristics are shown in Table 33-12 and Table 33-13.

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 Symbol Min Max Unit

1 QADC Clock (QCLK) Frequency1

1 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.

FQCLK 0.5 2.1 MHz

2 Conversion Cycles CC 14 28 QCLK cycles

3

Conversion TimeFQCLK = 2.0 MHz1

Min = CCW/IST =%00Max = CCW/IST =%11

TCONV 7.0 14.0 µs

4 Stop Mode Recovery Time TSR — 10 µs

5 Resolution2

2 At VRH – VRL = 5.12 V, one count = 5 mV

— 5 — mV

6 Absolute (total unadjusted) error 3, 4, 5

FQCLK = 2.0 MHz 2, 2 clock input sample time

3 Accuracy tested and guaranteed at VRH – VRL = 5.0V ± 0.5V4 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.

5 Performance expected with production silicon.

AE-2 2 Counts

7 Absolute (total unadjusted) error 3, 4, 5

FQCLK = 2.0 MHz 2, 2 clock input sample time—

-3 3 Counts

Table 33-12. SGFM Flash Program and Erase Characteristics

(VDDF = 2.7 to 3.6 V)

Parameter Symbol Min Typ Max Unit

System clock (read only) fsys(R) 0 — 80 MHz

System clock (program/erase)1

1 Refer to the Flash section for more information

fsys(P/E) 0.15 — 80 MHz

Table 33-13. SGFM Flash Module Life Characteristics

(VDDF = 2.7 to 3.6 V)

Parameter Symbol Value Unit

Maximum number of guaranteed program/erase cycles1 before failure P/E 10,0002 Cycles

Data retention at average operating temperature of 85°C Retention 10 Years

Page 283: Control Motor Tesis

Electrical Characteristics

MCF5282 Coldfire Microcontroller User’s Manual, Rev. 2.3

33-12 Freescale Semiconductor

Figure 33-2. General Input Timing Requirements

33.9 Processor Bus Output Timing SpecificationsTable 33-14 lists processor bus output timings.

Table 33-15. External Bus Output Timing Specifications

Name Characteristic Symbol Min Max Unit

Control Outputs

B6a CLKOUT high to chip selects valid 1 tCHCV — 0.5tCYC +10 ns

B6b CLKOUT high to byte enables (BS[3:0]) valid2 tCHBV — 0.5tCYC +10 ns

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

Invalid Invalid

CLKOUT(66.67 MHz)TSETUP

THOLD

Input Setup And Hold

1.5V

trise = 1.5 nsVh = VIH

Vl = VIL

1.5V1.5V Valid

tfall = 1.5 nsVh = VIH

Vl = VIL

Input Rise Time

Input Fall Time

* The timings are also valid for inputs sampled on the negative clock edge.

Inputs

CLKOUT B4B5

Page 284: Control Motor Tesis

ANEXO 4

NMRA Electrical Standards for Digital

Command Control, July 2004.

Page 285: Control Motor Tesis

© 2001,2004 by the National Model Railroad Association, Inc.S-9.1 Electrical Standards for DCC Page 1 of 3 Printed: July 2004

5

Communication from a Digital Command Station to a Digital Decoder is accomplished by transmitting aseries of bits that convey instructions. A bit is a signal which represents one of two conditions, which wewill call "1" and "0". This portion of the standard covers the electrical characteristics of the digitalcommand control signal that encodes these bits.10

A: Technique For Encoding BitsThe 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. Theremaining transitions divide each bit into a first part and a last part. Digital Command Stations shallencode bits within this digital command control stream of transitions by varying the duration of the parts of15the 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 Stationcomponents shall transmit "1" bits with the first and last parts each having a duration of between 55 and 6120microseconds. A Digital Decoder must accept bits whose first and last parts have a duration of between 52and 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 orequal to 100 microseconds. To keep the DC component of the total signal at zero as with the "1" bits, the25first and last part of the "0" bit are normally equal to one another. Digital Command Station componentsshall transmit "0" bits with each part of the bit having a duration of between 95 and 9900 microsecondswith the total bit duration of the "0" bit not exceeding 12000 microseconds. A Digital Decoder must acceptbits whose first or last parts have a duration of between 90 and 10000 microseconds as a valid bit with thevalue of "0". Figure 1 provides an example of bits encoded using this technique.30

Figure 1: Bit Encoding

Digital Decoders must accept one bits whose positive and negative components differ by as much as 6microseconds.35

1 Note that since a locomotive or piece of rolling stock can be placed upon a given section of track facing ineither direction, it is impossible to define, from the point of view of a Digital Decoder, whether the first orlast part of a bit will have the "positive" voltage polarity.2 All timing measurements are done between zero volt crossings.

This Standard received approval from the NMRAmembership and Board of Trustees in January1994, July 2002 and July 2004.

NMRA STANDARD

Electrical Standards

For Digital Command Control,

All Scales

Adopted July 2004 S 9.1

Page 286: Control Motor Tesis

© 2001,2004 by the National Model Railroad Association, Inc.S-9.1 Electrical Standards for DCC Page 2 of 3 Printed: July 2004

One Bit Timing40

For Power Station Output under Load:

Relationship for One Bits ResultPeriod A < 55 µSec or Period A > 61 µSec BadPeriod A = Period B OK|Period A – Period B| <= 3 µSec OK|Period A – Period B| > 3 µSec Bad

Decoders must accept:

Relationship for One Bits ResultPeriod A >= 52µSec and Period A <= 64 µSec OKPeriod A = Period B OK|Period A – Period B| <= 6 µSec OK

B: Command Control Signal ShapeThe NMRA digital signal applied to the track by any Digital Command Control system, as measured at thepower station output, shall have the following characteristics, as measured under conditions ranging from45no load to the maximum continuous load permitted by the power source. Transitions that cross the regionbetween -4 volts and +4 volts3 shall occur at 2.5 volts per microsecond or faster. This signal may containnon-monotonic distortion at the zero-crossing transitions, provided that this distortion shall have anamplitude of no greater than +/- 2 volts4.

50Digital Decoders shall be designed to correctly decode signals with transitions whose slope is 2.0 volts permicrosecond or faster across the voltage range from -4 volts to +4 volts. A Digital Decoder shall correctlydecode 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 ofthe peak-to-peak amplitude of the NMRA digital signal5.55

The exact shape of the NMRA digital signal shall be designed to minimize electromagnetic radiation suchthat a large layout operated using this standard can meet applicable United States Federal CommunicationsCommission electromagnetic interference requirements6.

3 0 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 CErequirements.

Page 287: Control Motor Tesis

© 2001,2004 by the National Model Railroad Association, Inc.S-9.1 Electrical Standards for DCC Page 3 of 3 Printed: July 2004

C: Power Transmission and Voltage Limits For Transmitting60

Power Through the RailsThe baseline method for providing the power to operate locomotives and accessories, which shall besupported by all Digital Command Stations and Digital Decoders, is by full-wave rectification of thebipolar NMRA digital signal within the Digital Decoder7. In order to maintain power to the DigitalDecoders, gaps in bit transmission are only allowed at specified times (see S-9.2, Section C). The RMS65value of NMRA digital signal, measured at the track, shall not exceed by more than 2 volts8 the voltagespecified in standard S9 for the applicable scale9. In no case should the peak amplitude of the commandcontrol signal exceed +/- 22 volts. The minimum peak value of the NMRA digital signal needed to providepower to the decoder shall be +/-7 volts measured at the track. Digital Decoders intended for "N" andsmaller scales shall be designed to withstand a DC voltage of at least 24 volts as measured at the track.70Digital Decoders intended for scales larger than "N" shall be designed to withstand a DC voltage of atleast 27 volts as measured at the track.

7 Alternate means for supplying power are acceptable, provided that Digital Command Station power unitsare capable of producing the baseline track signal, and Digital Decoders are capable of operation from thebaseline track signal as described by this standard.8 The additional voltage is to compensate for voltage drop in the Digital Decoder, to ensure that themaximum 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 periodshave a stall rating that exceeds the amplitude of the signal, or sufficiently high impedance at 4-9 kHz toreduce the current to normal operating level. This appears to only be a concern for high-precision core-lesscan motors, which present a low impedance load, or for layouts using an NMRA digital signal with anamplitude in excess of +-18 volts.

ZERO-CROSSING +5uS +10uS0

5

10

15

20

25

TYP. N-SCALE SIGNAL

TYP. O/S/HO-SCALE SIGNAL

TYP. LARGE-SCALE SIGNAL

POWER STATION MINIMUM

VO

LTA

GE

Minimum Voltage for Power Stations

ZERO-CROSSING +5uS +10uS0

5

10

15

20

25

TYP. N-SCALE SIGNAL

TYP. O/S/HO-SCALE SIGNAL

TYP. LARGE-SCALE SIGNAL

N-SCALE DECODER MAXIMUM

NON N-SCALE DECODER MAXIMUM

VO

LTA

GE

Maximum Voltage for Decoders

ZERO-CROSSING +5uS +10uS0

5

10

15

20

25

TYP. N-SCALE SIGNAL

TYP. O/S/HO-SCALE SIGNAL

TYP. LARGE-SCALE SIGNAL

DECODER MINIMUM

VO

LTA

GE

Minimum Voltage for Decoders

ZERO-CROSSING +5uS +10uS0

5

10

15

20

25

TYP. N-SCALE SIGNAL

TYP. O/S/HO-SCALE SIGNAL

TYP. LARGE-SCALE SIGNAL

POWER STATION MAXIMUM

VO

LTA

GE

Maximum Voltage for Power Stations

Page 288: Control Motor Tesis

ANEXO 5

NMRA Communications Standards for Digital

Command Control, July 2004.

Page 289: Control Motor Tesis

© 2001-2004, by the National Model Railroad Association, Inc.S-9.2 Communications Standards for DCC Page 1 of 4 Printed: July 2004

5

This standard covers the format of the information sent via Digital Command Stations to Digital Decoders. A10Digital Command Station transmits this information to Digital Decoders by sending a series of bits using theNMRA digital signal described in S-9.1. This sequence of bits, termed a packet, is used to encode one of a set ofinstructions that the Digital Decoder operates upon. Packets must be precisely defined to ensure that the intendedinstructions can be properly encoded and decoded.

A. General Packet Format15

The following sequence of bits defines a valid NMRA packet. Any sequence of bits not meeting the fullspecifications of this general packet format is not, for the purpose of this standard, a "packet". Digital decodersshould not act on any instructions that are not contained within a valid packet while in the NMRA digital mode ofoperation1. Note, portions within square [ ] brackets must occur one or more times.

20Preamble: 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 forproper reception of a packet with more than 12 complete one bits. A command stationmust 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. ThePacket Start Bit terminates the preamble and indicates that the next bits are an addressdata 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 theaddress data byte. Address Data Bytes with values 00000000, 11111110, and 11111111are reserved for special operations and must not be transmitted except as provided in thisStandard 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, orerror detection purposes. The first transmitted data bit of each data byte shall be definedto 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.

1 It is permissible for Digital Decoders to accept formats in addition to the NMRA General Packet Format. SeeSection C for details.2 The first byte can also be used in special cases to indicate instructions. See the Service Mode RecommendedPractice (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 bitsfrom an alternative command control protocol. The DCC bitstream must continue for an additional 26 µS(minimum) after the packet end bit.

NMRA STANDARD

Communications Standards

For Digital Command Control,

All Scales

Adopted July 2004 S 9.2

This Standard received approval from the NMRAMembership and the Board of Trustees in January1994, July 2002 and July 2004.

Page 290: Control Motor Tesis

© 2001-2004, by the National Model Railroad Association, Inc.S-9.2 Communications Standards for DCC Page 2 of 4 Printed: July 2004

Figure 1 provides an example of an acceptable command control packet that uses three data bytes: one address databyte, one instruction data byte and one error detection data byte.

Preamble Address Data Byte Instruction Data Byte Error Detection Data Byte

Packet Start Bit Data Byte Start Bit Data Byte Start Bit Packet End Bit

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

25Figure 1 Example of a Transmitted Packet

B: Baseline PacketsThe Baseline Packets are included to provide the minimum interoperability between different systems. Morecomplex packet formats that support different types of decoders, additional functions, addresses and speeds areprovided in the Extended Packet Format Recommended Practice (RP-9.2.1). It is the intention of this Standard30that, in order to conform: a Command Station must encode operator control input in conformance with the BaselinePacket semantics; and a Digital Decoder must recognize and provide suitable locomotive control electrical output inconformance with the Baseline Packet semantics. Digital Decoder Idle Packets and Digital Decoder Broadcast StopPackets4 (defined below) are optional for Command Stations, and required for decoders.

35

Speed and Direction Packet For Locomotive Decoders

111111111111 0 0AAAAAAA 0 01DCSSSS 0 EEEEEEEE 1 Preamble Byte One Byte Two Byte Three (Error Detection Data Byte)

40

Byte One: Address Data Byte = 0AAAAAAA The address data byte contains the address of the intended recipientof the packet. Every Digital Decoder shall be capable of retaining and recognizing its own address forpurposes of responding to Baseline Packets. Locomotive Digital Decoders shall support the full range ofbaseline addresses in such a manner that this address is easily configurable by the user5. It is acceptablefor Digital Command Stations to restrict the number of valid addresses supported so long as this45restriction 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 anddirection information to the locomotive Digital Decoder. Bits 0-36 provides 4 bits for speed (S) with bit0 being the least significant speed bit. Bit four of byte 2 (C) by default shall contain one additional speed50bit, which is the least significant speed bit. For backward compatibility, this bit may instead be used tocontrol 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. Adirection bit with the value of "0" should cause the locomotive to go in the reverse direction. Bits 7 and 6contain the bit sequence "01"8 which are used to indicate that this instruction data byte is for speed and55direction.

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 addressconfiguration.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 positionwithin the locomotive.8 Other bit patterns in bits 7 and 6 are reserved for other types of instruction data, and are defined in the ExtendedPacket Format Recommended Practice (RP-9.2.1).

Page 291: Control Motor Tesis

© 2001-2004, by the National Model Railroad Association, Inc.S-9.2 Communications Standards for DCC Page 3 of 4 Printed: July 2004

CS3S2S1S0 Speed CS3S2S1S0 Speed CS3S2S1S0 Speed CS3S2S1S0 Speed

00000 Stop 00100 Step 5 01000 Step 13 01100 Step 2110000 Stop (I) 10100 Step 6 11000 Step 14 11100 Step 2200001 E-Stop* 00101 Step 7 01001 Step 15 01101 Step 2310001 E-Stop* (I) 10101 Step 8 11001 Step 16 11101 Step 2400010 Step 1 00110 Step 9 01010 Step 17 01110 Step 2510010 Step 2 10110 Step 10 11010 Step 18 11110 Step 2600011 Step 3 00111 Step 11 01011 Step 19 01111 Step 2710011 Step 4 10111 Step 12 11011 Step 20 11111 Step 28

• *Digital Decoders shall immediately stop delivering power to the motor.• (I) Direction bit may be ignored for directional sensitive functions. (Optional)60

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 thepresence of transmission errors. The contents of the Error Detection Data Byte shall be the bitwiseexclusive OR of the contents of the Address Data Byte and the Instruction Data Byte in the packet65concerned. (e.g. the exclusive OR of bit 0 of the address data byte and bit 0 of the instruction data bytewill be placed in bit 0 of the error detection data byte...) Digital Decoders receiving a Baseline Packetshall compare the received error detection data byte with the bitwise exclusive OR of the received addressand instruction data bytes and ignore the contents of the packet if this comparison is not identical.

70The example packet shown in figure 1 illustrates a baseline packet with the instruction to locomotive 55 to proceedin the forward direction at speed step 6.

Digital Decoder Reset Packet For All Decoders75

111111111111 000000000 0 00000000 0 00000000 1 Preamble Byte One Byte Two 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 aDigital Decoder Reset Packet. When a Digital Decoder receives a Digital Decoder Reset Packet, it shall erase all80volatile memory (including any speed and direction data), and return to its normal power-up state. If the DigitalDecoder is operating a locomotive at a non-zero speed when it receives a Digital Decoder Reset, it shall bring thelocomotive to an immediate stop.

Following a Digital Decoder Reset Packet, a Command Station shall not send any packets with an address data byte85between the range "01100100" and "01111111" inclusive within 20 milliseconds, unless it is the intent to enterservice mode9.

Digital Decoder Idle Packet For All Decoders90

111111111111 0 11111111 0 00000000 0 11111111 1 Preamble Byte One Byte Two Byte Three (Error Detection Data Byte)

A three byte packet, whose first byte contains eight "1"s, whose second byte contains eight "0"s and whose thirdand final byte contains eight "1"s, is defined as a Digital Decoder Idle Packet. Upon receiving this packet, Digital95Decoders shall perform no new action, but shall act upon this packet as if it were a normal digital packet addressedto some other decoder.

9 Digital Decoders can have their configurations altered immediately after a digital decoder reset packet. See theService Mode Recommended Practice(RP-9.2.3) for details.

Page 292: Control Motor Tesis

© 2001-2004, by the National Model Railroad Association, Inc.S-9.2 Communications Standards for DCC Page 4 of 4 Printed: July 2004

Digital Decoder Broadcast Stop Packets For All Decoders10

111111111111 0 00000000 0 01DC000S 0 EEEEEEEE 1100

Preamble 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 andwhose third and final byte contains an error byte that is identical to the second byte of the packet, is defined as a105Digital Decoder Broadcast Stop Packet. Upon receiving this packet where bit zero of byte two (S) contains a valueof "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 tocontrol a locomotive's motor shall stop delivering energy to the motor. If bit four of byte 2 (C) contains a value of110"1", the direction bit contained in bit five of byte 2 (D) may optionally be ignored for all direction sensitivefunctions.

C: Frequency Of Packet TransmissionPackets sent to Digital Decoders should be repeated as frequently as possible, as a packet may have been lost due tonoise or poor electrical conductivity between wheels and rails. Power may also be removed from the rails between115the Packet End Bit and the Preamble of the next packet to allow for alternative command control formats. A DigitalDecoder shall be able to act upon multiple packets addressed to it, provided the time between the packet end bit ofthe first packet and the packet start bit of the second packet are separated by at least 5 milliseconds11. If a decoderreceives a bit sequence with a missing or invalid data byte start bit, a missing or invalid packet end bit, or anincorrect error detection byte, it must recognize the next valid preamble sequence as the beginning of a new packet.120Alternative command control formats are specifically allowed between the packet end bit and the start of the nextpreamble.Manufacturers of decoders are encouraged to provide automatic conversion for a variety of power signals andcommand control formats in addition to the NMRA digital signal (per S-9.1), provided that automatic conversionto these alternate power signals can be disabled. If automatic conversion is enabled, Digital Decoders must remain125in digital mode and not convert to using any alternate power signal so long as the time between Packet Start Bits isless than or equal to 30 milliseconds in duration. If automatic conversion is disabled, Digital Decoders mustremain in digital mode regardless of the timing of Packet Start Bits. It shall be possible to configure DigitalCommand Stations to transmit at least one complete packet every 30 milliseconds as measured from the timebetween packet start bits12.13130

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 5milliseconds of each other for addresses in the range between 112-127 as older decoders may interpret these packets asservice mode packets (see RP-9.2.3).12 Some DCC decoders manufactured prior to the NMRA standards require a valid baseline packet be received every30 milliseconds to prevent analog power conversion.13 Longer repetition rates may result in less than optimal decoder performance

Page 293: Control Motor Tesis

ANEXO 6

Hojas de características (DataSheets)

Page 294: Control Motor Tesis

rev.04/01

Selective Photodiode EPD-740-5

Spectral range Type Technology Case

Infrared EPD-740-5 AlGaAs/AlGaAs/GaAs 5 mm plastic lens

DescriptionNarrow response range (740 nm peak),single heterostructure on the substrate

ApplicationsOptical communications,safety equipment

5,3

- 0,

3

7,1 - 0,6

1,1 - 0,1

10,6 - 0,6

6,2 - 0,5

0,7 - 0,4

0,8

- 0

,4

1,7

- 0

,1

Anode

2,54

16,5 - 2,0

2

Maximum Ratings

Parameter Value Unit

Storage Temperature - 40...+90 °C

Operating Temperature -40...+85 °CSoldering Temperature 240 °C

Optical and Electrical CharacteristicsTamb = 25°C, unless otherwise specified

Parameter Test conditions Symbol Min Typ Max Unit

Active area A 0.13 mm2

Peak sensitivity λSmax 700 740 780 nm

Spectral bandwidth at 50% Äλ0,5 60 nm

Acceptance angle at 50% Së 40 deg.

Responsivity at 740 nm VR = 0 V Së 0.5 A/W

Short-circuit current* VR = 0, Ee=1mW/cm²

ISC 1 µA

Dark current VR = 5 V, Ee=0 ID 40 200 pA

Reverse voltage IR = 10 µA VR 10 V

Junction capacitance VR = 0, Ee=0 Ñ 40 pF

Rise time

Fall time

RL = 50 ,

VR = 5 V

trtf

15

30ns

Parameter Test conditions Symbol Min Typ Max Unit*Light source is an AlGaAs LED with a peak emission wavelength of 740 nm

Page 295: Control Motor Tesis

Small and Thin ±5 g iMEMS® Accelerometer ADXL320

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.

FEATURES 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

APPLICATIONS Cost-sensitive motion- and tilt-sensing applications

Smart hand-held devices Mobile phones Sports and health-related devices PC security and PC peripherals

GENERAL DESCRIPTION

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 ADXL320’s 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.

The ADXL320 is available in a very thin 4 mm × 4 mm × 1.45 mm, 16-lead, plastic LFCSP.

FUNCTIONAL BLOCK DIAGRAM 04

993-

001

ADXL320

SENSOR

+3V

OUTPUTAMP

OUTPUTAMP

COM ST

VS

CDC DEMODACAMP

RFILT32kΩ

XOUTCX

YOUTCY

RFILT32kΩ

Figure 1.

Page 296: Control Motor Tesis

ADXL320

Rev. 0 | Page 2 of 16

TABLE OF CONTENTS Specifications..................................................................................... 3

Absolute Maximum Ratings............................................................ 4

ESD Caution.................................................................................. 4

Pin Configuration and Function Descriptions............................. 5

Typical Performance Characteristics (VS = 3.0 V) ....................... 7

Theory of Operation ...................................................................... 11

Performance ................................................................................ 11

Applications..................................................................................... 12

Power Supply Decoupling ......................................................... 12

Setting the Bandwidth Using CX and CY ................................. 12

Self-Test ....................................................................................... 12

Design Trade-Offs for Selecting Filter Characteristics: The Noise/BW Trade-Off.................................................................. 12

Use with Operating Voltages Other than 3 V............................. 13

Use as a Dual-Axis Tilt Sensor ................................................. 13

Outline Dimensions ....................................................................... 14

Ordering Guide .......................................................................... 14

REVISION HISTORY

9/04—Revision 0: Initial Version

Page 297: Control Motor Tesis

ADXL320

Rev. 0 | Page 3 of 16

SPECIFICATIONS1

TA = 25°C, VS = 3 V, CX = CY = 0.1 μF, Acceleration = 0 g, unless otherwise noted.

Table 1. Parameter Conditions Min Typ Max Unit SENSOR INPUT Each axis

Measurement Range ±5 g Nonlinearity % of full scale ±0.2 % Package Alignment Error ±1 Degrees Alignment Error X sensor to Y sensor ±0.1 Degrees Cross Axis Sensitivity ±2 %

SENSITIVITY (RATIOMETRIC)2 Each axis Sensitivity at XOUT, YOUT VS = 3 V 156 174 192 mV/g Sensitivity Change due to Temperature3 VS = 3 V 0.01 %/°C

ZERO g BIAS LEVEL (RATIOMETRIC) Each axis 0 g Voltage at XOUT, YOUT VS = 3 V 1.3 1.5 1.7 V 0 g Offset Versus Temperature ±0.6 mg/°C

NOISE PERFORMANCE Noise Density @ 25°C 250 μg/√Hz rms

FREQUENCY RESPONSE4 CX, CY Range5 0.002 10 μF RFILT Tolerance 32 ± 15% kΩ Sensor Resonant Frequency 5.5 kHz

SELF-TESTT

6 Logic Input Low 0.6 V Logic Input High 2.4 V ST Input Resistance to Ground 50 kΩ Output Change at XOUT, YOUT Self-test 0 to 1 55 mV

OUTPUT AMPLIFIER Output Swing Low No load 0.3 V Output Swing High No load 2.5 V

POWER SUPPLY Operating Voltage Range 2.4 5.25 V Quiescent Supply Current 0.48 mA Turn-On Time7 20 ms

TEMPERATURE Operating Temperature Range −20 70 °C

1 All minimum and maximum specifications are guaranteed. Typical specifications are not guaranteed. 2 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.

Page 298: Control Motor Tesis

ADXL320

Rev. 0 | Page 4 of 16

ABSOLUTE MAXIMUM RATINGS

Table 2. Parameter Rating Acceleration (Any Axis, Unpowered) 10,000 g Acceleration (Any Axis, Powered) 10,000 g VS −0.3 V to +7.0 V All Other Pins (COM − 0.3 V) to

(VS + 0.3 V) Output Short-Circuit Duration (Any Pin to Common) Indefinite Operating Temperature Range −55°C to +125°C Storage Temperature −65°C to +150°C

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.

Page 299: Control Motor Tesis

ADXL320

Rev. 0 | Page 5 of 16

PIN CONFIGURATION AND FUNCTION DESCRIPTIONS

NC XOUT

ST NC

COM YOUT

NC NC

COM COM COM NC

NC VS VS NC

NC = NO CONNECT

ADXL320TOP VIEW

(Not to Scale)

0499

3-02

2

Figure 2. Pin Configuration

Table 3. Pin Function Descriptions Pin No. Mnemonic Description 1 NC Do Not Connect 2 ST Self-Test 3 COM Common 4 NC Do Not Connect 5 COM Common 6 COM Common 7 COM Common 8 NC Do Not Connect 9 NC Do Not Connect 10 YOUT Y Channel Output 11 NC Do Not Connect 12 XOUT X Channel Output 13 NC Do Not Connect 14 VS 2.4 V to 5.25 V 15 VS 2.4 V to 5.25 V 16 NC Do Not Connect

Page 300: Control Motor Tesis

ADXL320

Rev. 0 | Page 6 of 16

0499

3-00

2

tP

tL

t25°C TO PEAK

tSPREHEAT

CRITICAL ZONETL TO TP

TEM

PER

ATU

RE

TIME

RAMP-DOWN

RAMP-UP

TSMIN

TSMAX

TP

TL

Figure 3. Recommended Soldering Profile

Table 4. Recommended Soldering Profile Profile Feature Sn63/Pb37 Pb-Free Average Ramp Rate (TL to TP) 3°C/second max 3°C/second max Preheat Minimum Temperature (TSMIN) 100°C 150°C Maximum Temperature (TSMAX) 150°C 200°C Time (TSMIN to TSMAX), tS 60 − 120 seconds 60 − 150 seconds TSMAX to TL Ramp-Up Rate 3°C/second 3°C/second Time Maintained Above Liquidous (TL) Liquidous Temperature (TL) 183°C 217°C Time (tL) 60 − 150 seconds 60 − 150 seconds Peak Temperature (TP) 240°C + 0°C/−5°C 260°C + 0°C/−5°C Time within 5°C of Actual Peak Temperature (tP) 10 − 30 seconds 20 − 40 seconds Ramp-Down Rate 6°C/second max 6°C/second max Time 25°C to Peak Temperature 6 minutes max 8 minutes max

Page 301: Control Motor Tesis

ADXL320

Rev. 0 | Page 7 of 16

TYPICAL PERFORMANCE CHARACTERISTICS (VS = 3.0 V) 25

0

5

10

15

20

1.40 1.42 1.44 1.46 1.48 1.50 1.52 1.54 1.56 1.58 1.60

0499

3-00

3

OUTPUT (V)

% O

F PO

PULA

TIO

N

Figure 4. X-Axis Zero g Bias Deviation from Ideal at 25°C

35

0

5

10

15

20

25

30

–2.8–2.4–2.0–1.6–1.2–0.8–0.4 0 0.4 0.8 1.2 1.6 2.0 2.4 2.8

0499

3-00

4

TEMPERATURE COEFFICIENT (mg/°C)

% O

F PO

PULA

TIO

N

Figure 5. X-Axis Zero g Bias Temperature Coefficient

90

0

10

20

30

40

50

70

80

60

164 184182180178176174172170168166

0499

3-00

5

SENSITIVITY (mV/g)

% O

F PO

PULA

TIO

N

Figure 6. X-Axis Sensitivity at 25°C

25

0

5

10

15

20

1.40 1.42 1.44 1.46 1.48 1.50 1.52 1.54 1.56 1.58 1.60

0499

3-00

6

OUTPUT (V)

% O

F PO

PULA

TIO

N

Figure 7. Y-Axis Zero g Bias Deviation from Ideal at 25°C

35

0

5

10

15

20

25

30

–2.8–2.4–2.0–1.6–1.2–0.8–0.4 0 0.4 0.8 1.2 1.6 2.0 2.4 2.8

0499

3-00

7

TEMPERATURE COEFFICIENT (mg/°C)

% O

F PO

PULA

TIO

N

Figure 8. Y-Axis Zero g Bias Temperature Coefficient

70

0

10

20

30

40

50

60

164 184182180178176174172170168166

0499

3-00

8

SENSITIVITY (mV/g)

% O

F PO

PULA

TIO

N

Figure 9. Y-Axis Sensitivity at 25°C

Page 302: Control Motor Tesis

ADXL320

Rev. 0 | Page 8 of 16

1.54

1.53

1.52

1.51

1.50

1.49

1.48

1.47

1.46–30 –20 –10 0 10 20 30 40 50 60 70 80

0499

3-00

9

TEMPERATURE (°C)

OU

TPU

T (S

CA

LE =

174

mV/

g)

Figure 10. Zero g Bias vs. Temperature—Parts Soldered to PCB

35

30

25

20

15

10

5

0170 190 210 230 250 270 290 310 330 350

0499

3-01

0

NOISE ug/ Hz

% O

F PO

PULA

TIO

N

Figure 11. X-Axis Noise Density at 25°C

25

20

15

10

5

0–5 –4 –3 –2 –1 0 1 2 3 4 5

0499

3-01

1

PERCENT SENSITIVITY (%)

% O

F PO

PULA

TIO

N

Figure 12. Z vs. X Cross-Axis Sensitivity

0.180

0.170

0.171

0.172

0.173

0.174

0.175

0.176

0.177

0.178

0.179

–30 –20 –10 0 10 20 30 40 50 60 70 80

0499

3-01

2

TEMPERATURE (°C)

SEN

SITI

VITY

(V/g

)

Figure 13. Sensitivity vs. Temperature—Parts Soldered to PCB

30

25

20

15

10

5

0170 190 210 230 250 270 290 310 330 350

0499

3-01

3

NOISE ug/ Hz

% O

F PO

PULA

TIO

N

Figure 14. Y-Axis Noise Density at 25°C

30

25

20

15

10

5

0–5 –4 –3 –2 –1 0 1 2 3 4 5

0499

3-01

4

PERCENT SENSITIVITY (%)

% O

F PO

PULA

TIO

N

Figure 15. Z vs. Y Cross-Axis Sensitivity

Page 303: Control Motor Tesis

ADXL320

Rev. 0 | Page 9 of 16

60

50

40

30

20

10

035 7570656055504540

0499

3-01

5

SELF-TEST (mV)

% O

F PO

PULA

TIO

N

Figure 16. X-Axis Self-Test Response at 25°C

40

35

30

25

20

15

10

5

0420 430 440 450 460 470 480 490 500 510 520 530

0499

3-01

6

CURRENT (μA)

% O

F PO

PULA

TIO

N

Figure 17. Supply Current at 25°C

60

50

40

30

20

10

035 7570656055504540

0499

3-01

7

SELF-TEST (mV)

% O

F PO

PULA

TIO

N

Figure 18. Y-Axis Self-Test Response at 25°C

0499

3-02

0

Figure 19. Turn-On Time—CX, CY = 0.1 μF, Time Scale = 2 ms/DIV

Page 304: Control Motor Tesis

ADXL320

Rev. 0 | Page 10 of 16

0499

3-01

8

XOUT = 1.500V

YOUT = 1.500V

XOUT = 1.500V

YOUT = 1.326V

XOUT = 1.326V

YOUT = 1.500V

XOUT = 1.674V

YOUT = 1.50V

XOUT = 1.500V

YOUT = 1.674V

EARTH'S SURFACE

XL320J

#12345678P

XL320J#12345678PXL 32

0J#1

234

5678

P

XL320J

#12345678P

Figure 20. Output Response vs. Orientation

Page 305: Control Motor Tesis

ADXL320

Rev. 0 | Page 11 of 16

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 open-loop 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 demodulator’s 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 −20°C to +70°C temperature range).

Figure 10 shows the zero g output performance of eight parts (X- and Y-axis) over a −20°C to +70°C 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 −20°C to +70°C temperature range.

Page 306: Control Motor Tesis

ADXL320

Rev. 0 | Page 12 of 16

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

F−3 dB = 1/(2π(32 kΩ) × C(X, Y))

or more simply,

F–3 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.

Table 5. Filter Capacitor Selection, CX and CY

Bandwidth (Hz) Capacitor (μF) 1 4.7 10 0.47 50 0.10 100 0.05 200 0.027 500 0.01

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 open-circuit or connected to common (COM) in normal use.

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.

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 accelerometer’s 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

)1.6()μg/(250 ××= BWHzrmsNoise

At 100 Hz bandwidth the noise will be

mg3.2)1.6100()μg/(250 =××= HzrmsNoise

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

Peak-to-Peak Value % of Time That Noise Exceeds Nominal Peak-to-Peak Value

2 × rms 32 4 × rms 4.6 6 × rms 0.27 8 × rms 0.006

Page 307: Control Motor Tesis

ADXL320

Rev. 0 | Page 13 of 16

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)

CX, CY (μF)

RMS Noise (mg)

Peak-to-Peak Noise Estimate (mg)

10 0.47 1.0 6 50 0.1 2.25 13.5 100 0.047 3.2 18.9 500 0.01 7.1 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,

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.

USE AS A DUAL-AXIS TILT SENSOR Tilt measurement is one of the ADXL320’s 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 earth’s 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 earth’s surface, it can be used as a 2-axis 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.

Page 308: Control Motor Tesis

ADXL320

Rev. 0 | Page 14 of 16

OUTLINE DIMENSIONS

16

5

13

8

9

12 1

40.65 BSC

2.431.75 SQ1.08

1.95 BSC

0.20 MIN PIN 1INDICATOR

BOTTOMVIEW

0.20 MIN

SEATINGPLANE

1.501.451.40

PIN 1INDICATOR TOP

VIEW

COPLANARITY0.05

0.05 MAX0.02 NOM

0.350.300.25

0.550.500.45

4.154.00 SQ3.85

*STACKED DIE WITH GLASS SEAL. 0726

06-A

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 Measurement Range

Specified Voltage (V)

Temperature Range Package Description

Package Option

ADXL320JCP1 ±5 g 3 −20°C to +70°C 16-Lead LFCSP_LQ CP-16-5a ADXL320JCP–REEL1 ±5 g 3 −20°C to +70°C 16-Lead LFCSP_LQ CP-16-5a ADXL320JCP–REEL71 ±5 g 3 −20°C to +70°C 16-Lead LFCSP_LQ CP-16-5a ADXL320EB Evaluation Board

1 Lead finish—Matte tin.

Page 309: Control Motor Tesis

5–1

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• VDE Approvals #0884

(Optional with Option 1, Add -X001 Suffix)

DESCRIPTION

The IL74 is an optically coupled pair with a Gal-lium 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 applica-tions such as CRT modulation.

The ILD74 has two isolated channels in a single DIP package; the ILQ74 has four isolated chan-nels per package.

VD E

Dimensions in inches (mm)

.008 (.20)

.012 (.31)

.130 (3.30)

.150 (3.81)

.130 (3.30)

.150 (3.81).280 (7.11).330 (8.38)

.020 (.51)

.030 (.76)

.300 (7.62)typ.

3° to 9°.0255 (.65) typ.

.100 (2.54) typ.

.040 (1.02)

.050 (1.27)

.016 (.41)

.020 (.51)

123

.240 (6.10)

.260 (6.60)

.780 (19.81)

.800 (20.32)

pin one ID.

149

8

.048 (1.22)

.052 (1.32)

.033 (.84) typ.

1615

.034 (.86)

67 45

10 11 12 13

.014(.35)typ.

1

2

3

4

8

7

6

5

Emitter

Collector

Collector

Emitter

Anode

Cathode

Cathode

Anode

16

15

14

13

12

11

10

9

1

2

3

4

5

6

7

8

Emitter

Collector

Collector

Emitter

Emitter

Collector

Collector

Emitter

Anode

Cathode

Cathode

Anode

Anode

Cathode

Cathode

Anode

1

2

3

6

5

4

Base

Collector

Emitter

Anode

Cathode

NC

.010 (.25)

.014 (.35)

.110 (2.79)

.150 (3.81)

.130 (3.30)

.150 (3.81)

.020 (.051) min.

.300 (7.62)typ.

.031 (0.80)

.035 (0.90)

.100 (2.54) typ.

.039 (1.00)

min.

.018 (0.45)

.022 (0.55)

.248 (6.30)

.256 (6.50)

.335 (8.50)

.343 (8.70)

Pin One ID.

654

123

18° typ.

.300 (7.62)

.347 (8.82)

4°typ.

.268 (6.81)

.255 (6.48)

34

65

.390 (9.91)

.379 (9.63)

.045 (1.14)

.030 (.76)

4°Typ.

.100 (2.54) Typ.

10°Typ.3°–9°

.305 typ.(7.75) typ.

.022 (.56)

.018 (.46) .012 (.30).008 (.20)

.135 (3.43)

.115 (2.92)

12

87

Pin One I.D.

.150 (3.81)

.130 (3.30)

.040 (1.02)

.030 (.76 )

SINGLE CHANNEL

IL74

DUAL CHANNEL

ILD74

QUAD CHANNEL

ILQ74

PHOTOTRANSISTOR OPTOCOUPLER

Page 310: Control Motor Tesis

5–2

IL/ILD/ILQ74

Maximum Ratings

Emitter

(each channel)

Peak Reverse Voltage .....................................3.0 VContinuous Forward Current .........................60 mAPower Dissipationat 25

°

C...........................100 mWDerate Linearly from 25

°

C....................1.33 mW/

°

C

Detector

(each channel)

Collector-Emitter Breakdown Voltage ..............20 VEmitter-Base Breakdown Voltage.......................5 VCollector-Base Breakdown Voltage .................70 VPower Dissipation at 25

°

C..........................150 mWDerate Linearly from 25

°

C......................2.0 mW/

°

C

Package

Isolation Test Voltage (t=1 sec.) ........5300 VAC

RMS

Isolation ResistanceV

IO

=500 V, T

A

=25

°

C ...............................

10

12

Ω

V

IO

=500 V, T

A

=100

°

C .............................

10

11

Ω

Total Package Dissipation at 25

°

C Ambient (LED Plus Detector)IL74.........................................................200 mWILD74 ......................................................400 mWIL74Q ......................................................500 mW

Derate Linearly from 25

°

CIL74.....................................................2.7 mW/

°

C ILD74 ................................................5.33 mW/

°

C ILQ74 ................................................6.67 mW/

°

C Creepage ............................................... 7 mm min.Clearance............................................... 7 mm min. Storage Temperature ...................–55

°

C to +150

°

COperating Temperature ...............–55

°

C to +100

°

CLead Soldering Time at 260

°

C .................... 10 sec.

Electrical Characteristics

(T

A

=25

°

C)

Symbol Min. Typ. Max. Unit Condition

Emitter

Forward Voltage V

F

1.3 1.5 V I

F

=20 mA

Reverse Current I

R

0.1 100

µ

A V

R

=3.0 V

Capacitance C

O

25 pF V

R

=0

Detector

Breakdown Voltage,Collector-Emitter

BV

CEO

20 50 V I

C

=1 mA

Leakage Current,Collector-Emitter

I

CEO

5.0 500 nA V

CE

=5 V, I

F

=0

Capacitance, Collector-Emitter

C

CE

10.0 pF V

CE

=0, F=1 MHz

Package

DC Current Trans-fer Ratio

CTR

DC

12.5 35 % I

F

=16 mA, V

CE

=5 V

Saturation Voltage, Collector-Emitter

V

CEsat

0.3 0.5V

I

C

=2 mA, I

F

=16 mA

Resistance, Input to Output R

IO

100 G

Ω

Capacitance, Inputto Output C

IO

0.5 pF

Switching Times t

ON

,t

OFF

3.0

µ

s R

E

=100

Ω

,V

CE

=10 V,I

C

=2 mA

Figure 1. Forward voltage versus forward current

Figure 2. Normalized non-saturated and saturated CTR at T

A

=25

°

C versus LED current

Figure 3. Normalized non-saturated and saturated CTR at T

A

=50

°

C versus LED current

Figure 4. Normalized non-saturated and saturated CTR at T

A

=70

°

C versus LED current

100101.10.7

0.8

0.9

1.0

1.1

1.2

1.3

1.4

IF - Forward Current - mA

VF

- F

orw

ard

Vo

ltag

e -

V Ta = -55°C

Ta = 25°C

Ta = 85°C

100101.10.0

0.5

1.0

1.5

NCTR(SAT)NCTR

IF - LED Current - mA

Normalized to:Vce = 10V, IF = 10mA Ta = 25°CCTRce(sat) Vce = 0.4V

NC

TR

- N

orm

aliz

ed C

TR

100101.10.0

0.5

1.0

1.5

NCTR(SAT)NCTR

IF - LED Current - mA

Normalized to:Vce = 10V, IF = 10mA, Ta = 25°C

Ta = 50°C

CTRce(sat) Vce = 0.4V

NC

TR

- N

orm

aliz

ed C

TR

100101.10.0

0.5

1.0

1.5

NCTR(SAT)NCTR

IF - LED Current - mA

NC

TR

- N

orm

aliz

ed C

TR Vce = 10V, IF = 10mA

Ta = 25°C

Ta = 70°C

CTRce(sat) Vce = 0.4V

Normalized to:

Page 311: Control Motor Tesis

5–3

IL/ILD/ILQ74

Figure 5. Normalized non-saturated and saturated CTR at T

A

=85

°

C versus LED current

Figure 6. Collector-emitter current versus temperature and LED current

Figure 7. Collector-emitter leakage current versus temperature

Figure 8. Normalized CTRcb versus LED current and temperature

100101.10.0

0.5

1.0

1.5

NCTR(SAT)NCTR

Normalized to:Vce = 10V, IF = 10mA, Ta = 25°C

Ta = 85°C

CTRce(sat) Vce = 0.4V

IF - LED Current - mA

NC

TR

- N

orm

aliz

ed C

TR

6050403020100

0

5

10

15

20

25

30

35

50°C

70°C

85°C

IF - LED Current - mA

Ice

- C

olle

cto

r C

urr

ent

- m

A

25°C

100806040200-2010

10

10

10

10

10

10

10

-2

-1

0

1

2

3

4

5

g p

Ta - Ambient Temperature - °C

Iceo

- C

olle

cto

r-E

mit

ter

- n

A

TYPICAL

Vce = 10V

.1 1 10 100

0.0

0.5

1.0

1.5

25°C50°C70°C

IF - LED Current - mA

NC

TR

cb -

No

rmal

ized

CT

Rcb Normalized to:

IF =10 mAVcb = 9.3 VTa = 25°C

Figure 9. Collector base photocurrent versus LEDcurrent

Figure 10. Normalized photocurrent versus If and temperature

Figure 11. Normalized non-saturated HFE versusbase current and temperature

Figure 12. Normalized saturated HFE versus base current and temperature

100101.1

.01

.1

1

10

100

1000

IF - LED Current - mA

Icb

- C

olle

cto

r B

ase

Ph

oto

curr

ent

- µA Icb = 1.0357 *IF ^1.3631

Ta = 25°C

100101.1.01

.1

1

10

NIB-Ta=-20°C

NIb,Ta=25°C

NIb,Ta=50°C

NIb,Ta=70°C

If LED Current mA

No

rmal

ized

Ph

oto

curr

ent

Normalized to:

If = 10ma, Ta = 25°C

1 10 100 10000.4

0.6

0.8

1.0

1.2

Ib - Base Current - µA

NH

FE

- N

orm

aliz

ed

HF

E

Ib = 20µA Vce = 10 VTa = 25°C

-20°C

25°C 50°C

70°C Normalized to:

1 10 100 10000.0

0.5

1.0

1.5

Ib - Base Current - (µA)

NH

FE

(sat

) -

No

rmal

ized

S

atu

rate

d H

FE

-20°C

25°C

50°C 70°C

Normalized to:Vce = 10VIb = 20µA

Ta = 25°C

Vce = 0.4V

Page 312: Control Motor Tesis

5–4

IL/ILD/ILQ74

Figure 14. Propagation delay versus collector load resis-tor

100101.11

10

100

1000

1.0

1.5

2.0

2.5

RL - Collector Load Resistor - KΩ

tpLH

- Pr

opag

atio

n De

lay

- µs

tpHL

- Pr

opag

atio

n De

lay

- µs

tpLH

tpHL

Ta = 25°C, IF = 10mAVcc = 5 V, Vth = 1.5 V

Figure 13. Propagation delay versus collector load resis-tor

100101.11

10

100

1000

1.0

1.5

2.0

2.5

RL - Collector Load Resistor - KΩ

tpLH

- Pr

opag

atio

n De

lay

- µs

tpHL

- Pr

opag

atio

n De

lay

- µs

tpLH

tpHL

Ta = 25°C, IF = 10mAVcc = 5 V, Vth = 1.5 V

Page 313: Control Motor Tesis

L298

Jenuary 2000

DUAL FULL-BRIDGE DRIVER

Multiwatt15

ORDERING NUMBERS : L298N (Multiwatt Vert.) L298HN (Multiwatt Horiz.)

L298P (PowerSO20)

BLOCK DIAGRAM

.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 15-lead Multiwatt and PowerSO20 packages. It is ahigh voltage, high current dual full-bridge driver de-signed to accept standard TTL logic levels and driveinductive loads such as relays, solenoids, DC andstepping motors. Two enable inputs are provided toenable or disable the device independently of the in-put signals. The emitters of the lower transistors ofeach bridge are connected together and the corre-sponding external terminal can be used for the con-

nection of an external sensing resistor. An additionalsupply input is provided so that the logic works at alower voltage.

PowerSO20

®

1/13

Page 314: Control Motor Tesis

PIN CONNECTIONS (top view)

GND

Input 2 VSS

N.C.

Out 1

VS

Out 2

Input 1

Enable A

Sense A

GND 10

8

9

7

6

5

4

3

2

13

14

15

16

17

19

18

20

12

1

11 GND

D95IN239

Input 3

Enable B

Out 3

Input 4

Out 4

N.C.

Sense B

GND

ABSOLUTE MAXIMUM RATINGS

Symbol Parameter Value Unit

VS Power Supply 50 V

VSS Logic Supply Voltage 7 V

VI,Ven Input and Enable Voltage –0.3 to 7 V

IO Peak Output Current (each Channel)– Non Repetitive (t = 100µs)–Repetitive (80% on –20% off; ton = 10ms)–DC Operation

32.52

AAA

Vsens Sensing Voltage –1 to 2.3 V

Ptot Total Power Dissipation (Tcase = 75°C) 25 W

Top Junction Operating Temperature –25 to 130 °CTstg, Tj Storage and Junction Temperature –40 to 150 °C

THERMAL DATA

Symbol Parameter PowerSO20 Multiwatt15 Unit

Rth j-case Thermal Resistance Junction-case Max. – 3 °C/W

Rth j-amb Thermal Resistance Junction-ambient Max. 13 (*) 35 °C/W

(*) Mounted on aluminum substrate

1

2

3

4

5

6

7

9

10

11

8

ENABLE B

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

13

14

15

12

CURRENT SENSING B

OUTPUT 4

OUTPUT 3

INPUT 4

D95IN240A

Multiwatt15

PowerSO20

L298

2/13

Page 315: Control Motor Tesis

PIN FUNCTIONS (refer to the block diagram)

MW.15 PowerSO Name Function

1;15 2;19 Sense A; Sense B Between this pin and ground is connected the sense resistor tocontrol the current of the load.

2;3 4;5 Out 1; Out 2 Outputs of the Bridge A; the current that flows through the loadconnected between these two pins is monitored at pin 1.

4 6 VS Supply Voltage for the Power Output Stages.A non-inductive 100nF capacitor must be connected between thispin and ground.

5;7 7;9 Input 1; Input 2 TTL Compatible Inputs of the Bridge A.

6;11 8;14 Enable A; Enable B TTL Compatible Enable Input: the L state disables the bridge A(enable A) and/or the bridge B (enable B).

8 1,10,11,20 GND Ground.

9 12 VSS Supply Voltage for the Logic Blocks. A100nF capacitor must beconnected between this pin and ground.

10; 12 13;15 Input 3; Input 4 TTL Compatible Inputs of the Bridge B.

13; 14 16;17 Out 3; Out 4 Outputs of the Bridge B. The current that flows through the loadconnected between these two pins is monitored at pin 15.

– 3;18 N.C. Not Connected

ELECTRICAL CHARACTERISTICS (VS = 42V; VSS = 5V, Tj = 25°C; unless otherwise specified)

Symbol Parameter Test Conditions Min. Typ. Max. Unit

VS Supply Voltage (pin 4) Operative Condition VIH +2.5 46 V

VSS Logic Supply Voltage (pin 9) 4.5 5 7 V

IS Quiescent Supply Current (pin 4) Ven = H; IL = 0 Vi = L Vi = H

1350

2270

mAmA

Ven = L Vi = X 4 mA

ISS Quiescent Current from VSS (pin 9) Ven = H; IL = 0 Vi = L Vi = H

247

3612

mAmA

Ven = L Vi = X 6 mA

ViL Input Low Voltage(pins 5, 7, 10, 12)

–0.3 1.5 V

ViH Input High Voltage(pins 5, 7, 10, 12)

2.3 VSS V

IiL Low Voltage Input Current(pins 5, 7, 10, 12)

Vi = L –10 µA

IiH High Voltage Input Current(pins 5, 7, 10, 12)

Vi = H ≤ VSS –0.6V 30 100 µA

Ven = L Enable Low Voltage (pins 6, 11) –0.3 1.5 V

Ven = H Enable High Voltage (pins 6, 11) 2.3 VSS V

Ien = L Low Voltage Enable Current(pins 6, 11)

Ven = L –10 µA

Ien = H High Voltage Enable Current(pins 6, 11)

Ven = H ≤ VSS –0.6V 30 100 µA

VCEsat (H) Source Saturation Voltage IL = 1AIL = 2A

0.95 1.352

1.72.7

VV

VCEsat (L) Sink Saturation Voltage IL = 1A (5)IL = 2A (5)

0.85 1.21.7

1.62.3

VV

VCEsat Total Drop IL = 1A (5)IL = 2A (5)

1.80 3.24.9

VV

Vsens Sensing Voltage (pins 1, 15) –1 (1) 2 V

L298

3/13

Page 316: Control Motor Tesis

Figure 1 : Typical Saturation Voltage vs. Output Current.

Figure 2 : Switching Times Test Circuits.

Note : For INPUT Switching, set EN = HFor ENABLE Switching, set IN = H

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.

ELECTRICAL CHARACTERISTICS (continued)

Symbol Parameter Test Conditions Min. Typ. Max. Unit

T1 (Vi) Source Current Turn-off Delay 0.5 Vi to 0.9 IL (2); (4) 1.5 µs

T2 (Vi) Source Current Fall Time 0.9 IL to 0.1 IL (2); (4) 0.2 µs

T3 (Vi) Source Current Turn-on Delay 0.5 Vi to 0.1 IL (2); (4) 2 µs

T4 (Vi) Source Current Rise Time 0.1 IL to 0.9 IL (2); (4) 0.7 µs

T5 (Vi) Sink Current Turn-off Delay 0.5 Vi to 0.9 IL (3); (4) 0.7 µs

T6 (Vi) Sink Current Fall Time 0.9 IL to 0.1 IL (3); (4) 0.25 µs

T7 (Vi) Sink Current Turn-on Delay 0.5 Vi to 0.9 IL (3); (4) 1.6 µs

T8 (Vi) Sink Current Rise Time 0.1 IL to 0.9 IL (3); (4) 0.2 µs

fc (Vi) Commutation Frequency IL = 2A 25 40 KHz

T1 (Ven) Source Current Turn-off Delay 0.5 Ven to 0.9 IL (2); (4) 3 µs

T2 (Ven) Source Current Fall Time 0.9 IL to 0.1 IL (2); (4) 1 µs

T3 (Ven) Source Current Turn-on Delay 0.5 Ven to 0.1 IL (2); (4) 0.3 µs

T4 (Ven) Source Current Rise Time 0.1 IL to 0.9 IL (2); (4) 0.4 µs

T5 (Ven) Sink Current Turn-off Delay 0.5 Ven to 0.9 IL (3); (4) 2.2 µs

T6 (Ven) Sink Current Fall Time 0.9 IL to 0.1 IL (3); (4) 0.35 µs

T7 (Ven) Sink Current Turn-on Delay 0.5 Ven to 0.9 IL (3); (4) 0.25 µs

T8 (Ven) Sink Current Rise Time 0.1 IL to 0.9 IL (3); (4) 0.1 µs

L298

4/13

Page 317: Control Motor Tesis

Figure 3 : Source Current Delay Times vs. Input or Enable Switching.

Figure 4 : Switching Times Test Circuits.

Note : For INPUT Switching, set EN = HFor ENABLE Switching, set IN = L

L298

5/13

Page 318: Control Motor Tesis

Figure 5 : Sink Current Delay Times vs. Input 0 V Enable Switching.

Figure 6 : Bidirectional DC Motor Control.

L = Low H = High X = Don’t care

Inputs Function

Ven = H C = H ; D = L Forward

C = L ; D = H Reverse

C = D Fast Motor Stop

Ven = L C = X ; D = X Free RunningMotor Stop

L298

6/13

Page 319: Control Motor Tesis

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)1.1. POWER OUTPUT STAGE

The L298 integrates two power output stages (A ; B).The power output stage is a bridge configurationand its outputs can drive an inductive load in com-mon or differenzial mode, depending on the state ofthe inputs. The current that flows through the loadcomes out from the bridge at the sense output : anexternal resistor (RSA ; RSB.) allows to detect the in-tensity of this current.

1.2. INPUT STAGE

Each bridge is driven by means of four gates the in-put of which are In1 ; In2 ; EnA and In3 ; In4 ; EnB.The In inputs set the bridge state when The En inputis high ; a low state of the En input inhibits the bridge.All the inputs are TTL compatible.

2. SUGGESTIONS

A non inductive capacitor, usually of 100 nF, mustbe foreseen between both Vs and Vss, to ground,as near as possible to GND pin. When the large ca-pacitor of the power supply is too far from the IC, asecond smaller one must be foreseen near theL298.

The sense resistor, not of a wire wound type, mustbe grounded near the negative pole of Vs that mustbe near the GND pin of the I.C.

Each input must be connected to the source of thedriving signals by means of a very short path.

Turn-On and Turn-Off : Before to Turn-ON the Sup-ply Voltage and before to Turn it OFF, the Enable in-put must be driven to the Low state.

3. APPLICATIONS

Fig 6 shows a bidirectional DC motor control Sche-matic Diagram for which only one bridge is needed.The external bridge of diodes D1 to D4 is made byfour fast recovery elements (trr ≤ 200 nsec) thatmust be chosen of a VF as low as possible at theworst case of the load current.

The sense output voltage can be used to control thecurrent amplitude by chopping the inputs, or to pro-vide overcurrent protection by switching low the en-able input.

The brake function (Fast motor stop) requires thatthe Absolute Maximum Rating of 2 Amps mustnever be overcome.

When the repetitive peak current needed from theload is higher than 2 Amps, a paralleled configura-tion can be chosen (See Fig.7).

An external bridge of diodes are required when in-ductive loads are driven and when the inputs of theIC are chopped ; Shottky diodes would be preferred.

L298

7/13

Page 320: Control Motor Tesis

This solution can drive until 3 Amps In DC operationand until 3.5 Amps of a repetitive peak current.

On Fig 8 it is shown the driving of a two phase bipolarstepper motor ; the needed signals to drive the in-puts of the L298 are generated, in this example,from the IC L297.

Fig 9 shows an example of P.C.B. designed for theapplication of Fig 8.

Fig 10 shows a second two phase bipolar steppermotor control circuit where the current is controlledby 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 VF ≤ 1.2 V @ I = 2 Atrr ≤ 200 ns

L298

8/13

Page 321: Control Motor Tesis

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

L298

9/13

Page 322: Control Motor Tesis

Multiwatt15 V

DIM.mm inch

MIN. TYP. MAX. MIN. TYP. MAX.

A 5 0.197

B 2.65 0.104

C 1.6 0.063

D 1 0.039

E 0.49 0.55 0.019 0.022

F 0.66 0.75 0.026 0.030

G 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

L 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 0.713

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.114

M 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

S 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

OUTLINE ANDMECHANICAL DATA

L298

10/13

Page 323: Control Motor Tesis

DIM.mm inch

MIN. TYP. MAX. MIN. TYP. MAX.

A 5 0.197

B 2.65 0.104

C 1.6 0.063

E 0.49 0.55 0.019 0.022

F 0.66 0.75 0.026 0.030

G 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

L 20.57 0.810

L1 18.03 0.710

L2 2.54 0.100

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

L5 5.28 0.208

L6 2.38 0.094

L7 2.65 2.9 0.104 0.114

S 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

OUTLINE ANDMECHANICAL DATA

L298

11/13

Page 324: Control Motor Tesis

JEDEC MO-166

PowerSO20

e

a2 A

E

a1

PSO20MEC

DETAIL A

T

D

1

1120

E1E2

h x 45

DETAIL Alead

sluga3

S

Gage Plane0.35

L

DETAIL B

R

DETAIL B

(COPLANARITY)

G C

- C -

SEATING PLANE

e3

b

c

NN

H

BOTTOM VIEW

E3

D1

DIM.mm inch

MIN. TYP. MAX. MIN. TYP. MAX.

A 3.6 0.142

a1 0.1 0.3 0.004 0.012

a2 3.3 0.130

a3 0 0.1 0.000 0.004

b 0.4 0.53 0.016 0.021

c 0.23 0.32 0.009 0.013

D (1) 15.8 16 0.622 0.630

D1 9.4 9.8 0.370 0.386

E 13.9 14.5 0.547 0.570

e 1.27 0.050

e3 11.43 0.450

E1 (1) 10.9 11.1 0.429 0.437

E2 2.9 0.114

E3 5.8 6.2 0.228 0.244

G 0 0.1 0.000 0.004

H 15.5 15.9 0.610 0.626

h 1.1 0.043

L 0.8 1.1 0.031 0.043

N 10 (max.)

S

T 10 0.394(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"

OUTLINE ANDMECHANICAL DATA

8 (max.)

10

L298

12/13

Page 325: Control Motor Tesis

II.- PLANOS

Page 326: Control Motor Tesis

PLANOS

II.- PLANOS

1. Lista de Planos

2. Esquemáticos

3. Circuitos Impresos

3.1. Circuito Integrado

3.2. Máscara de soldadura

3.3. Serigrafía

Page 327: Control Motor Tesis

PLANOS

1. Lista de Planos

• Plano nº1: esquema circuito 1. Etapa de potencia, medida de intensidad

por el motor, acondicionamiento microprocesador.

• Plano nº2: esquema circuito 2. Acondicionamiento del acelerómetro.

• Plano nº3: esquema circuito 3. Balizas.

• Plano nº4: esquema circuito 4. Reguladores de tensión LM2736Y.

• Plano nº5: circuito impreso 1. Capa TOP.

• Plano nº6: circuito impreso 1. Capa BOTTOM.

• Plano nº7: circuito impreso 1. Capa GND.

• Plano nº8: circuito impreso 1. Capa INNER1.

• Plano nº9: circuito impreso 1. Capa INNER2.

• Plano nº10: circuito impreso 1. SERIGRAFÍA.

• Plano nº11: circuito impreso 1. PADS.

• Plano nº12: circuito impreso 2. Capa TOP.

• Plano nº13: circuito impreso 2. Capa BOTTOM.

• Plano nº14: circuito impreso 2. SERIGRAFÍA.

• Plano nº15: circuito impreso 2. PADS.

Page 328: Control Motor Tesis

PLANOS

2. Esquemáticos

Page 329: Control Motor Tesis

PLANOS

3. Circuitos Impresos

Page 330: Control Motor Tesis

III.- PLIEGO DE

CONDICIONES

Page 331: Control Motor Tesis

CONDICIONES

III.- PLIEGO DE CONDICIONES

1. Generales y Económicas

2. Técnicas y particulares

Page 332: Control Motor Tesis

CONDICIONES Generales y económicas

1

1. Generales y Económicas

1.1. CONDICIONES GENERALES

Las condiciones y cláusulas que se establecen en este documento

tratan de la contratación, por parte de persona física o jurídica, 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 continuación se exponen:

1. Las dos partes se comprometen desde la fecha de la firma del

contrato, a cumplir todo lo que a continuación se estipula.

2. En el caso de reclamación o discrepancia en lo concerniente al

cumplimiento por cualquiera de las dos partes, una vez agotada

la vía del entendimiento, se tramitará el asunto por vía legal.

3. El suministrador se compromete a cumplir fielmente las

condiciones técnicas, de diseño, fabricación y capacidad que se

estipulen en los planos, listas de materiales y especificaciones

indicadas en el proyecto, a comprobar por el comprador desde

la recepción del mismo.

4. La conformidad de los inspectores del comprador no exime al

proveedor de la responsabilidad que le atañe en los defectos de

diseño y construcción 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 Económicas.

Page 333: Control Motor Tesis

CONDICIONES Generales y económicas

2

5. El plazo de entrega será de tres semanas a partir de la fecha de

la firma del contrato.

6. Si la entrega se retrasara más de las tres semanas acordadas, el

comprador podrá rescindir el contrato, siéndole retribuidas

todas las cantidades abonadas.

7. El equipo está garantizado por un año a partir de la fecha de

puesta en servicio del mismo, cubriendo la reparación de fallo

interno o defecto de fabricación 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 garantía sólo será válida siempre que se lleve a cabo una

correcta instalación del equipo, así como un correcto uso del

mismo. La garantía 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 ningún caso pagará indemnizaciones por

cualquier otro daño o perjuicio directo o indirecto a personas o

cosas por lucro cesante.

Page 334: Control Motor Tesis

CONDICIONES Generales y económicas

3

1.2. CONDICIONES ECONÓMICAS

Los precios indicados en este proyecto son firmes y sin revisión por

ningún concepto, siempre y cuando se acepten dentro del período de

validez posteriormente indicado. El período de validez del presupuesto es

hasta el mes de Diciembre de 2008.

La forma de pago del presente proyecto será:

5% a la recepción del pedido.

15% a la entrega de planos y documentación técnica.

50% a la entrega del equipo.

30% a la puesta en marcha del sistema, siempre y cuando

este plazo no exceda los 100 días de la fecha de entrega del

equipo.

Page 335: Control Motor Tesis

CONDICIONES Técnicas y particulares

4

2. Técnicas 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 características para el

soporte aislante:

Para la fabricación de la placa impresa se utilizará el método 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 inserción, y por

horno de fusión 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 deberán permitir el alojamiento de las mismas

en una caja de 100x94 mm.

Page 336: Control Motor Tesis

CONDICIONES Técnicas y particulares

5

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 alimentación será lo más grande posible. Ay pistas

de alimentación de 0,015” para lo que ha sido necesario diseñar convenientemente

el trazado, en función del consumo de cada zona.

2.3. DIAMETRO DE LOS PADS

Los diámetros recomendados para los pads de los distintos componentes son

los que se muestran a continuación:

Page 337: Control Motor Tesis

CONDICIONES Técnicas y particulares

6

2.4. DIÁMETRO DE LOS TALADROS

Los diámetros recomendados para los taladros son los que se muestran a

continuación:

2.5. CONDICIONES DE MONTAJE

- Las placas de circuito llevarán capa de serigrafía.

- Los puestos de montaje dispondrán de protección antiestática.

2.6. CONDICIONES AMBIENTALES

El sistema se diseñará para un funcionamiento correcto dentro de los

márgenes siguientes:

Temperatura de almacenamiento……………..-30º C a +75º C.

Temperatura de trabajo……………………….+0º C a +70º C.

Humedad relativa: 85% sin precipitación y sin condensación.

Vibración: 2G entre 20 y 400Hz en cualquier plano y dirección.

Sock en operación: 5G en cualquier plano y dirección.

Sock en transporte: 10G en cualquier plano y dirección.

Page 338: Control Motor Tesis

CONDICIONES Técnicas y particulares

7

2.7. OTROS CRITERIOS DE DISEÑO

- Se deben evitar en lo posible los cableados, para lo que se utilizarán conexiones

mediante conectores enchufables, evitando la utilización del sistema cable plano.

No se puede evitar el cableado externo para la utilización del controlador.

- Se intentarán, en lo posible, utilizar componentes lo más normalizados dentro

del mercado electrónico 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 tropicalización de la misma, y evitar así

los defectos de una posible corrosión 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

características.

- Se utilizarán componentes con alto margen de características climáticas y para

funcionamiento en entorno industrial.

- Como estándar, el sistema se diseñará para obtener un funcionamiento óptimo,

dentro de los siguientes márgenes:

- Con respecto a las características eléctricas, la tensión de funcionamiento deberá

ser capaz de variarse en un ±20 % de su valor, sin que se aprecie en el equipo

ningún cambio de características de medida o funcionamiento.

Page 339: Control Motor Tesis

CONDICIONES Técnicas y particulares

8

2.8. NORMATIVA

El equipo tendrá que cumplir las normas citadas a continuación:

Page 340: Control Motor Tesis

9

Page 341: Control Motor Tesis

IV.- PRESUPUESTO

Page 342: Control Motor Tesis

PRESUPUESTO

IV.- PRESUPUESTO

1. Mediciones

2. Presupuestos parciales

3. Presupuesto total

Page 343: Control Motor Tesis

PRESUPUESTO

1. Mediciones 1.1. Circuito 1: Etapa de potencia, medida de intens idad

por el motor, acondicionamiento microprocesador.

# COMPONENTE REFERENCIA # COMPONENTE REFERENCIA

1 0.1UF C2 35 68NF C26

2 0.1UF C3 36 68NF C27

3 0.1UF C4 37 100N C1B

4 0.1UF C5 38 100N C2B

5 0.1UF C17 39 100PF C10

6 0 R1B 40 100PF C11

7 1NF C6 41 100PF C12

8 1NF C7 42 100PF C13

9 1NF C8 43 100PF C15

10 1NF C9 44 150k R9

11 1NF C14 45 200 R2

12 1 R6 46 270 R10

13 2N3904 Q1 47 7805/SIP U9

14 2k R7 48 CARGA J7

15 4.7K R4 49 Conector Acelerómetro J10

16 4X 22 RP1 50 DIODE BRIDGE D2

17 4X 22 RP2 51 DIODE ZENER (3.3 V) D1

18 5.6k R3 52 DIODE ZENER (3.3 V) D3

19 6.8k R11 53 FUENTE J8

20 10K R12 54 Flash Voltage Ref. JP1

21 10K R13 55 L298/MUTIV U3

22 10UF TANT. C1 56 MCF5282CVF66 U1

23 10UF TANT. C16 57 OP-07 U4

24 10u C3B 58 OP-07 U5

25 13k R8 59 OP-07 U6

26 43 R1 60 OP-07 U7

27 68NF C18 61 SIPSOC-3 J9

28 68NF C19 62 STANDBY SUPPLY JP2

29 68NF C20 63 STANDBY SUPPLY JP4

30 68NF C21 64 STANDBY SUPPLY JP6

31 68NF C22 65 Voltage Ref. High JP3

32 68NF C23 66 Voltage Ref. Low JP5

33 68NF C24 67 ilq74 U2

34 68NF C25

Page 344: Control Motor Tesis

PRESUPUESTO

1.2. Circuito 2: Acondicionamiento del acelerómetro

# COMPONENTE REFERENCIA # COMPONENTE REFERENCIA

1 1.5K R8 18 100K R11

2 1.5K R10 19 ADXL320 U1

3 1K R2 20 BYV28-150 D1

4 1K R3 21 BYV28-150 D2

5 1K R4 22 BYV28-150 D3

6 1K R5 23 BYV28-150 D4

7 1K R6 24 CONECTOR ACELERóMETRO J4

8 1K R12 25 FUENTE J1

9 1K R13 26 FUENTE J2

10 1K R14 27 FUENTE J3

11 1K R15 28 OP-07 U2

12 1K R16 29 OP-07 U3

13 3.3U C1 30 OP-07 U4

14 3.3U C2 31 OP-07 U5

15 5.6K R7 32 OP-07 U6

16 5.6K R9 33 OP-07 U7

17 100K R1

1.3. Circuito 3: Balizas # COMPONENTE REFERENCIA # COMPONENTE REFERENCIA

1 0.33K R1 19 100K R12

2 0.33K R6 20 Conector Micro J4

3 0.47K R14 21 DIODE ZENER (3.3V) D7

4 0.47K R15 22 DUMMY D2

5 1.5k R8 23 DUMMY D4

6 1K R2 24 FUENTE J1

7 1K R5 25 FUENTE J2

8 1K R9 26 LED D8

9 1K R10 27 LED D9

10 1K R16 28 OP-07 U1

11 1K R17 29 OP-07 U2

12 2N3904 Q1 30 OP-07 U3

13 2N3904 Q2 31 OP-07 U4

14 4.7k R4 32 OP-07 U5

15 70k R13 33 OP-07 U6

16 100K R3 34 PHOTODIODE D1

17 100K R7 35 PHOTODIODE D3

18 100K R11

Page 345: Control Motor Tesis

PRESUPUESTO

2. Presupuestos parciales 2.1. Circuito 1: Etapa de potencia, medida de intens idad

por el motor, acondicionamiento microprocesador.

REFERENCIA COMPONENTE UDS. PRECIO

UD. TOTAL

1 C1,C16 10uF TANT. 2 1,60 € 3,20 €

2 C1,C2 100n 2 0,01 € 0,02 €

3 C10,C11,C12,C13,C15 100pF 5 0,01 € 0,05 €

4 C18,C19,C20,C21,C22,C23, 68nF 10 0,01 € 0,10 €

5 C1B,C2B 100n 2 0,01 € 0,02 €

6 C2,C3,C4,C5,C17 0.1uF 5 0,01 € 0,05 €

7 C24,C25,C26,C27 0,01 € 0,00 €

8 C3 10u 1 0,01 € 0,01 €

9 C3B 10u 1 0,01 € 0,01 €

10 C6,C7,C8,C9,C14 1nF 5 0,01 € 0,05 €

11 D1,D3 DIODE ZENER (3V) 2 0,03 € 0,06 €

12 D1,D3 DIODE ZENER (3.3 V) 2 0,03 € 0,06 €

13 D2 DIODE BRIDGE 1 0,15 € 0,15 €

14 D2 DIODE BRIDGE 1 0,15 € 0,15 €

15 J10 Conector Acelerómetro 1 0,20 € 0,20 €

16 J7 CARGA 1 0,20 € 0,20 €

17 J7 CARGA 1 0,20 € 0,20 €

18 J8 FUENTE 1 0,20 € 0,20 €

19 J8 FUENTE 1 0,20 € 0,20 €

20 J9 SIPSOC-3 1 0,20 € 0,20 €

21 J9 SIPSOC-3 1 0,20 € 0,20 €

22 JP1 Flash Voltage Ref. 1 0,15 € 0,15 €

23 JP2,JP4,JP6 Standby supply 3 0,15 € 0,45 €

24 JP3 Voltage Ref. High 1 0,15 € 0,15 €

25 JP5 Voltage Ref. Low 1 0,15 € 0,15 €

26 Q1 2N3904 1 0,03 € 0,03 €

27 Q1 2N3904 1 0,03 € 0,03 €

28 R1 43 1 0,02 € 0,02 €

29 R1 43 1 0,02 € 0,02 €

30 R10 270 1 0,02 € 0,02 €

31 R10 270 1 0,02 € 0,02 €

32 R11 6.8k 1 0,02 € 0,02 €

33 R11 6.8k 1 0,02 € 0,02 €

34 R12,R13 10k 2 0,02 € 0,04 €

35 R12,R13 10k 2 0,02 € 0,04 €

Page 346: Control Motor Tesis

PRESUPUESTO

36 R1B 0 1 0,02 € 0,02 €

37 R2 200 1 0,02 € 0,02 €

38 R2 200 1 0,02 € 0,02 €

39 R3 5.6k 1 0,02 € 0,02 €

40 R3 5.6k 1 0,02 € 0,02 €

41 R4 4.7k 1 0,02 € 0,02 €

42 R4 4.7k 1 0,02 € 0,02 €

43 R6 1 1 0,02 € 0,02 €

44 R6 1 1 0,02 € 0,02 €

45 R7 2k 1 0,02 € 0,02 €

46 R7 2k 1 0,02 € 0,02 €

47 R8 13k 1 0,02 € 0,02 €

48 R8 13k 1 0,02 € 0,02 €

49 R9 150k 1 0,02 € 0,02 €

50 R9 150k 1 0,02 € 0,02 €

51 RP1,RP2 4x 22 2 0,70 € 1,40 €

52 U1 MCF5282CVF66 1 47,29 € 47,29 €

53 U10 7803/SIP 1 0,53 € 0,53 €

54 U2 ilq74 1 2,77 € 2,77 €

55 U3 L298/MUTIV 1 4,45 € 4,45 €

56 U4,U5,U6,U7 OP-07 4 0,04 € 0,16 €

57 U9 7805/SIP 1 0,53 € 0,53 €

TOTAL 63,92 €

2.2. Circuito 2: Acondicionamiento del acelerómetro

REFERENCIA COMPONENTE UDS.

PRECIO

UD. TOTAL

1 C1,C2 3.3u 2 0,01 € 0,02 €

2 D1,D2,D3,D4 BYV28-150 4 0,02 € 0,08 €

3 J1,J2,J3 FUENTE 3 0,20 € 0,60 €

4 J4 Conector Acelerómetro 1 0,20 € 0,20 €

5 R1,R11 100k 2 0,02 € 0,04 €

6 R2,R3,R4,R5,R6,R12,R13, 1k 10 0,02 € 0,20 €

R14,R15,R16 0,00 €

7 R7,R9 5.6k 2 0,02 € 0,04 €

8 R8,R10 1.5k 2 0,02 € 0,04 €

9 U1 ADXL320 1 10,08 € 10,08 €

10 U2,U3,U4,U5,U6,U7 OP-07 6 0,04 € 0,24 €

TOTAL 11,54 €

Page 347: Control Motor Tesis

PRESUPUESTO

2.3. Circuito 3: Balizas

REFERENCIA COMPONENTE UDS.

PRECIO

UD. TOTAL

1 D1,D3 PHOTODIODE 2 10,44 € 20,88 €

2 D2,D4 Dummy 2 10,44 € 20,88 €

3 D7 DIODE ZENER (3.3V) 1 0,03 € 0,03 €

4 D8,D9 LED 2 0,44 € 0,88 €

5 J1,J2 FUENTE 2 0,20 € 0,40 €

6 J4 Conector Micro 1 0,20 € 0,20 €

7 Q1,Q2 2N3904 2 0,03 € 0,06 €

8 R1,R6 0.33k 2 0,02 € 0,04 €

9 R2,R5,R9,R10,R16,R17 1k 6 0,02 € 0,12 €

10 R3,R7,R11,R12 100k 4 0,02 € 0,08 €

11 R4 4.7k 1 0,02 € 0,02 €

12 R8 1.5k 1 0,02 € 0,02 €

13 R13 70k 1 0,02 € 0,02 €

14 R14,R15 0.47k 2 0,02 € 0,04 €

15 U1,U2,U3,U4,U5,U6 OP-07 6 0,03 € 0,18 €

TOTAL 43,85 €

2.4. Maqueta:

COMPONENTE UDS. PRECIO UD. TOTAL

1 Maqueta tren eléctrico 1 89,5€ 89,5€ 2 Vía recta tren 2 1,1€ 2,2€ 3 Vía curva tren 12 1,1€ 13,2€

TOTAL 104,9€

2.5. Recursos:

Concepto UDS. PRECIO

UD. TOTAL

Ordenador AMD Athlon 64 1 1200.00 € 1200.00 €

Licencia Matlab 1 600.00 € 600.00 €

Licencia Freescale Codewarrior 1 380.00 € 380.00 €

Licencia PSPICE 1 350.00 € 350.00 €

Licencia Microsoft Office 1 450.00 € 450.00 €

TOTAL 3580.00 €

Page 348: Control Motor Tesis

PRESUPUESTO

2.6. Diseño:

Concepto UDS. PRECIO

UD. TOTAL

Hora ingeniería 1056 35.00 € 36960.00 €

TOTAL 36960.00 €

Page 349: Control Motor Tesis

PRESUPUESTO

3. Presupuesto total

Concepto TOTAL

Gastos de materiales 224,21€

Gastos de recursos empleados 3580€

Gastos de ingeniería 36960€

TOTAL 40764,21€

Page 350: Control Motor Tesis

Fdo.: Fernando Moreno Pérez

Madrid, 17 de Junio de 2010