FSM- Alternate Verilog Model for designing the FSM

1
N S E O Zeanuri Lexartza San Justo Iondegorta Mandabidea Arraba Pagomakurre Egiriñao Upokomakatxa Larreder Undurraga Ipiñaburu Saldropo Altzuaga Otzerinmendi Urkiaga Ubidea Barazar Esparta Uribe Areatza Artea Orozko Beraza Sendegi Orrotegi Zugutxu Zubiaur San Martin Uribaso Aranguren Ibarra Zeberio Arisketa Urigoiti Belaustegi Baleriaga Aldabide Atxular Gallartu Altzagorta Zaloa Arbaiza Mantzarraga Llodio Gorbeia (1482 m) Aldamin (1376 m) Oderiaga (1245 m) Lekanda (1302 m) Ipergorta (1.256 m) Oketa (1031 m) Arralde (945 m) Undurragako urtegia Azero (967 m) Upo (608 m) Usategieta (1187 m) Nafakorta (1017 m) Araneko Harria Kolometa (1006 m) Ubixeta (1117 m) Lobantzo (684 m) Gaztañazarreta Urizar Usabel Bikotzgane 1 1 1 2 2 Jauregi 3 3 3 4 4 5 5 5 6 7 7 E E D E E D D Aitzkorrigane (1054 m) E A A A A A A N S E O Etxaguen San Pedro Goiuri / Gujuli Izarra Altube Baranbio Ziorraga Ametzaga Guillerna/Gilierna Bitoriano Murguía Oro Aretxaga Sarría Markina Lekandai Jugo Zárate Olano Manurga Murua Azkor Araza (1.139m) Gorostiano Arkarai Aldarro Igatz Ondategi Gopegui Beluntza Katxabaso Garrastatxu Gorbea (1482 m) Oketa (1031 m) Azero (967 m) Arralde (945 m) El Tocornal La Llana Peña Rota Embalses del Gorbea Canteras Mairuelegorreta Nafakorta (1017 m) Oderiaga (1245 m) Usategieta (1187 m) Burbona (935 m) Berretin (1.226 m) 1 1 2 2 3 3 3 4 5 5 5 6 6 7 7 Pagazuri Egillolarra Iturrikiano Arlobi Araneko Harria E E E E E A S/A E E D E E E E S/A vertiente alavesa gorbeia parque natural Creación: Declarado Parque Natural en junio de 1994. Extensión: 20.016 ha. Localización: En el límite de los territorios de Álava y Bizkaia. Ayuntamientos: Incluye terrenos de los municipios: Zuia, Zigoitia y Urkabustaiz en Álava y Orozko, Zenauri, Areatza, Zeberio y Artea en Bizkaia. Accesos: Desde Vitoria-Gasteiz la N-622 lleva hasta Murguía y de aqui a Sarria y a la Casa del Parque de la zona alavesa. La N-240 que une Bilbao y Vitoria-Gasteiz lleva a la localidad de Areatza donde se encuentra la Casa del Parque de la zona vizcaína. Altitud: El punto más alto corresponde al monte Gorbea con 1.482 m. y el más bajo a Ziorraga y Areatza con apenas 300 m. Información meteorológica Cuadro de temperaturas Primavera Verano Otoño Invierno Media máxima 25,2 36,4 27,4 16,3 Media mínima 9,2 17,3 11,9 4,4 Sendas Vertiente vizcaína espacios naturales álava gorbeia parque natural Sendas El Parque Natural de Gorbeia –el más extenso de la Comunidad Autónoma del Pais Vasco– guarda en su interior un sinfín de tesoros naturales y culturales. Una red de 14 sen- das –unas comienzan en la ver- tiente alavesa y otras en la viz- caína– permiten al caminante descubrir los bellos parajes de este espacio protegido, obser- var su flora y su fauna y, tam- bién, apreciar las tradiciones y la cultura de los seres huma- nos que habitaron y habitan este territorio. La excursión más típica es ascender a la famosa Cruz. Para ello, existen diversas alternativas: sendas Baias- Gorbeia, Pagomakurre, Murua... Otras rutas conducen al viajero por caminos en los que es posible observar “hue- llas” de la historia humana como dólmenes, menhires, majadas, carboneras, molinos y chabolas. Si se pasea en silencio y con respeto hacia la naturaleza, Gorbeia lo agradece “mostran- do” su cara más natural. Así, es posible ver u oír al ciervo, al picapinos, a la rana bermeja... Paseando por sus bosques y pastos de montaña, junto a ríos y arroyos y entre sus rocas, se comprende claramente los motivos por los que Gorbeia es hoy un espacio natural protegi- do. A la vez, ayuda a entender que es preciso conservarlo, para que cuando las generacio- nes futuras recorran estas mis- mas sendas, puedan seguir dis- frutando de todos sus valores naturales. Proyecto cofinanciado por el FEDER FEDERek ordaindutako proiektua Diseño: Idea y Vino S.L. Textos: Ekos, asesoría e investigación medioambiental. Fotografía: Joseba del Villar. Diseño cartografía: Gorosti Neuretak S.L. Coordinación: Luis Alfonso Quintana Impresión: Imprenta Diputación Foral de Álava. Editado por: Diputación Foral de Álava. Departamento de Urbanismo y Medio Ambiente. Depósito legal: VI-XXX-2004. Color N. Sendas Distancia Duración Dificultad 1. Garrastatxu 5,4 km 1 h 40 min Media 2. Altube 7,2 km 1 h 55 min Baja 3. Baias-Gorbeia 10 km 3 h 15 min Media-Alta 4. Zárate 5 km 1 h 25 min Media 5. Murua 8,1 km 2 h 40 min Media 6. Zubialde-Egillolarra 8,5 km 3 h 15 min Media-Alta 7. Etxaguen 4 km 1 h 15 min Baja Sendas Álava 1 2 3 4 5 6 7 Color N. Sendas Distancia Duración Dificultad 1. Lobantzo 10,3 km 2 h 30 min Media-Baja 2. Araneko Harria 5,6 km 1 h 45 min Media 3. Zastegi 8,3 km 2 h 40 min Media-Baja 4. Gallartu 2,7 km 50 min Media-Baja 5. Pagomakurre 10,2 km 3 h Baja 6. San Justo 2,3 km 50 min Alta 7. Atxurri 8,4 km 2 h 50 min Media Sendas Bizkaia ENLACE: de senda a senda DERIVACION: senda a un punto ACCESO: a inicio de senda Sendas gorbeia parque natural espacios naturales álava Leyenda Restaurantes Información Puente histórico Cueva Agroturismo Ermita Hotel-Casa rural Mirador Zona recreativa Arbol singular Casa del Parque Cantabria Mar Cantábrico BIZKAIA Gipuzkoa Navarra La Rioja Burgos Vitoria-Gasteiz Logroño Bilbao Condado de Treviño Á L AVA Parque Natural de Gorbeia Parque Natural de Urkiola Parque Natural de Valderejo Parque Natural de Izki (Burgos) Cantabria Reserva de la Biosfera de Urdaibai E A D vertiente vizcaina 2 3 4 5 6 7 1 Prohibiciones Consejos Antes de iniciar una excursión infórmese de la dificultad de la ruta y de la previsión del tiempo. Las Casas del Parque y su personal están a su servicio. Pasear en silencio y conocer los hábitos de los animales, llevar prismáticos y prendas de colores no llamativos facilitarán la observación de la fauna. Encender fuego y cortar leña. Aparcar, excepto en las zonas autorizadas. Lavar utensilios y vehículos en los ríos, lagos o arroyos. Circular con vehículos motorizados, excepto en los espacios autorizados. Abandonar y/o enterrar cualquier tipo de basura. Alterar, modificar y/o retirar elementos del medio natural.

