<4D F736F F F696E74202D C6F672D48444CC0BB20C0CCBFEBC7D120B5F0C1F6C5D0BDC3BDBAC5DBBCB3B0E82E707074>

Similar documents
MAX+plus II Getting Started - 무작정따라하기

Microsoft PowerPoint - hw4.ppt [호환 모드]

歯Chap1-Chap2.PDF

Microsoft PowerPoint - verilog문법new.ppt

untitled

ºÎ·ÏB

PowerPoint 프레젠테이션

디지털공학 5판 7-8장

Microsoft PowerPoint - CHAP-03 [호환 모드]

1

Microsoft PowerPoint - ch03ysk2012.ppt [호환 모드]

step 1-1

歯15-ROMPLD.PDF

Orcad Capture 9.x

4. #include <stdio.h> #include <stdlib.h> int main() { functiona(); } void functiona() { printf("hihi\n"); } warning: conflicting types for functiona

C++-¿Ïº®Çؼ³10Àå

PowerPoint 프레젠테이션

강의10

example code are examined in this stage The low pressure pressurizer reactor trip module of the Plant Protection System was programmed as subject for

Microsoft PowerPoint - AC3.pptx

wire [n-1:0] a, b, c, d, e, f, g, h; wire [n-1:0] x; // internal wires wire [n-1:0] tmp0, tmp1, tmp2, tmp3, tmp4, tmp5; mux_2to1 mux001 (.x(tmp0),.a(a

Microsoft PowerPoint - VHDL01_chapter1.ppt [호환 모드]

4 CD Construct Special Model VI 2 nd Order Model VI 2 Note: Hands-on 1, 2 RC 1 RLC mass-spring-damper 2 2 ζ ω n (rad/sec) 2 ( ζ < 1), 1 (ζ = 1), ( ) 1

hwp

10주차.key

T100MD+

#Ȳ¿ë¼®

Page 2 of 5 아니다 means to not be, and is therefore the opposite of 이다. While English simply turns words like to be or to exist negative by adding not,

Page 2 of 6 Here are the rules for conjugating Whether (or not) and If when using a Descriptive Verb. The only difference here from Action Verbs is wh

Microsoft PowerPoint - DSD03_verilog3b.pptx

PRO1_09E [읽기 전용]

C# Programming Guide - Types

<32382DC3BBB0A2C0E5BED6C0DA2E687770>

Microsoft Word - logic2005.doc

슬라이드 1

<B3EDB9AEC1FD5F3235C1FD2E687770>

휠세미나3 ver0.4

PowerPoint 프레젠테이션

슬라이드 1

DIY 챗봇 - LangCon

6주차.key

DE1-SoC Board

Something that can be seen, touched or otherwise sensed

Microsoft PowerPoint - ICCAD_Digital_lec03.ppt [호환 모드]

Microsoft PowerPoint - DSD01_verilog1a.pptx

IKC43_06.hwp

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

04-다시_고속철도61~80p

Journal of Educational Innovation Research 2018, Vol. 28, No. 3, pp DOI: NCS : * A Study on

Microsoft PowerPoint - Freebairn, John_ppt

Microsoft Word - logic2005.doc

PRO1_04E [읽기 전용]

Microsoft PowerPoint - PL_03-04.pptx

public key private key Encryption Algorithm Decryption Algorithm 1

Microsoft Word - 제6장 Beyond Simple Logic Gate.doc

슬라이드 1

Slide 1

300 구보학보 12집. 1),,.,,, TV,,.,,,,,,..,...,....,... (recall). 2) 1) 양웅, 김충현, 김태원, 광고표현 수사법에 따른 이해와 선호 효과: 브랜드 인지도와 의미고정의 영향을 중심으로, 광고학연구 18권 2호, 2007 여름

PowerChute Personal Edition v3.1.0 에이전트 사용 설명서

<BFA9BAD02DB0A1BBF3B1A4B0ED28C0CCBCF6B9FC2920B3BBC1F62E706466>

VHDL 기초 VHDL 두원공과대학정보통신미디어계열이무영

Microsoft PowerPoint - Ieee standard pptx

PowerPoint 프레젠테이션

Microsoft PowerPoint - VHDL08.ppt [호환 모드]

- 2 -

182 동북아역사논총 42호 금융정책이 조선에 어떤 영향을 미쳤는지를 살펴보고자 한다. 일제 대외금융 정책의 기본원칙은 각 식민지와 점령지마다 별도의 발권은행을 수립하여 일본 은행권이 아닌 각 지역 통화를 발행케 한 점에 있다. 이들 통화는 일본은행권 과 等 價 로 연

歯Intro_alt_han_s.PDF

Microsoft PowerPoint - hw8.ppt [호환 모드]

Microsoft PowerPoint - CHAP-01 [호환 모드]

The_IDA_Pro_Book

디지털 ASIC 설계 (1주차) MAXPLUS II 소개 및 사용법


. 고성능마이크로프로세서 LU 와레지스터 파일의구조 (2.). 직접디지털주파수합성기 (FS) 의구조 3. 고성능마이크로프로세서부동소수점연산기 (Floating-Point Unit) 구조 (2) (2.) (2.) 2. 암호화를위한 VLSI 구조와설계의개요 (2.) 다음참

DBPIA-NURIMEDIA

Remote UI Guide

아니라 일본 지리지, 수로지 5, 지도 6 등을 함께 검토해야 하지만 여기서는 근대기 일본이 편찬한 조선 지리지와 부속지도만으로 연구대상을 한정하 기로 한다. Ⅱ. 1876~1905년 울릉도 독도 서술의 추이 1. 울릉도 독도 호칭의 혼란과 지도상의 불일치 일본이 조선

untitled

6자료집최종(6.8))

Microsoft PowerPoint - Verilog_Summary.ppt

슬라이드 1

11¹Ú´ö±Ô

#KM-235(110222)

13주-14주proc.PDF

Microsoft PowerPoint - 27.pptx

Libero Overview and Design Flow

CPX-E-SYS_BES_C_ _ k1


Microsoft Word - FunctionCall

<3130C0E5>

예제 1.1 ( 관계연산자 ) >> A=1:9, B=9-A A = B = >> tf = A>4 % 4 보다큰 A 의원소들을찾을경우 tf = >> tf = (A==B) % A

지능정보연구제 16 권제 1 호 2010 년 3 월 (pp.71~92),.,.,., Support Vector Machines,,., KOSPI200.,. * 지능정보연구제 16 권제 1 호 2010 년 3 월

Chap06(Interprocess Communication).PDF

歯처리.PDF

감각형 증강현실을 이용한

0125_ 워크샵 발표자료_완성.key

RVC Robot Vaccum Cleaner

untitled

#KM560

Microsoft PowerPoint - ICCAD_Digital_lec02.ppt [호환 모드]

methods.hwp

Transcription:

Verilog-HDL 에의한

참고문헌 Verilog HDL : A Guide to Digital Design and Synthesis Author : Samir Palnikar Publisher : PTR-PH HDL Chip Design Author : Douglas J. Smith Publisher : Doone Publications Verilog Center http://www.angelfire.com/in/rajesh52/verilog.html Online Books, Technical Papers on Design Tips in Verilog Online Quick Reference http://www.sutherland-hdl.com/on-line_ref_guide/vlog_ref_top.html

본모듈의특징 목적 시많이사용되는 Verilog-HDL을배우고이를활용하여다양한디지털시스템을설계할수있도록한다. 본모듈을마치고나면 PC에서 C 언어를이용하여소프트웨어를개발하듯이, Verilog-HDL을이용하여디지털하드웨어를설계할수있게된다. 소요시간 : 2시간 / 주, 3주 선수내용 : 논리설계

본모듈에서다루고자하는내용 먼저 Verilog-HDL 이무엇인지알아보기위한예제를다룸 Verilog-HDL 을이용하여 4-bit 카운터설계하기 일반적인과정에대해간략히소개 Verilog-HDL 를소개 언어에대한기본이해 조합회로와순차회로설계하기 위에서배운 Verilog-HDL 을이용한 시계, Dice game, 교통신호제어기등

사양 Verilog-HDL 을이용하여 4-bit 카운터설계하기 (1/5) Verilog-HDL 이하드웨어설계에어떻게이용되는지알아보기위해카운터를설계해본다. 비동기식 (asynchronous) 4-bit 카운터만들기 비동기식은카운터를구성하고있는플립플롭 (flip-flop, FF) 의출력이다음단의플립플롭클럭단에연결된다. 카운터의각 bit 을구성하고있는부분은 T-FF 으로구성한다. T-FF 은 D-flipflop 과인버터 (inverter) 로구성한다고가정한다.

Verilog-HDL 을이용하여 4-bit 카운터설계하기 (2/5) 4-bit 카운터구성도 q0 q1 q2 q3 clock reset Counter-4 q0 q1 q2 q3 clock TFF clk q TFF clk q TFF clk q TFF clk q reset tf0 tf1 tf2 tf3 clock D Q DFF clk q reset

Verilog-HDL 을이용하여 4-bit 카운터설계하기 (3/5) 계층적구성도 (Hierarchical view) counter4 TFF (tf0) TFF (tf1) TFF (tf2) TFF (tf3) DFF INV DFF INV DFF INV DFF INV Here, each building block is a Verilog module (in VHDL : entity declaration + architecture body)

Verilog-HDL 을이용하여 4-bit 카운터설계하기 (4/5) Top-level 코딩 module counter4 (q,clk,reset); output [3:0] q; input clk, reset; TFF tf0 (q[0], clk, reset); TFF tf1 (q[1], clk, reset); TFF tf2 (q[2], clk, reset); TFF tf3 (q[3], clk, reset); endmodule -- in VHDL entity counter4 is port (q : out std_logic_vector(3 downto 0); clk, reset : in std_logic) end counter4; architecture RTL of counter_4 is component TFF port (q : out std_logic; clk, reset : in std_logic) end component; begin tf0: TFF port map(q(0), clk, reset); tf1: TFF port map(q(1), clk, reset); tf2: TFF port map(q(2), clk, reset); tf3: TFF port map(q(3), clk, reset); end RTL;

module TFF (q, clk, reset); output q; input clk, reset; wire d; // internal connection D_FF dff0 (q,d,clk, reset); not n1 (d, q); // primitive gate endmodule Verilog-HDL 을이용하여 4-bit 카운터설계하기 (5/5) Submodule 예 module D_FF (q, d, clk, reset); output q; input d, clk, reset; reg q; always @(posedge reset or negedge clk) if(reset) q <= 1 b0; else q <= d; endmodule

