38
EX3: Designing sequential systems using FSM º EX 3ELECTRONICS I Designing sequential systems using FSM 1.1 Cooperative group TEAM NUMBER: GROUP 2 DUE DATE: 31/05/2010 1 st review due date: ________________ STUDY TIME: Study time (in hours) Group work Classroom and laboratory sessions Sessions out of classroom Individu al Alex Murillo Ruiz Jefferson Ortiz 12 7 STATEMENT: My signature below indicates that I have (1) made equitable contribution to EX 3 as a member of the group, (2) read and fully agree with the contents (i.e., results, conclusions, analyses, simulations) of this document, and (3) acknowledged by name anyone outside this group who assisted this learning team or any individual member in the completion of this document. Today’s date: __________________ Active members Roles: (reporter, simulator, etc.) 1

EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

º

EX 3 ELECTRONICS I

Designing sequential systems using FSM

1.1 Cooperative groupTEAM NUMBER: GROUP 2

DUE DATE: 31/05/2010 1st review due date: ________________

STUDY TIME:

Study time

(in hours)

Group work Classroom and laboratory sessions

Sessions out of classroom

Individual Alex Murillo Ruiz

Jefferson Ortiz

12

7

STATEMENT:

My signature below indicates that I have (1) made equitable contribution to EX 3 as a member of the group, (2) read and fully agree with the contents (i.e., results, conclusions, analyses, simulations) of this document, and (3) acknowledged by name anyone outside this group who assisted this learning team or any individual member in the completion of this document.

Today’s date: __________________

Active members Roles: (reporter, simulator, etc.)

(1) Alex Murillo Ruiz ALL

(2) Jefferson Ortiz ALL

Acknowledgement of individual(s) who assisted this group in completing this document:

1

Page 2: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

(1) Francesc Josep Sànchez i Robert

1.2 Abstract Explain here the most significant developments, results or conclusions about the exercise. Use the remaining space in this sheet (200 words maximum).

Gracias a este ejercicio hemos aprendido a desarrollar toda una metodología de trabajo que nos permite usando el siguiente esquema lógico solucionar cualquier problema generado véase Fig. 1.

2

Page 3: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

Fig. 1 Diagrama de resolución de problemas aplicado al Ejercicio 3

3

Page 4: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

4

Page 5: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

CONTENT

Designing sequential systems using FSM....................................................................................................1

1.1 Cooperative group.....................................................................................................................................1

1.2 Abstract.....................................................................................................................................................1

1.3 Description................................................................................................................................................4

1.4 Topics........................................................................................................................................................4

1.5 Designing clock frequency dividers..........................................................................................................4

1.5.1 Plan a quartz oscillator frequency divider chip................................................................................4

1.5.2 Design a T-FF as a simple FSM.......................................................................................................4

1.5.3 Design synchronous cascadable binary counters as FSM................................................................5

1.5.4 Do gate-level/timed simulations........................................................................................................5

1.6 Designing the 16-key keypad scanning decoder.......................................................................................5

1.6.1 Keypad characteristics and wiring...................................................................................................5

1.6.2 Plan and code in VHDL the state diagram for the component.........................................................6

1.6.3 Complete the project adding clock and display modules..................................................................6

1.6.4 Synthesise the matrix keyboard application into a CPLD or a FPGA chip......................................7

1.7 Debouncing keys.......................................................................................................................................7

1.7.1 Visualise the problem of mechanical pushbuttons interfaced to digital systems..............................7

1.7.2 Solve the problem..............................................................................................................................7

2 Solución del Ejercicio 3...................................................................................................................................8

2.1 Divisor de frecuencia................................................................................................................................8

2.1.1 Planteamiento del problema.............................................................................................................8

2.1.2 ¿Qué és un Crystall Oscillator?........................................................................................................8

2.1.3 Divisores de Frecuencia...................................................................................................................8

2.1.4 ¿Qué és un Biestable?.......................................................................................................................9

2.1.5 Resolución del primer problema: Divisor de frecuencia poco eficiente...........................................9

2.1.6 Divisor de frecuencia óptimo............................................................................................................9

2.2 Design synchronous cascadable binary counters as FSM.......................................................................10

5

Page 6: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

2.2.1 ¿Qué és una FSM?..........................................................................................................................10

En este punto del proyecto, debemos implementar un synchronous cascadable binary counters con una FSM.................................................................................................................................................................10

2.3 Debouncing Filter....................................................................................................................................14

2.3.1 Planteamiento de la problemática..................................................................................................14