description

This paper tells how to code FSM for a logic design. Definitions of state, state registers and decoder logic.

Transcript of FSM- Alternate Verilog Model for designing the FSM

Page 1: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 1 S. Yoder ND, 2013

CSE 20221: Logic Design

Timers, Frequency Divider Examples

Page 2: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 2 S. Yoder ND, 2013

Timers

• Timer

– time events

– divide clock frequency

– provide delay

• In each case the basic idea is to count clock

pulses

Page 3: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 3 S. Yoder ND, 2013

Verilog Code for Timer

Page 4: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 4 S. Yoder ND, 2013

Verilog Code for Frequency Divider

output reg clkDivOut;

Page 5: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 5 S. Yoder ND, 2013

Design of a Derived Clock

• Design a 1 millisecond clock that is derived from

a 50 MHz system clock.

• Design approach

– Frequency divider

– Divide by 50,000

• Determining size (N) of counter

– given division factor, DF

– N = roundUp(ln DF / ln 2) -1

– Parameter [N:0] countValue;

Page 6: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 6 S. Yoder ND, 2013

Verilog Description

Make sure the size of countValue

is set large enough to represent

the maximum count.

Page 7: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 7 S. Yoder ND, 2013

Test Fixture (See next slide for explanation)

Page 8: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 8 S. Yoder ND, 2013