전체목차 흐름도 Verilog-HDL Overview Basic Idea Verilog-HDL의역사 Verilog-HDL Basics Modules & Ports Verilog Simulation Gate Level Modeling Dataflow Modeling Behavioral Modeling Application to Synchronous Logic FSM Design Parameterized Design More on Blocks Tasks & Functions Logic Synthesis 참고문헌

흐름도 (Design Flow) Design Entry Design Entry High-level Analysis Technology Mapping Low-level Analysis 회로를표현하고기술하는단계 : - 스키매틱 (schematic) - 하드웨어설계언어 (HDL, 예 : verilog, VHDL) 회로설계의결과물은다음과같은종류들의 netlist 들로표현될수있음 : - 논리게이트나플립플롭과같은 generic primitive 들이거나 - LUT/CLB, 트랜지스터등과같은 technology specific primitive 들, - 또는 adder, ALU, 레지스터파일, 디코더등과같은상위수준의라이브러리소자등

흐름도 High-Level Analysis Design Entry High-level Analysis Technology Mapping Low-level Analysis 상위수준의분석 (High-level analysis) 은원하는설계규격대로정확히동작하는지를검증하는단계이고, 타이밍과파워, 비용등에대해서도간단한수준에서검증 주요사용되는툴 : - simulator ( 기능검증 ) - Verilog-XL (Cadence 사 ) - VCX (Synopsys 사 ) - static timing analyzer - 라이브러리소자또는기본 primitive 들에대한타이밍모델과지연파라미터등에기초하여회로의지연시간을분석

흐름도 Technology Mapping 외 Design Entry High-level Analysis Technology Mapping Low-level Analysis Technology mapping 단계에서는상위설계단계에서얻어진 netlist 를사용하여실제하드웨어구현에사용될 technology 에적합하게변환시킴 : 라이브러리소자들을확장 partitioning, placement, routing 등을수행 Low-level analysis : - simulation 과 static 툴들을사용하여정확한타이밍모델과선로지연시간등을모두고려한하위수준에서검증. - FPGA 를사용할경우, 이단계에서는실제 FPGA 소자를정하여검증을시행함.

Verilog-HDL : Overview Basic Idea Basic idea : 언어를사용하여회로구성을기술 Structural description 은계층적 netlist 와유사 Behavioral description 은보통프로그래밍처럼상위수준의개체를사용 처음에는 abstraction 과 simulation 에도움을주기위해고안 지금은 behavioral description 을자동으로 gate netlist 로변환해주는 logic synthesis 라는툴이있음 이를활용하면설계자의생산성을매우높여줌 그러나, 이것은하드웨어설계를단순히프로그래밍의일부처럼잘못인식할수있음. Structural example: Decoder (a, b, x0, x1, x2, x3); input a, b; output x0, x1, x2, x3; { wire abar, bbar; inv(bbar, b); inv(abar, a); nand(x0, abar, bbar); nand(x1, abar, b); nand(x2, a, bbar); nand(x3, a, b); } Behavioral example: Decoder (a, b, x0, x1, x2, x3); input a, b; output x0, x1, x2, x3; { case (a, b) 00: [x3 x2 x1 x0 ] = 0hE; 01: [x3 x2 x1 x0 ] = 0hD; 10: [x3 x2 x1 x0 ] = 0hB; 11: [x3 x2 x1 x0 ] = 0h7; endcase; }

Verilog-HDL : Overview Verilog HDL 의역사 Originated at Automated Integrated Design Systems (renamed Gateway) in 1985. Acquired by Cadence in 1989. Invented as simulation language. Synthesis was an afterthought. Many of the basic techniques for synthesis were developed at Berkeley in the 80 s and applied commercially in the 90 s. Around the same time as the origin of Verilog, the US Department of Defense developed VHDL. Because it was in the public domain it began to grow in popularity. Afraid of losing market share, Cadence opened Verilog to the public in 1990. An IEEE working group was established in 1993, and ratified IEEE Standard 1394 in 1995. Verilog is the language of choice of Silicon Valley companies, initially because of high-quality tool support and its similarity to C-language syntax. VHDL is still popular within the government, in Europe and Japan, and some Universities. Most major CAD frameworks now support both. Latest HDL: C++ based. OSCI (Open System C Initiative). 1984-5 1986 Verilog-XL 1988 1989 1990-5 Synopsis Design Compiler ASIC Signoff Certification Opening of Verilog 1992-present Multiple Vendors

Verilog-HDL 목차 (Verilog-HDL) Basics Modules & Ports Verilog Simulation Gate Level Modeling Dataflow Modeling Behavioral Modeling Application to Synchronous Logic FSM Design Parameterized Design More on Blocks Tasks & Functions Logic Synthesis

Verilog-HDL : Basics Lexical conventions - 1 White Space 단어를구분하거나텍스트를좀더알아보기쉽도록하는데사용됨 예 : black space, tab, carriage return, new-line, form-feed Comment Single line comment 토큰 // 로시작하고 carriage return 으로끝남 Multi line comment 토큰 /* 로시작하고토큰 */ 로끝남 /* 1-bit adder example for showing few verilog */ Multi line comment module addbit ( a, b, ci, sum, co); // Input Ports Single line comment input a; input b; input ci; // Output ports output sum; output co; // Data Types wire a; wire b; wire ci; wire sum;

Verilog-HDL : Basics Case sensitivity Verilog HDL은대소문자구분함 Verilog에서사용하는모든키워드는소문자임 ( 비고 ) 키워드는대소문자조합상관없이변수명등으로절대로사용하지않기 Identifiers Lexical conventions - 2 module이나 signal, variable 등에부여되는이름 반드시영문자나 _ 로시작 (a-z A-Z _) 사용할수있는문자들 a-z A-Z _ 0-9 $ Escaped Identifiers Back slash ( ) 를사용하며, 임의의모든문자를사용가능하게함 Escaped identifier는 white space로끝남 < 대소문자구분하는이름들의예 > input // Verilog keyword wire // Verilog keyword WIRE // unique name ( 키워드아님 ) Wire // unique name ( 키워드아님 ) <Identifier 예 > data_in, my$clk, i486, A In VHDL, Comments : -- Identifier cannot start with _ Case insensitive

Verilog-HDL : Basics Data Types Integer Numbers Sized or unsized number 지정가능 Sized number의경우 Syntax: <size> <base><value> Binary, octal, decimal, hexadecimal 형태 예 : 4 b1111 12 habc 16 d255 In VHDL Unsized number의경우 : no sized number Syntax: <radix><base> 또는 <value> 23456 // default is decimal (32-bit : machine dependent) hc3 // 32-bit hexadecimal o21 // 32-bit octal Negative numbers: -3 (32 bit, signed number), -6 d3 (6 bit unsigned nbr, 2 s complement representation of -3) Underscore character is ignored in a number except for the first character: 12 b1111_0000_1010 Quotation marks? means z in the context of number: 4 b10??

Verilog-HDL : Basics Data Types Real Numbers Verilog 에서실수형상수또는변수를지원 Real number 를 integer 로변환시 rounding 함 Real number 에는 Z 나 X 를포함할수없음 Decimal 이나공학표현식으로지정 Syntax: <value>.<value> <mantissa>e<exponent> 예 : 1.2 0.6 3.5E6

Verilog-HDL : Basics Data Types Data Values Value set 0 : logic zero 1 : logic one X : unknown Z : high impedance In VHDL, std_logic type 9 value types ( 0, 1, Z, X, U,-, W, H, L ) user defined type Strength level Supply Strong Pull Large (trireg type only) Weak Medium (trireg type only) Small (trireg type only) Highz

Verilog-HDL : Basics Data Types Data Types - 1 Verilog Variables register net reg integer time real wire In VHDL, all signals can be both register and net type

Verilog-HDL : Basics Data Types Data Types - 2 두가지기본데이터형 Nets: 컴포넌트간의구조적연결을나타냄 Registers: 데이터를저장하는데사용되는변수를지정 Verilog code에서내부기본선언은 wire 형태의 net의속성과 1-bit임 Net 연결된디바이스의출력값으로항상구동, default 값은 z 임 키워드 wire, trireg, tri, wand, wor, triand, trior 등으로선언됨 wire가가장많이사용됨 ( 예 ) wire a;

Verilog-HDL : Basics Data Types Data Types - 3 Register 의데이터 type 데이터를저장하는데사용되는변수를지정 Register 배열을사용하면메모리를선언할수있음 키워드 reg, integer, real, time 으로선언 실제회로에서의레지스터 ( 플립플롭 ) 과는상관없음. reg type은실제회로에서wire에해당 Register 데이터형은 procedural block에서사용 Procedural block은키워드 initial과 always로시작함 reg가가장많이사용됨 ex) reg reset; initial begin reset = 1 b1; #100 reset = 1 b0; end

Verilog-HDL : Basics Data Types 예제 : net 와 reg module design (a,x,b,c); input a,x; output b,c; reg b; assign c = x and a; always @(a or x) b = a or x; endmodule --In VHDL, all output signal is register data type entity design is port (a, x : in std_logic; b, c : out std_logic); end design; architecture archi of design is begin c <= a and x ; process (a,x) begin b <= a or x; end process; end archi;

Verilog-HDL : Basics Data Types reg 형 : integer, real Integer Register type Default bit width is machine-dependent (at least 32) Ex) integer counter; initial counter = -1; Real Register type Decimal or scientific notation Ex) real delta; initial begin delta = 4e10; delta = 2.13; end

Verilog-HDL : Basics Data Types reg 형 : time Register data type Simulation time The width is implementation-dependent (at least 64) $time system function returns current simulation time Ex) time save_sim_time; initial save_sim_time = $time; Simulation time is measured in terms of simulation seconds (denoted by s) Time scale (relation between real time and simulation time is defined by user)

Verilog-HDL : Basics Data Types Vectors: multiple-bit data Nets or reg data type can be declared as multiple bit width using vector Syntax: data-type [MSB#:LSB#] signal-name Left number is MSB and right number is LSB Ex) wire [7:0] bus; wire [31:0] busa, busb; // 31 is MSB reg [0:40] addr; // 0 is MSB Parts of vector bits can be addressed as : busa[7] busb[2:0] addr[0:1]

Verilog-HDL : Basics Data Types 배열 (Arrays) Allowed for reg, integer, and time, and vector register data type Not allowed for real variable Syntax: data_type <array_name> [<subscript>] Multi-dimensional array is not permitted Ex) integer counter [3:0]; reg bool [31:0]; time chk_point[1:100]; reg [4:0] port_id[0:7]; // array of 8port_ids ; each port_id is 5 bits width Array elements are addressed as: count[2], chk_point[3], port_id[3] Notice! vector is a single element with n-bits wide arrays are multiple elements that are 1-bit (default) or n-bits wide