2.3.2 Estudio teórico de una posible solución al problema.....................................................................15

2.3.3 Implementación en VHDL Quartus II........................................................................................16

2.3.4 Comprobaciones de la funcionalidad.............................................................................................17

2.4 References...............................................................................................................................................20

2.5 Topics and activities checklist................................................................................................................21

2.6 Grading grid............................................................................................................................................21

2.7 Questions in solving EX2........................................................................................................................21

6

Page 7: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

1.3 DescriptionIn this third exercise, basic sequential systems will be implemented and tested. We learn how to describe any synchronous sequential system through the architecture of a FSM consisting of three blocks: (1) the state register, (2) the next state logic and (3) the output logic. The state register based on D-FF will be written in VHDL using a clock sensitive process, while the next state and output logic will be specified as combinational blocks. For example, the T-FF which will be used to obtain squared waveforms will be conceived as a simple FSM. Any other basic or standard sequential block, as a counter or a data register will be implemented in the same way. Part 1 will be devoted to the study of structured frequency dividers so that we will able to generate the required clock frequencies for our digital systems from an external crystal oscillator. In Part 2, the general architecture or a finite state machine (FSM) will be studied and used once more to implement any kind of sequential system like, in this case, a matrix keypad encoder or a traffic light controller. As in previous EX2, all the projects have to be simulated functionally in ModelSim or ActiveHDL so that their major bugs will be detected before attempting the final phase of prototyping. Furthermore, in this exercise, the gate-level or timed simulation of the final synthesised circuit will also be introduced and executed using TCL do macros and timing diagrams.

1.4 Topics The following topics have been listed from the course’s specific and cross-curricular learning objectives1: #9, #10 and #11. After studying Chapter 2 and successfully completing all the assignments in this task, you will be able to:

------------- Part 1 -------------

1. Explain the FSM architecture consisting of: (1) the state register, (2) the next state logic and (3) the output logic.

2. Design the block diagram of a structured synchronous crystal oscillator frequency divider using expandable counters and other basic components.

3. Design a toggle flip-flop (T-FF).

4. Generate a real-time square waveform of 1Hz from a high frequency crystal oscillator.

5. Assign pins and synthesise the project for a CPLD or FPGA chip in a training board.

------------- Part 2 -------------

6. Explain the way to write in VHDL a state diagram for a given FSM.

7. Use the Quartus II tool:state diagram netlist to produce automatically a state diagram from the VHDL listing

8. Explain how a matrix keypad encoder works.

9. Design a matrix keypad encoder using a simple synchronous canonical FSM.

10. Do gate-level simulations in ModelSim using VHO and DSO files.

1 http://epsc.upc.edu/projectes/ed/E1/units/Guia_docent_E1_v2.pdf

7

Page 8: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

11. Use the oscilloscope to measure pulsed wave parameters and signal delays.

1.5 Designing clock frequency dividers 1.5.1 Plan a quartz oscillator frequency divider chip

a) Draw the block diagram of a synchronous frequency divider for a crystal oscillator of 25.175 MHz. The system has to produce three clock signals: pulsed waveforms of 100 Hz and 5Hz, and a final square wave of 1Hz. Explore the many ways to do it, and choose an optimum architecture like the one represented in Fig. 2. Write down the main differences in the three VHDL writing styles, and explain why the last style, the one using cascaded blocks instantiating components into a top design is the best option.

1.5.2 Design a T-FF as a simple FSM

b) Explain using a circuit schematic or a block diagram the structure of a FSM.

c) Design a project and simulate using the FSM style a T-FF. Represent the timing diagram to show that the output of the system is he input frequency divided by 2.

CD

CE

CLK

TC25

CD

CE

CLK

TC1007

CD

CE

CLK

TC5000

CD

CLKCE

CLK_1MHzCLK_1kHz

CLK_02Hz

freq_div_5000:Freq_div_5000_Comp1freq_div_1007:Freq_div_1007_Comp1freq_div_25:Freq_div_25_Comp1

Fig. 2 RTL netlist view for a given frequency divider (third design style) which produces pulsed waveforms of 1 Mhz, 1 kHz and 200 mHz

1.5.3 Design synchronous cascadable binary counters as FSM

d) Find or invent the VHDL code, using the FSM style, for a synchronous cascadable (CE and TC) modulo-N binary counter with asynchronous clear direct (CD). Do a ModelSim simulation to demonstrate the way it works. For large values of N, modify the code to speed up simulations (reduce the max_count constant to a lower value).