Testing Circuits With Long Delays

• Testing circuits that require a large number of

clock delays before an event occurs can be done

by modifying the circuit design specifically for

testing.

– In the previous circuit you should check that three

events occur:

• The countValue resets when it equals period – 1

• The clkOut signal = 0 once the countValue resets

• The clkOut signal = 1 when the countValue == halfPeriod

– While testing, set the period to a small value

– In the test fixture insert the line #20 (@posedg clk) as

many times as necessary to see the above events.

Page 9: FSM- Alternate Verilog Model for designing the FSM

9

Finite-State Machines (FSMs)— Alternate Verilog

Model

Logic Design :Verilog FSM in class design example s 9 S. Yoder ND, 2013

Page 10: FSM- Alternate Verilog Model for designing the FSM

`10

Finite-State Machines (FSMs)— Review

• Finite-state machine (FSM)

– State diagram models behavior

– FSM architecture made of:

• State register

• Next State / Output Decoder

– A hardware description language

(HDL) should be capable of

modeling this architecture

– Previously we showed how Verilog

can model an FSM

– Now we will show another approach

of modeling an FSM with Verilog

Inputs: B; Outputs: X

On2 On1 On3

Off

X=1 X=1 X=1

X=0

B’;

B

Next State /

Output Decoder

State register

State

X B

Clk F

SM

inp

uts

FS

M

ou

tpu

ts

next state

Logic Design :Verilog FSM in class design example s 10 S. Yoder ND, 2013

Page 11: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 11 S. Yoder ND, 2013

Define States

off

on1

on2

on3

reset

State Diagram

x = 1

x = 1

x = 1

b

!b

off = 00

on1 = 01

on2 = 10

on3 = 11

Page 12: FSM- Alternate Verilog Model for designing the FSM

12

Definition of States and Declaration of State Registers

module LaserTimer(

input B,

output X,

input Clk, Rst);

// define the states

parameter S_Off = 0, S_On1 = 1,

S_On2 = 2, S_On3 = 3;

//declare present/next state reg

reg [1:0] State, StateNext;

Inputs: B; Outputs: X

On2 On1 On3

Off

X=1 X=1 X=1

X=0

B’

B

next state

decoder

State register

State

X B

Clk

FS

M

inp

uts

FS

M

outp

uts

next state

Logic Design :Verilog FSM in class design example s 12 S. Yoder ND, 2013

Page 13: FSM- Alternate Verilog Model for designing the FSM

13

Next State Decoder Logic

//next state decoder always @(State, B) begin case (State) S_Off: begin if (B == 0) StateNext <= S_Off; else StateNext <= S_On1; end S_On1: begin StateNext <= S_On2; end S_On2: begin StateNext <= S_On3; end S_On3: begin StateNext <= S_Off; end endcase end

Inputs: B; Outputs: X

On2 On1 On3

Off

X=1 X=1 X=1

X=0

B’

B

next state

decoder

State register

State

X B

Clk

FS

M

inp

uts

FS

M

outp

uts

next state

Sensitivity list is composed of the state variables

and all inputs that control branching.

Page 14: FSM- Alternate Verilog Model for designing the FSM

Verilog for Digital Design

Copyright © 2007

Frank Vahid and Roman Lysecky 14

Procedures with Case Statements

• Procedure may use case statement

– Preferred over if-else-if when just one expression determines which statement to execute

– case (expression)

• Execute statement whose case item expression value matches case expression

– case item expression : statement

– statement is commonly a begin-end block, as in example

– First case item expression that matches executes; remaining case items ignored

– If no item matches, nothing executes

– Last item may be "default : statement"

• Statement executes if none of the previous items matched

// CombLogic

always @(State, B) begin

case (State)

S_Off: begin

if (B == 0)

StateNext <= S_Off;

else

StateNext <= S_On1;

end

S_On1: begin

StateNext <= S_On2;

end

S_On2: begin

StateNext <= S_On3;

end

S_On3: begin

StateNext <= S_Off;

end

endcase

assign X = (State != S_Off);

end

Page 15: FSM- Alternate Verilog Model for designing the FSM

15

Clock Controled State Registers

// set next state

always @(posedge Clk) begin

if (Rst == 1 )

State <= S_Off;

else

State <= StateNext;

end

Inputs: B; Outputs: X

On2 On1 On3

Off

X=1 X=1 X=1

X=0

B’

B

next state

decoder

State register

State

X B

Clk

FS

M

inp

uts

FS

M

outp

uts

next state

Logic Design :Verilog FSM in class design example s 15 S. Yoder ND, 2013

Page 16: FSM- Alternate Verilog Model for designing the FSM

Verilog for Digital Design

Copyright © 2007

Frank Vahid and Roman Lysecky 16

When do the state register inputs get updated?

// CombLogic

always @(State, B) begin

case (State)

S_Off: begin

if (B == 0)

StateNext <= S_Off;

else

StateNext <= S_On1;

end

S_On1: begin

StateNext <= S_On2;

end

S_On2: begin

StateNext <= S_On3;

end

S_On3: begin

StateNext <= S_Off;

end

endcase

end

• The state register inputs, i.e., the D inputs to

the flip-flops, must get updated whenever

the present state changes, and whenever an

external input changes.

• The state register outputs get updated

whenever the clock edge occurs

always @(posedge Clk) begin

if (Rst == 1 )

State <= S_Off;

else

State <= StateNext;

end

Page 17: FSM- Alternate Verilog Model for designing the FSM

17

Output Decoder

//output decoder

assign X = State != S_Off;

Inputs: B; Outputs: X

On2 On1 On3

Off

X=1 X=1 X=1

X=0

B’

B

next state

decoder

State register

State

X B

Clk

FS

M

inp

uts

FS

M

outp

uts

next state

Moore machine means the outputs are a

function of only the present state (see next

slide). //output decoder, alternate equation

assign X = (State == S_On1)|

(State == S_On2)|(State == S_On3);

Logic Design :Verilog FSM in class design example s 17 S. Yoder ND, 2013

Page 18: FSM- Alternate Verilog Model for designing the FSM

Moore and Mealy FSM’s

18

Next State

Decoder Logic

Bistable Memory

Devices

Output Decoder

Logic

External

Inputs

External

Outputs

State Outputs

Next State

Decoder Logic

Bistable Memory

Devices

Output Decoder

Logic

External

Inputs

External

Outputs

State Outputs

Next State

Decoder Logic

Bistable Memory

Devices

Output Decoder

Logic

External

Inputs

External

Outputs

State Outputs

Next State

Decoder Logic

Bistable Memory

Devices

Output Decoder

Logic

External

Inputs

External

Outputs

State Outputs

Moore Type Mealy Type

Logic Design :Verilog FSM in class design example s 18 S. Yoder ND, 2013

Page 19: FSM- Alternate Verilog Model for designing the FSM

19

Complete Verilog Model of FSM

module LaserTimer(

input B,

output X,

input Clk, Rst);

// define the states

parameter S_Off = 0, S_On1 = 1,

S_On2 = 2, S_On3 = 3;

//declare present/next state reg

reg [1:0] State, StateNext;

// CombLogic

//next state decoder

always @(State, B) begin

case (State)

S_Off: begin

if (B == 0)

StateNext <= S_Off;

else

StateNext <= S_On1;

end

S_On1: begin

StateNext <= S_On2;

end

S_On2: begin

StateNext <= S_On3;

end

S_On3: begin

StateNext <= S_Off;

end

endcase

end

// set next state

always @(posedge Clk) begin

if (Rst == 1 )

State <= S_Off;

else

State <= StateNext;

end

//output decoder

assign X = (State != S_Off);

endmodule

Inputs: B; Outputs: X

On2 On1 On3

Off

X=1 X=1 X=1

X=0

B’

B

next state

decoder

State register

State

X B

Clk

FS

M

inp

uts

FS

M

outp

uts

next state

Logic Design :Verilog FSM in class design example s 19 S. Yoder ND, 2013

Page 20: FSM- Alternate Verilog Model for designing the FSM

20

Link Between State Diagram and Verilog Model

reg [1:0] State, StateNext;

// CombLogic

always @(State, B) begin

case (State)

S_Off: begin

if (B == 0)

StateNext <= S_Off;

else

StateNext <= S_On1;

end

S_On1: begin

StateNext <= S_On2;

end

S_On2: begin

StateNext <= S_On3;

end

S_On3: begin

StateNext <= S_Off;

end

endcase

assign X = (State != S_Off);

end

On2 On1 On3

Off

X=1 X=1 X=1

X=0

B'

B

parameter S_Off = 0, S_On1 = 1,

S_On2 = 2, S_On3 = 3;

Logic Design :Verilog FSM in class design example s 20 S. Yoder ND, 2013

Page 21: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 21 S. Yoder ND, 2013

FSM Testbench

//continued from left column

initial begin

B = 0;

reset = 1;

#100;

@ (negedge clk) reset = 0;

@ (negedge clk) B = 1;

#20;

@ (negedge clk) B = 0;

#20;

@ (negedge clk) #20;

@ (negedge clk) #20;

@ (negedge clk) #20;

@ (negedge clk) #20;

@ (negedge clk) #20;

end

endmodule

module testbench;

// Inputs

reg B;

reg clk;

reg reset;

// Outputs

wire X;

wire [1:0] presentState;

// Instantiate the Unit

);always begin

clk = 0;

#50;

clk = 1;

#50;

end

Page 22: FSM- Alternate Verilog Model for designing the FSM

Logic Design :Verilog FSM in class design example s 22 S. Yoder ND, 2013

Simulation Verification

Page 23: FSM- Alternate Verilog Model for designing the FSM

Verilog for Digital Design

Copyright © 2007

Frank Vahid and Roman Lysecky 23

Self-Checking Testbench (optional)

// Vector Procedure

initial begin

Rst_s <= 1;

B_s <= 0;

@(posedge Clk_s);

#5 if (X_s != 0)

$display("%t: Reset failed", $time);

Rst_s <= 0;

@(posedge Clk_s);

#5 B_s <= 1;

@(posedge Clk_s);

#5 B_s <= 0;

if (X_s != 1)

$display("%t: First X=1 failed", $time);

@(posedge Clk_s);

#5 if (X_s != 1)

$display("%t: Second X=1 failed", $time);

@(posedge Clk_s);

#5 if (X_s != 1)

$display("%t: Third X=1 failed", $time);

@(posedge Clk_s);

#5 if (X_s != 0)

$display("%t: Final X=0 failed", $time);

end

B_s

X_s

time (ns)

10 20 30 40

Clk_s

50 70

Rst_s

60 80 90 110 100

• Reading waveforms is error-prone

• Create self-checking testbench

– Use if statements to check for expected values

• If a check fails, print error message

• Ex: if X_s fell to 0 one cycle too early, simulation might output:

– 95: Third X=1 failed

Page 24: FSM- Alternate Verilog Model for designing the FSM

Verilog for Digital Design

Copyright © 2007

Frank Vahid and Roman Lysecky 24

Simulation $Display System Procedure (optional)

// Vector Procedure

initial begin

Rst_s <= 1;

B_s <= 0;

@(posedge Clk_s);

#5 if (X_s != 0)

$display("%t: Reset failed", $time);

Rst_s <= 0;

@(posedge Clk_s);

#5 B_s <= 1;

@(posedge Clk_s);

#5 B_s <= 0;

if (X_s != 1)

$display("%t: First X=1 failed", $time);

@(posedge Clk_s);

#5 if (X_s != 1)

$display("%t: Second X=1 failed", $time);

@(posedge Clk_s);

#5 if (X_s != 1)

$display("%t: Third X=1 failed", $time);

@(posedge Clk_s);

#5 if (X_s != 0)

$display("%t: Final X=0 failed", $time);

end

• $display – built-in Verilog system procedure for printing information to display during simulation – A system procedure interacts with the

simulator and/or host computer system • To write to a display, read a file, get the

current simulation time, etc.

• Starts with $ to distinguish from regular procedures

• String argument is printed literally... – $display("Hello") will print "Hello"

– Automatically adds newline character

• ...except when special sequences appear – %t: Display a time expression

– Time expression must be next argument • $time – Built-in system procedure that

returns the current simulation time – 95: Third X=1 failed

Page 25: FSM- Alternate Verilog Model for designing the FSM

25