Verilog-HDL : Basics Data Types 메모리 RAM, ROM, or register files are modeled as array of registers Each element of the array is a word (each word can be multiplebits) Ex) reg [7:0] mem [0:1023] ; // 1K 8bit words mem word #1 (mem[0]) word #2 (mem[1]) word #3 (mem[2]) word #n (mem[1023]) bit0 bit1 bit2 bit3 bit7

Verilog-HDL : Basics Data Types 문자열 (strings) 문자열 (strings) Double quote 를사용하여문자열을만듬 하나의 line 에표현되어야함 각각의문자는 1 바이트로표현되고레지스터에저장될수있음 예 : reg [8*17:0] version; // declare a register variable that is 18 bytes reg [8*18:1] string_val; // 18 bytes wide initial version = model version 1.0 ; string_val = Hello Verilog World ; // store string value, 19bits width of reg > the size of string => fills bits to the left with 0s width of reg < the size of string => truncates the leftmost bits of string

Verilog-HDL : Basics Data Types 파라미터 (Parameters) Constant definition The value can be overridden at compile time by defparam statement Example) parameter port_id = 5; // define a constant port_id parameter cache_width = 256 ; // define a constant cache_width reg [cache_width - 1 : 0] cache; dest = port_id ;

Verilog-HDL : Basics Basic Compiler Directives Macro definition Syntax : `define macro_name macro_value Similar to #define in C Ex) `define WORD_SIZE 32 `define WORD_REG reg [32:0] reg [`WORD_SIZE-1 : 0] line ; `WORD_REG line_var ; File inclusion Syntax : `include filename Similar to #include filename in C Ex) `include header.v

Verilog-HDL : Basics Exercises 1. What are the types of one bit signal value in Verilog? 2. Which of the following types are net type? 1. reg 2. wire 3. integer 4. real 5. Time 3. Define Constants Phi (=3.14159) and Delay (=10) by means of parameter and define respectively. 4. Find the variable definitions for a and b. reg [7:0] M [0:15]; a = M[0]; b = a[0];

Verilog-HDL : Modules and Ports Components of Verilog Module module modulename ; Port list, port declarations (optional) Parameters (optional) Declarations of wire, reg,and other variables Dataflow statements (assign statements) Instantiation of lower level modules Behavioral statements (Always and initial blocks) Tasks and functions endmodule

Verilog-HDL : Modules and Ports 동시성 (Concurrency) Following Verilog HDL constructs are independent processes that are evaluated concurrently in simulation time: Module Instances Primitive Instances Continuous Assignments Procedural Blocks

Verilog-HDL : Module 과 Port 모듈의포트 (Port) 모듈과외부와데이터를주고받을수있도록해줌 각포트의모드세가지 : input, output 또는 inout 모든포트는기본적으로 wire의속성으로선언됨 따라서출력포트단자의값을유지하려면 reg로선언해야함 input, inout 형의포트는 reg로선언할수없음 ( 뒤에설명 ) syntax: input [range_val1:range_val2] list_of_identifiers; output [range_val1:range_val2] list_of_identifiers; inout [range_val1:range_val2] list_of_identifiers; 예 : input clk; // Clock input input [15:0] data_in; // 16 bit data input bus output [7:0] count; // 8 bit counter output inout data_bi; // Bi-directional data bus reg q; // Output port q holds value

Verilog-HDL : Module 과 Port Signal 과 Instance Port 간의연결 순서 (order) 에의한연결 module top; reg A,B, C_IN; wire C_O, SUM; fulladder4 U0 (SUM, C_O, A,B,C_IN); endmodule fulladder4 (sum, cout, a,b,c); endmodule 이름 (name) 에의한연결 module top ; fulladder4 U0 (.cout(c_o),.sum(sum),.a(a),.b(b),.c(c_in)); endmodule Width matching Legal to connect signals with different width But typically issued Warning Unconnected ports fulladd4 U0 (SUM,, A, B, C_IN); // carry_out is disconnected

Verilog-HDL : Module 과 Port 포트연결규칙 (Port Connection Rules) input port 는 net 형이어야함 inout port 도 net 형이어야함 output port 는 net or reg 타입일수있음 reg or net net inputs outputs reg or net net net net inouts Width matching: 서로다른크기의내 / 외부포트를연결하는것이가능 Unconnected ports: 연결되지않는포트는, 를사용하여표시 예 : dff u1 (q,, clk, d, rst, pre); // here second port is not connected inout port 도 net 형이어야함 output port 는 net or reg 타입일수있음

Verilog-HDL: Module 과 Port 계층이름 (Hierarchical Names) top u0 n1 (nand) q, qbar, set, reset n1 (nand) n2 (nand) Q, Qbar, S, R 계층적경로이름은 top module identifier와 module instant identifier로구성되며점 (.) 으로구분함 Syntax: Module_name.instance_name.port_name Ex) top.q top.u0.q top.n1

Verilog-HDL : Module 과 Port 회로예제 Sbar n1 Q Rbar n2 Qbar module SR_latch (Q, Qbar, Sbar,Rbar) ; // SR latch module output Q, Qbar; input Sbar, Rbar ; nand n1 (Q, Sbar, Qbar); nand n2 (Qbar, Rbar, Q); endmodule

Verilog-HDL : Module 과 Port Exercise 1. What are the basic components of module? And which are mandatory? 2. Write a Verilog code of instantiation of a module without ports. 3. Write down the port declaration for the module of the shift_reg module. reg_in[3:0] clock shift_reg (4 bits) reg_out[3:0]

Verilog-HDL 목차 Basics Modules & Ports Verilog Simulation Testbench System Tasks for Simulation Timescale Gate Level Modeling Dataflow Modeling Behavioral Modeling Application to Synchronous Logic FSM Design Parameterized Design More on Blocks Tasks & Functions Logic Synthesis

Verilog-HDL : Verilog Simulation Testbench and Verilog Simulation Testbench Input stimulus Unit Under Test output monitoring Testbench is written in Verilog is a module for simulation only (not synthesized) Component instantiation + input waveform + output monitoring statements

Verilog-HDL: Verilog Simulation Verilog Testbench Frame module testbench ; // module without IO port wire out1, out2; reg in1, in2; // Internal signal declaration myckt uut ( out1, out2, in1, in2); // module instantiation under test // stimulus via input signals initial begin in1 = 1 b0; in2 = 1 b0; #8 in1 = 1 b1; #8 in2 = 1 b1; end in1 in2 myckt initial // output signal monitor $monitor( siga = %d sigb=%d, out1, out2); out1 out2 endmodule

Verilog-HDL : Verilog Simulation module testbench; // simulation module wire q, qbar; reg set, reset; SR_latch UUT (q, qbar, ~set, ~ reset); // lower level module instantiation initial begin // stimulus input and monitor outputs set = 0; reset = 0; The result waveform #5 reset = 1; #5 reset = 0; #5 set = 1; end endmodule Simulation Example

Verilog-HDL : Verilog Simulation Basic System Tasks for Simulation $display : print text message on the screen once $strobe : similar to $display except that the printing of text is delay until all events in the current time step have been executed $monitor : print text message on the screen whenever its argument values are changed $stop : suspend simulation $finish : terminate simulation

Verilog-HDL : Verilog Simulation $display Usage: $display (p1,p2, pn) Similar to printf in C Language Automatically insert newline String format specifier %d or %D : in decimal %b or %B : in binary %h or %H : in Hexadecimal %o or %O : in Octal %s or %S : string %m or %M : hierarchical name of the module (no argument required) %f or %F : real number in decimal Example) $display ( Hello Verilog ); $display ($time); $display( At time %d virtual address is %h, $time, v_addr); $display( This is from %m level of hierarchy );

Verilog-HDL : Verilog Simulation $monitor Usage: $monitor (p1, p2, pn); Unlike $display, $monitor needs to be invoked only once Only one monitoring list can be active at a time. If there is more than one $monitor, the last $monitor is effective Example) initial $monitor($time, clock =%b reset = %b,clock, reset); $monitoron : a system task enabling monitoring $monitoroff : a system task disabling monitoring Monitoring is turned on by default at the beginning of simulation

Verilog-HDL : Verilog Simulation $stop / $finish $stop Usage : $stop Puts the Simulator into Interactive Mode Allows Designer to Debug the Design in the interactive mode $finish Usage : $finish Terminates the Simulation Examples) initial begin clock = 0; reset = 1; #100 $stop // this will suspend the simulation at time = 100 #900 $finish // this will terminate the simulation at time = 900 end

Verilog-HDL : Verilog Simulation Testbench Example with System Tasks module stimulus ; reg clock, reset; wire [3:0] q; bin_counter r1 (q, clock, reset); // clock period :10 initial forever #5 clock = ~ clock ; initial begin clock = 1 b0; reset = 1 b1; #20 reset = 1 b0; #40 reset = 1 b1; #20 reset = 1 b0; #10 $finish; end initial $monitor($time, output = %d, q); endmodule clock reset q (stimulus) clock reset q[3:0] counter 0 output = 0 25 output = 1 35 output = 2 45 output = 3 55 output = 4 60 output = 0 85 output = 1

Verilog-HDL : Verilog Simulation Time scales The Unit of Delay values in a simulation are defined by a compiler directive `timescale Usage : `timescale <reference time unit> / <time_precision> <time_precision> specifies the precision to which the delays rounded off in simulator <reference_time> and <time_precision> are one of 1, 10, 100 with time unit (ps, ns, us, ms) Example) `timescale 100 ns / 1 ns `timescale 1 us / 10 ns

Verilog-HDL 목차 Basics Modules & Ports Verilog Simulation Gate Level Modeling Primitive Gates Gate Delay Dataflow Modeling Behavioral Modeling Application to Synchronous Logic FSM Design Parameterized Design More on Blocks Tasks & Functions Logic Synthesis Appendix: FPGA Kit 요약

Verilog-HDL : Gate Level Modeling 회로기술의 3 가지유형 Structural: net-list description Hierarchical design with submodule instantiation list of components and how they are connected just like schematics, but using text Dataflow: Boolean expression description Assign statements Behavioral: algorithm description describe what a component does, not how it does it synthesized into a circuit that has this behavior Always block Mixed description in a module is also possible