e) Finally design the synchronous clock divider system to obtain pulsed waveforms of 100 Hz and 5Hz, and a final square wave of 1Hz. Implement a Quartus-II project for the MAX128S chip in the UP2 and use the laboratory instruments (oscilloscope or logic analyser) to measure the output waveform parameters. Check the signals synchronicity with respect to the input clock and measure the circuit propagation delays.

8

Page 9: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

1.5.4 Do gate-level/timed simulations

f) Try to reach similar results in ModelSim performing gate-level simulations of the synthesised circuit. Circuit’s structure VHDL file vho and delay file sdo have to be used in the project instead of the source VHDL files by which functional simulations where conducted. Again, to speed up simulations, reduce the main counter’s Max_count constant.

1.6 Designing the 16-key keypad scanning decoder 1.6.1 Keypad characteristics and wiring

g) Find the characteristics of a commercial 16-key keypad like the one represented in Fig. 3. You may run the project downloading the Proteus design from the web page.

1 2 3

654

8 97

0

TS

HS

MS

SSENTER24H/AM-PM

A

B

C

D

1 2 43

Fig. 3 Example of a commercial matrix keypad and the value obtained when pressing key “E” while scanning (setting a “0”) at RowD. Indeed, the DEC2:4 will be an integrated part of the scanning chip, and so, only the 4 pull-up resistors are the necessary hardware for the interface. An adapted keyboard can be easily obtained sticking new plastic labels on the keys (in Proteus-VSM, you can decompose a component, make the required modifications and adding the new component to the library)

The keyboard will be available in the laboratory and ready to be connected to the FLEX_EXPAN_A connector of the UP2 board. The pin assignment is as follows:

Row : OUT std_logic_vector(3 downto 0); -- Flex_EXPAN (41, 43, 45, 47) == pins (79, 81, 83, 86)

Column : IN std_logic_vector(3 downto 0); -- Flex_EXPAN (49, 51, 53, 55) == pins (88, 95, 98, 100)

-- Flex_EXPAN (57, 59) == VCC

1.6.2 Plan and code in VHDL the state diagram for the component

h) Invent what is usually called intellectual property (IP): a scanning chip for the 16-key keypad, which in some way has to be similar the commercial chip MM74C922. The chip has to be based essentially in a VHDL-written FSM running a state diagram for scanning rows and decoding the key pressed. See Fig. 4.

9

Page 10: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

Fig. 4 RTL netlist view for the keyboard decoder identified as a component

i) Write the VHDL code for the chip’s state diagram and verify it using a ModelSim project. Compile the project and use the Quartus II tool: State diagram netlist to verify if the state diagram that implements the FSM coincides with the one specified.

j) In case of having used any of the projects in Unit 2.8, which really represent a complete solution of the previous section i), fix the problem that appears when clicking simultaneously 2 keys of the same column. For example, the solution can be to introduce a final tri-state buffer to deactivate/disconnect all the rows which are not driven at logic low. See Fig. 5.

Fig. 5 A short-circuit is produced when clicking several keys in the same column. Driving the row through tri-state buffers can be a possible solution to this problem

1.6.3 Complete the project adding clock and display modules

k) Complete the project adding: (1) a hex-7segment decoder so that the hexadecimal code captured when pressing key will be displayed into the 7 segment display of the UP2 board; (b) the previous frequency divider so that the keyboard scanner entity will be driven by the 100 Hz pulse waveform. Do the necessary ModelSim simulations to verify your entity.

1.6.4 Synthesise the matrix keyboard application into a CPLD or a FPGA chip

l) Synthesise the module into the CPLD 7128S of the UP2 board and test it.

10

Page 11: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

(1)

VHDL source files

(2)

Functional simulation

(3) Device selection, pin assignment

(constraints) and project synthesis

(4)

RTL and technology

view

(5)

Gate-level simulation

(6)

Device programming

(7)

Verification using a

prototype board

EX3: Designing sequential systems using FSM

Fig. 6 Main steps in the programmable chip design flow

1.7 Debouncing keys1.7.1 Visualise the problem of mechanical pushbuttons interfaced to digital systems

m) Studying examples in Unit 2.8, and state the problem which arises when connecting a mechanical key, pushbutton or switch as an input to a digital system (synchronisation, glitches, bounces). See Fig. 7.

1.7.2 Solve the problem

n) Solve the problem designing a debouncing filter as a FSM to produce a clean and synchronised waveform considering any of these two options for the output: (1) Qa, a single pulse of one clock period wide; (2) Qb, a pulse that will last for all the push and release action.

RP10k

KEY

VccCLK

PB_L

Qa

Qb

