31
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) Alex Murillo Ruiz ALL 1

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

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

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

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 view2. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz. 1. EX. 3: Designing sequential systems using FSM

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

(1) Alex Murillo Ruiz

(2) Jefferson Ortiz

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).

(This section is mandatory. You must complete it in order to get a mark.)

2

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

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................................................................................................................................................3

1.4 Topics........................................................................................................................................................3

1.5 Designing clock frequency dividers..........................................................................................................3

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

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

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

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

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

1.6.1 Keypad characteristics and wiring...................................................................................................4

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

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

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

1.7 Debouncing keys.......................................................................................................................................6

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

1.7.2 Solve the problem..............................................................................................................................6

1.8 Problem solution (títol 2)..........................................................................................................................7

1.8.1 Part 1 (títol 3)....................................................................................................................................7

1.9 References.................................................................................................................................................8

1.10 Study plan to solve the exercise................................................................................................................9

1.11 Topics and activities checklist................................................................................................................10

1.12 Grading grid............................................................................................................................................10

1.13 Questions in solving EX2........................................................................................................................10

3

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

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

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

4

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

EX3: Designing sequential systems using FSM

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. 1. 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. 1 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.

5

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

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

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. 2. 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. 2 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. 3.

6

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

EX3: Designing sequential systems using FSM

Fig. 3 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. 4.

Fig. 4 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.

7

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

(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

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

Fig. 5 Main steps in the programmable chip design flow

1.7 Debouncing keys 1.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. 6.

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. 6 The problem of pressing and releasing mechanical keys and a circuit to solve it.

8

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

EX3: Designing sequential systems using FSM

Do not modify the text from page 3 to page 6

9

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

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

2 Solución del Exercise 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 5x10^3Hz

1Khz 1x10^3Hz

100 Hz

2.1.2 ¿Qué és un Crystall Oscillator? (Fig. 7)

Se trata de un oscilador de cristal que se caracteriza por su estabilidad de frecuencia ysu 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. 7 Ejemplos de crystall oscillators

10

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

EX3: Designing sequential systems using FSM

2.1.3 Divisores de Frecuencia Crossover

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 Biestable RS (Set Reset) asíncrono Fig. 8

Sólo posee las entradas R y S. Se compone internamente de dos puertas lógicas NO-Y (NAND) o NO-O (NOR), según se muestra en la siguiente figura Fig. 8 y podemos ver su funcionamiento gracias a su truth table Fig. 9

11

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

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

Fig. 8 Ejemplos de Biestables RS asíncronos

Tabla de verdad biestable RS

R S Q (NO-O) Q' (NO-Y)

0 0 q N. D.

0 1 1 0

1 0 0 1

1 1 N. D. q

N. D.= Estado no determinado

Fig. 9 Truth table Biestable RS asíncrono

2.1.6 Biestable RS (Set Reset) síncrono Fig. 11

Además de las entradas R y S, posee una entrada C de sincronismo cuya misión es la de permitir o no el cambio de estado del biestable. En la figura (Fig. 10) se muestra un ejemplo de un biestable síncrono a partir de una asíncrona, podemos ver también su esquema normalizado. Además su funcionamiento viene definido por la siguiente truth table Fig. 12.

12

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

EX3: Designing sequential systems using FSM

Fig. 10 Circuito Biestable RS síncrono a) y esquema normalizado b).

Fig. 11 Funcionamiento de un Biestable RS síncrono

Tabla de verdad biestable RS

C R S Q (NO-O)

0 X X q

1 0 0 q

1 0 1 1

1 1 0 0

13

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

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

1 1 1 N. D.

X=no importa

Fig. 12 Thruth table Biestable RS síncrono

2.1.7 Resolución del primer problema: Crossover 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. 13.

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.

+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. 13 Captura de pantalla del RTL viewer del divisor de frencuencia poco óptimo

2.1.8 Divisor de frecuencia óptimo Fig. 14

Por último, encontramos en la página web de la asignatura un ejemplo de un Crossover optimizado, 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.

14

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

EX3: Designing sequential systems using FSM

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. 14 Dibujo del diseño de un divisor con el formato de un “cascading synchronous counter”

2.2 Design synchronous cascadable binary counters as FSMEn este punto del proyecto, debemos implementar un synchronous cascadable binary counters con una FSM.

2.2.1 ¿Qué és una FSM? Fig. 15

Con el término FSM 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:

15

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

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

Fig. 15 Ejemplo genérico FSM

Del mismo modo, podemos implementar un algoritmo del “parsing Word: nice” (Fig. 16) 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

Fig. 16 Ejemplo de “parsing Word: nice”

16

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

EX3: Designing sequential systems using FSM

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

Fig. 17 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

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;

17

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

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

-- 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 ;

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

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

18

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

EX3: Designing sequential systems using FSM

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 =>

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

19

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

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

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. 18), 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 view2. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz. 1. EX. 3: Designing sequential systems using FSM

EX3: Designing sequential systems using FSM

Fig. 18 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. 19, el funcionamiento de nuestro Finite State Machine y su correspondiente truth table, la cual determina su funcionamiento:

21

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

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

Fig. 19 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. 20, 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 view2. EPSC – EX3: Electronics I – Alex Murillo Ruiz & Jefferson Ortiz. 1. EX. 3: Designing sequential systems using FSM

EX3: Designing sequential systems using FSM

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

23

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

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

2.3 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.

[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

24

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

EX3: Designing sequential systems using FSM

25

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

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

2.4 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)

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.5 Grading grid Here you are the way the exercise could be grades.

26

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

EX3: Designing sequential systems using FSM

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 1p 1,5p 2p 1p

Instructor’s grades

2.6 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 tornar 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.

27