Verilog-HDL : Gate Level Modeling Introduction Very intuitive, especially, for small circuit Verilog Language Provides Primitive Logic Gates Structural description Gate instantiation without instance name : legal Instance type (submodule name) and, or, xor, xnor, nand, nor, buf, not, bufif1, bufif0, notif1, notif0 One output and any number of inputs

Verilog-HDL : Gate Level Modeling AND/OR type (N-input primitives) Types : and, or, nand, nor, xor, xnor Ports order : for N input gate Output, Input-1, Input-2, Input-N Input/output ports number : only 1 output ports, any number of input ports (>= 2) Examples) and a1 (OUT, IN1, IN2); -- 2 input AND gate and a2 (OUT, IN1, IN2, IN3); -- 3 input AND gate and (OUT, IN1, IN2, IN3, IN4) ; -- legal gate instantiation

Verilog-HDL : Gate Level Modeling Buffer (N-output primitives) Types : buf, not Ports order : Output1, [Output2,,] Input Number of IOs any number of output ports (>= 1) Only 1 input port Examples) buf b1 (OUT, IN); -- simple buffer not n1 (OUT, IN) ; -- inverter not buf buf bf_2out (OUT1, OUT2, IN) ; -- more than 2 outputs

Verilog-HDL : Gate Level Modeling Tri-state buffer Types : bufif1, notif1, bufif0, notif0 bufif0 notif0 Input output control bufif1 notif1 Port order : output, input, control (Ex)bufif1 u0 (out, in, ctrl);

Verilog-HDL : Gate Level Modeling NAND 게이트를이용하여 AND 게이트만들기 X F=X Y Y // Structural model of AND gate from two NANDS module and_from_nand(x, Y, F); input X, Y; output F; wire W; // Two instantiations of the module NAND nand U1(W, X, Y); nand U2(F, W, W); endmodule

Verilog-HDL : Gate Level Modeling NAND 게이트를이용하여 DFF 만들기 D Q module dff(q, Q_BAR, D, CLK); output Q,Q_BAR; input D,CLK; CLK X Y Q_BAR nand U1 (X,D,CLK) ; nand U2 (Y,X,CLK) ; nand U3 (Q,Q_BAR,X); nand U4 (Q_BAR,Q,Y); endmodule

Verilog-HDL : Gate Level Modeling Example: 4-to-1 Multiplexer Block diagram i0 i0 i1 i2 i3 4-to-1 Mux out i1 i2 i3 out s1 s0 s1 s0

Verilog-HDL : Gate Level Modeling Example: 4-to-1 Multiplexer Verilog code module mux4_1 (out, i0, i1, i2, i3, s1,s0); output out; input i0, i1, i2, i3 ; input s1, s0; wire s1n, s0n; wire y0, y1, y2, y3; not (s1n, s1); not (s0n, s0); and (y0, i0, s1n, s0n); and (y1, i1, s1n, s0); and (y2, i2, s1, s0n); and (y3, i3, s1, s0); or (out, y3, y2, y1, y0); endmodule i0 i1 i2 i3 sn1 s1 sn0 s0 y0 y1 y2 y3 out

Verilog-HDL : Gate Level Modeling Example: 4-to-1 Multiplexer Testbench module testbench; reg IN0, IN1, IN2, IN3; reg S1, S0; wire OUTPUT; mux4_to_1 mymux (OUTPUT, IN0, IN1, IN2, IN3, S1, S0); initial begin IN0 = 1; IN1 = 0; IN2 = 1; IN3 = 0; S1 = 0; S0 = 0; #1 S1 = 0; S0 = 1; #1 S1 = 1; S0 = 0; #1 S1 = 1; S0 = 1; end endmodule

Verilog-HDL : Gate Level Modeling Exercise 1. Design 1-bit full-adder described as followed. Use only and, or and not primitive gates sum = A B CIN + A B CIN + A B CIN + A B CIN cout = A B + B CIN + A CIN 2. Write down a Verilog testbench for the 1-bit full adder above to verify by simulation

Verilog-HDL : Gate Level Modeling Gate Delays: rise, fall, turn-off 1 1, x or z 0,x, or z rise_t fall_t 0 delay for all transition Ex) and #(delay_time) a1 (out, i1, i2); rise and fall time delay specification Ex) and #(rise_t, fall_t) a2 (out, i1, i2); rise, fall, and turn off delay specification turn-off delay is a transaction time to z from another value Ex) and #(rise_t, fall_t, turn_off_t) a3 (out, i1, i2);

Verilog-HDL : Gate Level Modeling Gate Delays: min, typ, max Model a device whose delays vary within a range because IC fabrication process variation for each of rise, fall, and turn-off time three values, min, typ, and max, can be specified Verilog simulators choose one of these values at run time Examples) and # (4:5:6) a1 (out, i1, i2); and #(3:4:5, 5:6:7) a2 (out, i1, i2); and # (2:3:4, 3:4:5, 4:5:6) a3 (out, i1, i2);

Verilog-HDL : Gate Level Modeling Examples: Gate Delay module D (out, a, b, c); output out; input a,b,c ; wire e; and #(5) a1 (e, a, b); or #(4) o1 (out, e, c); endmodule a b c #5 D e #4 out #4 #5 #4

Verilog-HDL 목차 Basics Modules & Ports Verilog Simulation Gate Level Modeling Dataflow Modeling Continuous Assignment Inertia Delay Verilog Operators Behavioral Modeling Application to Synchronous Logic FSM Design Parameterized Design More on Blocks Tasks & Functions Logic Synthesis

Verilog-HDL : Dataflow Modeling Introduction Provides Circuit Description in terms of Data Flow between Registers and Processes on Data rather than Gate Instantiation Describes Circuits at a Higher (more abstract) Level of Abstraction than Gate Level Description Is Expressed by Continuous Assignments and Operators

Verilog-HDL : Dataflow Modeling Continuous Assignments Net에특정논리값을지정하는데사용 키워드 assign 으로시작 Syntax : assign <drive_strength> <delay> <list of assignments> ; 특징 Left-hand-side of assignment signal cannot be a register type Continuous assignments are always active Right-hand-side operands of assignment can be register type or function calls. And they can be either scalars or vectors Examples) assign out = i1 & i2; assign { c_out, sum[3:0] } = a[3:0] + b[3:0] + c_in; // concatenation of LHS

Verilog-HDL : Dataflow Modeling Implicit Continuous Assignments 선언시 Assignment Operator (=) 로함께지정 키워드 assign 으로시작하지않음 Examples wire out = in1 & in2 ; 위의 Implicit Continuous Assignment는다음과같이동일하게표현할수있음 wire out; assign out = in1 & in2 ;

Verilog-HDL : Dataflow Modeling Delay Type 과예제 다음의세예제는동일한효과 regular delays : assign #10 out = in1 & in2 ; // Delay in a continuous assign Implicit Continuous Assignment delays : wire #10 out = in1 & in2 ; // Declaration + Delay + Implicit Continuous Assignment Net Declaration Delay Delay can be specified on a net when declared without a continuous assignment on the net Ex) wire # 10 out; assign out = in1 & in2;

Verilog-HDL : Dataflow Modeling Inertia Delay Delay model is basically Inertia Delay Model An input pulse shorter than the delay of assignment statement does not propagate to the output assign #10 out = in1 & in2; in1 in2 out 10 20 30 60 70 80 85

Verilog-HDL : Dataflow Modeling Expressions Expressions are constructs that combine operators and operands to produce a result Operands constants, integers, real numbers, nets, registers, times, bit-select (one bit of vector), part-select (more than 2 bit select), memories, function calls Examples) integer count, final_cnt; reg [51:0] reg1, reg2 ; reg [3:0] reg_out ; reg reg_val; final_cnt = count + 1; reg_out = reg1[3:0] ^ reg2[3:0]; reg_val = calculate_parity (A,B) ;

Verilog-HDL : Dataflow Modeling Operators Arithmetic operators Logical operators Relational operators Equality operators Bit-wise operators Reduction operators Shift operators Concatenation operator Conditional operator Operator precedence

Verilog-HDL : Dataflow Modeling Arithmetic Operators Types *, /, +, Arithmetic % Modulus If any operands has x value, the result of the expression is x Negative numbers are represented as 2 s complement. Do not use negative number except integer and real type (Ex) d10 / 5 ; // (2 s complement of 10) / 5 = (2 32 10)/5 % (modulus) operator takes the sign of the first operand (Ex) (-7) % (+2) = -1 (+7) % (-2) = +1

Verilog-HDL : Dataflow Modeling Logical Operators Types && logical AND logical OR! logical Not Logical operators evaluate to 1-bit value 1(True) or 0 (False) If an operand is not equal to zero, it is equivalent to a True(1). If an operand is equal to zero, it is False(0). If an operand is x or z, it is equivalent to x (ambiguous) and treated as false condition by simulators Examples) A = 3; B = 0; A && B // equivalent to 0 (logical-1 AND logical-0) (A == 3) && ( B == 0) // evaluates to 1-bit value 1 (1 b1)

Verilog-HDL : Dataflow Modeling Relational Operators The relational operators returns a logical value 1 or 0 Operators > greater than < less than >= greater than or equal to <= less than or equal to == equality!= inequality) === case equality:identical!== case inequality: not identical Case/logical equality!= and == return x if one of operands has x or z (returns 0, 1, or x)!== and === compare bit by bit including x and z (returns either 1 or 0) Ex) // X=4 b1010, Y=4 b1101, Z=4 b1xxz, M=4 b1xxz X == Y // 0 X == Z // x M == Z //? x M === Z // 1

Verilog-HDL : Dataflow Modeling 종류 ~ bit-wise negation & bit-wise AND bit-wise OR ^ bit-wise exclusive OR ^~, ~^ bit-wise equivalence (XNOR) Example) // X = 4 b1010, Y = 4 b1101, Z = 4 b10x1 ~ X // Negation, Result is 4 b0101 X & Y // Bitwise AND, Result is 4 b1000 X Y // Bitwise OR, Result is 4 b1111 X ^ Y // Bitwise XOR, result is 4 b0111 X ^~ Y // Bitwise XNOR, Result is 4 b1000 X & Z // Bitwise XOR, Result is 4 b10x0 주의 : Bitwise Operators Do not confuse bitwise operator ~, &, (returns a vector value) with logical operator!, &&, (returns 1 bit value)