DEBOUNCING CIRCUIT

KEY_FILTER

QaQbCLK

PB_L

Fig. 7 The problem of pressing and releasing mechanical keys and a circuit to solve it.

11

Page 12: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

Do not modify the text from page 3 to page 6

12

Page 13: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

2 Solución del Ejercicio 3

2.1 Divisor de frecuencia2.1.1 Planteamiento del problema

En esta parte del problema se nos pide que a partir de una señal cuadrada de 25.175 MHz producida por un “crystal oscillator” obtengamos 3 frecuencias menores a partir de divisores de frecuencia:

5kHz

1Hz

100 Hz

2.1.2 ¿Qué és un Crystall Oscillator?

Se trata de un oscilador de cristal [4], véase Fig. 8, que se caracteriza por su estabilidad de frecuencia y su pureza de fase, dada por el resonador.

La frecuencia es estable frente a variaciones de la tensión de alimentación. La dependencia con la temperatura depende del resonador, pero un valor típico para cristales de cuarzo es de 0' 005% del valor a 25 °C, en el margen de 0 a 70 °C.

Fig. 8 Ejemplos de crystall oscillators

13

Page 14: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

2.1.3 Divisores de Frecuencia

A continuación nos debemos preguntar cómo podemos dividir una frecuencia determinada. Buscando dicha información obtenemos la respuesta mediante el uso de contadores, los cuales se componen de otros tantos Biestables; flip-flops en inglés.

Una problemática de los divisores de frecuencia es que no siempre podemos extraer la frecuencia exacta que nosotros queremos, ya que hemos de dividir el señal de entrada por 2^X, esto no limitas las opciones, por lo que según para que tipo de señal deberemos adaptarnos a frecuencias muy parecidas, pero no exactas o jugar con multiplicadores, por ejemplo el multiplicador x 2 que añade simplemente un “0” sin Carry Out al string binario.

Otra opción es utilizar divisores en cascada, que vayan tratando el señal por etapas, dividiendo o multiplicando según el señal de salida que deseemos obtener.

2.1.4 ¿Qué és un Biestable?

Dispositivo de almacenamiento temporal de dos estados (alto y bajo), cuyas entradas principales, R y S, a las que debe el nombre, permiten al ser activadas:

R: el borrado (reset en inglés), puesta a 0 ó nivel bajo de la salida.

S: el grabado (set en inglés), puesta a 1 ó nivel alto de la salida

Si no se activa ninguna de las entradas, el biestable permanece en el estado que poseía tras la última operación de borrado o grabado.

2.1.5 Resolución del primer problema: Divisor de frecuencia poco eficiente

Este primer ejemplo obtenido de la página web de la asignatura consta de un único archivo VHDL en el cual encontramos varias deficiencias:

Demasiados componentes debido al uso de bloques en paralelo, véase Fig. 9.

Al tener todo el código concentrado en un único bloque y no modulado en varios ficheros se nos hace más difícil la lectura del código, así como sus posteriores modificaciones.

14

Page 15: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

+A[26..0]

B[26..0]

ADDER

+A[14..0]

B[14..0]

ADDER

+A[4..0]

B[4..0]

ADDER

=A[26..0]

B[26..0]

EQUAL

=A[14..0]

B[14..0]

EQUAL

=A[4..0]

B[4..0]

EQUAL

SELDATAA

DATABOUT0

MUX21

SELDATAA

DATABOUT0

MUX21

SELDATAA

DATABOUT0

MUX21

D QPRE

ENA

CLR

D QPRE

ENA

CLR

D QPRE

ENA

CLR

SELDATAA

DATABOUT0

MUX21

SELDATAA

DATABOUT0

MUX21

SELDATAA

DATABOUT0

MUX21

Add0

27' h0000001 --

Add2

5' h01 --

CLK_1kHz

CLK_1MHz

CLK_02HzEqual0

27' h7806337 --

Equal1

15' h6256 --

Equal2

5' h18 --

future_state_1khz[14..0]

future_state_1Mhz[4..0]

future_state_02hz[26..0]

present_state_1khz[14..0]

present_state_1Mhz[4..0]

present_state_02hz[26..0]

future_state_1Mhz~[4..0]

5' h00 --

future_state_02hz~[26..0]

27' h0000000 --

CD

CLK

CE

CLK_1MHz

CLK_1kHz

CLK_02Hz

future_state_1khz~[14..0]

15' h0000 --

Add1

15' h0001 --

Fig. 9 Captura de pantalla del RTL viewer del divisor de frencuencia poco óptimo