Verilog-HDL : Dataflow Modeling Reduction Operators Unary Operators Types : & reduction AND ~& reduction NAND reduction OR ~ reduction NOR ^ reduction XOR ~^, ^~ reduction XNOR Perform a bitwise operation bit-by-bit from right to left on a single vector Yield 1-bit result (Examples) // X = 4 b1010 & X // equivalent to 1 & 0 & 1 & 0 = 0 X // equivalent to 1 0 1 0 = 1 ^X //equivalent to 1 ^ 0 ^ 1 ^ 0 = 1

Verilog-HDL : Dataflow Modeling Shift Operators Types : << left shift >> right shift Examples) // X = 4 b1101 Y = X >> 1 // Y is 0110 (0 is filled in MSB position) Y = X << 2 // Y is 0100 (0 is filled in LSB position)

Verilog-HDL : Dataflow Modeling Conditional Operators 세개의Operand를가짐 Syntax Conditional_exp? True_exp : false_exp If its conditional_exp returns x (ambiguous) both true_exp and false_exp is evaluated Is similar to MUX / if-else statement 중첩될수있음 (can be nested) Example) assign out = control? In1 : in0 ; // 2-to-1 MUX assign out_sig = ( A == 3)? (control? x : y) : (control? m : n); //nested assign muxout = (sel == 1 b1)? A : B;

Verilog-HDL : Dataflow Modeling Concatenation and Replication Operators Concatenation Operators: { } // A = 1 b1 B =2 b00 C = 2 b10 Y = { B, C } // Results Y is 4 b0010 X = { A, B, 3 b110 } // Result X is 6 b100110 Z = { A, B[0], C[1] } // Result Z is 3 b101 assign #102 {co,sum} = a + b + ci; Replication Operators: {{ }} reg A = 1 b1; reg [1:0] B = 2 b01; reg [1:0] C = 2 b00; Y = { 4{A} } // Result Y is 4 b1111 X = { 4{A}, 2{B} } // Result X is 11110101 Z = {4{A}, 2{B}, C} // Result Z is 1111010100 assign byte = {4{2 b01}}; // Generate 8 b01010101 assign word = {{8 {byte[7]}}, byte}; // Sign extension

Verilog-HDL : Dataflow Modeling Operators Summary - 1 Arithmetic operators + - * / arithmetic % modulus Logical operators! logical negation && logical and logical or Relational operators >< >= <= relational Equality operators == logical equality!= logical inequality === case equality!== case inequality Bit-wise operators ~ bit-wise negation & bit-wise and bit-wise inclusive or ^ bit-wise exclusive or ^~ bit-wise equivalence ~^ bit-wise equivalence Reduction operators & reduction and ~& reduction nand reduction or ~ reduction nor ^ reduction xor ~^ reduction xnor ^~ reduction xnor

Verilog-HDL : Dataflow Modeling Operators Summary - 2 Shift operators << left shift >> right shift Concatenation operator {} concatenation Replication {{}} replication Conditional operator?: conditional

Verilog-HDL : Dataflow Modeling Operator Precedence Operator Operator Symbols Precedence 1. Unary, Multiply, Divide, Modulus 2. Add, Subtract, Shift 3. Relational, Equality 4. Reduction. Logical + -! ~ * / % + - << >> < <= > >= ==!= ===!== &,~& ^ ^~ ~ && Highest Precedence 5. Conditional?: Lowest Precedence

Verilog-HDL : Dataflow Modeling Example: Multiplexer module mux4_1 (out, i0, i1, i2, i3, s1, s0); output out; input i0, i1, i2, i3; input s1, s0; assign out = (~s1 & ~s0 & i0) (~s1 & s0 & i1 ) (s1 & ~s0 & i2) (s1 & s0 & i3) ; endmodule module mux4_1 (out, i0, i1, i2, i3, s1, s0); output out; input i0, i1, i2, i3; input s1, s0; assign out = s1? (s0? i3:i2) : (s0? i1:i0); endmodule

Verilog-HDL : Dataflow Modeling Exercises - 1 1. Design Parity Generator /Checker for 7-bit data. If control signal PRT is 0 it is even parity system, Others it s odd parity system PRT parity parity_gen data[6:0] 2. Design a magnitude comparator for two 4 bit data. A[7:0] B[7:0] comparator GT(A>B) LT(A<B) EQ(A=B) 3. Design a 4-to-1 Multiplexer using (1) only conditional operators or (2) logical equation

Verilog-HDL : Dataflow Modeling Exercises - 2 4. Combinational Design : Design 7 segment Display decoder. Output form is as follows : 5. Hierarchical Design : Target output LED shape is shown on the right. Use the module above as a submodule instance.

Verilog-HDL 목차 Basics Modules & Ports Verilog Simulation Gate Level Modeling Dataflow Modeling Behavioral Modeling initial vs. always Blocking vs. non-blocking assignment Delay based timing control Event-based timing control Statements (if-else, case, while, repeat, forever) Application to Synchronous Logic FSM Design Parameterized Design More on Blocks Tasks & Functions Logic Synthesis

Verilog-HDL : Behavioral Modeling Introduction Description of Design Functionality in an Higher Level All the behavioral statements appear only inside initial and always blocks always block / initial block : Two main Structured procedure in behavioral modeling These are Similar to Process Statements in VHDL Each activity flow starts at time 0 They Cannot be Nested They can Have Multiple Statements Between the keyword begin and end

Verilog-HDL : Behavioral Modeling Initial Statement Usage : initial statement It starts at time 0 Execute exactly once (do not re-executed during simulation) If multiple initial block exist, each of them starts concurrently and finish independently of the other blocks module stim; reg x,y,a,b,m ; initial m = 1 b1; initial begin #5 a = 1 b1; #25 b = 1 b0; end initial begin #10 x = 1 b0; #25 y = 1 b1; end initial #50 $finish; endmodule Time statement executed 0 m = 1 5 a = 1 10 x = 0 30 b = 0 35 y = 1 50 $finish

Verilog-HDL : Behavioral Modeling Always Statement Usage : always statement Starts at time 0 Executes the statements in the block continuously in a looping fashion Similar to infinite loop in C Starts on power-on (simulation begin), stop by power off ($finish/$stop) Models a block of activity that is repeated continuously (e.g. clock generator) module clock_gen reg clock; initial clock = 1 b0; always #10 clock = ~ clock; initial #1000 $finish 0 10 20 30 40 50

Verilog-HDL : Behavioral Modeling Exercises 1. What happens if the following code is simulated module test ; reg a, b, c ; always begin a = b ; c = b; end initial begin b = 0; #5 b = 1; end endmodule Ans: Simulation time cannot advance because of the infinite loop of always block

Verilog-HDL : Behavioral Modeling Verilog Assignments Types Verilog assignments types Procedural (in always or initial) Continuous (keyword assign) Blocking( = ) Nonblocking (<=)

Verilog-HDL : Behavioral Modeling Procedural Assignments Updates values of reg, integer, real, or time variables (register types) The value placed on a variable will remain unchanged until another procedural assignment updates the variable Syntax : <lvalue> = <expression> or <lvalue> <= <expression> The lvalue can be reg, integer, real, or time register The lvalue can be a concatenation of any of the above In the expression of right hand, all the operators in dataflow modeling can be used 2-types of procedural assignments :Blocking and Non-Blocking

Verilog-HDL : Behavioral Modeling Blocking Statement Are Executed in the order they are specified Are Sequential Exactly (similar to variable assignments in VHDL process) Use the = assignment operator initial begin x = 0; y = 1; z = 1; count = 0; reg_a = 16 b0; reg_b = reg_a; #15 reg_a[2] = 1 b1; #10 reg_b[15:13] = {x, y, z} count = count + 1; end 1. Executes All Statements x=0 through reg_b = reg_a (at time = 0) 2. reg_a[2] = 1 at time = 15 3. reg_b[15:13] = {x,y,z} at time = 25

Verilog-HDL : Behavioral Modeling Nonblocking Statement Schedule assignments without blocking execution of the next statements in a sequential block (similar to signal assignments in VHDL process) Use Operartor <= Example) A <= B; When Verilog Simulator Sees NonBlocking Assignment Statements it Schedules the Statements (Read or Evaluate the RHS expression and then Store the RHS value in temporal storage) and Continue to the Next Statement without Waiting for the Nonblocking Statement to Complete Execution.

Verilog-HDL : Behavioral Modeling Nonblocking 과 Blocking Assignment 비교 initial begin x = 0; y = 1; z = 1; count = 0; reg_a = 16 b0; reg_b = reg_a; 0 unit에 update reg_a[2] <= #15 1 b1; 15 unit 뒤에 update reg_b[15:13] <= #10 {x, y, z} 10 unit 뒤에 update count = count + 1; 0 unit에 update end 1. Execute All Statements x=0 through reg_b = reg_a (at time = 0) 2. reg_a[2] = 1 is scheduled to execute after 15 time units (i.e. time = 15) 3. reg_b[15:13] = {x,y,z} is scheduled to execute after 10 time units(i.e. time = 10) 4. count = count + 1 is scheduled to be executed without any delay (i.e. time = 0)

Verilog-HDL : Behavioral Modeling Nonblocking Statement 에서 Read, Write 문분리 always @(posedge clock) begin reg1 <= #1 in1; reg2 <= @(negedge clock) in2 ^ in3; reg3 <= #1 reg1; // old value of reg1 end At each positive edge of clock, 1. Read operation is performed on each RHS(right hand side) variable in1, in2, in3, and reg1. And right hand side expressions are evaluated, and the results are stored internally in temporary storage of the simulator 2. The write operation to the left hand side variables are scheduled to be executed at the time specified 3. The write operations are executed at the scheduled time steps. (Note that the order of statements is not important because internally stored RHS expression values are used to be assign to the LHS variables)

Verilog-HDL : Behavioral Modeling Race Condition // illustration 1 : blocking always @(posegde clk) a = b ; always @(posedge clk) b = a; // illustration 2 : nonblocking always @(posegde clk) a <= b ; always @(posedge clk) b <= a; There is a race condition. Two blocking assignments in different always are executed sequentially depending on the simulator implementation. The result will be b< a< b or a< b< a Race condition is eliminated. At the rising edge of clock, RHS value of nonblocking assignments are read and the expressions evaluated. During write operation, the stored values are used

Verilog-HDL : Behavioral Modeling Nonblocking Assignments // illustration 2 : nonblocking always @(posegde clk) a <= b ; always @(posedge clk) b <= a; Separating Read and Write Ensures a and b are swapped Regardless of the Write Operation Order! // illustration 2 : nonblocking always @(posegde clk) begin temp_a = a; // read operation temp_b = b; // read operation a = temp_b; // write operation b = temp_a; // write operation end