2.1.6 Divisor de frecuencia óptimo

Por último, encontramos en la página web de la asignatura un ejemplo de un divisor de frecuencia optimizado (Fig. 10), gracias a las siguientes características que le diferencian de sus antecesores:

Como en otros casos más optimizamos volvemos a utilizar la programación estructurada en varios ficheros VHDL, de este modo se nos hace más fácil localizar cada parte del problema y en un futuro nos facilitará posibles modificaciones y/o arreglos al código.

Diseño en casacada en serie. De este modo reaprobechamos las salidas como entradas del siguiente bloque y optimizamos componentes.

Menor uso de Biestables: log2 25+ log21007+ log25000=5+10+13=28 Biestables, frente a los 47 de la segunda opción colgada en la web.

CD

CE

CLK

TC25

CD

CE

CLK

TC1007

CD

CE

CLK

TC5000

freq_div_25:Freq_div_25_Comp1 freq_div_1007:Freq_div_1007_Comp1 freq_div_5000:Freq_div_5000_Comp1

CD

CLKCE

CLK_1MHzCLK_1kHz

CLK_02Hz

Fig. 10 Dibujo del diseño de un divisor con el formato de un “cascading synchronous counter”

15

Page 16: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

2.2 Design synchronous cascadable binary counters as FSM2.2.1 ¿Qué és una FSM?

En este punto del proyecto, debemos implementar un synchronous cascadable binary counters con una FSM.

Con el término FSM (Fig. 11) Finite State Machine (Maquina d’estats en català) lo que queremos es obtener la solución de algún problema determinado utilizando una lógica algorítmica de estados, representados (por ejemplo en papel) mediante distintos bloques. Cada bloque corresponde a uno de los estados de nuestro proyecto, y las interacciones entre un bloque y otro (entre un estado y otro) vendrán determinadas por diferentes flechas que marcarán la evolución del algoritmo según el valor de las distintas variables definidas para el funcionamiento de nuestra FSM.

Un ejemplo genérico de lo que hemos definido mediante palabras, sería el siguiente:

Fig. 11 Ejemplo genérico FSM

Del mismo modo, podemos implementar un algoritmo del “parsing Word: nice” (Fig. 12) mediante una Finite State Machine, este algoritmo podría ser el encargado de un control de password (contraseñas), de tal manera que si no introducimos la palabra adecuada el sistema nos dará siempre error.

Para poder obtener un OK deberemos introducir en orden y correctamente la palabra esperada nice

16

Page 17: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

Fig. 12 Ejemplo de “parsing Word: nice”

Nuevamente en la página web de la asignatura encontramos otro ejemplo de una FSM, representada en la siguiente figura Fig. 13.

Fig. 13 Ejemplo de FSM

Utilizaremos un ejemplo encontrado en la página web de la asignatura, dentro del temario correspondiente al la unidad 2.8 Designing FSM for any application: FSM for debouncing a key pushbutton http://digsys.upc.es/ed/CSD/units/Ch2/U2_08/Unit2_8.html

17

Page 18: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

Examinamos el contenido del proyecto y encontramos un archivo para Altera QUARTUS II, gracias a este programa podemos editar y compilar el proyecto para ver su funcionamiento.

Código VHDL FSM for debouncing a key pushbutton

---------------------------------------------------

-- FSM for debouncing an active-low key switch

-- A Synchronous Moore FSM build following SED style

-- Output XD goes LOW when 3 consecutive zero readings are obtained in X

---------------------------------------------------

LIBRARY IEEE;

USE IEEE.STD_LOGIC_1164.ALL;

USE IEEE.NUMERIC_STD.ALL;

-- Only for ispLEVER and SYNPLIFY: if attributes must be placed (as in choosing coding styles for FSM)

-- LIBRARY Synplify;

-- USE Synplify.attributes.ALL;

ENTITY key_debounce IS

PORT(

--> Inputs to the state register

CLK, CD : IN std_logic; -- CD will not be used

--> Inputs to the CS1

X : IN std_logic;

--> Outputs from the CS2

XD : OUT std_logic

);

END key_debounce;

ARCHITECTURE FSM_structure_design OF key_debounce IS

-- state signals declaration

TYPE State_type IS (S0, S1, S2, S3);

SIGNAL present_state, future_state : State_type ;

18

Page 19: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

-- If you want to choose the coding style

-- Only for ispLEVER and SYNPLIFY: For selecting the code: "sequential, gray, oneshot,

-- ATTRIBUTE syn_encoding OF present_state : signal is "sequential";