Verilog-HDL : Behavioral Modeling Nonblocking Statement 특징 NonBlocking Assignments are Used as a Method to Model Several Concurrent Data Transfers that take place After a Common Event. In Nonblocking Assignments, Final Assignment Results Are Not Dependent On the Order They Are Evaluated. While In Blocking Assignments, Final results Depends on the Order in which they are Evaluated Blocking Assignments can Potentially Cause a Race Condition

Verilog-HDL : Behavioral Modeling Signal Statement 사용에대한가이드 For combinational logic description Use Blocking Assignment For data transfer in edge-triggered Memory Elements description Use Nonblocking Assignment Do not Mix Blocking and Nonblocking Assignments in the same always / initial block Do not use the same variable as LHS variable in different always / initial blocks => to prevent race condition

Verilog-HDL : Behavioral Modeling Verilog Event Queue Priority Queue Execution Order High priority Blocking assignments, $display (#0)Zero delay assignments Update LHS of nonblocking assignments Low priority Monitoring statements ($monitor, $strobe)

Verilog-HDL : Behavioral Modeling Exercises (1) 1. What is the difference of the two codes? module pipe1 (q3, d, clk); output [7:0] q3; input [7:0] d; input clk; reg [7:0] q3, q2, q1; always @(posedge clk) begin q1 = d; q2 = q1; q3 = q2; end endmodule How about the reverse ordering? module pipe2 (q3, d, clk); output [7:0] q3; input [7:0] d; input clk; reg [7:0] q3, q2, q1; always @(posedge clk) begin q1 <= d; q2 <= q1; q3 <= q2; end endmodule

Verilog-HDL : Behavioral Modeling Exercises (2) 2. What is the difference of the simulation results of the 3 codes? // generates clock signal of period 10 module osc1 (clk); output clk; reg clk; initial #5 clk = 0;. always @(clk) #5 clk = ~clk; endmodule module osc1 (clk); output clk reg clk; initial #5 clk = 0; always @(clk) #5 clk <= ~clk; endmodule // generates clock signal of period 10 module osc1 (clk); output clk; reg clk; initial #5 clk = 0;. always #5 clk = ~clk; endmodule

Verilog-HDL : Behavioral Modeling Exercises (3) 3. Find the Difference of the 2 codes. Which corresponds to the picture? a1 en1 a2 en2 module drivers_cont (y, a1, a2, en1, en2); output y; input a1, a2, en1, en2; assign y = en1? a1 : 1 bz; assign y = en2? a2 : 1 bz; endmodule y module drivers_seq (y,a1,a2,en1,en2); output y; input a1, a2, en1, en2; reg y; always @(en1 or a1) if(en1) y = a1; else y = 1 bz; always @(en2 or a2) if(en2) y = a2; else y = 1 bz; endmodule

Verilog-HDL : Behavioral Modeling Answer for Exercises (3) module drives_cont; wire y; reg x ; reg a1,a2,en1,en2; assign y = en1? a1:1'bz; assign y = en2? a2:1'bz; always @(en1 or a1) if(en1) x = a1; else x = 1'bz; always @(en2 or a2) if(en2) x = a2; else x = 1'bz; initial begin a1 = 1; a2 = 0; en1 = 0; en2 = 0; #5 en1 = 1; #5 en2 = 1; #5 en1 = 0; end endmodule

Verilog-HDL : Behavioral Modeling Timing Control Timing Control Provides a Way to Specify the Simulation Time at which Procedural Statements will Execute If there is No Timing Control Statements, the Verilog Simulator will Not Advance! 3 methods of timing control Delay-based control Event-based control Level sensitive control

Verilog-HDL : Behavioral Modeling Delay-Based Timing Control Delays are Specified Explicitly in the Procedural Statements Syntax : <delay> ::= #<number> #<identifier> #(<min_typ_max_exp>,<< min_typ_max_exp>>*) 3 types of delay-based timing controls initial #10 z = x + y; z = #10 x + y end initial begin #0 x = 1 end; initial begin x = 1; end regular delay control intra-assignment delay control Zero delay control

Verilog-HDL : Behavioral Modeling Delay Control 의세가지형태 Regular delay control Is Specified left of a procedural statement Defers the execution of entire assignment statements Example) #3 x = y ; Intra-assignment delay control Is Specified to the right of the assignment operator Computes (Evaluates) the RHS expression at current time and defer the assignment of the computed value to the LHS variable Example) x = #3 y ; Zero Delay control #0 procedural_statements Example) #0 x = y Objective : To Eliminate the race condition between different always-initial blocks at time 0

Verilog-HDL : Behavioral Modeling Regular Delay Control parameter latency = 20; parameter delta = 2 ; reg x, y, z, p, q; initial begin x = 0; z =0 ; #10 y = 1; #latency z = 0; #(latency + delta) p = 1; // delay with expression #y x = x + 1; // delay with identifier takes the y value #(4:5:6) q = 0; // minimum, typical, maximum values end

Verilog-HDL : Behavioral Modeling Intra-Assignment Delay Control // intra-assignment delay example initial begin x = 0; z =0 ; y = #5 x + z; // Take the value of x and z at time 0 and evaluate // x + z and then wait 5 time units to assign it to y end initial // Regular delay control with temporary variable has // equivalent effect to the intra-assignment delay above x = 0; z = 0; temp_xz = x + z; // takes the value of x + z and stores it in a temporary variable. #5 y = temp_xz; // Even though x and z might be change between 0 and 5, // the value assigned to y at time 5 is unaffected end

Verilog-HDL : Behavioral Modeling Zero Delay Control initial begin x = 0; y = 0; end initial begin #0 x = 1; #0 y = 1; end Results : (deterministic) x = 1 and y = 1 The Order of Procedural Statement Executions in Different Blocks at the Same Simulation Time is Nondeterministic Zero Delay Control Ensure that the statement is executed last, after all other statements in that simulation time. But, Between Multiple Zero Delay Statement, The Order Between Them is also Nondeterministic.

Verilog-HDL : Behavioral Modeling Exercises 1. What is the simulation waveform? module delay_control_test ; integer a,b,c,d,x ; integer A,B,C,D ; // blocking assignment initial begin #0 a = 0; b = 0; c = 0; d = 0; a = #35 x; #15 b = x; #10 c = # 20 x; d = #10 x; end // nonblocking initial begin #5 A = 0; B <= 0; C = 0; D = 0; A <= #10 x; #10 B <= x; #10 C <= # 20 x; D <= #10 x; end regular delay : 문장전체의접근을지연시킴 (RHS 자체의 read 를지연 ) intra assignment delay : RHS 가 LHS 로전달되는것을지연시킴 blocking : LHS 가 update 된후에야다음문장으로제어가넘어감 non-blocking :RHS 에대한 eval(read) 만일어난후에다음문장으로제어가넘어감 // stimulus initial begin x = 5; #10 x = 6; #10 x = 7 ; #10 x = 8; #10 x = 9; #10 x = 10; #10 x = 11; #10 x = 12; #30 $stop; end endmodule

Verilog-HDL : Behavioral Modeling Hints for the Answer : Blocking Time for the execution of the assignment statement (x= #5 y) #10 X = #5 Y ; Time for the value of Y to be transferred to the variable X The control will not pass to the next statement. until the execution (not scheduling ) of the blocking assignment is completed. (after 10 + 5 time, the control is passed to the next statement) Value of Y is read & saved Saved Y is copied to X Time = 0 Time = 10 Time = 15

Verilog-HDL : Behavioral Modeling Hints for the Answer : Nonblocking Time for the execution of the assignment statement (x <= #5 y) #10 X <= #5 Y ; Time for the value of Y to be transferred to the variable X After the evaluation of RHS expression (time = 10) of nonblocking assignments, the Control will be passed to the Next Statements Value of Y is read & saved Saved Y is copied to X Time = 0 Time = 10 Time = 15 To the Next Statement

Verilog-HDL : Behavioral Modeling RHS eval time 0 50 80 90 Answer (1) initial begin #0 a = 0; b = 0; c = 0; d = 0; a = #35 x; #15 b = x; #10 c = # 20 x; d = #10 x; end Ensures the x value is initialized at time = 0 The value of x at time = 0 is saved in temporal storage and will be assigned to a at time = 35 15 time units after the nonblocking assignment of a = x is completed (at time 50 = 35+15), b = x is executed After 10 time units (At time = 60) value of x is saved and the value is transferred to c executed after 20 time units 35 80 90

Verilog-HDL : Behavioral Modeling RHS eval time 5 15 25 25 Answer (2) initial begin #5 A = 0; B <= 0; C = 0; D = 0; A <= #10 x; #10 B <= x; #10 C <= #20 x; D <= #10 x; end The value of x at time = 5 is saved in temporal storage and transferred to A after 10 time units The value of x at time = 15+10 is saved and is transferred to C after 20 time units The value of x (7) is read non blocking 문장이나오면더복잡. time =5 에서 A 가 update 되기전에다음문장 (#10 B <= x) 로제어가넘어간다. (A 의 update 는 time=15 에서이루어진다.) time = 15 에서 x 의값이읽히고스케쥴된다. time =25 에서 x 의값이읽히고스케쥴된다. 이값이전달되는것은 time=45 이다.. 5 15 25 35 45

Verilog-HDL : Behavioral Modeling Event-Based Timing Control An Event is a change in the value on register or a net Event can be used to trigger execution of a statement or a block of statements 4 types of event-based timing control regular event control (@) named event control (-> and @) event OR control (or) level-sensitive timing control (wait)

Verilog-HDL : Behavioral Modeling Regular Event Control Use @ symbol to specify event control The keyword posedge and negedge are used to specify transition on the signal value (edge-sensitive) @(clock) q = d; // whenever clock changes value @(posedge clock) q = d; // whenever clock does a positive transition // (0 to 1, x, or z, x to 1, z to 1) @(negedge clock) q = d; // whenever clock does a negative transition // (1 to 0, x, or z, x to 0, z to 0) q = @(posedge clock) d ; // d is evaluated immediately // and assigned to q at the next positive edge of clock signal

Verilog-HDL : Behavioral Modeling Named Event Control In Verilog We can Declare an Event and then Trigger and Recognize the Occurrence of the Event An Event is triggered by the symbol -> The triggering of an event is recognized by the symbol @ event received_data; // declare event variable always @(posedge clock) if(last_data_packet) -> received_data; //trigger event always @(received_data) data_buf = {data_pkt[0], data_pkt[1], data_pkt[2]};

Verilog-HDL : Behavioral Modeling Event OR Control A Transition on Any One of Multiple Signals or Events can Trigger the Execution of Statements The keyword OR is used to specify multiple triggers always @(reset or clock or d) begin if(reset) q = 1 b0; else if (clock) q = d; end

Verilog-HDL : Behavioral Modeling Level-Sensitive Timing Control - 1 Verilog has The ability to wait for a certain condition to be true (Note that @ provide the edge-sensitive control) The keyword wait is used for level-sensitive constructs always wait (count_enable) #20 count = count + 1; // count_enable is monitored continuously. // If count_enable = 1, the statement count = count + 1 is // executed after 20 time units // Note that if count_enable stays at 1, // count will be incremented every 20 time units

Verilog-HDL : Behavioral Modeling Level-Sensitive Timing Control - 2 module wait_tst ; reg enable; integer cnt = 0; initial begin cnt = 0; enable = 0; #5 enable = 1; #35 enable = 0; #10 enable = 1; #15 enable = 0; #20 $stop; end always wait(enable) #10 cnt = cnt + 1; endmodule

Verilog-HDL : Behavioral Modeling Conditional Statements : if Types : if(<expr>) true_statement; // type 1 if(<expr>) true_statement else false_statement // Type 2 if(<expr1>) true_statement1 ; // Type 3 else if(<expr2>) true_statement2; else if(<expr3>) true_statement3; else default_statement; If <Expression> result is zero, the true_statement is executed Each true_statement and default_statement can be a group of statements enclosed by keywords begin and end

Verilog-HDL : Behavioral Modeling Multiway Branching : case Case Statement Syntax case (<expr>) altrenative1 : statement1; alternative2 : statement2; default : default_statement ; // optional endcase The <expr> is compared to alternatives in the order they are listed (Priority). If none of values are matched, default_statement is executed A block of multiple statements must be a grouped by keywords begin and end Case statements can be nested If <expr> and alternatives are not equal width, they are filled with 0s to match the width of the widest of the them

Verilog-HDL : Behavioral Modeling Multiway Branch : casex, casez If expr contains x and z value, default is matched Csaex and casez allows comparison of only non-x and/or non-z position in the case <expr> and the alternatives Casez treats all z values in <expr> or alternatives as don t cares Casex treats all x and z values in <expr> or alternatives as don t cares reg [3:0] encoding; integer state; casex (encoding) 4 b1xxx : next_state = 3; 4 bx1xx : next_state = 2; 4 bxx1x : next_state = 1; 4 bxxx1 : next_state = 0; default : next_state = 5; endcase encoding = 4 b10xz matches 4 b1xxx resulting in next_state = 3 encoding = 4 b00x0 matches 4 bxx1x resulting in next_state = 1 encoding = 4 b0110 matches 4 bx1xx resulting in next_state = 2; encoding = 4 bxxxx matches 4 b1xxx resulting in next_state = 3;

Verilog-HDL : Behavioral Modeling Example: casex vs case module case_test ; reg [3:0] encode; integer ns, ns2; initial begin encode = 0; #10 encode = 4'bxxxx; #10 encode = 4'b10xz; #10 encode = 4'bx11x; #10 encode = 4'b1111; #10 encode = 4'b0001; #10 encode = 4'b0xx0; #10 $stop; end always @(encode) begin casex (encode) 4'b1xxx : ns = 3; 4'bx1xx : ns = 2; 4'bxx1x : ns = 1; 4'bxxx1 : ns = 0; default : ns = 5; endcase case (encode) 4'b1xxx : ns2 = 3; 4'bx1xx : ns2 = 2; 4'bxx1x : ns2 = 1; 4'bxxx1 : ns2 = 0; default : ns2 = 5; endcase end endmodule 10 20 30 40 50 60

Verilog-HDL : Behavioral Modeling Loops while (<expr>) statements for (initial condition ; check for terminal condition ; procedural assignment to control variable) statements repeat (a fixed iteration number) statements forever statements initial cnt = 0; while (cnt < 128) begin $display( Count=%d, cnt); cnt = cnt + 1; end end initial begin clock = 1 b0; forever #10 clock = ~clock; end initial for (cnt =0; cnt < 128; cnt = cnt + 1) $display( Count=%d, cnt); parameter cycle = 8; reg [15:0] buff [0:7]; always @(posedge clock) begin if(data_start) begin repeat (cycle) begin @(posedge clock) buff[i] = data; i = i + 1; end end end

Verilog-HDL Agenda Basics Modules & Ports Verilog Simulation Gate Level Modeling Dataflow Modeling Behavioral Modeling Application to Synchronous Logic Latches Flip-Flops & Registers Shift Registers Counters BCD Counters & Cascading Counters FSM Design Parameterized Design More on Blocks Tasks & Functions Logic Synthesis

Verilog-HDL : Application to Synchronous Logic Level Sensitive Latch module latch (Q, en, D); output Q; reg Q; input en, D; always @(en or D) if (en) Q <= D; endmodule D en Q

Verilog-HDL : Application to Synchronous Logic D Flip-Flops - 1 // FlipFlop with asynchronous reset module DFF (Q, QBAR, D, clk, rstn); output Q, QBAR; input D, clk, rstn; reg Q; always @(posedge clk or negedge rstn) if (!rstn) Q <= 1 b0; else Q <= D; clk D Q QBAR rstn assign QBAR = ~ Q ; endmodule

Verilog-HDL : Application to Synchronous Logic D Flip-Flops - 2 // DFF with synchronous reset and enable module DFF2 (Q,QBAR, D, en, clk, rstn); output Q, QBAR; input D, en, clk, rstn; reg Q; always @(posedge clk ) if (!rstn) Q <= 1 b0; else if (en) Q <= D; clk D en Q QBAR rstn assign QBAR = ~ Q ; endmodule

Verilog-HDL : Application to Synchronous Logic Data Registers // 8-bit register with synchronous load and reset module REG (Q, D, ld, rtn, clk); output [7:0] Q; input [7:0] D; input ld, rstn,clk; reg [7:0] Q; D ld 8 Q 8 always @(posedge clk ) if (!rstn) Q <= 8 d0; else if (ld) Q <= D; rstn clk endmodule

Shift Registers (PISO type) // Shift register with asynchronous reset and synchronous load, shift module shiftreg (sout, shiftr, D, Sin, load, clk, rstn); output sout; input [7:0] D ; input shiftr, Sin, load, clk, rstn; reg [7:0] Q; // temporal register always @(posedge clk or negedge rstn) if (!rstn) Q <= 8 b0; else if (load) Q <= D; // parallel in else if (shiftr) Q <= {Sin, Q[6:0]}; assign sout = Q[0]; // serial out endmodule Verilog-HDL : Application to Synchronous Logic

Verilog-HDL : Application to Synchronous Logic 4-bit Binary Counter module cnt4 (Q, D, ld, inc, rstn, clk); output [3:0] Q; input [3:0] D; input ld, inc, rstn, clk; reg [3:0] Q; always @(posedge clk or negedge rstn) if (!rstn) Q <= 4'd0; else if (ld) Q <= D; else if (inc) Q <= Q + 1; D[3:0] ld Inc clk rstn cnt4 Q[3:0] endmodule

Verilog-HDL : Application to Synchronous Logic BCD Counter module BCDcnt (Q, inc, rstn, clk); output [3:0] Q ; input inc, rstn, clk; reg [3:0] Q; always @(posedge clk or negedge rstn) if (!rstn) Q <= 4'd0; else if (inc) if(q == 4'd9) Q <= 4'd0; else Q <= Q + 1; endmodule inc clk rstn BCDcnt Q[3:0]

Verilog-HDL : Application to Synchronous Logic Cascadable BCD Counter module BCDcnt_cas (Q, TC, inc, rstn, clk); output [3:0] Q; output TC; // indicate terminal count input inc, rstn, clk; reg [3:0] Q; wire finl; // Q reached terminal value always @(posedge clk) if (!rstn) Q <= 4'd0; // synchronous reset else if (inc) if (fin) Q <= 4'd0; else Q <= Q + 1; assign fin = (Q == 4 d9)?1:0; assign TC = fin & inc ; endmodule inc clk rstn BCDcnt _cas Q[3:0] TC

module BCD_3digit (Q0,Q1,Q2, TC, inc, rstn, clk); output [3:0] Q0,Q1,Q2 ; output TC; input inc, rstn, clk; wire tc1, tc2; BCDcnt_cas CNT0(Q0, tc1, inc, rstn, clk); BCDcnt_cas CNT1(Q1, tc2, tc1, rstn, clk); BCDcnt_cas CNT2(Q2, TC, tc2, rstn, clk); endmodule Verilog-HDL : Application to Synchronous Logic Cascading 3-digit BCD Counters Inc clk rstn Q0 Q1 BCDcnt BCDcnt inc _cas tc1 _cas tc2 clk BCD_3digit Q0[3:0] Q1[3:0] Q2[3:0] TC Glitch(fin & inc)

Verilog-HDL : Application to Synchronous Logic Cascading 3-digit BCD Counters - 동작 TC = fin & inc Has No Effect on CNT1 Has Effect on CNT1

module BCDcnt (Q,TC, inc, rstn, clk); parameter Delay = 1; output [3:0] Q ; output TC; input inc, rstn, clk; reg [3:0] Q; wire fin; always @(posedge clk) if(!rstn) Q <= #Delay 4'd0; else if (inc) begin if(fin) Q <= #Delay 4'd0; else Q <= #Delay Q + 1; end assign #Delay fin = (Q == 4'd9)? 1 : 0 ; assign #Delay TC = fin & inc ; endmodule The glitch of TC signal has no Effect Clearly Verilog-HDL : Application to Synchronous Logic Cascading 3-digit BCD Counters Gate Delay 를고려한경우 Explicit Delay Specification Clarifies the Precedence between signals (Delay helps to figure out which one precedes the other) It Makes Clear if a glitch is harmless or not (effective) Note : Signal Dependency is clk -> Q -> fin -> TC

Verilog-HDL : Application to Synchronous Logic Exercises (1) 1. Design a Dice (mod-6 counter) that counts from 1 to 6. 2. Cascade the two Dice designed above Question. If one dice rolls 6 times the next dice increments by one. roll (inc) Dice1 roll2 (inc2) Dice2 clk rst

Verilog-HDL : Application to Synchronous Logic Exercises (2) 3. Design a clock circuit which has 2 digit for second and 2 digits for minute. Design the logic in a synchronous fashion (NOT Asynchronous manner). Assume that the input clock is 25MHz. sec0 sec1 min0 min1 1 inc mod10 inc mod10 inc mod10 inc mod6 rst clk

Verilog-HDL : FSM Design FSM (Finite State Machine) 설계 Moore output = f(current_state) Mealy output = f(current_state, input) input Compute Next state Next state State register Compute output output Current state input Compute Next state Next state State register Compute output output Current state

Verilog-HDL : FSM Design FSM Coding with Verilog State Register with Asynchronous Reset always @(posedge clk or posedge rst) begin if (rst == 1) current_state <= `INIT_STATE; else current_state <= next_state; end Combinational Logic Computing Next State always @(current_state or inputs) case (current_state) `INIT_SATE : if (inputs == 1 ) ns = `WAIT_STATE ; else ns = `INIT_STATE; `WAIT_STATE : `RUN_STATE: default : ns <= `INIT_STATE endcase

Verilog-HDL : FSM Design Synchronous FSM State Register의두가지형태 Synchronous Reset logic in next_state computation circuit always @(posedge clk ) current_state <= next_state; always @(current_state or inputs or reset) begin if(reset == 1) next_state <= `INIT_STATE; else case (current_state) `INIT_STATE : if(inputs == 1) next_state = `WAIT_SATE; else next_state = `INIT_STATE; `WAIT_STATE : `RUN_STATE : endcase end Synchronous Reset in the State Register always @(posedge clk) if(reset == 1) current_state <= `INIT_STATE; else current_state <= next_state;

Verilog-HDL : FSM Design 예제 : Traffic Light Controller X=0 S0 S3 x farmway highway x X=1 S1 X=0 S2 X=1 clk rst X Traffic_light controller X : sensor that indicates if there is a traffic in the farmway Output Table (Moore type) highway farmway S0 Green Red S1 Yellow Red S2 Red Green S3 Red Yellow hwy fwy

Verilog-HDL : FSM Design 예제 : Traffic Light Controller Verilog Code // traffic light definition `define YELLOW 2 d0 `define RED 2 d1 `define GREEN 2 d2 // state assignment definition `define S0 2 b00 `define S1 2 b01 `define S2 2 b10 `define S3 2 b11 module sig_controller (hwy,fwy, X, clk,rst) ; output [1:0] hwy, fwy; reg [1:0] hwy, fwy ; input X, clk, rst ; reg [1:0] cs, ns ; // state variable State Reg Next state FSM Output always @(posedge clk or posedge rst) if (rst) cs <= `S0; else cs <= ns; always @(cs or x) case cs `S0 : if(x) ns <= `S1; else ns <= `S0; `S1 : ns <= `S2; `S2 : if(x) ns <= `S2; else ns <= `S3; `S3 : ns <= `S0; endcase always @(cs) case cs `S0 : hwy = `GREEN; fwy = `RED; `S1 : hwy = `YELLOW; fwy = `RED; `S2 : hwy = `RED; fwy = `GREEN; `S3 : hwy = `RED; fwy = `YELLOW; endcase endmodule

Verilog-HDL : FSM Design 예제 : TLC Verilog Code (Synchronous Version) FSM Output module sig_controller (hwy, fwy, X, clk, rst) ; output [1:0] hwy, fwy; reg [1:0] hwy, fwy ; input X, clk, rst ; reg [1:0] cs, ns ; // state variable always @(cs) case cs `S0 : hwy = `GREEN; fwy = `RED; `S1 : hwy = `YELLOW; fwy = `RED; `S2 : hwy = `RED; fwy = `GREEN; `S3 : hwy = `RED; fwy = `YELLOW; endcase State Reg Next state always @(posedge clk or posedge rst) cs <= ns; always @(cs or x or rst) if(rst) ns <= `S0; else case cs `S0 : if(x) ns <= `S1; else ns <= `S0; `S1 : ns <= `S2; `S2 : if(x) ns <= `S2; else ns <= `S3; `S3 : ns <= `S0; endcase endmodule

Verilog-HDL : FSM Design 예제 : Traffic Light Controller - Testbench module testbench; reg clk = 0; reg rst,x ; wire [1:0] hwy, fwy; module sig_controller (hwy, fwy, X, clk, rst) ; initial forever #5 clk = ~ clk; // or always # clk = ~ clk; initial begin rst = 1; #10 rst = 0; X = 1; #40 X = 0; #20 X = 1; #10 rst = 1; #10 rst = 0; #20 $stop; end endmodule

Verilog-HDL : FSM Design Exercises (1) 1. Design a Dice Game Machine. The game is played with 2 dices. The controller inputs are X, clock, and reset. The outputs are Win, Lose, Dice0[2:0], and Dice1[1:0]. The Flowchart for the game is as follows. Roll two dices Point <= sum Sum = 7 or 11 Yes Roll two dices No Sum = 6 Yes lose No win Sum = 7 or 6 Sum = Point Yes win No Yes lose

Verilog-HDL : FSM Design Hints for the Answer (1) clk reset roll The Top Level Submodules Dice game win lose roll Sync hroni zer clock datapath eq D 6 D 7 D 11 ld inc controller win lose reset roll

Verilog-HDL : FSM Design Hints for the Answer (2) inc1 The Datapath and Control Signals inc2 Dice0 Dice1 D7 D11 D6 eq roll Game controller loadp Inc1 win lose 3 bit Adder comparator eq D7 D11 D6 Decoder Point Reg Dice Game Datapath loadp clk

Verilog-HDL : FSM Design Hints for the Answer (3) reset The Game Controller S2/win reset roll (D 7 +D 11 ) roll S0 S1 roll roll/inc roll D 7 D 11 D 6 /ld S0 is an initial state This FSM has Synchronous Reset roll D 6 reset S3/lose reset S4 roll roll eq roll S5 roll Eq D 7 D 6 roll rq (D 7 +D 6 ) roll/inc

Verilog-HDL : FSM Design Hints for the Answer (4) Synchronizer Design Sometimes Asynchronous Inputs are unavoidable (e.g. User Inputs: roll) Asynchronous Inputs : Signals from different Clock Domain Synchronizer Objectives : Synchronization & DeBouncing Clock domain B Clock domain A Asynchronous Inputs X A Y System core logic Clock B Clock A X A Y Clock A

Verilog-HDL : FSM Design Exercises (2) 2. Implement the previous design targeting at XC2S100 Xilinx FPGA. And Verify using the FPGA prototyping board. The Pin locations for the board are as follows : roll (P180) reset (P62) win (P18) Lose (P21) OSC (25MHz): P80

Verilog-HDL : FSM Design Exercises (3) 3. Design a 4 * 4 key pad input module in a dynamic fashion. VCC 0 1 2 3 4 5 6 7 입력스위치 (SW21~SW36) 버튼번호핀번호비고 8 9 A B Row0 P191 첫번째행 C D E F Row1 P192 두번째행 0 1 2 3 2:4 decoder Row2 Row3 Col_sel0 P193 P194 P195 세번째행네번째행디코더 bit 0 Col_sel1 P199 디코더 bit 1 col_sel(1) col_sel(0) row(0) row(1) row(2) row(3) Data(3:0) new_key pressed

Verilog-HDL 목차 Basics Modules & Ports Verilog Simulation Gate Level Modeling Dataflow Modeling Behavioral Modeling Application to Synchronous Logic FSM Design Parameterized Design Parameter Value Change by defparam Parameter value change at Module instance Conditional Compilation More on Blocks Tasks & Functions Logic Synthesis

Verilog-HDL : Parameterized Design Parameter Value Change Parameters are defined in a module with predefined value Parameter values can be overridden in any module instance during compilation time by 2 way defparam statement module instance parameter value assignment

Verilog-HDL : Parameterized Design defparam In defparam statements use hierarchical name of module instance to override the parameter values module hello_world ;; parameter id_num= 0; 0; initial $display ( Hello_world id id num num = %d, %d, id_num) ;; endmodule module top top ;; defparam w1.id_num = 1, 1, w2.id_num = 2; 2; Hello_world w1 w1 (); (); Hello_world w2 w2 (); (); endmodule Hello_world id num = 1 Hello_world id num = 2

Verilog-HDL : Parameterized Design Module Instance Parameter Values New parameter values are passed during module instantiation module hello_world ; parameter id_num= 0; initial $display ( Hello_world id num = %d, id_num) ; endmodule module top ; Hello_world #(1) w1 (); Hello_world #(2) w2 (); endmodule Multiple parameters can be override by specifying new values in the same order as the parameter declarations the in module module bus_master ; parameter delay1 = 2; Parameter delay2 = 3 ; endmodule Module top; bus_master #(4, 5) b1 (); bus_master #(9) b2 ; // delay2=3

Verilog-HDL : Parameterized Design Compiler Directives: Conditional Compilation `ifdef `else `endif A portion of Verilog might be suitable for one environments and not for other. `ifdef TEST module test ; endmodule; `else module stimulus ; endmodule `endif

Verilog-HDL : Parameterized Design Compiler Directives: Conditional Execution All statements are compiled but executed conditionally Use System task $test$pulsargs to check if a flag is set during the run-time (in Verilog-XL simulator) module test ; initial begin if($test$pulsargs( DISPLAY_VAR )) $display ( Display = %b, {a,b,c}); else $display( No Display ); end endmodule

Verilog-HDL Agenda Basics Modules & Ports Verilog Simulation Gate Level Modeling Dataflow Modeling Behavioral Modeling Application to Synchronous Logic FSM Design Parameterized Design More on Blocks Parallel blocks Named blocks Nested blocks Tasks & Functions Logic Synthesis

Verilog-HDL : More on Blocks Block Types Block is used to group multiple statements Begin end Fork join Sequential blocks Keywords begin and end are used Statements in a block execute in the order listed one after another. delay or event control is relative to the time when the previous statement completed its execution Parallel blocks Keywords fork and join are used Ordering of statements is controlled by delay or event control Delay or Event control is relative to the time the block was entered

Verilog-HDL : More on Blocks Parallel Block: Fork and Join Parallel Block is Surrounded by fork and join All Statements in a Parallel Block Starts at the Same Time when the Block was Entered. => The order of Statements in the Block is Not Important. reg x, y; reg [1:0] z, w; initial fork x = 0; #5 y = 1; #10 z = {x, y}; #20 w = {y,x}; join #5 y=1 fork #10 z={x,y} join #20 w={y,x} Race Condition reg x, y; reg [1:0] z, w; initial fork x = 0; y = 1; z = {x, y}; w = {y,x}; join z = 01 or xx w = 10 or xx