--Only for ispLEVER and PRECISION: For selecting the code: "binary, onehot, twohot, gray, auto, random

-- ATTRIBUTE FSM_STATE : STRING;

-- ATTRIBUTE FSM_STATE OF State_type : TYPE IS "BINARY";

BEGIN

-----------------------------------------------------------

-- State register, D-type flip-flops

-----------------------------------------------------------

state_register: PROCESS (CD,CLK)

BEGIN

IF (CD = '1') THEN -- reset counter

present_state <= S0;

ELSIF (CLK'EVENT and CLK = '1') THEN -- Synchronous register (D-type flip-flop)

present_state <= future_state;

END IF;

END PROCESS state_register;

------------------------------------------------------------

-- CS1: combinational logic for determining the future state

-- Using a process, state variables and the "case" sentence

------------------------------------------------------------

CS1: PROCESS (present_state, X)

BEGIN

CASE present_state IS

WHEN S0 =>

IF (X = '0') THEN

future_state <= S1; -- 1 zero

ELSE

future_state <= S0;

END IF ;

WHEN S1 =>

19

Page 20: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

IF (X = '0') THEN

future_state <= S2; -- 2 zero

ELSE

future_state <= S0;

END IF ;

WHEN S2=>

IF (X = '0') THEN

future_state <= S3; -- the third zero has beeen detected

ELSE

future_state <= S0;

END IF ;

WHEN S3 =>

IF (X = '0') THEN

future_state <= S3; -- Output LOW while keeping reading zeros

ELSE

future_state <= S0; -- go to the start point

END IF ;

END CASE;

END PROCESS CS1;

---------------------------------------------------------------

-- CS2: combinational logic to determine the outputs

---------------------------------------------------------------

XD <= '0' when present_state = S3 else '1';

END FSM_structure_design ;

A continuación procedemos a compilar el proyecto en Altera QUARTUS II y a examinar su funcionamiento mediante el RTL Viewer (Fig. 14), el cual nos mostrará la implementación con puertas lógicas del código VHDL para poder ser implementado en un chip de la familia MAX-7000S

20

Page 21: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

Fig. 14 Representación mediante Altera Quartus II RTL Viewer de nuestro proyecto debouncing a key pushbutton

Podemos observar de una forma mucho más intuitiva que examinando el código VHDL el funcionamiento del proyecto, el cual consta de:

INPUT CLK Será la entrada del clock, gracias a la cual funcionará todo el proyecto, ya que a partir del señal del clock se irán ejecutando escalonadamente y en función de su frecuencia todos los pasos.

INPUT CD Corresponde a la señal del RESET para el COUNTER, de tal manera que: present_state <= S0;

INPUT X Entrada del CSI (contador número 1), esta entrada se aprecia desde esta vista tan global debido a que puede venir dada desde el exterior (sería un push button de la placa por ejemplo).

OUT PUT XD Salida del CSII

Se puede observar en el siguiente diagrama de estados, Fig. 15, el funcionamiento de nuestro Finite State Machine y su correspondiente truth table, la cual determina su funcionamiento:

21

Page 22: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

Fig. 15 Diagrama de estados para debouncing a key pushbutton más la Truth Table

Además, disponemos del motor de simulación de códigos VHDL “Altera MODELSIM”, véase Fig. 16, gracias al cual podemos simular el funcionamiento del proyecto asignando valores a sus entradas y viendo la evolución de sus INPUTS/OUTPUTS a través del tiempo gracias a su entorno gráfico. Hemos realizado una simulación con las siguientes condiciones iniciales:

CD 0, no queremos resetear los valores

CLOCK Le asignamos funcionamiento de clock

XD Durante X segundos estará ON (TRUE = 1) y pasado un periodo de tiempo estará en OFF (FALSE = 0) para ver cómo evolucionan el resto de señales.

Podemos observar en la gráfica como los estados van evolucionando en función del CLOCK y del valor de las demás entradas tal y como están configuradas, de este modo vemos como desde el present_state va empujando los estados hacia el future_state, de tal manera que mientras XD=1 va evolucionando nuestra FSM.

22

Page 23: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

Fig. 16 Visualización del comportamiento del proyecto mediante ModelSim

2.3 Debouncing Filter2.3.1 Planteamiento de la problemática

Hemos de desarrollar una solución para nuestro problema con los botones y su rebote (Fig. 17), el problema es que cuando presionamos un botón físico éste produce una serie de interferencias (ruido) que debemos de filtrar antes de poder pasar esta información (la de haber presionado el botón) a cualquier tipo de sistema, para no producir un fallo.

RP10k

KEY

VccCLK

PB_L

Qa

Qb

DEBOUNCING CIRCUIT

KEY_FILTER

QaQbCLK

PB_L

Fig. 17 Problemática del rebote de los botones

2.3.2 Estudio teórico de una posible solución al problema

Para ello, primero hemos de estudiar el problema y intentar darle forma y solución mediante un diagrama de estados, véase Fig. 18.

23

Page 24: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

Fig. 18 Diagrama de estados para solucionar la problemática del Debouncing Push Button Filter

Además, hemos de acompañar la solución en forma de diagrama de estados con una aproximación teórica de cómo funcionaria nuestro sistema en función de las entradas y salidas, véase Fig. 19.

24

Page 25: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

Fig. 19 Solución gráfica del Debouncing Push Button Filter en función de sus entradas/salidas

2.3.3 Implementación en VHDL Quartus II

Una vez hemos hecho nuestras estimaciones teóricas procedemos a desarrollar su código VHDL para poder probar la solución, a continuación adjuntamos el código VHDL propuesto:

Código VHDL Solución Debouncing Push Button Filter

----------------------------------------

-- Debouncing Key FILTER

-- By: Alex Murillo -> [email protected]

-- Digital Electronics - EPSC @2010

----------------------------------------

LIBRARY IEEE;

USE IEEE.STD_LOGIC_1164.ALL;

USE IEEE.NUMERIC_STD.ALL;

25

Page 26: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

ENTITY Debouncing_Filter IS

PORT(

--> Inputs to the state register

CLK : IN std_logic;

--> Inputs to the CS1

--PB_L : IN std_logic;

PB : IN std_logic;

--> Outputs from the CS2

Qa,Qb : OUT std_logic

);

END Debouncing_Filter;

ARCHITECTURE FSM_structure_design OF Debouncing_Filter IS

-- state signals declaration

TYPE State_type IS (S0, S1, S2, S3);

SIGNAL present_state, future_state : State_type ;

--SIGNAL PB : std_logic;

BEGIN

-----------------------------------------------------------

-- State register, D-type flip-flops

-----------------------------------------------------------

state_register: PROCESS (CLK)

BEGIN

IF (CLK'EVENT and CLK = '1') THEN -- Synchronous register (D-type flip-flop)

present_state <= future_state;

END IF;

END PROCESS state_register;

------------------------------------------------------------

-- CS1: combinational logic for determining the future state

-- Using a process, state variables and the "case" sentence

------------------------------------------------------------

CS1: PROCESS (present_state, PB)

26

Page 27: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

BEGIN

CASE present_state IS

WHEN S0 =>

-- si pulso el botón me cambio de estado

IF (PB = '0') THEN

future_state <= S1;

-- si no pulso de botón me mantengo en el mismo estado

ELSE

future_state <= S0;

END IF ;

WHEN S1 =>

-- si pulso de nuevo el botón garantizo limpieza y salto al siguiente estado

IF (PB = '0') THEN

future_state <= S2;

-- si detecto ruido me vuelvo al primer estado

ELSE

future_state <= S0;

END IF ;

WHEN S2=>

-- si detecto PB = 1 es que sigo presionando el botón

IF (PB = '0') THEN

future_state <= S3;

ELSE

-- si no pulso el boton vuelvo al principio

future_state <= S0;

END IF ;

WHEN S3 =>

-- mientras detecte que pulsa el boton me quedo en el estado

IF (PB = '0') THEN

future_state <= S3;

-- si suelto el boton vuelvo al principio

ELSE

27

Page 28: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

future_state <= S0; -- go to the start point

END IF ;

END CASE;

END PROCESS CS1;

---------------------------------------------------------------

-- CS2: combinational logic to determine the outputs

---------------------------------------------------------------

Qa <= '1' when present_state = S2 else '0';

Qb <= '1' when present_state = S2 or present_state = S3 else '0';

-- PB <= NOT (PB_L);

END FSM_structure_design ;

2.3.4 Comprobaciones de la funcionalidad

Quartus II nos ofrece la posibilidad de comprobar nuestro código y nos ofrece varias comprobaciones gráficas a nuestra solución implementada en VHDL, las cuales comparamos con nuestros estudios previos y comprobamos que coinciden con nuestras previsiones.

RTL Viewer (FSM) Fig. 20

Diagrama de estados Fig. 21

Fig. 20 FSM Debouncing Push Button Filter Solution

28

Page 29: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

Fig. 21 Diagrama de estados Debouncing Push Button Filter Solution

Una vez comprobado el código y compilado en Altera QUARTUS II, procedemos a simularlo con la aplicación ModelSim.

Para ello, deberemos desarrollar una macro de tiempo que nos permita darle valores a nuestras entradas, simulando el problema y de este modo comprobar el funcionamiento de nuestro sistema solución propuesto.

Código do_Macro Para ModelSim

restart

add wave CLK

add wave PB

add wave Qa

add wave Qb

force CLK 0 0, 1 5ms -repeat 10ms

force PB 1

run 300ms

-- push_button activity

force PB 0

run 1.3ms

force PB 1

run 1ms

force PB 0

29

Page 30: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

run 1ms

force PB 1

run 1ms

force PB 0

run 1ms

force PB 1

run 1ms

force PB 0

run 1ms

force PB 1

run 1ms

force PB 0

run 1ms

force PB 1

run 3.45us

force PB 0

run 1.45us

force PB 1

run 2.234ms

force PB 0

run 36.234ms

force PB 1

run 200ms

Con este código generamos una aproximación a nuestra problemática (Fig. 22), en la cual podemos ver el siguiente comportamiento:

Mientras PB (Push Button) = 1, Qa = Qb = 0

Generamos ruido y Qa = Qb = 0

El ruido se estabiliza y Qa = Qb = 1

Pasado un tiempo, el botón sigue presionado y Qa = 0 pero Qb = 1

El botón se deja de presionar y Qa = Qb = 0

30

Page 31: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

Fig. 22 Simulación con ModelSim y la Macro realizada para simular la problemática a solucionar.

2.4 References Modify or add new references to this section. Follow the same format.

[1] http://epsc.upc.edu/projectes/ed/ . Comment: Course wed page where to find a lot of resources for the course. Specially, materials from previous editions. Read the section on theory about digital systems. [visited 12/2009]

[2] Brown,S., Vranesic, Z., “Fundamentals of digital logic with VHDL design”, McGraw-Hill, 2005. Comment: Figure 1. 7 contains an example of design flow for logic circuits and Figure 2.29 the structure of a typical CAD/EDA system.

31

Page 32: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

[3] An image to define a concept map: http://redie.uabc.mx/contenido/vol2no1/art-11-eng/contenido-ruiz-figura1.png

[4] Información detallada sobre varios components, así como diversas imágenes http://www.wikipedia.org

[5] Archivos de distintos proyectos de la Agenda de la asigntura http://digsys.upc.es/ed/CSD/terms/09_10_Q2/news_1BM.html

[6] Información sobre Finite State Machines http://digsys.upc.es/ed/CSD/units/Ch2/U2_08/Unit2_8.html

32

Page 33: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EX3: Designing sequential systems using FSM

2.5 Topics and activities checklist

Topics Activities

Group member in

charge Comments

1 2 3

1. The architecture of a FSM b)

2. A block diagram for the frequency divider. a)

3. A toggle flip-flop (T-FF). c)

4. A square wave of 1 Hz from the 25.175 MHz crystal quartz oscillator. d)

5. Pin assignment tool e)

6. Use the digital oscilloscope to measure signal delays and waveforms parameters. e)

33

Page 34: EX1 - murilloruiz.com  · Web view1. EX. 3: Designing sequential systems using FSM. 22. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz

7. Do gate-level simulations in ModelSim f)

8. Explain how a matrix keyboard encoder works g)

9. Invent the block diagram for a scanning matrix keyboard or debouncing circuits h), m)

10. Translate a state diagram into VHDL code i), n)

11. Tristate buffers in VHDL j)

12. Use the Quartus II tool:state diagram netlist i)

13. Complete the whole project using most of the components in a structural design k), l)

2.6 Grading grid Here you are the way the exercise could be grades.

Part 1

Design and simulation

a), b), c), d), f)

Part 1

Implementation and laboratory

e)

Part 2

Design and simulation

g), h), i)

Part 2

Implementation and laboratory

k), l)

Total

Scores 2p 3p 3p 2p

Self-assessment

Instructor’s grades

2.7 Questions in solving EX22

Write here your questions, comments, doubts, opinions, etc. ...

2 Add more sheets if necessary to report your progress or comments though the exercise.

Aquests fulls de dubtes i d’explicació de com heu anat fent l’exercici són obligatoris. Si no és present, no es corregeix l’exercici i s’ha de torna a lliurar. Abans de corregir i posar-vos qualificacions volem saber quin ha estat procés en què heu dissenyat els circuits i comparar-lo amb les nostres pròpies observacions de classe.

34