Ss Limay Vhdl Book

132
Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048 Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman , This manual specially created for EFY & IT Magazine CD DIGITAL DESIGN WITH VHDL Dr. S. S. Limaye Professor of Electronics, RKN Engg College CMR Design Automation P. Ltd. [email protected] [email protected]

Transcript of Ss Limay Vhdl Book

Page 1: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

DIGITAL DESIGN WITH

VHDLDr. S. S. Limaye

Professor of Electronics,RKN Engg College

CMR Design Automation P. Ltd.

[email protected]@cmr-da.com

Page 2: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

About the author

Dr. S. S. Limaye passed B.E. (Electrical Engineering) exam with a goldmedal From Visvesvaraya Regional College of engineering, Nagpur in 1971. He passedM. Tech. (Electrical Engineering) from Indian Institute of Technology, Kanpur in 1973with a specialization in electronics. He started his career as an assistant design engineerin the R&D department of DCM Data products, New Delhi. Initially he worked on a TTLMSI based minicomputer named Galaxy 11. Later, he worked on several microprocessorbased designs. In 1978 he was made Manufacturing Support Services Manager. Here, hedesigned various test jigs and diagnostic software for computer manufacturing. He laterworked as a Works manager at Eiko Computers Bangalore, Development manager(Process control) at PSI data systems at Bangalore and Vice President (Technical) atCherry Computronics, Srinagar.

He joined Shri Ramdevbaba Kamla Nehru Engineering college, Nagpur in 1989as an Assistant Professor. In 1997, he was awarded a Ph.D. degree by the NagpurUniversity and subsequently he was promoted as a Professor. He has published severalpapers in national and international journals. He has guided several VHDL based projectsat the undergraduate level and conducted VHDL training programs in collaboration withM/S CMR design automation P. Ltd.

Page 3: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

FOREWORD

This book is the result of a series of training courses we conducted for electronicsdesign professionals. Interaction with customers in Microelectronics Design for over aDecade has given a clear idea about the typical design projects undertaken in India. Wesaw that HDL based design methodology was fast gaining ground there was a great needfor training working design engineers who may not have had a chance to learn this designmethodology while at College.

We at CMR formulated a four days intensive training package in collaborationwith academicians. This program was immensely popular. In a span of 1 year, we endedup training nearly 120 professionals from 30 different organizations. We went onupgrading the contents of the package based on the feedback received from each trainingbatch.

Now we are enlarging the contents and making them available in a book form sothat it will also be useful to the students undergoing a VLSI design course and to theprofessionals who can do self-study. To facilitate hands on experience, we have basedour practical exercises based on VIEWLOGIC software suit.

I hope that this book will be well received by the readers.

Mahesh ChandraDirector, CMR Design Automation P. Ltd. New Delhi

Page 4: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

PREFACE

VHDL (VHSIC Hardware Description Language) is a relatively new language.VHDL is mainly used for simulation, synthesis and testing of digital circuits. VHDL userbase has been sky rocketing in the recent years. Although many books have appeared onthe subject, I feel that the readers’ bookshelves have space for another book written witha different perspective. We have given equal emphasis on digital design and VHDL. Thusit is not just a dull language reference manual but a lively text which introduces thelanguage in a step by step way, provides many tips and tricks, gives plenty of examplesand also gives review questions to reinforce your learning. Care has been taken to ensurea smooth transition from popular undergraduate textbooks on digital design to VHDL.Practical exercises based on Viewlogic software suit have also been given. I hope thatuniversity students as well as professionals will like this book.

I started my career as a digital hardware designer in 1973 at DCM Data products,New Delhi. I was part of the design team that designed a 16-bit minicomputer calledGALAXY 11. It was a proprietary design that inherited many useful features fromHP21MX and PDP 11, which were popular those days. It was built from scratch using74XX series TTL SSI and MSI parts. Then in 80’s we witnessed a wave ofmicroprocessor based designs in which the role of hardware design engineer underwent aradical change. The digital design was divided into two distinct areas. The first area wasdesign of chips and the second was design of equipment and systems. With theincreasingly sophisticated fabrication technology the chip designers included more andmore functionality in the chips. The system designer selected a collection of LSI chipssuitable for his application bound them together through glue logic made from TTL MSIIC’s. The glue logic mostly consisted of chip select decoders and tristate bus drivers. Asfar as general-purpose computers are concerned, the world was swamped with IBM PCwave. For the sake of compatibility, the clone makers made the chip addresses and busarchitecture identical to the IBM PC and therefore, the glue logic was also standardized.This led to a flourishing industry of glue logic designers and manufacturers. The standardglue chips were built from Programmable Gate Arrays. Electronics system designers’services were required mainly for the design of special purpose dedicated computers andrandom interface logic.

The use of standard chips for a given application was not always optimal. If a chipcould be designed starting from scratch, then the resulting design would be most optimal.Such chips were called Application Specific IC’s or ASIC’s. However, the costeconomics those days did not permit a custom chip design unless the production volume

Page 5: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

was very large. Custom design for medium volume was done with the help ofProgrammable Gate Arrays and the design for small volume was done with the help ofField Programmable Gate Arrays (FPGA’s). Today, with the help of sophisticatedComputer aided design tools, the set up costs have dramatically reduced and the ASICoption is cheaper for a production volume as low as 1000 pieces. PGA’s and FPGA’s areeconomical at even lower volumes. Apart from cost reduction, custom chips offer otheradvantages such as less time to market, more reliability and compactness. There is nodoubt that shortly ASIC design will be as common as a PCB design.

Thus the digital design philosophy has done a full circle and come back to thestate of 70’s. We are back to the drawing board with diagrams of gates, registers anddecoders. There is one significant difference however, that the complexity of the circuitsthat we design today is 10 to 50 times higher. This necessitates a total change in thedesign methodology. Earlier, we followed a schematic based methodology in which wedesigned smaller blocks by interconnecting available chips and then compounded theseblocks to realize the full system. This is known as the bottom up approach to the design.Pundits agree that this approach is suitable when the complexity of the system is upto10000 basic gates. Beyond this, we must switch over to a hardware description languagewith a top down approach. Imagine that you are designing a chip as big as a Pentium with2 million transistors. It is meaningless to draw its schematics. In such cases it is moreconvenient to describe the design functionality at a higher level and leave the task ofconverting it to silicon to an automaton. This is where hardware description languagescome into picture.

Organization of the book.

The learning curve of VHDL is quite steep. Some people describe VHDL as aVery Hard Description Language. But it is possible to start with a small subset of thelanguage and then gradually enlarge the scope of learning. Therefore, although thepreferred design methodology is top down, the preferred sequence of learning in myopinion is bottom up. This is the sequence followed in this book.

In chapter 1, an overview of design methodology and the language is presented.In chapter 2, the language fundamentals i.e. data types, assignment statements andoperators are described. Then in chapter 3, we come to the design of simple entities at thedata flow level. Once a set of primary entities is built, in chapter 4 we build compositecomponents at the structural level. In chapter 5, we design bigger components at thebehavioral level. Design of test benches is also covered here. In chapter 6, some designexamples are given.

Page 6: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

The exercises at the end of each chapter will stimulate your thinking and reinforceyour learning. The suggested lab experiments will give you hands on training. Thecompanion CD that comes with this book contains the source code for the examples andalso a large number of design projects collected from the field. You could use theseexamples as templates for starting a similar project.

In the end, I hope that this book will be useful for university students undergoinga VLSI design course and also to practicing design professionals for self-study.

Dr.S.S.Limaye.Professor of electronics,

Ramdevbaba Kamla Nehru Engg. CollegeNagpur

Page 7: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

CONTENTS

Chap Title Page No1 Introduction 1

1.1 History1.2 Design Methodology1.3 Hardware modeling issues1.4 Overview of VHDL

2 Language fundamentals2.1 Data types2.2 Assignment statements and Operators2.3 Objects2.4 Attributes of objects2.5 Simple logic examples2.6 Practical session on simulator

3 DATAFLOW style of description3.1 Conditional concurrent assignment3.2 Selected concurrent assignment3.3 Block statement3.4 If and Wait statements3.5 Examples of simple sequential circuits3.6 Finite State Machines3.7 Designing for synthesizability3.8 Practical session on FPGA express

4 STRUCTURAL style of description4.1 Component declaration and instantiation4.2 Configuration statement4.3 Configuration declaration4.4 Generate statement4.5 Generic statement4.6 Package statement4.7 Examples of structural style4.8 Practical session with ACTEL backend tool

5 BEHAVIORAL style of description5.1 Case statement5.2 Loop and exit statements5.3 Null statement5.4 Assert and Report statements5.5 Functions5.6 Procedures5.7 File I/O operations5.8 Test Benches

6 Design examples6.1 Digital Filters6.2 Simple CPU

Page 8: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

CHAPTER 1

INTRODUCTION

1.1 HISTORY

VHDL (VHSIC Hardware Description Language) is a language for describinghardware. Its requirement emerged during the VHSIC development program of the USDepartment of Defense. The department organized a work shop in 1981 to lay down thespecifications of a language which could describe hardware at various levels ofabstractions, could generate test signals and record responses, and could act as a mediumof information exchange between the chip foundries and the CAD tool operators.However, due to military restrictions, it remained classified till 1985. There was a largeparticipation of the private sector electronics industry in the development of the language.It felt that there was a need to make the language industry standard. In 1985, the DODgranted a permission to hand over the specs to IEEE. Subsequently IEEE released theIEEE 1076/A standard in 1987. It was later revised in 1993. The 1993 revisions areminor and many of the simulation and synthesis tools have not yet adopted them.

Being a DOD project, it is no surprise that the syntax of VHDL is very similarto ADA. It is an object-oriented language and therefore people familiar with C++ orPASCAL can grasp it easily. The same language is used for both analysis and synthesis.However there are some constructs in the language, which can only be simulated but notsynthesized. At the moment, what can be synthesized is vague and very much tooldependant. To solve this difficulty, IEEE is working on a synthesizable subset of VHDL,which will be supported by all synthesis vendors.

1.2 Design Methodology

A hardware circuit can be described in two ways.1 Structural description: - In this method, the circuit is described as an

interconnection of known components.2 Behavioral description: - In this method, the behavior of the circuit is described by

means of Boolean equations and a set of sequentialinstructions.

Page 9: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

When a designer is handed over the specifications of a new product, he can start thedesign using one of the following approaches.

TOP DOWN.

In this approach, first the top-level behavior is designed and then it is partitioned it intosmaller subsystems and then sub subsystems till it is reduced to simple components.Behavioral description is suitable here. It has been observed that this approach is suitablefor large designs, typically involving more than 10000 basic gates. Many FPGA baseddesigns follow this approach.

BOTTOM UP.

This is the traditional schematic based approach. It is used when a library of known lowlevel components such as 74XX TTL is available. You build medium subsystems fromthem and then finally interconnect them to realize the overall system. This approach issuitable for small systems using standard components.MIXED.

This approach is similar to the top down approach in sense that you start from top level.But here you don’t go right up to the component level. You can stop when you can findsuitable medium level entities for realizing the design. A library of medium levelcomponents is prepared for this purpose, using the bottom up approach. This approach issuitable for ASIC design where vendor supplied cell libraries are available.

Design process: -

Digital system design starts from the user specifications. The specifications definethe terminal behavior of the proposed system and provide a natural language descriptionof how the input signals are transformed into outputs. Translation from this stage tosilicon is a giant step. To make it manageable, it has to be broken down into severalsmaller steps as shown in Figure 1.1. A translation from a higher level of abstraction to alower level is SYNTHESIS and a study of the behavior of a lower level model in terms ofthe higher level description is ANALYSIS.

BEHAVIOURIAL DESCRIPTION (VHDL)

REG. TRANSFER DESCRIPTION (VHDL)

GATE LEVEL NET LIST (FPGA EXPRESS,AMBIT)

MOREABSTRACTLEVEL

ANALYSIS SYNTHESIS

Page 10: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Fig 1.1A typical design process

First, we need to design the system architecture, identify major blocks and definetheir interface signals. This is a job, which requires the creative abilities of the righthemisphere of the human brain. We can’t expect any computer support at this stage apartfrom some drawing tools. Having done this, the circuit behavior can be transcribed into amachine-readable form using the behavioral description style of VHDL. At this stage, theemphasis is on obtaining the terminal behavior without bothering about how the circuitwill be realized. This description serves as a test environment for part by part testing ofindividual subsystem realizations at lower levels of abstractions.

Then each subsystem is rewritten in Register Transfer Level (RTL) form. In thisform, the system is described as a set of registers and ALU’s interconnected by set ofdata buses. The selection of registers on data buses, function selection of ALU andstorage of bus contents into selected registers is done in a sequential manner using thecontrol signals generated by a control unit. Today’s synthesis tools can understandVHDL code written in RTL style.

From this point onwards, it is only the mechanical work of optimization andmapping. If done manually, it is done with the left hemisphere of the brain. This is thearea that is most suitable for computerization. The synthesis tool translates the RTLdescription to a structural description using the components available in the target

Page 11: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

system. In case of CPLD’s, these devices are AND-OR arrays, in case of SRAM basedFPGA’s they are configurable logic modules and in case of ASIC’s they are standard celllibraries. The synthesis tool must be aware of the target device’s component repertory.The FPGA express from Viewlogic supports a large family of FPGA’s from popularFPGA vendors. While FPGA express is available on PC’s, the synthesis tools for ASIC’slike ambit are available only on workstations.

Having obtained the structural description, our next job is to physically place thelogic blocks on the target device and interconnect them using the availableinterconnection resources. We also need to assign I/O pads and buffers for the portsignals and assign pin numbers. This job is done with the help of back end softwaretools supplied by the chip manufacturers.

1.3HARDWARE MODELLING ISSUES

Since VHDL describes hardware, it has to address many tricky issues, which are notpresent in the normal languages.a. Concurrency- In an electronic circuit, all components are active simultaneously and

therefore they have to be simulated like a multi-threaded program. Consider thecircuit of fig 1.2 and corresponding VHDL code.

B A D

CE

A<=B or C;D<=A and E;

Fig 1.2Typical circuit

(Note that “<=” is the assignment operator in VHDL. The syntax details are coveredlater.) To simulate the above circuit properly, the order of execution of statements in aVHDL program can not be same as the order in which the statements have been

Page 12: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

typed. All statements in VHDL are considered to be “Concurrent”. I.e. a statement isexecuted whenever any variable in its RHS changes state. In the above example, thesecond statement (D<= A and E;) will execute earlier than the first statement if Echanges earlier than B or C. The list of variables in the RHS of a statement is calledits sensitivity list. Whenever a state change occurs on any of the variables in thesensitivity list, the statement is fired.

b. Sequential blocks: - It is not possible to describe complicated operations in a singlestatement as shown above. To take care of such cases, process, procedure andfunction blocks are used. The statements in these blocks execute in a sequentialmanner like a normal programming language. The process statement can beoptionally assigned a sensitivity list. It then gets triggered whenever any variable inthe process sensitivity list changes. Thus a process as a whole operates concurrentlywith other processes and concurrent statements. Sequential blocks allow the use of if,case and loop statements and therefore it is commonly used at the top-leveldescription.

c. Delays: - In actual hardware, when an input to a gate changes, the output appears aftera delay. The language must have an easy way to describe a delay. VHDL provides delaystatements like

B<=A after 10ns;If the signal A changes state in the current simulation cycle, nothing is doneimmediately. Only a change is scheduled to occur on B after 10 ns. When thesimulation time will advance by 10 ns, the change will take effect.

The delay can be of two types. Transport or inertial. In most practicalsituations, RC low pass circuits cause the delay. These circuits typically introduce aninertial type of delay. An important property of the inertial delay is that, if a narrowpulse (having width less than the delay time) appears at the input of an inertial delayelement, then the pulse is not passed to the output. The transport delay on the otherhand faithfully repeats the input waveform after the specified delay irrespective of thepulse width. It represents delay lines. A delay can be specified to be of transport typeby adding the keyword “transport” after the “<=” operator.

A<= transport B after 5ns; Unless specified, the delay is assumed to be inertial.

d. Delta time: -To maintain the cause and effect relationship between inputs andoutputs, the concept of delta time is introduced. If a delay is not mentioned in anassignment statement, then a delta time delay is assigned to it. Physically, delta timeis zero but logically, it represents a delay of one evaluation cycle. The simulation

Page 13: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

process goes in two phases, namely evaluate and propagate. In the evaluation phase,all inputs those have changed state trigger corresponding statements. But the valuesare not assigned to the target variables of these statements unless the entire evaluationprocess is over. The propagate phase starts after all statements are evaluated,. In thisphase, the changed values are assigned to the LHS variables. Since these variablesmay be appearing on right hand side of some other statements, these assignments mayagain trigger some more statements. This cycle continues till the circuit reaches asteady state and no further triggering occurs. Then the simulation clock is advancedby an amount known as ‘tick’ and signal changes scheduled to occur due to earlierstatements are checked. The tick period should be set to a value that is less than thesmallest delay you want to simulate. However, making the tick value too small makesthe execution very slow. By default, it is set to .1ns.Note that a statement like “A<= not A” will cause the simulator to go into anindefinite evaluation cycle and hang. If the statement is modified as “A<= not A after5 ns;” then the problem is solved.Circular references like “A<=B; B<=C; C<=A;” will also cause the simulator to hang.

e. Back annotation: - The designer cannot predict the gate delays at the design time asthe are dependent on the target technology and routing. The delays mentioned inVHDL programs are for simulation only. The synthesis tool ignores them and acts ononly the logical part of the statement. After realizing the circuit and routing, the backend tool calculates the delays and pastes them back to the higher level for a realisticsimulation. This is called back annotation. IEEE has evolved a standard calledVITAL for this purpose.Note that it is not possible to synthesize a delay line by a statement likeB<=A after 20 ns.For synthesizing delays, one has to instantiate a delay line component on the targetdevice if it exists.

f. Free mix: - To allow flexibility, VHDL allows structural and behavioral styles to befreely mixed.

g. Hierarchical structure: - For managing large projects, it is necessary to split it intoseveral levels of hierarchy. VHDL allows a hierarchical design by making use of librariesand packages.

1.4 Overview of VHDL

Page 14: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

VHDL syntax is very close to that of ADA. The VHDL literature uses terms likeobjects and classes but VHDL is not a fully object oriented language. It incorporatessome features of object oriented languages like C++ or Object Pascal, namely functionswith default parameters, function overloading and operator overloading. The “classes” inVHDL are more like structures of C++ because they are not allowed to have functionmembers. In VHDL, anything that occupies memory is called an “Object”. These objectshave to be derived from some predefined classes. However, for defining classes, thekeyword “TYPE” is used instead of “CLASS”. This is similar to the Object Pascalconvention. “Inheritance”, which is an important OOPS feature, is not supported byVHDL as it complicates synthesis.

There are three types of objects in VHDL, namely variables, constants andsignals. While variables and constants have same meaning as in other languages, signal isa special type of object. Every signal has an associated driver that maintains a history ofits past transactions and a list of future transactions scheduled for it.

The most unusual aspect of VHDL is that the order in which VHDL statementsare typed is immaterial because all statements are evaluated concurrently. It also hasprovision for sequential blocks that can be enclosed in process, procedure or functionbodies. Functions and procedures are “called” by other statements but a process isautomatically triggered when an object in its sensitivity list changes state. VHDL hastotally different sets of statements for the sequential and concurrent parts of theprogram. One of the often-committed mistakes by new designers is to use a sequentialinstruction in a concurrent part and vice versa.

Organization of a VHDL design file

A VHDL program consists of one or more “Design Units”. A Design unit is asmallest compilable piece of code. A statement must be enclosed inside a design unit toget compiled. Isolated statements cannot be compiled. There are 5 types of design unitsnamely entity, architecture, configuration, package declaration and package body. Onecan have a meaningful program with entity and architecture units only. The other unitsare used for additional information.A) Entity

Each component or subsystem that we want to design is identified by its entityname. The entity unit defines the component’s name and its port signals. The syntax ofentity declaration is:Entity ENTITY_NAME is

Port (SIGNAL_NAME: mode DATA_TYPE, …more signals);End ENTITY_NAME;

Page 15: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Where “mode” can be in, out, inout or buffer. The inout mode is used for bi-directionalsignals and buffer mode is used for outputs whose values also sensed inside the entity. Ifa signal is defined as “out” instead of “buffer”, then it can not appear on the RHS of anyassignment statement. Similarly, a signal with “in” mode can not appear as a target of anassignment statement.Physically the inputs and outputs of an entity will be bunches of wires carrying binarydata. However, we can specify composite data types such as bit vectors, records orintegers in the “port” statement. In the final synthesis, they get converted into individualbits. The data types are covered in chapter 2.A typical entity unit looks like this:

Entity ANDGATE isPort (in1, in2: in BIT; output: out BIT);

End ANDGATE;

The entity unit may also define additional objects, generic parameters, functionsand procedures as explained in the later chapters.

The port objects are automatically treated as “signals” and not “variables”.

B) ArchitectureThe architecture unit describes the implementation of the port behavior

declared in the entity unit. In high level behavioral description, it consists ofseveral process statements. In the Data flow description style (Generally used fordescribing basic gates or simple logic blocks), it consists of a set of concurrentstatements. In the structural style, various components i.e. other smaller entities,are instantiated and their interconnections are specified by the port mapstatements.Syntax:

Architecture ARCH_NAME of ENTITY_NAME is<signal, procedure, function and component declaration>Begin

<Concurrent statements><Processes><Component instantiations>

End ARCH_NAME;The component declarations and Component instantiations are used for thestructural modeling style. Of course VHDL allows all modeling styles to bemixed.The architecture for the above entity will look like this.

Page 16: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Architecture DATAFLOW of ANDGATE isBegin

Output<= in1 and in2 after 10 ns;End DATAFLOW;

There can be any number of architecture units for a single entity unit. All thearchitecture names referring to a single entity must be distinct. Usually thearchitecture name denotes its description style. Objects, functions etc. that are definedin the entity unit are passed on to all its architectures.

C) ConfigurationThe component declaration in a structural description only defines a socket wheresome component will be plugged in. If there exits a component by the same name inthe design library, then it is automatically chosen to be plugged in. Otherwise theconfiguration unit is used to specify the entity and the architecture that will be usedfor instantiating the components. The configuration unit is optional. Its job can alsobe done by means of configuration statement inside the architecture as explainedlater.

D) Package declarationThe Package and Package body units are used for declaring a set of useful typedeclarations, functions and procedures. Other programs can easily use the packagecontents with the “use” statement.

E) Package bodyThe package declaration gives only the prototype declarations of the functions. Theimplementation is provided in the Package body.

The entity, configuration and package declarations are called “Primary design units”because they can be compiled independently. Architecture and Package bodies are called“Secondary design units” as they can be compiled only with reference to a primarydesign unit.

Libraries: - A set of utility packages can be put inside a library. Library is basically asubdirectory in the host environment. The present working library is identified by thekeyword “work” in VHDL. A package named STANDARD containing some basicdefinitions is automatically included in every program. The STANDARD packagedefines a data type “BIT” for representing binary numbers. In many situations we need touse multivalued logic to represent don’t care values and tristate buses. In such cases, it isrecommended that one should use a package called std_logic_1164 from the IEEE

Page 17: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

library. For using a library for a design unit, we need to type the “library” and “use”statement before that design unit. The visibility of the use statement is only for the nextdesign unit. Thus if we have 5 design units, then the library and use statements must berepeated before each unit. However, the definitions used by a primary unit areautomatically passed on to its secondary unit. So if we have IEEE library statementbefore an entity unit, we don’t have to repeat it before its architecture unit.Syntax:Library LIBRARY_NAME;Use LIBRARY_NAME. PACKAGE_NAME. <List of definitions>

Example:Library IEEE;Use IEEE.STD_LOGIC_1164.ALL;The key word ALL causes all definitions in the STD_LOGIC_1164 package to be used.The entity name or the function name must be unique within a library. It is possible tohave the same name repeated in different libraries. The compiler searches for the namesin various libraries in a user defined search order. The “work” library is always the firstin the search order. The first match in the search sequence is accepted.

General:All VHDL statements end with a semicolon. New line may be freely introduced to

break long statements. Note that the “entity” statement ends with the “end” statement andtherefore, the semicolon is put after “end”.

The language is not case sensitive. So entity, ENTITY and ENtity have samemeaning. In this book, we have followed the “C” convention of using the small letters forthe key words and capital letters for the user defined identifiers. Some people like to usethe exactly opposite convention.

Indentation should be used to clearly identify various statement blocks. However, it isnot mandatory.

A pair of dashes denotes the beginning of comment. All matter on the line after “- -“is ignored.

Page 18: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

REVIEW QUESTIONS

Q1.1 Fill in the blanksa) Work on VHDL was started by _________in the year ________.b) Latest IEEE standard on VHDL was released in the year _________.c) The syntax of VHDL is similar to that of ______________.d) If the pulse width of a signal is less than the inertial delay, then ______________.e) In the waveform display, delta delay is shown as __________ns.f) The visibility of a library clause is for the next ____________ design unit(s).g) If you want to use tri-state logic, use must use the _______________ package.

Q1.2 Write true or falsea) The order of execution of VHDL statements can not be predicted.b) The time delay parameters are used by the synthesis tool to choose delay lines.c) VHDL is a true Object oriented language.d) Every VHDL statement can be synthesized.e) One entity may have many architectures.f) Every variable in the sensitivity list must change to fire the statement.g) We cannot mix structural and data flow description in the same architecture unit.

Q1.3 Consider the statement: - A<= not A and B;Will it hang the simulator if B is initialized to 0?

Q1.4 Name the 5 types of VHDL design units and indicate which of them are primaryunits.

Q1.5 Suppose you have designed an entity ANDGATE having architecture namedDATAFLOW. Can we design another entity ORGATE and name its architecture asDATAFLOW?

Q1.5 Suppose you have defined a function “PARITY” in your source program and afunction having the same name exists in one of the libraries used by you. Whichversion of the function will be selected?

Page 19: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

CHAPTER 2Language fundamentals

1.1 Data typesInterestingly, core VHDL does not have any built in data types. The basic data types

namely BIT, INTEGER, REAL, CHARACTER, STRING, TIME etc. are declared in apackage called “STANDARD”, which is automatically included with every program. Inaddition to the standard types, the user is free to define an unlimited number of customdata types for meeting his requirement. The VHDL data types are categorized into 4major categories.1. Scalar types.2. Composite types.3. Access types.4. File types.

There are three kinds of objects, which store data, namely signals, variables andconstants. A signal type object maintains a time history of its value changes while avariable type object can store only its current value. A constant can be assigned valueonly at the time of its definition.

Scalar types:Scalar data types consist of a single data element. Objects belonging to scalar data typeshave an ordering relation defined for them. I.e. if A and B are two objects of a scalartype, then a relation like A<B is defined for the entire range of values of A and B.Defining a new type- enumeration:A new data type can be defined by the enumeration method. The syntax of enumeration isas follows.type TYPENAME is (IDENTIFIER LIST);e.g.type FOUR_VALUED_LOGIC is (’X’,’Z’,’0’,’1’);type STATE_TABLE is (RESET,S0,S1,S2,FINAL);

Note that the keyword “type” has been borrowed from object PASCAL. In C++,the keyword “class” is used for this purpose. In VHDL literature, the terms classand type are often used interchangeably. The type declaration statementdescribes only the internal structure of an object. It does not have any physicalexistence. The objects derived from the above classes have a physical existencein the sense that memory is allocated for them. Defining an object of a class iscalled instantiation of the class. The syntax for object instantiation is as follows.<object class name> <identifier>:<data type name> [:=initial value];Examples:Variable A: FOUR_VALUED_LOGIC;Signal PRESENT_STATE, NEXT_STATE: STATE_TABLE;Constant C: STATE_TABLE: = S0;

In the above statements, the colon symbol (:) may be pronounced as “derivedfrom”. In the enumeration identifier list, the value of a symbol increases from left toright. E.g. in the FOUR_VALUED_LOGIC enumeration given above, ‘X’ is the smallest

Page 20: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

element and ‘1’ is the largest element. So, an expression like ‘Z’ < ‘0’ will evaluate toTRUE.

The STANDARD package starts from scratch to define the basic data types using theenumeration method. Some basic declarations are given below..

type BOOLEAN is (FALSE, TRUE);type BIT is ('0', '1');type INTEGER is range -2147483648 to +2147483647;-- 32 bits signedtype REAL is range -0.179769313486231e+309 to +0.179769313486231e+309;type CHARACTER is ( NUL, SOH, STX, ETX, EOT, ENQ, ACK, BEL, BS, HT, LF, VT, FF, CR, SO, SI, DLE, DC1, DC2, DC3, DC4, NAK, SYN, ETB, CAN, EM, SUB, ESC, FSP, GSP, RSP, USP, ' ', '!', '"', '#', '$', '%', '&', ''', '(', ')', '*', '+', ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\', ']', '^', '_', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', DEL);We can define our own versions of numeric types having a different range. E.g.Type RAM_ADDRESS is range 0 to 8191;--custom integerType MY_REAL is range –7.5 to 12.5; --custom realType TTL_VCC is range 4.75 to 5.25; --custom real

Note that the above user defined types are completely new types. Onlynumerical operations are permitted on them. Mixing them with standard integersor any other user defined numerical types is not permitted. Also, the operatorsand functions, which are overloaded for integers or real numbers, are notapplicable to the user defined numeric types. If we want the new type to inherit allthe overloading properties of the base type, then we must declare them assubtypes of integer or real as explained later.

VHDL does not allow mixed mode arithmetic. The type of all objects in anarithmetic operation and the type of the target object must be same. If we want toperform mixed mode arithmetic, then all the operands must be converted to onetype by suitable conversion functions. Various numeric types can be convertedinto each other simply by treating the name of the desired type as a function. E.g.

Signal STD_INT: integer;Signal STD_REAL: real;Signal ADDR: RAM_ADDRESS;Signal X: MY_REAL;

ADDR <= RAM_ADDRESS (STD_INT) + 1;STD_INT <= integer(STD_REAL);STD_INT <= integer(ADDR);

Page 21: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

X <= MY_REAL(5.3)+7.1;

The STANDARD package, which was a part of the original release of theIEEE standard, declares only one data-type for representing binary numbers,namely BIT. Unfortunately, this data type does not adequately represent manypractical situations where we need to consider the strength of the driver,unknown state, don’t care state and high Impedance State. To tackle thisproblem, many tool developers defined their own multi valued logic types, whichmade portability a big problem. To solve these difficulties, IEEE later released theSTD_LOGIC_1164 package, which declares a data type STD_ULOGIC having 9values as follows.

TYPE std_ulogic IS('U', -- Uninitialized 'X', -- Forcing Unknown '0', -- Forcing 0 '1', -- Forcing 1 'Z', -- High Impedance 'W', -- Weak Unknown 'L', -- Weak 0 'H', -- Weak 1 '-' -- Don't care );The std_ulogic is an unresolved type. I.e. it does not include a resolution functionto take care of two outputs driving a single signal. Such functions are required fordescribing tri- state buses and wired-or logic. For this purpose, the packagedeclares a subtype called STD_LOGIC derived from STD_ULOGIC as follows.

SUBTYPE std_logic IS resolved std_ulogic;

The function “resolved” returns a single value for the signal considering the state andstrength of all its drivers. For new designs, it is recommended to use either BIT orstd_logic data types so that portability will not be a problem.Physical type:VHDL allows definition of physical types, i.e. quantities having physical units like time,length, resistance, capacitance etc. The STANDARD package defines one physical typecalled TIME as follows.type TIME is range -9223372036854775807 to +9223372036854775807 units fs; -- femtosecond ps = 1000 fs; -- picosecond ns = 1000 ps; -- nanosecond us = 1000 ns; -- microsecond ms = 1000 us; -- millisecond sec = 1000 ms; -- second min = 60 sec; -- minute hr = 60 min; -- hour end units;

Internally, the physical type is stored as an integer in terms of the baseunit. E.g. a time of 5 ns is equivalent to 5,000,000 fs and so, it is stored as5,000,000. Since it is basically an integer type, it can be multiplied by anotherinteger giving a result in physical units. Similarly, when a physical data-type isdivided by the base unit, the result is an integer. E.g.

Page 22: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Signal IntTime: integer;Signal PhyTime: time:= 5 ns;IntTime <= PhyTime/ 1 fs;-- The value of IntTime will be 5,000,000Subtypes:Subtype is a type with a range constraint. The set of values that a subtype canhave is a subset of the values of the base type. The arithmetic and logicaloperations that are defined for the base type are valid for the subtype alsobecause they inherit all properties of the base type. Subtypes are basically usedfor range checking during simulation.E.g.Subtype SMALL_INT is integer range 0 to 15;Subtype NUM_CHAR is character range ‘0’ to ‘9’;Variable x: SMALL_INT;Variable y: NUM_CHAR;Renaming a standard type: A subtype declaration need not necessarily imposea range constraint. In that case, it just becomes an another name for the basetype like the “typedef” command of “C”. E.g.

Subtype int is integer;Subtype float is real;Variable x: int;Signal y:float;

The STANDARD package declares following subtypes.subtype NATURAL is INTEGER range 0 to INTEGER'HIGH;subtype POSITIVE is INTEGER range 1 to INTEGER'HIGH;INTEGER'HIGH denotes the highest value of the integer type. HIGH is anattribute of the integer data type. Attributes are discussed in detail later.

Numeric literals:Numeric values in an expression are called literals. Underscore characters maybe freely inserted in a number to improve its readability. Following are theexamples of valid integer literals.5 , 55E4, 0, 5_657_554, -70Real literals must have a decimal point in the mantissa and an optional exponent.Following are the examples of valid real literals.16.26, 0.0, 62.3 E –2We can express literals in other number systems also. Such literals are called“Based literals”. The general syntax is:Form 1: Base # Based value #Form 2: Base # Based value # E exponentThe base value and the exponent are given in decimal notation.

e.g.2#1101_0011# (Binary)16#1_B3# (Hex,1*256+11*16+3)16#A#E2 (Hex,10*256)Composite types:

Page 23: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

As opposed to scalars, the composite type contains a collection of dataelements. If the type of all the elements in a composite data type is identical, thenit is called an “ARRAY”, otherwise it is called a “RECORD”. The syntax of arraydeclaration is as follows.Type ARRAY_NAME is array (index range) of ELEMENT_TYPE;The range may be either ascending or descending. For declaring multidimensional arrays, multiple ranges have to be specified. E.g.type INT_ARR is array(0 to 15) of integer;type BIT_ARRAY is array(0 to 32, 7 downto 0) of BIT;

The objects of the above types can be declared as:Signal MY_INT_ARR: INT_ARR;Signal MY_BIT_ARR: BIT_ARRAY;

Instead of giving the index range in the declaration of an array type, we can alsogive a data-type name in its place. The index range then becomes the range ofthat data type. Using this method, we can declare a 2D array as follows.

type COLUMN is range 1 to 20;type ROW is range 1 to 10;type Table is array(ROW, COLUMN) of Boolean;variable MY_TAB:Table;Unconstrained arrays:We can declare an array type whose range is indefinite. The clause “data typerange <>” represents an indefinite range. E.g.Type FloatArray is array (integer range<>) of real; When we instantiate an object of the Unconstrained array class, we have tospecify the range. E.g.Signal MyFloatArray: FloatArray(0 to 31);

The STANDARD package declares two unconstrained array types namelySTRING and BIT_VECTOR as follows.type STRING is array ( POSITIVE range <> ) of CHARACTER;type BIT_VECTOR is array ( NATURAL range <> ) of BIT;

A two-dimensional array can also be declared as a one-dimensional array whoseelements are themselves a one dimensional array. E.g.Type RAM is array (0 to 1023) of BIT_VECTOR(7 downto 0);Signal MY_RAM: RAM;The maximum number of dimensions for an array is not specified in VHDL but mostsynthesis tools do not support more than 2 dimensions.

We can access the elements of an array by giving the object name followed by theindex value in parenthesis. E.g.MY_INT_ARR (8), MY_BIT_ARRAY (4,6), MY_RAM (654).

STRING LITERALS:String constants appearing in assignment expressions are called ”string

literals”. String literals are enclosed in double quote marks such as “My program”.

Page 24: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

An important subset of string literals is the “Bit string literal”. Bit string literalsare very convenient for assigning values to bit vectors. E.g.MY_RAM(22)<=”11000101”;Prefixing a string with “X” makes it a hex string. Similarly, prefixing with “O”makes it an octal string. E.g.MY_RAM(22)<=X”FF”;Note that a string like “1101” is treated either as a bit string or a std_logic stringdepending the type of the target object. However, the X and O prefixes always convertthe string into a bit string and therefore its target object must be a BIT_VECTOR. If thetarget is std_logic_vector, then the bit string literal must be converted into a std_logicstring literal by using the “To_StdLogicVector” function defined in the std_logic_1164package. E.g.

Signal S1, S2, S3: std_logic_vector (7 downto 0);Signal B1, B2, B3: bit_vector (7 downto 0);B1<= “11001100”;B2<= X”FF”;B3<= “11” & O”77”;-- Match the length by concatenating 2 bits with two octal digitsS1<= “11001100”;S2<= To_StdLogicVector (X”FF”);S3<= To_StdLogicVector (O”377”);-- Length taken care by To_StdLogicVector( )Integers and bit vectors:Logically speaking, integers and bit vectors are both groups of bits. But since VHDL is astrongly typed language it treats them quite differently. The arithmetic operations aredefined only for the integers and the concatenation operation is defined only for bitvectors. The ieee.std_logic_arith package overloads the arithmetic operators onstd_logic_vectors so that we can perform arithmetic operations on them. But if you wantto assign an integer value to a std_logic_vector or vice versa, then you have to explicitlyuse conversion functions CONV_STD_LOGIC_VECTOR and CONV_INTEGER. Theprototype of CONV_STD_LOGIC_VECTOR in std_logic_arith package is asfollows.function CONV_STD_LOGIC_VECTOR(ARG: INTEGER; SIZE: INTEGER)

return STD_LOGIC;The prototype of CONV_INTEGER in std_logic_unsigned package is as follows.function CONV_INTEGER(ARG: STD_LOGIC_VECTOR) return INTEGER;

Examples of type conversionConsider the declarations:

type int is range 0 to 15;subtype int1 is integer range -30 to 30;signal x,y,z:int1;signal h:string(1 to 6):="Hellow";signal A: Bit_vector ( 7 downto 0);signal B: std_logic_vector( 7 downto 0);signal I1: int1:=5;signal I2: integer;

Now let us consider the validity of some statements.

Page 25: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

A<="00001111";--OKA<=X"0F";--OKA<=O”377”;--not OK as length of RHS string is 3*3=9 and LHS=8A<="11"&O"77";--OK version of above

B<="00001111"; --OKB<= X"0F"; -- not OK as B is std_logic_vectorB<=To_StdLogicVector (X"0F");--OK version of aboveB<= O"377";" -- not OK as B is std_logic_vectorB<=To_StdLogicVector (O"377");--OK version of above

I2<=B; -- not OK as I2 is integer and B is std_logic_vectorI2<=conv_integer (B);--OK version of aboveB<=CONV_STD_LOGIC_VECTOR (I,8);--OKI2<=conv_integer (A); -- not OK as conv_integer is not defined for bit_vectorI2<=conv_integer (To_stdLogicVector(A)) ;--OK version of above

A4<=A4+1; -- not OK as + operator is not overloaded for bit_vectorB4<=B4+1; --OK as + operator is overloaded for std_logic_vector

I1<=I1+1;--OKI2<=I1; not OK as types are different

RECORDS:Record is a heterogeneous composite data type. The concept of record is similar

to the “struct” declaration in “C”. The syntax of record declaration is as follows.Type TYPE_NAME is record

MEMBER_NAME1: MEMBER_TYPE1;MEMBER_NAME2: MEMBER_TYPE2;- - -- - - - - - - - - - - - - - - - - - - - - - - - -MEMBER_NAMEn: MEMBER_TYPEn;

End record;Example of record type.Type address is bit_vector (11 downto 0);Type instruction is bit_vector (3 downto 0);type REGISTER_BANK is record

F0: real;F1: real;I0: integer;I1: integer;AD: address;IN: instruction;

End record;An object of the above type can be defined as:Signal MY_BANK: REGISTER_BANK;Members of a record can be addressed by means of the dot operator on the object.. E.g.MY_BANK.F0 <= 6.7;MY_BANK.R0 <= 50;

Page 26: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Access types: Values belonging to access types are memory addresses of dynamicallycreated objects of some other types. They are similar to “pointers” in “C”.e.g. type FIFO is array (0 to 63) of BIT_VECTOR(7 downto 0); type FIFO_PTR is access to FIFO;A FIFO-type object can be dynamically created by using the “new” operator.FIFO_PTR= new FIFO;Members of this object can be accessed, as FIFO_PTR (n) where n is the index.The object can be deleted by the DEALLOCATE procedure. E.g.DEALLOCATE (FIFO_PTR);The synthesis tools do not support access types.File types: Objects of file type represent files in the host environment. They provide amechanism by which a VHDL design communicates with the host environment. Thesyntax of file type is:Type FILE_TYPE is file of ELEMENT_TYPE;e.g. type TEST_VECTOR is file of BIT_VECTOR( 7 downto 0);While declaring a file object, we have to also specify its mode (in or out) and file name.e.g. file TESTFILE:TEST_VECTOR is in “C:\VHDL\MYFILE.DAT”;The data is transferred with the READ and WRITE commands as described later.The synthesis tools do not support file types.

1.2 PROCESS AND WAIT STATEMENTSThe process block is mainly used in behavioral descriptions. However it is also used

in the data flow descriptions occasionally. So, we are introducing it here.Syntax:[label:] process [(sensitivity list)]

[variable declarations]begin

sequential statementsend process [label];

Example:MY_PROC: process (x, y)

Variable a, b: BIT;Begin

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

end process MY_PROC;

The label and the sensitivity list are optional. Unlike a function or a procedure, theprocess does not have a “return” statement at the end. After executing the last statement,the program control again goes back to the first statement. Thus, it is an endless loop. If asensitivity list is given, then after coming to the first statement, the process remainssuspended till an event occurs on any signal in the sensitivity list. The process can also besuspended due to a “wait” statement anywhere in the statement-body. If the sensitivitylist is omitted, then the process is always active. In such processes, it is necessary toinclude wait statements otherwise they will cause the simulator to hang.Wait:

Page 27: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

The wait statement is used to suspend a process until some condition is met. There arethree types of wait statements in VHDL as follows.

Wait on SENSITIVITY LIST;Wait until BOOLEAN CONDITION;Wait for TIME EXPRESSION;

The meaning of “Wait until BOOLEAN CONDITION;” is that the process willcome out of wait state when the Boolean condition changes from false to true. If thecondition remains permanently high thereafter, it does not wake up the process again andagain. The other two types of wait are self-explanatory.Examples:Wait on A, B, C;Wait until A= B and C;Wait for 10 ms;

1.3 Assignment statements and Operators

Assignment statements in VHDL are of the form:

OBJECT_NAME <assignment operator> <Expression> [delay specifier];

Assignment operator “<=” is used if the target object is of signal type, otherwiseoperator “:=” is used. For initializing an object, assignment should be made during itsdefinition. These initializing assignments always use the “:=” operator irrespective of thetype of the object. Constants can be assigned value only during their definition. The onlyexception being that a constant can be declared in the package declaration and given avalue in the package body.Expression is either a single object or a literal or a combination of objects and literalsconnected by suitable operators.Delay specifier can be given only if the target of the assignment is a signal.

Types of assignments: Concurrent and sequentialAn assignment statement in concurrent portion of the program is called a concurrentassignment and an assignment statement in sequential portion of the program is called asequential assignment. Every concurrent assignment produces a “DRIVER” for thesignal, which contains the schedule for its future assignments. A sequential body like aprocess may contain several assignments to the same signal, but they are all added to asingle driver. The time, when an assignment becomes effective, is different for signalsand variables. If a process makes an assignment to a variable, then it takes effectimmediately but if it makes an assignment to a signal, then it takes effect in the nextsimulation cycle. In other words, during one invocation of a process, the signals retaintheir old values till the end of the process while the variables change their values as theprogram progresses.

Another interesting property of concurrent assignment statements is that allconcurrent statements get fired at t=0 irrespective of their sensitivity lists and theyoperate on the initialized data. All processes also get fired once at t=0.

Following are some examples of assignment statements.

Page 28: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Signal A: BIT;Signal B: BIT:=’0’;-- Initialization- - - - - - - - - - -- - - - - - - - - --variable C: string(1 to 6);variable D,E: integer;constant F: integer :=4;- - - - - - -- - - --- - - - - - - - - -- -A<= B or ‘1’;C<=”Hellow”;-- The length of the target array must exactly match the length of stringD := E+F+5;

Composite assignments:VHDL has many constructs, which make assignments to composite objects easy.

To illustrate composite assignments, let us define some objects using the typedeclarations given section 1.1.

BANK1, BANK2: REGISTER_BANK:RAM1, RAM2: RAM;A, B: bit_vector (7 downto 0);

A single assignment statement can copy a whole object as shown below.

BANK1 <= BANK2;RAM1 <= RAM2;A <= B;If we want to make an assignment to a portion of an array rather than the whole array,keeping the other bits intact, then we can use the “slice” operator. The syntax of slice isas follows.ARRAY_OBJ_NAME (RANGE)The direction of the slice range must be same as the direction of the parent array.

SLICE EXAMPLESLet us define some array types as follows.

Type nibble is array ( 3 downto 0) of BIT;Type byte is array ( 7 downto 0) of BIT;Type word is array (15 downto 0) of BIT;

signal W :word ;signal BL : byte :=”00001111”;signal BH : byte :=”11110000”;signal n1,n2,n3,n4 :nibble;signal B :BIT;

W <= BH & BL; -- W becomes “1111000000001111”

Page 29: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

n1 <= BL(7 downto 4);-- upper nibble of B is copied to n1n2 <= n1;-- whole array is copiedB <= n2(2);-- single bit B receives a bit from an array n2n1(2 downto 0 ) <= W(13 downto 11 );--both source and target are slicesn3<=n1(0) & n1(1) & n1(2) & n1(3); -- copy in reverse orderRemember that the direction of the slice range must be same as the direction of the parentarray. Hence copying in reverse order has to be done by concatenating individual bits.Aggregates:

Aggregates are a set of quantities separated by commas and enclosed inparenthesis. They can be used for making assignments to arrays or records. E.g.n1<= “1001”; can also be written as n1<=(‘1’,’0’,’0’,’1’);Assignments to records can be made using aggregates. E.g.MY_BANK <= (1.2, 4.8, 50, 25, “110011001100”,”1001”);The number of elements in the target object must exactly match the number of elementsin the aggregate.Aggregates can also be used as targets of assignments. E.g.(n1, n2, n3, n4) <= W;Named association for array assignments:We have seen how to make a whole array assignment and a sliced array assignment. Ifyou want to make an assignment only to some randomly selected elements of an array,keeping the others elements intact, then you can use named association. E.g. suppose youwant to assign ‘0’ and ‘1’ respectively to bits 7 and 13 of W without affecting theremaining bits. This can be achieved as follows.W <= (7 => ‘0’, 13 => ‘1’);If you want to make bits 8 and 10 equal to ‘1’ and make the remaining bits equal to ’0’,then we can write:W <= (8=> ‘1’, 10 => ‘1’, others => ‘0’);The “others” keyword denotes all unspecified bits. If none are specified, then it applies toall the bits. This property is very useful to reset all bits of an array, especially if the lengthof the array is unknown. E.g.W <= (others => ‘0’); -- makes the whole array ‘0’Alias declaration:Any object or its slice can be given an alternative name by means of the alias declaration.This improves the readability of the program. Let us consider that there is a 16-bit dataregister that receives data from memory. The bits 15-13 are op code, bits 12-11 areaddressing mode and bits 10-0 are address. We could declare following convenientaliases for them.Alias OP_CODE : bit_vector(2 downto 0) is DATA_REG(15 downto 13);Alias AD_MODE: bit_vector(1 downto 0) is DATA_REG(12 downto 11);Alias ADDRESS : bit_vector(10 downto 0) is DATA_REG(10 downto 13);

The alias names can be used in place of signal names thereafter. E.g.OP_CODE_REG <= OP_CODE;MAR <= ADDRESS;Operators:The operators in VHDL are classified into 6 categories:1. Logical Operators.2. Relational operators

Page 30: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

3. Shift operators4. Adding operators5. Multiplying operators.6. Miscellaneous operators.The precedence priority of operators increases from category 1 to category 6.The operators within the same category are at the same level. The expression isevaluated from left to right. Parenthesis may be used to clarify the order ofevaluation.Logical operators: and, or, nand, nor, xor, not.These operators are valid for BOOLEAN, BIT and STD_LOGIC types.E.g.variable SUM, A, B, C, D :BIT;SUM := A xor B;C:= (A and B) or (A and C);D:= not A;Relational operators: =, /=, <, <=, >, >=.These operators are normally used in IF statements. The result of a relational operator isTRUE or FALSE. The relational operators are valid for all scalars including enumeratedvariables. E.g. consider the statement-type FOUR_LOGIC_LEVEL is (‘U’,’0’,’1’,’Z’);signal a,b: FOUR_LOGIC_LEVEL; a<=’U’ ; b<= ‘Z’;Since the value of enumerated literals increases from left to right, an expression like“a<b” will evaluate to TRUE. The operators <=, <, >, >= are also valid for array typesprovided that the array elements are scalars. The comparison is made one element at atime starting from left to right. The operators = and /= are valid for all objects exceptFILE objects.

Shift operators: sll, srl, sla, sra, rol, ror.These operators were introduced in the1993 standard and some tools do not support them.These operators stand for shift left logical, shift right logical, shift left arithmetic, shiftright arithmetic, rotate right and rotate right respectively.E.g.“10001010” sll 2 gives “00101000”“10001010” rol 2 gives “00101010”“10000000” sra 3 gives “11110000”If your tool does not support these functions, then you can achieve the sameresult by using the slice and concatenation operator.Adding operators: +, -, &The + and – operators are valid for all numeric types. The concatenation operator & isvalid for strings. It joins the two argument strings together.Examples.variable SUM1, SUM2, A, B : integer;signal S3, S4:string;constant S1 : string := “abc”;constant S2 : string := “def”;

SUM1 := A+B;SUM2 := A-B;

Page 31: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

S3 <= S1 & S2;--value of S3 will be “abcdef”S4 <= S1 & ‘1’;--value of S4 will be “abc1”

Multiplying operators *, /, mod (modulus), rem (remainder).The operators * and / have their usual meanings for all numeric data types. The operatorsmod and rem operate on integers and the result is also an integer.A rem B is defined as A –(A/B)*B.e.g. (-7) rem 4 has value-3.The result or rem operator has a sign of the first operand.A mod B is defined as A-B*N---for some integer Ne.g. 7 mod (-4) has value –1.The result of mod operator has a sign of the second operand.Miscellaneous operators: abs (absolute), **(exponentiation).Operator abs (absolute value) is defined for any numeric type. Exponentiation operator“**” is defined when the left operand is an integer or floating-point type and theexponent is of integer type.

1.4 Objects in VHDL:Signals

Anything that stores information is called an “object “ in VHDL. For signalobjects, the simulator maintains a data structure called driver of the signal that recordsthe time and a value of each assignment to the signal (called transaction). When a newtransaction is added, certain old transactions have to be dropped from the driver in orderto be consistent with the delay model used. The rules for adding transaction are explainedin the next section.

Each concurrent statement produces one driver for the target signal. If more thenone concurrent statement assign values to the same target signal, then it becomes a multi-writer signal and it must be declared as a resolved signal type. A signal can be declaredas “resolved signal type” by specifying a resolution function in the declaration of thesignal. The resolution function takes all values that the individual drivers wish to assignto the signal and resolves them to produce a single value that is actually assigned to thesignal. Such functions are used to describe a tristate bus or a wired OR logic. e.g.signal Z : WIRED_OR BIT;Here, Z is resolved signal of type BIT, with WIRED_OR as the resolution function. Theprocedure for writing resolution functions is described in chapter 5.If we want to declare many resolved type signals, it is more convenient to declare aresolved subtype of a base type and then use this subtype to declare the signals.subtype RESOLVED_BIT is WIRED_OR BIT;signal Z : RESOLVED_BIT;Remember that the type STD_LOGIC has been already defined as a resolved subtype ofthe STD_ULOGIC type in the std_logic_1164 package.Signal declaration zones:Objects of signal class are declared in following zones.? Architecture-item-declaration zone: This zone is between the “architecture” and

“begin” keywords. Signals declared here are accessible throughout the architecturebody, but not outside it.

Page 32: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

? Entity-item-declaration zone: This zone is after the “port” and before the “end”keyword in an entity unit. Signals declared here are accessible throughout all thearchitecture bodies associated with the entity.

? Block-item-declaration zone: Architecture bodies sometimes have one or more“block” statements. Signals declared here are accessible throughout the block.(including any nested sub-blocks )

Examples:Entity XX is

Port (a, b: in BIT; c: out BIT);Signal d, e, f: BIT;

End XX;Architecture YY of XX is

signal X : BIT ;signal Y : BIT := ‘0’ ;signal X_BUS : bit_vector (7 downto 0) := X “FF” ;

begin- - - - - - - - - - -- - - - - - - - - - - - - -end YY;

Creating signal waveformsWe can conveniently generate waveforms by using assignment statements with multipletransactions. Suppose we want to create a waveform on the signal “phase” as shown infig 2.1.Phase:E)

T T+8 T+13 T+50 ns

Fig 2.1Wave form creation

The above waveform can be generated by the following statement.Phase <= ‘0’, ‘1’ after 8 ns, ‘0’ after 13ns, ‘1’ after 50 ns;

Signals driversA signal driver consists of an array of time-value pairs. Consider the statement:RESET <= 3 after 5 ns, 21 after 10 ns, 14 after 17 ns;It produces following entries in the driver.

F) RESET curr@now 3@T+5ns 21@T+10ns 14@T+17ns

Effect of transport delay on signal driversRecall that a transport delay faithfully reproduces the input waveform at the output after aspecified delay. Consider following multiple assignments in a process to the signalRX_DATA.Entity TEST is end TEST;-- this entity does not have any portsArchitecture T of TEST is

Page 33: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Signal RX_DATA: integer;begin

processbegin

RX_DATA <=transport 11 after 10ns;RX_DATA <=transport 20 after 22ns;RX_DATA <=transport 35 after 18ns;Wait;

end process;end T;The transactions are added to the driver according to the following rules.

RULES FOR ADDING A TRANSACTION TO A TRANSPORT DELAY.1. If the delay time of the new transactions is more than the time of all existing

transactions on the driver, then the new transaction is added at the end of the driver.2. If the delay time of the new transaction is earlier than or equal to one or more

transactions on the driver, then these transactions are deleted from the driver and thenew transaction is added at the end of the driver.

According to these rules, the driver looks like this after the first two statements.

G) RX_DATA curr@now 11@T+10ns 20@T+22ns

The third statement causes the 22 ns transaction to be deleted and the driver now lookslike this.

H) RX_DATA curr@now 11@T+10ns 35@T+18ns

Effect of inertial delay on signal drivers

Consider the following process block.Entity TEST is end TEST;Architecture T of TEST is

Signal TX_DATA: integer;begin

processbegin

TX_DATA <= 11 after 10 ns;TX_DATA <= 22 after 20 ns;TX_DATA <= 33 after 15 ns;wait; --suspends indefinitely .

end process;end T;

In the inertial delay model, following rules apply for adding a new transaction.

1. All transactions on a driver that are scheduled to occur at or after the delay of the newtransaction are deleted (as in the transport case).

Page 34: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

2. If the value of the new transaction is the same as the value of the transaction on thedriver, the new transaction is added to the driver.

3. If the value of the new transaction is the different from the values of one or moretransactions on the driver, these transactions are deleted from the driver and the newtransaction is added.

4. For a single signal assignment statement, if the first waveform element is added to thedriver, all subsequent waveform elements of that signal assignment are also added tothe driver.

The driver of the TX_DATA signal looks like this at the end of the process.

TX_DATA curr@now 11 @ 10ns 22 @ 20 ns

TX_DATA curr@now 33@15ns

Let us consider another example, which clearly demonstrates how the above rules filterout narrow pulses.Entity TEST is end TEST;Architecture T of TEST is

Signal A, B, C: BIT;begin

A<= ‘1’ after 10 ns, ’0’ after 18 ns;-- pulse of 8 ns widthB<= A after 15 ns;-- large inertial delayC<= A after 5 ns;-- small inertial delay

End T;At t=10, the first event on A places transactions (1,15) and (1,5) on the drivers of

B and C respectively. After 5 ns, i.e. at t=15, C becomes ‘1’. At t=18, second event on Aplaces a transaction (0,15) on B and (0,5) on C. By this time, the driver of C is empty andthe driver of B contains the old transaction which now looks as (1,7). Since the value ofthe new transaction (i.e. 0) is different from the old transaction (i.e.1), the old transactionis deleted and therefore, B remains ‘0’ throughout. C changes to 0 at t=23.VARIABLES

Objects of the variable class only have a current value and no time history. They are usedas intermediate storage locations and for passing parameters to functions in the sequentialbodies. Variables can not be defined in the concurrent portion of the code. Although 1993standard has introduced shared variables, most tools don’t support them. They can bedeclared only in the variable declaration zone of the process, function or procedure body.

Scope and Value retention:The scope of the variables is only limited to the process, procedure or a function where itis declared. Hence variables can not be used to transmit information from one process toanother. Process variables retain their values between two invocations but Procedure andfunction variables are initialized each time the procedure is called.Sometimes the programmer has a choice to choose the object type as a signal ora variable. In that case, it is preferable to choose variable because the synthesis

Page 35: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

tool does not distinguish between a variable and a signal but a simulation toolassigns a driver only to the signals. Unnecessarily defining too many signalsslows down the simulation.

Assignment to variables:Assignment to a variable can be made only within a sequential portion of the code. Theassignment operator “:=” is used for variables. The target variable immediately assumesthe value of the RHS expression. In contrast, recall that an assignment to a signal, madein a sequential body takes effect only at the end of that body.

Declaration of variables:Variables are declared before the “begin” keyword of the sequential body. E.g.Process

Variable a, b, c: BIT;Begin- - - -- -- - - - - -end process;

CONSTANTS

Objects of the constant class are similar to the variables but they have an additionalrestriction that they can be assigned values only during their declaration. E.g.

Constant RISE_TIME : time := 10 ns;Constant INIT_CHAR : BIT_VECTOR(7 downto 0) := “01010101”;Constant can be declared wherever signals and variables are declared. They can also bedeclared in the package declarations and package bodies.

1.4 ATTRIBUTES OF OBJECTS

The VHDL objects have various properties apart from their value. These properties arecalled attributes. There are several predefined attributes in the language. Theprogrammer can add his own attributes to objects if desired. Such attributes are used toeither convey some additional information to the synthesis tool or for documentationpurpose. The attribute is accessed by the expression <object name>’<attribute name>.Attributes of array: left, right, high, low, range, reverse_range, length

The attribute names are self-explanatory.Consider the declarations.

Type Nibble is array(3 downto 0) of BIT;Type NibVect is array(3 downto 0,0 to 7) of BIT;

Now let us see the attribute values of these arrays.

qvect’left(1) = 3 qvect’right(1) = 0

Page 36: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

qvect’high(2) = 7 qvect’low(2) = 0qvect’range(1)= 3 downto 0 qvect’range(2) = 0 to 7qvect’length= 4 qvect’length(1)=4q’range = 3 downto 0 q’reverse_range = 0 to 3

Since qvect is a multi dimensional array, we need to specify which index we are talkingabout. The index number (1 or 2) should be given in bracket after the attribute name. Inabsence of the index specification, the compiler automatically assumes the index to be 1.Thus qvect’length is same as qvect’length(1). Note that for an ascending range, left =low and right = high. For a descending range, left = high and right = low.Attributes of data types: left, right, high, low, base

Consider the following declarations. The meaning of the attributes becomes clear withthese examples.

subtype bit_position is integer range 15 downto 0;Type fraction is range -.999 to .999;

Bit_position’low= 0 Bit_position’left=15Bit_position’high= 15 Bit_position’right=0Bit_position’base= integer Bit_position’base’high=2147483647Fraction’right = .999 Fraction’left = -.999

Additional attributes for integers and enumerated data types: pos, val, succ, pred, leftof, rightofAttribute pos is zero based index of the given symbol in the enumeration list. Val isthe value at the given index in the enumeration list. Pred is predecessor and succ issuccessor.Consider the type declarationsType T1 is (A, B, C, D);

T1’Pos (B) = 1T1’val (3) = DT1’succ (C)=DT1’pred (C)=BT1’leftof (B)=AT1’rightof (A)=BT1’rightof (D)=error

Attributes of signals: event, stable, last_event, last_value, delayed, quiet, active,last_active, transaction

Consider the statementSignal A:BIT;The meanings of the attributes become clear with following illustration.A’event = TRUE if A has changed state at current simulation cycleA’stable = TRUE if A has not changed state at current simulation cycle

Page 37: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

A’stable(5 ns) = TRUE if A has not changed within last 5 nsA’last_event = time elapsed since last event on A (FALSE If A’event is true)A’last_value = value of A before the most recent eventA’delayed(10 ns) = another copy of A but delayed by 10nsA’quiet(10 ns) = TRUE if no transaction has been placed on A in last 10 nsA’active = TRUE if a transaction has been placed on A in the current simulation cycleA’last_active= time elapsed since last transaction on A (FALSE If A’active is true)

Notice the similarity between event and active attributes. Event is true only if thevalue of A changes but active is true even if the same value is placed on A again.Can you spot two more similar pairs in the above list?

USER DEFINED ATTRIBUTESIn addition to the above attributes, the user can define his own attributes

to various “entity class” elements. The entity class includes not only the entitydesign unit but also architecture, configuration, procedure, package, type,subtype, constant, signal, variable, component and label. The user-definedattribute has to be defined in two steps. In the first step, the attribute name andits type is declared as follows.Attribute ATTR_NAME: ATTR_DATA_TYPE; e.g.Type DATE is record

MM:integer;DD:integer;YYYY:integer;

End DATE;Attribute AUTHOR_NAME: string;Attribute UPDATE_DATE: DATE;

In the second step, the attribute is associated with the desired object as follows.

Attribute ATTR_NAME of OBJ_NAME: OBJ_CLASS is ATTR_VAL;

Example:

Entity CPU isPort (-------);Attribute AUTHOR_NAME of CPU: entity is “Dr. S. S. Limaye”;Attribute UPDATE_DATE of CPU: entity is (5, 12, 1999);

End CPU;

User defined attributes don’t have any computational significance. They can beused for various purposes. Some synthesis tools use these attributes to conveysome additional parameters of the objects being described. They can also beused for documentation.

1.5 EXAMPLES OF SIMPLE CIRCUITS

--TWO INPUT AND GATE

Page 38: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

entity AND2 isport (A, B: in BIT; Y: out BIT);

end AND2;

architecture DATAFLOW of AND2 isbegin

Y <= A and B after 10 ns;end DATAFLOW;

--HALF ADDERentity HADD is

port (A,B: in BIT; S,C: out BIT);-- S = sum, C= Carryend HADD;

architecture DATAFLOW of HADD isbegin

S<= A xor B after 10 ns;C<= A and B after 10 ns;

end DATAFLOW;

--FULL ADDERentity FADD is

port (A, B, Ci: in BIT; S, Co: out BIT);-- S = sum, Ci = Carry in, Co = Carry outend FADD;

architecture DATAFLOW of FADD isbegin

S<= A xor B xor Ci after 10 ns;C<= (A and B) or (A and Ci) or (Ci and B) after 10 ns;

end DATAFLOW;

--2:1 MUXentity MUX2 is

port (A, B, S: in BIT; Y: out BIT);-- A, B are inputs, S is select control, Y= outend MUX2;

architecture DATAFLOW of MUX2 isbegin

Y<= (A and (not S)) or (B and S);end DATAFLOW;

--QUAD 2 INPUT NAND GATE (7400)entity AND2_4 is

port (A, B: in BIT_VECTOR(3 downto 0);-- A, B are inputs

Page 39: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Y: out BIT_VECTOR( 3 downto 0));-- Y is outputend AND2_4;

architecture DATAFLOW of AND2_4 isbegin

Y <= A and B after 10 ns;end DATAFLOW;

-- 2:4 DECODERentity DECODER2_4 is

port (A1, A0: in BIT; Y0,Y1,Y2,Y3: out BIT);end DECODER2_4;

architecture DATAFLOW of DECODER2_4 isbegin

Y 0<= (not A1) and (not A0);Y 1<= (not A1) and A0;Y 2<= A1 and (not A0);Y 3<= A1 AND A0;

end DATAFLOW;

1.6 PRACTICAL SESSION ON SIMULATORFor simulating the above examples, we can use ViewLogic’s Workview Office®suite that supports digital, analog, and mixed digital/analog design andsimulation. It also supports synthesis through FPGA express. For installation ofthe package, refer to the Workview Office documentation.Before starting anything, we need to create a project through the ProjectManager program. The project manager creates a subdirectory in the project’name. All relevant files for the project are stored here. We use HDL manager forsource code entry and analysis and SpeedWave for simulation.

Creating a new project

First, create a folder named “VHDL” using windows explorer. We will create asubfolder for each project in this folder. The installation program would have put theWorkview office toolbar on the desktop. If the Workview office toolbar is not visible forsome reason, then invoke it through START> PROGRAM_FILES> Workview office>Workview office sequence.

c. Click on the Project Manager icon in the toolbar and then click on File> New. First adialog box appears which asks you whether you want to copy the current library pathsto the new project. Dismiss the dialog box with NO. Then “Creating new project”window gets invoked.

d. Enter the name of the desired project subdirectory, say C:\VHDL\GATES. You mayuse the BROWSE button to locate the parent directory, i.e. VHDL. Since the GATESsubdirectory is non-existent, the project manager will automatically create it.

e. Enter project name as SIMPLE_GATES and click NEXT.

Page 40: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

f. For instantiating components from FPGA or ASIC cell libraries, we need to includethe corresponding configured libraries. For the time being, we don’t need them, soclick NEXT.

g. If we need to include previously designed libraries, we can specify them. For the timebeing, we don’t need them, so click FINISH.

h. A dialog box appears which summarizes your choices. Click OK to confirm. Sincethe GATES subdirectory does not exist, a dialog box appears to ask whether it shouldbe created. Click OK for creation of the new subdirectory.

i. Click File >save, and then File> Exit.The project manager has now created a file named “SIMPLE_GATES.VPJ”. Wheneverspeedwave is invoked in future, the project settings will be automatically taken from thisfile. The default settings will change only when another project is opened or another newproject is created. Suppose somebody has changed the active project and you want torestore the SIMPLE_GATES as the active project. Open project manager from the maintoolbar and click File>open. Navigate to the SIMPLE_GATES.vpj file and double clickit.

Once the active project is set, we don’t need the project manager’s window. It isbetter to close it.

Entering VHDL code

a. VHDL code can be conveniently entered through the HDLPAD editor. HDLPAD is amodified version of WORDPAD having a facility of automatic color coding of thekey words. However the HDLPAD package does not have a facility to save a new filein plain text format. So, you should create a startup file with only one line entered onit using Notepad or any other plain text editor. Save the file as AND.VHD inC:\VHDL\GATES directory. Note that the VHDL source files have “.VHD”extension. While saving the file, click the file type tab and choose “All files” so that itgates saved as AND.VHD. Otherwise it gets saved as AND.VHD.TXT. Click on theSpeedWave icon. The SpeedWave dialog box pops up.

The speedwave dialog box may be considered as the parent window for all otherwindows. From this dialog box, we can either click the “Analyze design” tool buttonfor invoking the HDL manager or the “load design” tool button for invoking thesimulator. These packages can also be invoked through menu commands File>Analyze design and File> load design respectively.

b. Click on the HDL Manager tool button (Leftmost, i.e. under FILE menu) to invokethe HDL manager. For the first invocation in a project, the Jumpstart wizard opensup. You can answer the wizard queries as follows.

c. For using previously defined libraries we need to tick “Yes please use existinglibraries”, browse and include them. For the time being, just click NEXT.

d. User library name dialog pops up. Here we need to a name to the working library. Bydefault, the windows user name is selected as the library name. If the session wasstarted using administrator as the user name, then library is named asadministrator.lib. It is desirable to change the name to a self-explanatory name. Thiswill help in including useful files of this library in other projects. Inside the currentproject, the library is identified as “work”. Rename the library as GATES and ClickNEXT.

Page 41: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

e. Tick the “Add source files” option and navigate to the AND.VHD file that yougenerated in step “a”. Click NEXT.

f. A dialog box for selection of Standard libraries pops up. IEEE and synopsis librariesare automatically selected. At this stage, we don’t want to include any other libraries,so click on the FINISH button.

g. Now we need to complete the source file entry. For doing this, click on the userlibrary symbol in the left pane so that a source-file list is presented. RIGHT CLICKon AND.VHD. This will pop up a dialog box with options for analyze, edit etc. Clickon the Edit option.

h. HDLPAD gets invoked. Enter the complete program and save it.i. Close HDLPAD.Analyzing the VHDL designa. Again right click on file name AND.VHD in the user library window. The action

choices dialog box will again pop up. This time, choose the Analyze option. Thesource file gets analyzed and the results of analysis are presented in the messagewindow at the bottom.

b. If there are errors, double click on the error so that HDLPAD gets invoked with theerroneous line highlighted. Edit and make corrections for the mistakes. Again analyzetill you get an error free compilation.

Simulating a VHDL designa. In the SpeedWave dialog box, click the “Load design” tool button. The “Load VHDL

design” dialog box pops up. In the lower pane, a list of libraries is presented. Sinceour design is in the GATES.lib library, double click on it so that all entities in thelibrary are displayed. Click on the entity AND2. Click OK.

b. Now the simulator window opens up. The screen now has four areas. The top leftcorner is for command line interface. The bottom left corner displays the source code.This can be used for single stepping and break pointing. The right half is divided intotwo vertical panes. The left pane displays the design hierarchically. You should clickon the desired component in this pane. Its port signals are displayed in the right pane.Click on the SIGNALS keyword to display all signal names and their values. For thjeAND2 design, signals A, B and Y are displayed and their initial values are shown as‘0’.

c. Now we can give stimulus at the port inputs and observe the state of various signals.The stimulus commands should be typed in the command window. The importantcommands are:H <port name list> Force the listed signals high.L <port name list> Force the listed signals low.A <signal name> value Assign a integer or a bit vector valueSIM simulate for one step (100ns by default)STEP <time period> set step sizeSIM <time period> simulate for the specified time period.

For the AND design, first enter the commandsH ASIM

Note that the new value of A is reflected in the right pane. Y is still at ‘0’. Now type:

H BSIM

Page 42: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Now A, B and Y, all become ‘1’ in the right pane.Try with various values of A and B.

OTHER EXAMPLESFor simulating other examples, you may either add them to the same source file orcreate a separate source file for each one of them. Repeat the above steps for eachone. In the AND2_4 design, port signals A and B have been defined as vectors. So,the stimulus assignment command A has to be used instead of H or L. Thecommands can be given as follows:A A “0101” or A A 5\hA B “0011” or A B 3\h

SIMVIEWING SIGNAL WAVEFORMSWhen a design is loaded the port signals and internal signals are displayed in the rightpane. If signal names are not visible then Click on the “+” sign of port and signal icons.Click on the first signal name that you want to view. Keep SHIFT pressed and click on allother desired signal names. Then right click. A quick menu pops up. Click “Display inVwaves” option. The Vwaves window opens up and shows the selected signals. Applystimulus using command line interface. The corresponding waveforms are displayed inthe Vwaves window.

If a design has too many signals, then it becomes difficult to watch them in the rightpane. In such case, you can watch selected signals in a separate monitor window. Forthis, use the same procedure as described above but after right clicking, choose the “Addto monitor window” option instead of “Display in Vwaves” option.CREATING A COMMAND FILE FOR STIMULUS GENERATIONWe have seen how to give stimulus to ports by A, H and L commands. In case of largecircuits, too many commands have to be given to test the circuit fully. To avoid thetrouble of retyping the commands for each test run, we can make a command file and runit. The command file is a simple text file, which can be created through HDLPAD orNOTEPAD. To invoke the command file, click FILE>”Run command file” menuoptions.Some more simulator commands are listed below.Restart Reset time to 0.Stepsize 200ns set step size to 200ns.Ticksize .5us set tick size to 500ns.Clock <object name> value1 value2…. Define clock waveform cycle

e.g. clock MyClock 0 1Cycle Apply one clock cycle.Monitor object1 object2…Add to objects to the monitor windowWave filename.vwf object1 object2…Add objects to the Vwaves window

e.g. wave fusion.vwf a b cFollowing command file will be appropriate for testing the 2:4 decoder.

RestartWave decoder.vwf A1 A0 Y0 Y1 Y2 Y3SimH A0Sim

Page 43: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

H A1L A0SimH A0Sim

EXERCIZESE2.1 a) Declare a numeric type called NewInt having range –2 to 6. b) Declare a numeric type called NewFloat having range –5.3 to 16.2.

c) Declare an enumerated data type called VOWEL containing only vowelcharacters.d) Declare a subtype of integer called int1 having range 0 to 15.e) Declare a 2 by 5 array of integers called IntArray.f) Declare a type called slv4_16 which is a 4 element array of 16 bitstd_logic_vector.

E2.2 a) Define objects named NI, NF, VO, I1, IA, SLV for the above types. b) Write assignment statements to do the following.

- Add 1 to NI- Add contents of NI to NF- Multiply NI and I1 and store the result in IA(1,4)- Assign the leftmost vowel in the enumeration list to VO- Assign the hex value F0AC to SLV(0).- Assign the octal value 123456 to SLV(1).- Assign I1 to SLV(2).- Assign value of SLV(3) to I1 assuming it to be less than 16

E2.3 a) Derive subtypes from std_logic_vector to represent a nibble, byte and word.b) Define two nibble objects n1, n2, one byte object B and one word object W.c) Transfer 4 MSB’s of W to n1.d) Transfer contents of n2 to the upper nibble of B in reverse order.e) Transfer contents of B to LSB of W.f) Make bits 3 and 11 of W ‘1’ and make the other bits ‘0’.g) Rotate the contents of n1 right by one position using concatenation.

E2.4 a) Declare a record called MY_REC having two bytes B0 and B1, two integers I0and I1 and two real numbers R0 and R1.b) Define two record objects REC1 and REC2 derived from above record.c) Fill the members of REC1 with following values: X”FF”, X”00”, 5, 6, .2, 4.5.d) Transfer the contents of B0 and R1 of REC1 to B1 and R0 of REC2.

E2.5 a) Using a single concurrent statement, generate a symmetrical 1 MHz clock. Canit be synthesized?b) Using process and wait statements, generate a 1 MHz clock that is high for 600ns and low for 400ns.

E2.6 a) Write a single concurrent statement that produces a 10 ns wide pulse on asignal called EDGE_PULSE whenever a signal called INPUT_SIG changesstate.Hint: Use Delayed attribute and XORb) Repeat above so that EDGE_PULSE is generated only for the positivetransitions of INPUT_SIG.

Page 44: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

E2.7 a) Write the description of a CMOS inverter entity INV with a propagation delayof 10 ns.b) Rewrite architecture of INV such that the propagation delay PD is first definedas a constant with a value of 3RC where R is output impedance and C is loadcapacitance. Let the values be 1.5E4 ohms and 0.1E-12 F respectively.c) Declare a physical data type CAP with ff as the base unit and another data typeRES with ohm as the base unit. Write another architecture for INV where R and Care defined in physical units.

E2.8 Consider following VHDL program.Entity E28 is end E28;Architecture A of E28 is

Signal X,Y: BIT;Begin

X <= ‘0’, ‘1’ after 80 ns, ‘0’ after 110 ns, ‘1’ after 175 ns;Process (X)Begin

Y <= ‘1’, ‘0’ after 40 ns, ‘1’ after 80 ns;End process;

End A;

Draw the wave forms of X and Y.ANSWERS

E2.1type NewInt is range -2 to 6;type NewFloat is range -5.3 to 16.2;type VOWEL is ('a', 'e', 'i', 'o', 'u');subtype int1 is integer range 0 to 15;type IntArray is array(0 to 1, 0 to 4) of integer;type slv4_16 is array(0 to 3) of std_logic_vector(15 downto 0);

E2.2signal NI: NewInt;signal NF: NewFloat;signal VO:VOWEL;signal I1:int1;signal IA: IntArray;signal SLV:slv4_16;

NI<=NI+1;NF<=NF+ NewFloat(NI);IA(1,4)<=integer(NI)*integer(I1);VO<=VOWEL'left;SLV(0)<=To_StdLogicVector (X"F0AC");SLV(1)<=To_StdLogicVector (O"123456");SLV(2)<=CONV_STD_LOGIC_VECTOR(I1,16);I1<=int1(CONV_INTEGER(SLV(3)));

E2.3subtype nibble is std_logic_vector(3 downto 0);subtype byte is std_logic_vector(7 downto 0);

Page 45: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

subtype word is std_logic_vector(15 downto 0);signal n1,n2: nibble;signal B: byte;signal W: word;

n1 <= W(15 downto 12);B(7 downto 0) <= n2(0)&n2(1)&n2(2)&n2(3);W(7 downto 0) <= B;W <= (3 => '1', 11 => '1', others => '0');n1 <= n1(0) & n1 (3 downto 1);

E2.4type MY_REC is record

B0,B1: BYTE;I0,I1: integer;R0,R1: real;

end record ;signal REC1, REC2: MY_REC;REC1 <= (To_StdLogicVector (X"FF"), To_StdLogicVector (X"00"),

5, 6, 0.2, 4.5);REC2.B1 <= REC1.B0;REC2.R0 <= REC1.R1;

E2.5 (a)

Clock <= not Clock after 500 ns;(b)Entity CLK end CLK;Architecture TEST of CLK isSignal Clock: BIT;begin

Clock_proc: processBegin

Clock <= ‘0’;Wait for 400 ns;Clock <= ‘1’;Wait for 600 ns;

End Clock_proc;End TEST;

E2.6 (a)

EDGE_PULSE <= INPUT_SIG xor INPUT_SIG’delayed (10 ns);(b)EDGE_PULSE <= INPUT_SIG and (not INPUT_SIG’delayed (10 ns));

E2.7 (a)

Page 46: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

entity INV isport (A: in BIT; B: out BIT);

end INV;

architecture A1 of INV isbegin

B <= not A after 10 ns;end A1;(b)The product RC has units of second. We should multiply it with 1.0E15 to express it infemto seconds and then convert it into integer. Finally we multiply the product by 3femto seconds to get the result in time units.architecture A2 of INV is

constant R: real:= 1.5E4;constant C: real:= 0.1E-12;constant PD: integer:= integer(R*C*1.0E15) *3 fs;

beginB <= not A after PD;

end A2;

( c)In this case, the product of 1 ff and 1 ohm is 1 femto second. So we don’t have tomultiply it by any scaling constant as above.architecture A3 of INV is

type CAP is range 1 to 1E18units

ff;pf=1000 ff;nf=1000 pf;uf=1000 nf;mf=1000 uf;f =1000 mf;

end units;type RES is range 1 to 1E9units

ohms;Kohms=1000 ohms;Mohms=1000 Kohms;

End units;constant R: RES:= 15 Kohms;constant C: CAP:= 100 ff;constant PD: time:= (R/ 1 ohm)*(C/1 ff)*) *3 fs;

beginB <= not A after PD;

end A3;

E2.8

Page 47: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

X

0 80 110 175

Y 0 40 80 150 175 215 255

Explanation: The process get triggered at t=0 and places transactions (1,0),(0,40), (1,80) on the driver of Y. The process is again triggered at t=80 andplaces the same transactions on the driver. Before the first transaction can takeeffect at t=120, the process is again triggered at t=110. It causes the oldtransactions to be deleted and new transactions to be placed. Y goes low att=150. Y would have gone high at t=190 but the process is again triggered att=175. It deletes the old transactions and places a new trio which takes effect att=175, 215 and 255.

Page 48: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

CHAPTER 3

DATAFLOW style of descriptionDataflow description is a middle ground between behavioral and

structural descriptions. This description consists of concurrentassignment statements that specify the flow of data through various gates,registers or buses in the system. We have discussed realization of simplegates using unconditional signal assignments in chapter 2. More complexlogic blocks can be described using conditional and selected signalassignments. Synchronous Sequential circuits can be described either byusing guarded assignments, or by using clock edge expression as anenabling condition.

3.1 Concurrent conditional assignmentsA conditional assignment selects one of the several values based on the conditions

specified. The syntax of a concurrent conditional statement is as follows.

Signal name<=Expression1 when condition1 elseExpression2 when condition2 else- - - - - - - - - - - - - - - - - - - - - - -ExpressionN when conditionN elseExpressionN+1;

The conditions need not be mutually exclusive. During the execution of thestatement, the conditions are evaluated one by one and when a truecondition is detected, the corresponding expression is evaluated andassigned to the target signal. This method of evaluation forces a priorityencoding structure for the conditions. This statement is similar to the if-else if ladder structure which is used in sequential blocks. A 4:1 mux withselect inputs S1, S0, data inputs I0, I1, I2, I3 and out put can be describedas follows.--4:1 MUXY <= I0 after 5ns when (S1 & S0) = “00” else

I1 after 5ns when (S1 & S0) = “01” elseI2 after 5ns when (S1 & S0) = “10” elseI3 after 5ns;

3.2 Concurrent Selected signal assignmentThe concurrent selected signal assignment statement is similar to

the CASE statement of a sequential block. The choices are not evaluated ina sequence like the conditional statement. All possible values of theselecting object must be specified and they must be mutually exclusive.This statement results in a mux like structure instead of a priority structure.Any choice which is not explicitly specified may be covered by the “others”clause.Syntax:With control_object select

Target_object <= expression1 when value1,Expression2 when value2,

Page 49: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

- - - - - - - - - - - - - - - - - - -expressionN when valueN,expressionN+1 when others;

The 4:1 mux example can also be written using a selected signal assignment statement asfollows.-- 4:1 MUX--s has been declared as a bit_vector(1 downto 0))with s selectY <= I0 after 5ns when “00”,

I1 after 5ns when “01”,I2 after 5ns when “10”,I3 after 5ns when “11”;

More than one values may be specified to denote a OR condition. These valuesshould be separated by the symbol “|”. Eg “00”|”01”. The following example of a 3:1mux shows the use of oring condition.-- 3:1 MUX--s has been declared as a bit_vector(1 downto 0))with s selectY <= I0 after 5ns when “00”,

I1 after 5ns when “01”,I2 after 5ns when “10”|”11”;

In chapter 2 we have built a decoder using logical expressions. Now let usbuild a 3:8 decoder using a selected signal assignment statement.--3:8 decoderentity DECODER is

port(ADR : in STD_LOGIC_VECTOR(2 downto 0);Y: out STD_LOGIC_VECTOR (7 downto 0));

End DECODER;Architecture DF of DECODER isBegin

With ADR selectY<= “00000001” when “000”,

“00000010” when “001”,“00000100” when “010”,“00001000” when “011”,“00010000” when “100”,“00100000” when “101”,“01000000” when “110”,“10000000” when “111”,“XXXXXXXX” when others;

End DF;

In the above example, the signals belong to the std_logic class,which has 9 logic values. Therefore, defining only the binary values of ADRfrom “000” to “111” does not exhaust its all possible values. For simplicity,the output has been made ‘X’ whenever ADR has anything other than a

Page 50: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

binary value i.e. ‘Z’ , ‘X’ etc. Another thing to be noted here is that althoughVHDL is not a case sensitive language, the enumerated literals are casesensitive. So, in the above example, if ‘X’ is replaced by ‘x’, then it will notwork. The use of ‘Z’ state for describing a tristate bus is illustrated in thefollowing example.--OCTAL BIDIRECTIONAL TRISTATE BUFFER (74LS245)library IEEE;use IEEE.std_logic_1164.all;

entity BIDIBUF8 isport ( A: inout std_logic_vector(7 downto 0);

B: inout std_logic_vector (7 downto 0);dir, en: in std_logic);

end BIDIBUF8;architecture DF of BIDIBUF8 isbegin

A <= B when dir='0' and en ='0' else "ZZZZZZZZ";B <= A when dir='1' and en= '0' else "ZZZZZZZZ";

end DF;

Another way of implementing a mux by using a tristate bus is shown below.

--MUX using tristate logiclibrary IEEE;use IEEE.std_logic_1164.all;

entity MUX4 isport(I0,I1,I2,I3,S0,S1:in std_logic;

Y :out std_logic);end MUX4;architecture DF2 of MUX4 isbegin

Y<= I0 after 5 ns when S1='0' and S0='0' else'Z' after 5 ns;Y<= I1 after 5 ns when S1='0' and S0='1' else'Z' after 5 ns;Y<= I2 after 5 ns when S1='1' and S0='0' else'Z' after 5 ns;Y<= I3 after 5 ns when S1='1' and S0='1' else'Z' after 5 ns;

end DF2;

In the above program Y is a multiwriter signal and it is resolved by the std_logicresolution function.It is important to remember that the conditions in the selected conditional assignmentstatement must be mutually exclusive. E.g. consider following statements.-- c is bit vector

with c selecte<= "01" when "10" ,

"10" when "11" ,"11" when "00"|"10" ,

Page 51: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

"00" when others;This program will produce a compiler error because the condition “10” is repeated.3.3 BLOCK statement

BLOCK is a concurrent statement. It is used for following 3 purposes:1.Specifying a common enabling condition for a set of assignment statements.2.Partitioning a design unit.3.Limiting the scope of variables within a block.The syntax of BLOCK is:<Label>:block [<guard expression>]

[<local signal declarations>]begin

<Concurrent statements>end block [Label];Most synthesis tools do not support the BLOCK statement and hence it should be usedonly for non-synthesizable programs like test benches. The guard expression mustevaluate to a Boolean value. The statements within the block can use the guard conditionby using the “guarded” keyword. Following examples will clarify the use of BLOCKstatement.--Transparent Latchentity TLATCH is

port(D,CLK: in BIT; Q: out BIT);end TLATCH;architecture DF of TLATCH isbegin

B:block(CLK=’1’ )Begin

Q<= guarded D;End block B;

End DF;

--+ve edge triggered Quad D flipflopentity DFF is

port(D1,D2,D3D4,CLK: in BIT; Q1,Q2,Q3,Q4: out BIT);end DFF;architecture DF of DFF isbegin

B:block(CLK=’1’ and CLK’event )Begin

Q1<= guarded D1;Q2<= guarded D2;Q3<= guarded D3;Q4<= guarded D4;

End block B;End DF;

3.4 IF statementIF is a sequential statement and hence it can not be used in the concurrent part of

a program. IF statement has following three forms:

Page 52: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

1. if <Boolean expression> then <statements> end if;2. if <Boolean expression> then <statements> else <statements> end if;3. if <Boolean expression> then <statements> elsif <Boolean expression> then <statements> elsif<Boolean expression> then <statements> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - else <statements> end if;In the first form, if the Boolean expression evaluates to TRUE then the following

set of statements upto “end if” are executed, otherwise no action is taken. In the secondform, if the Boolean expression does not evaluate to TRUE, then the second set ofstatements is executed. In the third form, the Boolean expressions are evaluatedsequentially and when a first TRUE expression is found, the corresponding set ofstatements is executed. The same job could also be done by using nested if statements butthe advantage of using the third form is that it requires a single “end if” clause. This formresults in a priority encoder type of structure.3.5 Modeling of sequential circuits

VHDL has been designed in such a way that a programmer can write code in ahigh level language without bothering about its actual implementation. Accordingly,there is no explicit instruction to indicate whether a given signal is latched or not. Thesynthesis tool automatically “infers” a latch when we specify an enabling condition in anassignment statement. If the condition refers to a clock’s edge then it implies an edge-triggered flipflop. If the condition refers to a clock’s level then it implies a transparentlatch. A sequential circuit can be described either in concurrent part or in sequential part.In either case, the synthesis tool requires that the clock edge expression should not bemixed with other conditions. The modeling techniques for sequential circuits will be clearfrom the following examples.

Gated SR Latch

S S_BARQ

CLK R_BAR Q_BAR

R

Fig 3.1 Gated SR latch

The VHDL program for modeling this latch in dataflow style is as follows.entity RSLATCH is

port (R,S,CLK:in BIT;Q,Q_BAR:out BIT);end RSLATCH ;

architecture DATAFLOW of RSLATCH issignal S_BAR,R_BAR,INT_Q,INT_Q_BAR:BIT;

beginS_BAR <= S nand CLK ;

Page 53: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

R_BAR <= R nand CLK ;INT_Q <= S_BAR nand INT_Q_BAR ;INT_Q_BAR <= R_BAR nand INT_Q ;

Q <= INT_Q;Q_BAR <= INT_Q_BAR;

end DATAFLOW;Since Q and Q_BAR are output ports, their value can not be sensed. So the

intermediate signals INT_Q and INT_Q_BAR have been created. The above programworks well as long as R and S are not ‘1’ together. If we start simulation with R=S=‘1’and give a pulse on clock, then the simulator hangs because, when CLK is low and theinitial values of Q and Q_BAR are both low, the two nand gates at the output latch forman infinite loop. The hanging problem can be solved if Q_BAR is initialized to ‘1’.However if you are designing for synthesis, then initialization must be avoided becauseinitialization has no hardware counterpart. Instead of initialization, an asynchronous resetshould be used. If we introduce a delay in the assignment statements as follows then thereis no hanging problem but the Q and Q_BAR waveforms show a square wave of 10 nsperiod.S_BAR <= S nand CLK after 5 ns;R_BAR <= R nand CLK after 5 ns;INT_Q <= S_BAR nand INT_Q_BAR after 5 ns;INT_Q_BAR <= R_BAR nand INT_Q after 5 ns;

If the last statement is changed as follows, then there is no oscillation on Q.INT_Q_BAR <= R_BAR nand INT_Q after 6 ns;

D flip flop

Fig 3.2D type flip flop

A D type flipflop can be modeled as follows.entity DFF is

port (D,CLK,RESET_BAR:in BIT;Q:out BIT);end DFF ;architecture DATAFLOW of DFF is

D Q

D FLIP FLOP

CLK RST_BAR

Page 54: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

signal INT_Q:BIT;begin

INT_Q <= '0' when RESET_BAR='0' else D when CLK'event and CLK='1' else INT_Q;

Q <= INT_Q;end DATAFLOW;The concurrent conditional assignment statement requires that the else part of the

condition must be given. The else part reassigns the old value of the latched signal. SinceQ is an output port signal, it can not be read, so it is necessary to create an intermediatesignal INT_Q, which can be both read and written to. A concurrent statement at the endtransfers the value of INT_Q to Q. Instead of creating an intermediate signal, we couldhave achieved the same result by declaring the signal Q in either buffer or inout mode.But declaring a signal as inout is implemented by the synthesizer as a bi-directionaltristate buffer, which is not our intention here. Declaring it as inout has twodisadvantages. Firstly, many synthesis tools treat buffered signal as an inout signal.Secondly, when we use this entity as a component in another design, then the clientprogram must specify the matching port mode. Declaring an output signal as bufferincreases the chances of mistakes and confusion. Therefore the method of creatingintermediate signals is quite popular.

The above program runs all right on a simulator but does not work with asynthesizer. The reason being that the synthesis tool does not accept any assignments inthe else part of a clock edge expression. The best way to describe a flipflop is to embed itin a process as shown below.

entity DFF isport (D,CLK,RESET_BAR:in BIT;Q:out BIT);

end DFF ;architecture PROC of DFF isbegin

process(D,CLK,RESET_BAR)begin

if RESET_BAR='0' then Q <= '0';elsif CLK'event and CLK='1' then Q <= D;end if;

end process;end PROC;

T Flip flopThe following program is a synthesizable model of a T (toggle) flipflop.

entity TFF isport (T,CLK,RESET_BAR:in BIT;Q:out BIT);

end TFF ;

architecture BEH of TFF issignal INT_Q:BIT;begin

process(CLK,RESET_BAR)begin

Page 55: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

if RESET_BAR='0' then INT_Q <='0';elsif CLK'event and CLK='1' then

if T='1' then INT_Q <=not INT_Q;end if;end if;

end process;Q <= INT_Q;

end BEH;JK Flip flopThe following program is a synthesizable model of a master-slave JK flipflop.

entity JKFF isport (J,K,CLK,RESET_BAR:in BIT;Q:out BIT);

end JKFF ;architecture BEH of JKFF is

signal MQ,INT_Q:BIT;-- MQ= Master Q, INT_Q= intermediate slave Qbegin

process(J,K,CLK,RESET_BAR,INT_Q,MQ)begin

if RESET_BAR = '0' then MQ<='0'; INT_Q <='0';elsif CLK='1'then

if J='0' and K='1' then MQ<='0';elsif J='1' and K='0' then MQ<='1';elsif J='1' and K='1' then MQ<=not INT_Q;end if;

end if;if clk='0' then INT_Q<=MQ ; end if;

end process;Q<=INT_Q;

end BEH;Synchronous 4 bit counter (74163)

The 74163 IC is a Synchronous 4 bit counter with the facility of a parallel load. Ithas an asynchronous reset input and two count-enable inputs namely EN_P and EN_T. Italso has one terminal count output TC that goes high when all the four flip flops are in ahigh state. The following program shows a dataflow type modeling of this IC. The datatype has been chosen as std_logic because we want to do addition operation on COUNT.The library std_logic_unsigned contains the required overloaded function.

P3 P2 P1 P0

CLKRESET_BAR LOAD_BAR COUNTER 74163 TC

EN_PEN_T

Page 56: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Q3 Q2 Q1 Q0

Fig 3.34 bit presettable synchronous counter

library IEEE;use ieee.std_logic_1164.all;use ieee.std_logic_unsigned.all;--COUNTER 74163entity CNT123 is

port (P:in std_logic_vector(3 downto 0);CLK,EN_P,EN_T,RESET_BAR,LOAD_BAR:in std_logic;Q: out std_logic_vector(3 downto 0);TC:out std_logic);

end CNT123 ;

architecture DATAFLOW of CNT123 issignal INT_COUNT:std_logic_vector(3 downto 0);

beginINT_COUNT<= "0000" when RESET_BAR='0' else

P when CLK'event and CLK='1' and LOAD_BAR='0' elseINT_COUNT+1 when CLK'event and CLK='1'

and EN_P='1' and EN_T='1' elseINT_COUNT;

TC <= '1' when INT_COUNT="1111" else '0';Q <= INT_COUNT;

end DATAFLOW;

In the above program, the objects have been instantiated from the std_logic class becausewe want to take advantage of the “+” function defined in the std_logic_unsigned library.This design is not synthesizable due to the assignment in the else part of a clock edgeexpression. A synthesizable version using a process statement is given below.

library ieee;use ieee.std_logic_1164.all;use ieee.std_logic_unsigned.all;--COUNTER 74163entity CNT123 is

port (P:in std_logic_vector(3 downto 0);CLK,EN_P,EN_T,RESET_BAR,LOAD_BAR:in std_logic;Q: out std_logic_vector(3 downto 0);TC:out std_logic);

end CNT123 ;

architecture BEH of CNT123 issignal INT_COUNT:std_logic_vector(3 downto 0);

Page 57: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

beginprocess(clk,reset_bar,en_p,en_t,load_bar)begin

if RESET_BAR='0' then INT_COUNT<= "0000";elsif CLK'event and CLK='1' then

if LOAD_BAR='0' then INT_COUNT<= P;elsif EN_P='1' and EN_T='1' then INT_COUNT<=

INT_COUNT+1 ;end if;

end if;end process;TC <= '1' when INT_COUNT= "1111" else '0';Q <= INT_COUNT;

end BEH;

1K X 8 RAM1K X 8 RAM can be easily implemented as an array of std_logic_vectors. The addressinput acts as the index of the array. The address must be converted into integer by theconv_integer function so that it is accepted as an index. Notice that in the port definition,ADR has been given a default value of all zeroes. This is to avoid assertion errors at thestart of simulation. Remember that all concurrent statements are executed once at t=0using the initialized values. If we do not specify default for ADR, then conv_integerfunction is called with X values on ADR, which results in assertion error. Thisinitialization should be removed for synthesis otherwise synthesizer will give a warning.

library ieee;use ieee.std_logic_1164.all;use ieee.std_logic_unsigned.all;--RAMentity RAM1K is

port (ADR:in std_logic_vector(9 downto 0):=(OTHERS=>'0');CS_BAR,OE_BAR,WR_BAR:in std_logic;D:inout std_logic_vector(7 downto 0));

constant acc_time:time:=50 ns;end RAM1K ;architecture DATAFLOW of RAM1K istype RAM_ARRAY is array(0 to 1023) of std_logic_vector(7 downto 0);signal RAM:RAM_ARRAY;begin

D<=RAM(conv_integer(ADR)) after acc_time when CS_BAR='0' andOE_BAR='0' else (others=>'Z');RAM(conv_integer(ADR)) <= D when CS_BAR='0' and WR_BAR='0' else

RAM(conv_integer(ADR)) ;end DATAFLOW;

3.6 MODELING OF FINITE STATE MACHINES

Page 58: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Finite-state machine (FSM) is an important area in digital logic design.FSMs are commonly used as controllers or sequence detectors in a digitalsystem. A finite state machine can be described in terms of followingstructures.1. A set of inputs X.2. A set of outputs Z.3. A finite length state table enumerating valid states.4. Specifying which is the initial state.5. A Boolean Function NS(S,X) which maps present state S to next state NS.6. An output function F(S,X) which calculates Z from S and X in Mealy machines and

F(S) in case of Moore machines.EXAMPLE: SEQUENCE DETECTORConsider a single input single output FSM which gives an output=’1’ whena sequence “1011” is received on its input. Overlapping sequences areallowed. The state transition diagram for implementing this sequencedetector is given in fig 3.4.

0/0

0/0

1/1 1/0 1/1 0/0

1/0

1/0 0/0

Fig 3.4State diagram for 1011-sequence detector

The standard way of modeling a FSM is as follows.1. Define an enumerated data type to represent valid states. The actual code assignment

to the states is left to the synthesis tool. The encoding may be binary, gray code, onehot or one cold. Define signals PRESENT_STATE and NEXT_STATE belonging tothe enumerated state class.

2. Define one process for the memory elements which makes PRESENT_STATE as theinitial state if RESET is active else with the rising edge of the clock, it assigns theNEXT_STATE to the PRESENT_STATE.

3. Define either a concurrent statement with “when else” logic or a process with “case”logic which determines the NEXT_STATE based on the present state and the presentinput X.

4. Define either a concurrent statement with “when else” logic or a process with “case”logic which determines the output Z. In case of a mealy machine, Z depends on the

RESET

GOT1GOT10

GOT101

Page 59: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

present state and the present input X. In case of a moore machine, Z depends only onthe present state.

VHDL code for modeling the above FSM is given below.

--FINITE STATE MACHINE TO DETECT 1011 SEQUENCEentity FSM1011 is

port(RST,X,CLK :in BIT; Z: out BIT);end FSM1011;architecture DF of FSM1011 is

type STATE_TABLE is(RESET,GOT1,GOT10,GOT101);signal STATE,NEXT_STATE : STATE_TABLE;

beginprocess(CLK,RST,X)beginif(RST='1')then STATE <= RESET;elsif(CLK'event and CLK='1') then

STATE<=NEXT_STATE;end if;

end process;NEXT_STATE <= RESET when STATE=RESET and X='0' else

GOT1 when STATE=RESET and X='1' else GOT10 when STATE=GOT1 and X='0' else GOT1 when STATE=GOT1 and X='1' else RESET when STATE=GOT10 and X='0' else GOT101 when STATE=GOT10 and X='1' else GOT10 when STATE=GOT101 and X='0' else GOT1 ; --when STATE=GOT101 and X='1' ;

Z <= '1' when STATE= GOT101 and X='1' else'0';

end DF;

To test the FSM, use the following command file.

restartwave fusion.vwf rst clk x z state next_stateclock clk 0 1h rstsiml rstsimh xcyclel xcycleh xcycle

Page 60: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

cycle

3.7 GUIDELINES FOR SYNTHESISAs of today, there is no standard way to tell which VHDL statements are

synthesizable. IEEE is working to define a synthesizable subset of VHDL. Till thisstandard is released and adopted by the synthesis tool vendors we have to go by certainrules of thumb. Following guidelines will work with most synthesis tools.

1. Avoid initialization.A statement like signal A:BIT:=0; has no hardware counterpart and hence should beavoided. Instead of initialization, the memory elements should be initialized withasynchronous reset or preset signals.2. Completely specify all possibilities.In conditional assignments if all possibilities are not specified, it means that the old valueshould be carried forward. E.g.X <= ‘0’ when Y=’1’;In this case, if Y happens to be ‘0’, then X should retain its old value. The synthesis toolinfers a latch in this case. If you don’t want a latch, then you must specify all thepossibilities. In std_logic, it is not sufficient to specify the action for states ‘0’ and ‘1’alone, as there are 9 possible logic states.Similarly in case statements (discussed later) specify all cases or default.3. Don’t use physical data types like time.Synthesis tools do not support physical types. Delay specs are generated by thesynthesizers through their own low-level tools.4. Include every signal on the RHS of a process block in sensitivity list.By not doing so, you run the risk of missing some transitions. FPGA express generates awarning message if this rule is violated.5. Don’t mix edge expression with other conditions.A synthesis tool infers a synchronous flip flop from an edge expression like-Clk’event and clk=’1’Clk’event and clk=’0’Clk=’1’ and not clk’stableFollowing statement is likely to give trouble.If(clk’event and clk=’1’ and Y=’0’) then Q <= D; end if;

6.Don’t combine positive and negative edge triggered flip-flops in a single process or ablock.Following code will give trouble.Process(clock, X,Y)Begin

If(clock’event and clock=’1’) then Q1 <= X ; end if;If(clock’event and clock=’0’) then Q2 <= Y ; end if;

End process;Separate them out into two different processes.Also don’t use more than one edge-expressions in a single process.7. Don’t assign a value in the FALSE branch of an edge expressionConsider the statement.

Page 61: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

If(clk’event and clk=’1’) then Q<=X; else Q<=’Y’; end if;This means Q should receive Y in absence of an edge. This has no hardware equivalent.

Sometimes this type of error takes subtle forms. E.g. consider following statements.Q_PROC:process(RST, CLK, D)begin

If RST = ‘1’ then Q<=’0’; end if;If CLK’event and CLK=’1’ then Q<=D;end if;

End process Q_PROC;Here, the first statement assigns ‘0’ to Q in absence of clock edge and

therefore the synthesizer will flag this as an error. It can be corrected as follows.Q_PROC:process(RST, CLK, D)begin

If RST = ‘1’ then Q<=’0’;elsif CLK’event and CLK=’1’ then Q<=D;end if;

End process Q_PROC;

8. Don’t use edge expression as an operandFollowing is invalid.If ( not (clk’event and clk=’1’)) then …

3.8 PRACTICAL SESSION WITH FPGA EXPPRESS

The ultimate aim of any VHDL design process is synthesis. Some synthesis tools aretailored to a particular device family. Some tools like FPGA Express can take care of awide range of FPGA’s. Ambit is suitable for ASIC design. A synthesis tool converts aVHDL source code into another VHDL code but described in a structural style usingcomponents available in the target device. It also produces some files for use by the backend tool, which actually does layout and routing. For small designs, one may blindlychoose any FPGA and still produce successful design. But for larger designs, it isnecessary to be familiar with the architecture of the target FPGA.

PROCEDURE

a. First create a simulation project called DECODER using the code given above.b. Debug and simulate it on VWaves. Close speedwave.c. Click on FPGA Express icon to open FPGA screen.d. Click File New to open “Create FPGA project “ window.e. Enter project directory as FPGA within DECODER directory.f. Browse and identify the source file decoder.vhd. The work window with two panes

opens up.g. Right click on decoder.vhd to invoke pop up box and select “create implementation”.

The create implementation dialog box opens up.h. Select vendor as XILINX, Family as XC3000, Device as 3020ACB100 and leave the

other items at their default values. Click OK.i. An entry appears in the chips pane. Right click on it and select optimize chip.j. Another entry appears in the chips pane. Right click and select export netlist option.

Set output format as VHDL and specify dec_fpga.vhd as filename in the decoder\fpgadirectory. Click OK.

Page 62: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

k. Right click and select chip report option. Specify chip.txt as filename in thedecoder\fpga directory. Click OK. Open the report in any text editor and see theresults.

l. Open SpeedWave and start VHD manager. Click on add source file icon and add thenew source file dec_fpga.vhd. Analyze and simulate it.

m. In the next section we will discuss the use of a back end tool.

EXERCIZES

E3.1 Plot the waveforms of signals a, b and c in the following program.entity try isend try;

architecture DATAFLOW of try issignal a, b: bit;signal c: bit_vector(1 downto 0);begin

a <= '1' after 10 ns,'0' after 30 ns;b <= '1' after 20 ns,'0' after 40 ns, '1' after 50 ns;c <= "01" when (a = '1')else

"10" when (a and b)= '1' else"11" when (b = '0') else"00";

end DATAFLOW;

E3.2 Write the code for a 8 bit switchtail counter. I.e. an 8 bit shift register where the bit0 is inverted and fed to the D input of the bit 7.

E3.3 Write the code for a 4 bit mobius counter. I.e. an 8 bit shift register where the bits 0and 1 are XOR’ed and fed to the D input of the bit 7. Verify by simulation that thecounter cycles 15 states, i.e. all states except 0000.E3.4 Write VHDL code for a 4 bit carry look-ahead adder.

ANSWERS

E3.1

a 10 20 30 40 50

b

11 01 00 11 00

Page 63: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

c

E3.4-- 4 bit Look ahead adderentity LA_ADDER4 is

port (A,B: in BIT_VECTOR(3 downto 0);Cin:in BIT;S:out BIT_VECTOR(3 downto 0);Cout:out BIT);

end LA_ADDER4;architecture DF of LA_ADDER4 is

signal G0,G1,G2,G3,C1,C2,C3,P0,P1,P2,P3: BIT;begin

G0<=A(0) and B(0);G1<=A(1) and B(1);G2<=A(2) and B(2);G3<=A(3) and B(3);P0<=A(0) xor B(0);P1<=A(1) xor B(1);P2<=A(2) xor B(2);P3<=A(3) xor B(3);C1<=G0 or (P0 and Cin);C2<=G1 or (G0 and P1) or (P0 and P1 and Cin) ;C3<=G2 or (G1 and P2)or (G0 and P1 and P2) or (P0 and P1 and P2

and Cin) ;Cout<= G3 or (G2 and P3) or (G1 and P1 and P2)

or (G0 and P1 and P2 and P3) or (P0 and P1 and P2 and P3and Cin) ;

S(0)<= P0 xor Cin;S(1)<= P1 xor C1;S(2)<= P2 xor C2;S(3)<= P3 xor C3;

end DF;

Page 64: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

CHAPTER 4

STRUCTRAL of description

4.1 Component declaration, instantiation and configuration

In a structural description, the chip is modeled as an interconnection of an

available repertory of components. Structural description can be either a starting

point for a bottoms-up design or an end point for a top-down design.

One can create smaller components and immediately use them in a bigger

component in a single source file. Alternatively a library of commonly used parts can be

made and kept ready for inclusion in top level design files. If the components belong to

the same project, then “use work.all” instruction takes care of the linkage If the

components have been created in another library, then that library must be included using

the “library” statement.

Declaration:

All the components that you propose to use in the design have to be declared in

the architecture declaration zone, i.e. between the architecture and the begin keywords.

The component name need not be identical to the entity name in the library. In other

words, the component declarations only represent IC sockets on a PCB. What IC is to be

plugged in it is determined by the optional “configuration statement”. The configuration

statement is not required if the name of a component is found in the library search path. If

the detected entity has a unique architecture, then naturally it is selected for inclusion.

However if there are multiple architectures, then the most recently analyzed architecture

is selected. You can of course override the default choice of the architecture by a suitable

configuration statement.

Syntax of component declaration is as follows:

Component <entity name> port (<port definition>); end component;

For example:

Component XOR3 port (i1, i2, i3, i4: in std_logic; o: out std_logic); end component;

Unless you are using a configuration statement, the port definition must be identical to

the port definition given in the component library.

Instantiation:

Page 65: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

In the architecture body, i.e. after “begin”, the components are instantiated. . The

instantiation defines the component id-number and its port map. The id-number gives a

unique identification to the instance. E.g. IC1, IC2, ANDGATE1, ANDGATE2.The port

map defines the connection between the component port signals and the external signals

i.e. it describes how the component is wired to other entities. Any number of copies of

the same component can be instantiated by having multiple instantiation statements. The

component instantiation statement may be thought of as a concurrent procedure call. The

procedure gets invoked whenever an event occurs on one or more of the input signals of

the component.

The association between external signals to internal signals of the component can be done

either by a positional association statement or by a named association statement.

I) Syntax of positional association

In a positional association, the outer circuit signals are associated to the

component port signals serially.

CompId : EntityName port map(Sig1, Sig2, ….);

Where Sig1, Sig2 etc are the names of the outer signals (schematic signals) that are

connected to the port pins of the entity. For example, consider that the 4 input XOR gate

declared above is being used to generate even parity for a 4-bit vector “a”.

IC1: XOR3 port map (a(0), a(1), a(2), a(3), ParityOut);

Syntax of named association:

In a named association, you have to specify the association between internal and external

signals explicitly. The order is immaterial. The syntax is:

CompId : EntityName port map(PortSig1=>Sig1, PortSig2=>Sig2, ….);

The XOR3 component in the above example can be instantiated using named association

as follows:

IC1: XOR3 port map (o=>ParityOut, i1=>a(0), i3=>a(3), i2=>a(2), i1=>a(1));

Unconnected pins:

Sometimes we may decide to keep some pins of the component unconnected.

Such pins are associated with “open” key word in the port map. Output pins may be

freely associated with “open”. Input pins can be left open only if their default values are

defined in the port clause in the entity declaration.

Page 66: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Design Example - Full adder from half adders:

We know that a full adder can be constructed from two half adders and one

OR gate. We will first design a half adder component named HA and a 2-input OR

gate OR2. The port definition for HA is as follows:

Port (a, b: in std_logic; s, c: out std_logic);

The port definition for OR2 is as follows:

Port (i1,i2: in std_logic; o: out std_logic);

As shown in fig 4.1, we can realize a full adder from the above components.

a s

b

c

HALF ADDER

S1

x s

s

y

c2 co

c1

c1

Figure 4.1

Full adder from half adders

a s HA1

b c

a s

HA2b c

Page 67: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

From the above figure, the port definition of the full adder can be derived as follows.

Port (x, y, ci: in std_logic; sum, co: out std_logic);

For wiring the components, we need to create the intermediate signals s1, c1 and c2.

These signals appear in the port maps during the component instantiations. The complete

VHDL program for realizing a full adder is given below.

--HALF ADDER (USED FOR FULL ADDER)

library ieee;

use ieee.std_logic_1164.all;

entity HA is

port(a,b:in std_logic;s,c:out std_logic);

end HA;

architecture dataflow of HA is

begin

s<= a xor b;

c<= a and b;

end dataflow;

library ieee;

use ieee.std_logic_1164.all;

entity OR2 is

port(i1,i2:in std_logic;o:out std_logic);

end OR2;

architecture dataflow of OR2 is

begin

o<= i1 or i2;

end dataflow;

--STRURAL DESCRIPTION OF FULL ADDER

library ieee;

use ieee.std_logic_1164.all;

entity FA is

port(x,y,ci:in std_logic;sum,co:out std_logic);

Page 68: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

end FA;

architecture struct of FA is

component HA port(a,b:in std_logic;s,c:out std_logic);end component;

component OR2 port(i1,i2:in std_logic;o:out std_logic);end component;

signal s1,c1,c2:std_logic;

begin

HA1:HA port map(x ,y ,s1 ,c1);

HA2:HA port map(s1,ci,sum ,c2);

ORG:OR2 port map(c1,c2,co);

end struct;

4.2 CONFIGURATION STATEMENT

Sometimes multiple architectures for the same entity are available and we

have to choose one particular architecture for our design. Sometimes we also have to

choose between various alternative entities. For example, suppose an alternate

architecture of half adder is available or the component is defined in the library as

HALF_ADD. In such case, we need to use a configuration statement in the declaration

zone i.e. after component declaration and before “begin”. Following examples

illustrate the various forms of configuration. If the names of the port-signals and

their order are different, then they can be matched properly by using a named

association in the configuration statement.

Syntax:

For <Component Id>:<Component name> use <entity name>(<architecture name>)

[port map(LibSignalName1=>CompSignalName1, …)];

In the place of <ComponentId> we may give actual ComponentId or use the

keywords “others” and “all”. We may also give a list of ComponentId’s if more

than one instances should share the same entity. The port map clause should be

included if the names or the order of the port signals in the library differ from

those in the component declaration. This feature is very useful when we want to

use different entities for a component and the naming conventions in each library

are different. If the entity name is likely to be defined in more than one library,

Page 69: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

then we can prefix the library name to the entity name e.g. MyLib.AndGate.

Suppose there are following definitions for half adder in the library and we require

many instances of HA in our design.

entity and2 is

port(i1,i2: in BIT ;o : out BIT) ;

end and2;

architecture DF of and2 is

begin

o<= i1 and i2;

end DF;

entity xor2 is

port(i1,i2: in BIT ;o : out BIT) ;

end xor2;

architecture DF of xor2 is

begin

o<= i1 xor i2;

end DF;

entity HA is

port(a, b :in BIT; s, c: out BIT);

end HA;

architecture dataflow of HA is

begin

s<= a xor b;

c<= a and b;

end dataflow;

Page 70: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

architecture struct of HA is

component and2 port (i1,i2: in BIT ;o : out BIT); end component;

component xor2 port (i1,i2: in BIT ; o: out BIT); end component;

begin

A1: and2 port map (a, b, c);

X1: xor2 port map (a, b, s);

end struct;

--This definition is in library COMP_LIB

entity HALF_ADD is

port(sum, cy: out std_logic; x, y: in std_logic;);

end HALF_ADD;

architecture DF of HALF_ADD is

begin

sum <= x xor y;

cy <= x and y;

end DF;

Following statements illustrate the use of various types of configuration statements.

For all: HA use entity HA (dataflow);-- bind entity for ALL instances of the component

For HA1: HA use entity HA (struct);

For others: HA use entity HA (dataflow);-- for instances other than the HA1 instance

For HA1, HA2: HA use entity HA (dataflow);-- for HA1 and HA2 instances

For HA1: HA use entity COMP_LIB.HALF_ADD (DF)

port map (x => a, y => b, sum => s, cy => c);

4.3 Configuration declaration

Page 71: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

If the configuration statement is given in the architecture body, then the

entity assignment can not be changed unless we edit and reanalyze the

architecture. Sometimes we desire to have a “late binding” of entities to the

components, i.e. binding after the architecture is written and frozen. This can be

achieved by writing all configuration specifications in a separate design unit

called configuration declaration. The syntax of a configuration declaration is as

follows.

Configuration <config name> of <entity name> is

Block1

Block2

- - -

End [<config name>];

Where each block refers to a corresponding architecture. The block syntax

is:

For < arch name>

For <Component Id1>:<Component name1>

use <entity name1>(<architecture name1>)

[port map(LibSignalName1=>CompSignalName1, …)];

end for;

For <Component Id2>:<Component name2>

use <entity name2>(<architecture name2>)

[port map(LibSignalName1=>CompSignalName1, …)];

end for;

- - - - - - - - -

end for;

The configuration declaration for full adder can be written as follows.

Configuration MYCONFIG of FA is

For struct

Page 72: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

For H1: HA use entity HA (dataflow); end for;

For H2: HA use entity COMP_LIB.HALF_ADD (DF)

port map (x => a, y => b, sum => s, cy => c);

end for;

For ORG: OR2 use entity OR2 (dataflow); end for;

End for;

End MYCONFIG;

Sometimes the top-level design consists of many levels of nesting of components. The

same nesting structure should be reflected in the configuration declaration. Consider the

following example.

Configuration NESTCONFIG of FA is

For struct

For H1: HA use entity HA (dataflow); end for;

For H2: HA use entity HA (struct)

For DF

For A1: and2 use and2 (DF);

For X1: xor2 use xor2 (DF);

End for;

end for;

For ORG: OR2 use entity OR2 (dataflow); end for;

End for;

End NESTCONFIG;

4.4 GENERATE STATEMENT

In digital design, we often come across situations where one entity is replicated

several times and wired in a systematic way. E.g. generating an n-bit ripple-counter

from n T flip-flops, n-bit shift register from n D flip-flops, word-adder from a 16

bit-adders etc. Such systems are called iterative networks. VHDL provides a

powerful statement named “generate” to take care of such situations. The

“generate” statement can be used for replicating any set of concurrent statements.

Page 73: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Since component instantiation is a concurrent statement, “generate” statement can

be used for generating multiple copies of a component. The statement has two forms

namely “for … generate” and “if…generate”. The “if…generate” form is used for

conditional instantiation. As an example, let us consider that we have to create a

byte adder from 8 full adders. The port definition of the byte adder is:

Port (a, b: I n std_logic_vector (7 downto 0);cin :in std_logic;

s: out std_logic_vector(7 downto 0); cout: out std_logic);

Eight full adders can be connected as shown in fig 4.2.

a7 b7 a6 b6 a5 b5 a4 b4 a3 b3 a2 b2 a1 b1 a0 b0 cin

Cout s7 c6 s6 c5 s5 c4 s4 c3 s3 c2 s2 c1 s1 c0 s0

Fig 4.2

Byte adder from full adders

For realizing BA, we will need 8 copies of FA from FA0 to FA7. The Instances FA0

and FA7 have to be handled separately because their ports are connected to the

external ports of BA. The connections of the middle FA’s can be defined in an

iterative manner as follows.

FAm: FA port map (a(i),b(i),c(i-1),s(i),c(i));-- Where “i” is the position of the FA.

Where c (i) is an intermediate signal which is used to connect the carry-out of one stage

to the carry-in of the next stage. This has been declared in the architecture declaration

zone as:

signal c: std_logic_vector (6 downto 0);

FA FA FA FA FA FA FA FA

Page 74: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

This mapping can be achieved using a generate statement. The syntax of generate is:

GEN_LABEL: for LOOP_VAR in <range> generate

Concurrent statements

End generate [GEN_LABEL];

Note that the label is a must. The “generate” statement may be considered as a

MACRO, which gets elaborated at the time of simulation. For each replication, the value

of LOOP_VAR is substituted in the statement. This means that the range must be

globally static, i.e. computable at elaboration time.

This instantiation of full adders for a byte adder can be achieved as shown in the listing

below.

--BYTE ADDER

library ieee;

use ieee.std_logic_1164.all;

use work.all;

entity BA is

port(a,b:in std_logic_vector(7 downto 0);

cin :in std_logic;

s :out std_logic_vector(7 downto 0);

cout:out std_logic

);

end BA;

architecture structral of BA is

component FA

port(x,y,ci:in std_logic;sum,co:out std_logic);

end component;

signal c:std_logic_vector(6 downto 0);

begin

FA0 :FA port map(a(0),b(0),cin,s(0),c(0));

FAmid:for i in 1 to 6 generate

FAm:FA port map(a(i),b(i),c(i-1),s(i),c(i));

end generate;

Page 75: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

FA7 :FA port map(a(7),b(7),c(6),s(7),cout);

end structral;

The “if…generate” form can be used in the above example as follows.

FA_GEN: for i in 0 to 7 generate

If i = 0 generate FA0:FA port map(a(i),b(i), cin,s (i),c(i)); end generate;

If i >0 and I<7 generate FAm:FA port map(a(i),b(i),c(i-1),s(i),c(i)); end generate;

If i =7 generate FA7:FA port map(a(i),b(i),c(i),s(i),cout); end generate;

end generate FA_GEN;

Not that the “if…generate” form does not have provision for else or elsif clauses.

Use of libraries:

If we are using numbers with less than or equal to 32 bits in length, then the IEEE

library functions can be conveniently used for realizing arithmetic circuits. The “+”

operator automatically realizes an adder. However the carry in and carry out

implementation requires special attention. The length of the result of addition is equal to

the length of the larger of the two operands. We have to force the result to be 9 bits by

appending a ‘0’ bit to one of the operands and then treat the 9’th bit as carry out. An

alternative architecture for BA based on libraries is given below.

architecture LIB of BA is

signal sum: out std_logic_vector(8 downto 0);

begin

sum <= (“0”&A) + B + cin;

s <= sum(7 downto 0);

cout <= sum(8);

end LIB;

Let us consider another example where we want to interleave two nibbles A and B to

produce a byte C while each bit is XOR’ed with a signal X. The circuit to achieve this is

Page 76: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

given in fig 4.3. Let us use concurrent statements in a generate loop for implementing this

circuit.

a3 b3 a2 b2 a1 b1 a0 b0

X

c7 c6 c5 c4 c3 c2 c1 c0

Fig 4.3

Illustration of generating concurrent statements

Signal A,B: bit_vector (3 downto 0);

Signal C : bit_vector (7 downto 0);

Signal X : bit;

LABEL1: for I in 3 downto 0 generate

C (2*I+1) <= A (I) xor X;

C (2*I) <= B (I) xor X;

End generate LABEL1;

The “generate” statement can be nested to generate a 2 dimensional array. As an example

let us consider that we have two bytes A and B. We are interested in instantiating 256 and

gates which will produce AND of every bit of A with every bit of B. The code will be as

follows.

Signal A, B: bit_vector (7 downto 0);

Type tagAND_MATRIX is array (0 to 7, 0 to 7) of BIT;

Signal AND_MATRIX: tagAND_MATRIX;

Page 77: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

AND_GEN1: for i in 0 to 7 generate

AND_GEN2: for j in 0 to 7 generate

AND_MATRIX (i, j) <= A (i) and B (j);

End generate AND_GEN2;

End generate AND_GEN1;

8 Chip RAM module

In chapter 3 we have designed 1KX8 RAM chip and a 3:8 decoder. We can make

an 8KX8 RAM module using these components. The VHDL code for this is given below.

Note that the decoder has been modified to produce active low outputs. Also note that the

ADDR input has been initialized to zeroes to avoid assertion errors at t=0.

--RAM1K-------------------------------------------------------------

library ieee;

use ieee.std_logic_1164.all;

use ieee.std_logic_unsigned.all;

entity RAM1K is

port (ADR:in std_logic_vector(9 downto 0):=(OTHERS=>'0');

CS_BAR,OE_BAR,WR_BAR:in std_logic;

D:inout std_logic_vector(7 downto 0));

constant acc_time:time:=50 ns;

end RAM1K ;

architecture DATAFLOW of RAM1K is

type RAM_ARRAY is array(0 to 1023) of std_logic_vector(7 downto 0);

signal RAM:RAM_ARRAY;

begin

D<=RAM(conv_integer(ADR)) after acc_time when CS_BAR='0' and

OE_BAR='0' else

(others=>'Z');

RAM(conv_integer(ADR)) <= D when CS_BAR='0' and WR_BAR='0' else

RAM(conv_integer(ADR)) ;

Page 78: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

end DATAFLOW;

--DECODER-----------------------------------------------------------

library ieee;

use ieee.std_logic_1164.all;

entity DECODER is

port(ADR : in STD_LOGIC_VECTOR(2 downto 0):="000";

Y: out STD_LOGIC_VECTOR (7 downto 0));

End DECODER;

Architecture DF of DECODER is

Begin

With ADR select

Y<= "11111110" when "000",

"11111101" when "001",

"11111011" when "010",

"11110111" when "011",

"11101111" when "100",

"11011111" when "101",

"10111111" when "110",

"01111111" when "111",

"XXXXXXXX" when others;

End DF;

--RAM8 --------------------------------------------------------------

library ieee;

use ieee.std_logic_1164.all;

use ieee.std_logic_unsigned.all;

use work.all;

entity ram8 is

port(MEMR_BAR,MEMW_BAR : in std_logic;

ADDR : in std_logic_vector(12 downto 0):=(OTHERS=>'0');

DATA : inout std_logic_vector (7 downto 0));

end ram8;

Page 79: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

architecture struct of ram8 is

component RAM1K

port(ADR:in std_logic_vector(9 downto 0):=(OTHERS=>'0');

CS_BAR,OE_BAR,WR_BAR:in std_logic;

D:inout std_logic_vector(7 downto 0));

end component;

COMPONENT DECODER

port(adr : in std_logic_vector(2 downto 0);

y : out std_logic_vector(7 downto 0));

end COMPONENT;

SIGNAL CS: STD_LOGIC_VECTOR (7 DOWNTO 0);

Begin

DECODER1 : DECODER PORT MAP (addr(12 downto 10), CS);

RAM:for i in 0 to 7 generate

GENRAM: RAM1K port map(ADDR(9 downto

0),CS(i),MEMR_BAR,MEMW_BAR, DATA);

end generate;

end struct;

A command file for testing this module is given below.

restart

wave ram.vwf ADDR CS MEMW_BAR MEMR_BAR DATA

A ADDR 0\H

A DATA 00\H

SIM 20NS

L MEMW_BAR

SIM 200NS

H MEMW_BAR

Page 80: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

SIM 20NS

A ADDR 400\H

A DATA 11\H

SIM 20NS

L MEMW_BAR

SIM 200NS

H MEMW_BAR

SIM 20NS

A ADDR 800\H

A DATA 22\H

SIM 20NS

L MEMW_BAR

SIM 200NS

H MEMW_BAR

SIM 20NS

A ADDR C00\H

A DATA 33\H

SIM 20NS

L MEMW_BAR

SIM 200NS

H MEMW_BAR

SIM 20NS

A ADDR 0\H

SIM 20NS

L MEMR_BAR

SIM 200NS

H MEMR_BAR

SIM 20NS

Page 81: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

A ADDR 400\H

SIM 20NS

L MEMR_BAR

SIM 200NS

H MEMR_BAR

SIM 20NS

A ADDR 800\H

SIM 20NS

L MEMR_BAR

SIM 200NS

H MEMR_BAR

SIM 20NS

A ADDR C00\H

SIM 20NS

L MEMR_BAR

SIM 200NS

H MEMR_BAR

SIM 20NS

4.5 GENERIC STATEMENT

The generic statement helps us to parameterize our design. With “generic”,

we can define a family of components having same architecture but different

parameters such as delays. The generic parameters have to be included in the entity

declaration. The declaration may optionally include default values for the

parameters. During the instantiation of a component, the generic parameter values

are supplied to the architecture by means of the “generic map” statement. Just as in

the port map case, the association between formal and actual parameters can be

done either positionally or by using a named association statement. If the in the

Page 82: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

component instantiation statement does not contain the generic map, then the

default values are used. The default values are also used when the generic map with

named association is present but some parameters have been left out. The syntax of

the “generic” statement is as follows.

Entity <entity name> is

Generic ( <ParName1>:<Data type1>[:=<Initial value1>];

<ParName2>:<Data type2>[:=<Initial value2>];

- - - - );

port (- - - - - - - - -);

end <entity name>;

Example

Entity INVERTOR is

Generic (tplh:time := 5 ns; tphl:time := 3 ns);

Port(I : in BIT; O : out BIT);

End INVERTOR;

Architecture GEN_DELAY of INVERTOR is

Begin

O <= ‘1’ after tplh when I=’0’ else ‘0’ when I=’1’;

End GEN_DELAY;

The generic parameter values are supplied in the instantiation statement as follows.

CompId:Compname generic map (---) port map(---);

Examples:

INV1 : INVERTOR generic map(7 ns,4 ns) port map(x,y);-- positional association

INV1 : INVERTOR port map(x,y);-- default values used for generic parameters

INV1 : INVERTOR generic map(tphl =>7 ns, tplh => 4 ns)

Port map(x,y); --named association

INV1 : INVERTOR generic map(tphl =>7 ns)

port map(x,y);-- default value used for tplh

MIXED MODELLING STYLE

Page 83: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

So far we have seen examples where architecture body contains only the

component instantiation statements. However VHDL allows you to freely introduce

assignment statements anywhere in the architecture body. As an example, let us

rewrite the full adder architecture mixed modeling style.

Entity FA is

Port (A, B, CIN: in BIT; SUM, COUT: out BIT);

End FA;

Architecture MIXED of FA is

Component OR3 port (I1, I2, I3: in BIT; O : out BIT); end component;

Signal C1, C2, C3, HALF_SUM: BIT;

Begin

C1 <= A and B;

C2 <= A and CIN;

C3 <= B and CIN;

CARRY_OR: OR3 port map (C1, C2, C3, COUT);

HALF_SUM <= A xor B;

SUM <= HALF_SUM xor CIN;

End MIXED;

4.6 PACKAGE

A designer would normally make groups of related reusable entities and use them in

future designs as required. VHDL package statement provides a convenient way to

form such groups. A Package is a primary design unit. Declarations in a package

may typically be any of the following: type, subtype, constant, file, alias, component,

attribute, function and procedure. When a procedure or function is declared in a

package, its body (the algorithm part) must be placed in the package body, which is

a secondary design unit of package. If the package does not contain procedures or

functions then it need not have a package body. Items declared in a package are

visible in the next design unit wherever selected via a “use” clause. If you want to

used a non standard data type as a port signal, the only way to do it is to define it in

a package and “use” it before the entity declaration.

The syntax of a package statement is as follows:

Page 84: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

package <package_name> is

<declarations>

end <package_name>;

A constant declared in a package may be deferred. This means its value is defined in

the package body. Re-analyzing only the package body may change the value:

Examples:

Example1

package P is

constant C : integer;

end P;

package body P is

constant C : integer := 200;

end P;

Example 2:

Package My_Pack is

Type COLOR is (RED, GREEN, BLUE);

Type LOGIC4 is (‘X’,’Z’,’0’,’1’);

Constant rise_time: time :=7 ns;

Constant fall_time: time :=3 ns;

End My_Pack;

The above package declaration contains only data type declarations and constant

definitions and therefore it is self-contained. It does not need a package body.

EXERCISES

P4.1 Modify the TFF architecture described in chapter 3 to include a 5ns delay

between clock and output. Combine 3 TFF’s to realize a divide by 8 ripple counter.

Connect output of this counter to a 3:8 decoder. Simulate the circuit. First give

Page 85: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

RESET and then give clock pulses to the counter. Observe the glitches on the

decoded output.

P4.2 Modify the design of the byte adder to provide overflow detection for 2’s

complement arithmetic.

P4.3 A 3X3 bit combinational multiplier for multiplying two numbers X and Y to

produce a result Z can be realized as follows. Write a structural VHDL program for

this.

X2Y0 X1Y0 X0Y0

X2Y1 X1Y1 X0Y1

X2Y2 X1Y2 X0Y2

Z5 Z4 Z3 Z2 Z1 Z0

P4.4 Design an N bit parity generator using an XOR gate in a generate statement.

Value of N should passed as a generic parameter with a default value of 8.

P4.5 Rewrite the description of basic gates and architecture struct of HA described

in sec 4.2 using generic parameters delay_and and delay_xor for the basic gates. The

generics should passed from the HA entity to the inner AND and XOR entities.

ANSWERS TO SELECTED PROBLEMS

P4.2 Note that overflow occurs when both operands are positive but the result is

negative and vice versa. Add following in the port declaration.

OverFlow: out BIT;

Add following in the architecture body.

OverFlow <= (A(7) and B(7) and (not C(7)) or ((not A(7)) and (not B(7)) and C(7));

P4.3

FA FA

FA FA

FA FA

Page 86: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

-- 3X3 combinational multiplier

entity FA is

port(a,b,c:in BIT:='0';s,co:out BIT);

end FA;

architecture DF of FA is

begin

s <= a xor b xor c;

co <= (a and b) or (a and c) or (b and c);

end DF;

use work.all;

entity COMBMULT is

port (X,Y: in BIT_VECTOR(2 downto 0); Z: out BIT_VECTOR(5 downto 0));

end COMBMULT;

architecture STRUCT of COMBMULT is

type PRODARRAY is array(0 to 2,0 to 2)of BIT;

signal XY:PRODARRAY;

signal C00,C01,C10,C11,C20:BIT;

signal S01,S11:BIT;

component FA port(a,b,c:in BIT:='0';s,co:out BIT); end component;

begin

GEN1:for i in 0 to 2 generate

GEN2:for j in 0 to 2 generate

GEN3:XY(i,j) <= X(i) and Y(j);

end generate;

end generate;

FA00:FA port map(XY(1,0),open,XY(0,1),Z(1),C00);

FA01:FA port map(XY(2,0),open,XY(1,1),S01 ,C01);

FA10:FA port map(S01 ,C00 ,XY(0,2),Z(2),C10);

FA11:FA port map(XY(2,1),C01 ,XY(1,2),S11 ,C11);

FA20:FA port map(S11 ,C10 ,OPEN ,Z(3),C20);

FA21:FA port map(XY(2,2),C11 ,C20 ,Z(4),Z(5));

Page 87: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Z(0) <= XY(0,0);

end STRUCT;

P4.4

entity PARITY is

generic(N:integer:=8);

port (DATA:in BIT_VECTOR(0 to N-1);P:out BIT );

end PARITY ;

use work.xor2;

architecture STRUCT of PARITY is

signal INT_P:BIT_VECTOR(1 to N-2);

component XOR2 port (i1,i2: in BIT ; o: out BIT); end component;

begin

G0:for i in 1 to N-1 generate

G1:if i=1 generate X_FIRST:XOR2

port map (DATA(i),DATA(0),INT_P(i)); end generate;

G2:if i>1 and i< N-1

generate X_MID :XOR2

port map(DATA(i),INT_P(i-1),INT_P(i));

end generate;

G3:if i= N-1 generate X_LAST:XOR2 port map(DATA(i),INT_P(i-

1),P);

end generate;

end generate;

end STRUCT ;

P4.5

entity and2 is

generic(and_delay:time := 5 ns);

port(i1,i2: in BIT ;o : out BIT) ;

end and2;

architecture DELAY of and2 is

Page 88: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

begin

o<= i1 and i2 after and_delay;

end DELAY;

entity xor2 is

generic(xor_delay:time := 5 ns);

port(i1,i2: in BIT ;o : out BIT) ;

end xor2;

architecture DELAY of xor2 is

begin

o<= i1 xor i2 after xor_delay;

end DELAY;

entity HA is

generic(and_delay,xor_delay:time := 5 ns);

port(a, b :in BIT; s, c: out BIT);

end HA;

architecture DELAY of HA is

component and2

generic(and_delay:time := 5 ns);

port (i1,i2: in BIT ;o : out BIT); end component;

component xor2

generic(xor_delay:time := 5 ns);

port (i1,i2: in BIT ; o: out BIT); end component;

begin

A1: and2 port map (a, b, c);

X1: xor2 port map (a, b, s);

end DELAY;

Page 89: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Page 90: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

CHAPTER 5

BEHAVIORAL STYLE OF DESCRIPTION

In previous chapters, we have studied dataflow and structural styles of

hardware description. Most of the digital hardware can be modeled using these

styles. However these styles are difficult to program due to the restrictions imposed

by the synthesis tools. Sometimes we are not interested in synthesis at all, e.g. while

designing a test bench. Some times we want to first describe a circuit at top level and

then break it into parts for actual synthesis. Behavioral description style is suitable

for these cases. In behavioral description, we don’t bother about the actual

implementation of the circuit. In behavioral modeling, sequential blocks like process,

procedures and functions are heavily used. Various statements, which are available

only in sequential bodies, are described below.

5.1 CASE STATEMENT

The syntax of a “case” statement is as follows.

case EXPRESSION is

when value1 => STATEMENT(S);

when value2 => STATEMENT(S);

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

[when others => STATEMENT(S);]

end case;

This statement selects one of the given branches for execution depending on

the value of the expression. The expression value must be either a scalar or a single

dimensional vector. The choices (value1, value2…) may be single values, multiple

values separated by vertical lines “|” or a range of values (e.g. 4 to 8). All possible

values of the expression must be covered by the given choices. The “when others”

clause can be used as a “catch all” construct. If present, “when others” must be the

last choice.

Example 1

Page 91: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Suppose an automatic telephone booth charges different rates to the customers

depending the hour of the call. The case statement can be used to assign the correct

rate.

entity GetRate isport(HOUR:in integer;RATE:out real);

end GetRate;

architecture DATAFLOW of GetRate isbegin

process(HOUR)begin

Case HOUR isWhen 0|23 => RATE <= 1.00;When 20 to 22|1 to 3 =>RATE <= 1.50;When others =>RATE <= 2.00;

End case;end process;

end DATAFLOW;

Example2

Case statement can be used as follows to implement a 4:1 MUX. The select inputs

are in the form of a bit-vector “SEL”.

Case SEL is

When “00” => Y <= I0 after 5 ns;

When “01” => Y <= I1 after 5 ns;

When “10” => Y <= I2 after 5 ns;

When “11” => Y <= I3 after 5 ns;

End case;

5.2 LOOP, NEXT AND EXIT STATEMENTS

The loop statement is used to repeatedly execute a set of sequential statements. It

has 3 variations as shown below.

--Syntax 1 (Simple loop):

[LABEL]: loop

Statement(s);

End loop [LABEL];

Page 92: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

This is an endless loop and therefore, the statement body must have an appropriate

“next”, “exit” or “return” statement somewhere to make it meaningful.

--Syntax 2 (While loop):

[LABEL]: while CONDITION loop

Statement(s);

End loop [LABEL];

The statement body is repeatedly executed as long as the CONDITION is true.

However, an additional exit path may be provided through an “exit” statement.

--Syntax 3 (For loop):

[LABEL]: for LOOP_VAR_NAME in RANGE loop

Statement(s);

End loop [LABEL];

Here, the loop variable takes all values specified in the range and the statement

body is executed for each value. The loop variable need not be explicitly declared in

the variable declaration zone. However, if a variable of the same name is declared

outside the loop, then it is treated as a different variable. The type of the range

automatically determines the type of the loop variable.

EXIT STATEMENT

The “exit” statement can be used only inside a loop. It causes the program to jump

out of the innermost loop if the associated Boolean condition is true. If a loop label is

specified, then it jumps out of that loop. This statement is similar to the “break”

statement in C++.

Syntax of exit:

Exit [LOOP_LABEL] [when CONDITION];

NEXT STATEMENT

The “next” statement can be used only inside a loop. It causes the program to skip

the remaining statements of the innermost loop and continue with the next iteration

if the associated Boolean condition is true. If a loop label is specified, then it jumps

to the end of that loop. This statement is similar to the “continue” statement in C++.

Syntax of next:

Page 93: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

next [LOOP_LABEL] [when CONDITION];

Examples of loop:

Type int_array is array (0 to 7) of integer;

Variable X: int_array ;

Variable SUM,INDEX:integer :=0;

Example 1:

FOR_LOOP:For I in X’range loop

X(I) := I;-- fill the array elements with values 0,1,2…

End loop FOR_LOOP;

Example 2:

SIMPLE_LOOP:loop

SUM = SUM + X(INDEX);

INDEX: = INDEX + 1;

exit SUM_LOOP when SUM > 10;-- add array elements till sum becomes

greater than 10

end loop SIMPLE_LOOP;

Example 3:

WHILE_LOOP: while SUM <= 10 loop

SUM = SUM + X(INDEX); -- add array elements till sum becomes greater

than 10

INDEX: = INDEX + 1;

end loop SUM_LOOP;

NULL STATEMENT

The null statement is like a NOP. Some times we may wish to explicitly specify that

no action needs to be taken for some branches of an “if” or “case” statement. A

NULL statement is useful there.

Example:

If X=’1’ then BYTE1 <= BYTE2; else null; end if;

5.3 ASSERT AND REPORT STATEMENT

Page 94: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

This statement is useful for detecting any deviation from normal operation. It

is supported only for simulation and it can be used in both sequential and

concurrent bodies. It is not supported for synthesis. Its typical uses are to assert that

a given signal is within a specified range or that the setup/ holdup timing is not

violated.

syntax:

assert CONDITION [report MESSAGE] [severity SEVERITY_LEVEL]

If the CONDITION is FALSE, the MESSAGE is flashed on the screen and

associated severity level is also displayed. The standard severity levels are “note”,

“warning”, “error” and “failure”. In case of “error” or “failure”, simulation is

stopped. In case of “note” and “warning”, simulation continues after displaying the

message. The default severity level is “note”. The default message is “Assertion

violation”.

Examples:

Assert enable /= ‘X’ report “Enable Terminal in unknown state” severity ERROR;

Assert DATA <= 255 report “DATA is out of range” severity NOTE;

“Assert FALSE” will always produce a message on the console. This could be used

to give console messages from time to time and thus allow us to trace the flow of the

program. E.g.

Assert FALSE report “Reached procedure-1 step-4”;

5.4 SUBPROGRAMS-PROCEDURES AND FUNCTIONS

To simplify coding, to help modularizing, and to improve readability, VHDL

supports subprograms. There are two types of subprograms in VHDL, namely

procedures and functions. The subprograms perform a given computation in zero

simulation time. The statements within a procedure or a function body get executed

sequentially. A function returns a single value in its name. A procedure can not

return a value in its name but it can return any number of values through its “out”

parameters. The formal parameters of a procedure can be constants, variables or

signals and their modes can be in, out, or inout. The formal parameters of a function

can have only the input mode. By default, the “out” and “inout” parameters are

assumed to be “variable” objects and the “in” parameters are assumed to be

constants. If a “signal” is passed as a parameter to a subprogram, then its current

Page 95: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

value at the time of calling is passed to the subprogram. However, the parameters

may also be declared as signals in the procedure declaration statement and in that

case, the signal driver is also passed to the subprogram. In this case, if the value of

the signal is used after some delay in the subprogram, then the value prevalent at

the usage time is taken.

If necessary, local variables may be declared before the “begin” keyword.

The local variables are initialized every time a subprogram is invoked. Thus, they

can not be used for preserving values between two procedure calls. This in contrast

to the “process” block where variables are initialized only once during the start of

the simulation run.

A procedure or a function returns to the calling program either at the end of

the statement body or when it encounters a return statement. A function should

always return a value with return statement.

The syntax of “return” is-

Return [expression];

INVOKING A PROCEDURE

A procedure is invoked by a procedure call from either a sequential body or

a concurrent body. If the call is placed inside a sequential body, it is executed in its

natural sequence. If the call is placed inside a concurrent body, the procedure is

invoked when an event occurs on any one of the “signal” parameters in “in” or

“inout” mode. If any input parameter of the procedure is of the “variable” class

then the procedure can be called only from a sequential body because variables can

exist only in a sequential body. The association of the calling program variables (i.e.

actual parameters) to the formal parameters can be done either positionally or using

a named association.

The syntax for calling is-

PROC_NAME(ACT_PAR1, ACT_PAR2, ACT_PAR3…);--using positional

association.

PROC_NAME(FORMAL_PAR1=>ACT_PAR1,

FORMAL_PAR2=>ACT_PAR2…);--using positional association.

DEFINING PROCEDURES AND FUNCTIONS

Page 96: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

The procedure or function body should be placed in the signal declaration

zone of “entity” or “architecture” design units. Alternatively, the subprogram

prototype can be declared in a PACKAGE declaration and its definition can be

placed in the PACKAGE BODY.

The syntax for defining a procedure is as follows.

procedure PROC_NAME

(IN_SIG_NAME1, IN_SIG_NAME2…: in DATA_TYPE1;

OUT_SIG_NAME1, OUT_SIG_NAME2 … : out DATA_TYPE2;

INOUT_SIG_NAME1, INOUT_SIG_NAME2 … : inout

DATA_TYPE3;

) is

[local variable declarations]

Begin

Statement(s);

End PROC_NAME;

Example: Procedure to convert a bit-vector to integer

procedure BYTE_TO_INT(BYTE: in BIT_VECTOR;EQ_INT: out int) is

Variable SUM :integer :=0;

Begin

For I in BYTE’range loop

If BYTE(I) = ‘1’ then SUM := SUM + 2**I; end if;

End loop;

EQ_INT <= SUM;

End BYTE_TO_INT;

We have created a local variable SUM because EQ_INT is an “out” type variable

and it can not be used on the RHS of any expression.

Usage:

The above function can be “called” as –

Signal A:std_logic_vector; Signal B : integer;

BYTE_TO_INT(A,B);-- positional association

BYTE_TO_INT(EQ_INT =>B,BYTE => A);-- positional association

The syntax for defining a function is as follows.

Page 97: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Function FUNC_NAME (SIG_NAME1, SIG_NAME2 … : DATA_TYPE1)

Return DATA_TYPE2 is

Begin

Statement(s);

End FUNC_NAME;

Example:

We will now implement the above example as a function instead of a procedure.

Function BYTE_TO_INT(BYTE: BIT_VECTOR) return integer is

Variable sum :int :=0;

Begin

For I in BYTE’range loop

If BYTE(I) = ‘1’ then sum := sum + 2**I; end if;

End loop;

Return sum;

End BYTE_TO_INT;

Usage:

The above function can be “called” as –

Signal A:std_logic_vector; Signal B : integer;

B <= BYTE_TO_INT(A);

SUBPROGRAM OVERLOADING AND OPERATOR OVERLOADING

It is possible to define two or more different subprograms having same name

but differing in number or type of parameters. The function is said to be

“overloaded” in this case. The simulator or synthesizer automatically selects the

correct subprogram by looking at the parameters in the call statement. Overloading

is a very convenient mechanism for defining a set of functions that perform the same

operation on different data types.

Example:

Let us define a function ADD that works correctly for integers and bit-

vectors.

Function ADD (A, B: BIT_VECTOR) return BIT_VECTOR is

Variable SUM: integer;

Page 98: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Begin

SUM:= BYTE_TO_INT(A) + BYTE_TO_INT(B);

Return INT_TO_BYTE (SUM);

End ADD;

Function ADD (A, B: integer) return BIT_VECTOR is

Variable SUM: integer;

Begin

SUM:= A+B;

Return INT_TO_BYTE (SUM);

End ADD;

OPERATOR OVERLOADING

Just as functions can be made to behave differently depending on the type of

the parameters, the operators can also be made to behave differently depending on

the type of the operands they are acting on. This is achieved by “operator

overloading”. The standard VHDL operators like and, or, + etc. work only with the

standard data types. They have to be overloaded to define the operations on the user

defined data types. Operator overloading is defined by defining a function having

the same name as the operator. The name should enclosed in double quote marks

since all operator names are reserved words. Functions for binary operators have

two parameters and functions for unary operators have one parameter.

Example:

Consider a user defined data type LOGIC4 shown below. Since this is a user

defined enumerated data type, the standard VHDL operators are meaningless for it.

The meaning has to be necessarily assigned by overloading the operators. Let us

overload the “and” and “not” operators for this data type.

Type LOGIC4 is (‘0’,’1’,’Z’,’X’);

Type L4_TWO_DIM_ARR is array(LOGIC4,LOGIC4) of LOGIC4;

Type L4_ONE_DIM_ARR is array(LOGIC4) of LOGIC4;

Function “and” (a,b:LOGIC4) return LOGIC4 is

Constant and_table: L4_TWO_DIM_ARR:=

((‘0’,’0’,’0’,’0’),(‘0’,’1’,’1’,’X’),(‘0’,’1’,’1’,’X’),(‘0’,’X’,’X’,’X’))

;

Page 99: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

begin

return and_table(a,b);

end “and”;

Function “not” (a:LOGIC4) return LOGIC4 is

Constant not_table: L4_ONE_DIM_ARR:= (‘1’,’0’,’0’,’X’);

begin

return not_table (a);

end “not”;

5.5 FILE I/O OPERATIONS

For testing a design, we sometimes prefer to edit the stimulus using a standard

editing tool like notepad and use it during simulation. Sometimes we desire to record the

output values at periodic intervals into a disk file for a later review. Sometimes we want

to compare such recorded results with the results obtained from simulation of another

version of the architecture. All these tasks can be performed by means of the file I/O

statements. These statements supported only for simulation, as they are meaningless for

synthesis.

For performing file I/O, we have to first define an appropriate FILE type and then

create a FILE object belonging to that type. The file type defines the data type of the

records contained in the file. The read/write mode (in or out) and its path has to be

specified while creating the FILE object.

Syntax:

Type <file data type> is file of <record data type>;

File <file object name>:<file data type> is <mode> <path>;

Example:

Type LOGIC_DATA is file of character;

file INPUT_FILE : LOGIC_DATA is in “MY_FILE.DAT” ;

Reading and writing is performed through “read” and “write” commands.

Syntax: write(file object name, variable name);--variable should belong to the record

data type.

Page 100: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Read(file object name, variable name);--variable should belong to the record

data type.

Examples: variable C: character;

- - -

write(INPUT_FILE,C);

read(INPUT_FILE,C);

ENDFILE FUNCTION:

The function ENDFILE(File object name) returns a Boolean value TRUE if the

end of the file has been reached, else it returns FALSE. In the following example, the

statements fill a character array CH_ARRAY with values read from a file. The reading

stops either when the array is full or when the end of the file is reached.

For I in 0 to ARRAY_LEN-1 loop

Read(INPUT_FILE,CH_ARRAY(I));

If ENDFILE(INPUT_FILE) then exit;

End loop;

FORMATTED ASCII I/O

The file operations described in the previous section read or write numeric values

in binary format. Thus they are not intelligible to other word processors. For manual

viewing, it is more convenient to perform formatted ASCII I/O for numeric values. For

“BIT” and other standard data types, this can be done using functions defined in the

“TEXTIO” package in the std library. For std_logic data, we need to use the

std_logic_textio package in the IEEE library. This package defines two useful data types

namely TEXT and LINE. TEXT is a data type describing a file of characters and LINE is

a data type which is “access” to a string. The read and write functions have been

overloaded to work with a LINE object. When write is used with a LINE object instead

of a file object, then the variable to be written is converted into a formatted ASCII string

and added to the string buffer addressed by the LINE object. Then “writeline” function is

used to transfer the string to the disk file. Similarly “readline” function reads a string

from the disk file and “read function retrieves individual data elements from it.

Syntax of write:

Write(line variable name, variable name,[alignment(default LEFT)], [width(default 0)]);

Page 101: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

Alignment can be LEFT or RIGHT. If the specified width is less than the required width,

then the width is automatically expanded to fit the data. If the width is extra, then the

output is padded with blanks at left or right depending on the alignment option.

Syntax of read:

Read((line variable name, variable name);

EXAMPLE

The following example does not do any useful task but illustrates the use of assert and

file I/O operations.

--FILE and console I/O example

use std.textio.all;

entity FTEST is

end FTEST;

architecture TB of FTEST is

signal a,b:bit_vector(7 downto 0):="00001111";

signal c:integer:=100;

file TEST:text is out "fileio.txt";

begin

c <= 150 after 10 ns;

process(c)

variable L:LINE;

begin

assert FALSE report "Process start" severity NOTE;

write(L,a,LEFT,10); write(L,b,LEFT,10); write(L,c,LEFT,10);

writeline(TEST,L);

end process;

end TB;

5.6 RTL description

In Register Transfer Level (RTL) description, the transformation of input

into output is described as a timed sequence of processing steps according to an

algorithm. Since the algorithm executes over a number of time steps, intermediate

results of one step have to be stored in some registers so that they can be used in the

Page 102: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

next step. Thus the hardware architecture consists of a set of registers whose

contents can be routed to combinational processing elements like ALU’s, barrel

shifters or incrementers via buses. The output of the processing elements can be

routed back to any desired register. The orchestration of the system is managed by a

control unit, which issues appropriate control signals for selection of registers on

buses, selection of function of ALU and selection of target register.

TRI-STATE BUSES

Modeling of tri state buses requires the logic signals to be represented by the

std_logic data type because the BIT type does not support the tri state condition. A

tri state buffer is inferred when an enable signal is associated with a data signal such

that if the enable signal is de-asserted, then the output is forced into the high

impedance (Z) state.

Example:

Let us make a VHDL model for three 8 bit registers A, B, C which send their

data on a bus called TRI_BUS under the control of signals EN_A, EN_B, EN_C.

The hardware architecture is shown in fig 5.1.

EN_A

A

EN_B

B TRI_BUS

EN_C

Page 103: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

C

FIG 5.1

Signal A, B, C, TRI_BUS: std_logic_vector(0 to 7);

Signal EN_A, EN_B, EN_C : std_logic;

TRI_BUS <= A when EN_A = ‘1’ else “ZZZZZZZZ”;

TRI_BUS <= B when EN_B = ‘1’ else “ZZZZZZZZ”;

TRI_BUS <= C when EN_C = ‘1’ else “ZZZZZZZZ”;

The multi driver signal TRI_BUS in the above example is resolved by the standard

resolution function in the IEEE library.

WIRED-OR BUS

We can implement a wired-or bus or a wired-and bus for bit, std_logic or

any other data type by writing our own resolution function. The following example

shows the implementation of a wired-or bus for BIT.

EXAMPLE : WIRED OR RESOLUTION FUNCTION

The simulator calls the resolution function whenever any one of the drivers to a

multi-writer signal makes an assignment to the signal. The input to the function is an

array whose elements represent the assignments made by the drivers. The function should

return a single value that will be finally assigned to the signal. WIRED_OR function is

coded as follows:

function WIRED_OR(INPUTS : BIT_vector) return BIT is

begin

for J in INPUTS’RANGE loop

if INPUTS(J) = ‘1’ then return ‘1’; end if

return ‘0’;

end WIRED_OR;

Page 104: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

RTL EXAMPLE - SIGNED 8 BIT MULTIPLIER

As an exercise in RTL design, consider the design of a signed 8 bit two’s

complement multiplier. The hardware arrangement is as follows.

Q(7) M(0)

OUTBUSHI OUTBUSLO INBUSQ INBUSM

FIG 5.2

The multiplier and the multiplicand are made available at the INBUSQ and

INBUSM buses and a START signal is given to start the operation. After

multiplication, the 15-bit output is presented on OUTBUSHI and OUTBUSLO and

the DONE signal is asserted.

MULTIPLY ALGORITHM IN PSEUDOCODE

RESET: if RESET= 1

A,Q,M,F,COUNT=0;goto RESET

else if START= 1 goto INPUT

INPUT: M=INBUSM; Q=INBUSQ;

ADD: A= A+ M * Q(7)

F

A Q M

ADDER/SUBTRACTOR

COUNT

C) CONTROL

UNIT

Page 105: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

RSHIFT: A(0)=F;A(1,7)=A(0,6),Q(0)=A(7);Q(1,7)=Q(0,6);

TEST: if COUNT=6 THEN goto CORRECTION;

Else COUNT++;goto ADD;

CORRECTION:A=A – M * Q(7);Q(7)=0;

OVER: OUTBUSHI=A;OUTBUSLO=Q;DONE=1;

We can model this in VHDL behavioral style and successfully simulate it but

the step by step execution requires multiple wait commands for the clock

synchronization. The synthesis tool does not support multiple waits in a single

process. For writing a synthesizable version, we need to implement it as a state

machine.

-- 8 bit 2's complement multiplier BEHAVIORAL

library ieee;

use ieee.std_logic_1164.all;

use ieee.std_logic_unsigned.all;

entity MULT8 is

port(INBUSQ,INBUSM:in std_logic_vector(0 to 7);

OUTBUSHI, OUTBUSLO: out std_logic_vector(0 to 7);

CLK, START, RESET: in std_logic;

DONE :out std_logic);

end MULT8;

architecture BEH of MULT8 is

signal A ,Q , M : std_logic_vector(0 to 7);

type int3bit is range 0 to 7;

signal COUNT: int3bit;

signal F : std_logic;

begin

MULT_PROC:process

begin

wait until START='1';

--INPUT:

wait until(CLK='1');

A<="00000000";COUNT<=0;F<='0';M<=INBUSM;Q<=INBUSQ;

Page 106: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

ADD_LOOP:loop

wait until(CLK='1');

--ADD:

if Q(7)='1' then

A<=A+M;

F <= (M(0)and Q(7)) or F;

wait until(CLK='1');

end if;

--RSHIFT

Q(1 to 7) <= Q(0 to 6); Q(0) <= A(7);

A(1 to 7) <= A(0 to 6); A(0) <= F;

--TEST

if COUNT=6 then

wait until(CLK='1');

exit;

end if;

COUNT<=COUNT+1;

wait until(CLK='1');

end loop ADD_LOOP;

--CORRECTION

if Q(7)='1' then A <= A-M;end if;

Q(7) <= '0';

wait until(CLK='1');

--OUTPUT

OUTBUSHI <= A; OUTBUSLO <= Q;

DONE <= '1';

--wait;

end process MULT_PROC;

end BEH;

-- 8 bit 2's complement multiplier FOR SYNTHESIS

Page 107: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

library ieee;

use ieee.std_logic_1164.all;

use ieee.std_logic_unsigned.all;

entity MULT8 is

port(INBUSQ,INBUSM:in std_logic_vector(0 to 7);

OUTBUSHI, OUTBUSLO: out std_logic_vector(0 to 7);

CLK, START, RESET: in std_logic;

DONE :out std_logic);

end MULT8;

architecture RTL of MULT8 is

signal A ,Q , M ,NA, NQ, NM: std_logic_vector(0 to 7);

type int3bit is range 0 to 7;

signal COUNT, NCOUNT : int3bit;

type STATE_TABLE is (INIT, ADD, RSHIFT, TEST, CORRECTION, OVER);

signal STATE,NEXT_STATE : STATE_TABLE;

signal F ,NF : std_logic;

begin

state_proc:process(CLK, RESET)

begin

if RESET = '1' then STATE <= INIT;

elsif(CLK'event and CLK='1')then STATE <= NEXT_STATE;

end if;

end process state_proc;

reg_proc:process(CLK, RESET)

begin

if RESET = '1' then

A<="00000000";

Q<="00000000";

M<="00000000";

COUNT <= 0;

Page 108: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

F <= '0';

elsif(CLK'event and CLK='1')then

A<= NA;

Q<= NQ;

M<= NM;

F<= NF;

COUNT<=NCOUNT;

end if;

end process reg_proc;

NEXT_STATE <= ADD when STATE=INIT and START = '1' else

INIT when STATE=INIT and START = '0' else

RSHIFT when STATE=ADD else

TEST when STATE=RSHIFT else

CORRECTION when STATE=TEST and COUNT = 6 else

ADD when STATE=TEST and COUNT /= 6 else

OVER when STATE=CORRECTION else

STATE;

DONE <= '1' when STATE <= OVER else '0';

A_proc:process(STATE,START,Q)

begin

if STATE = INIT and START = '1' then

NA <= A;

NQ <= INBUSQ;

NM <= INBUSM;

NCOUNT <= COUNT;

NF <= F;

elsif STATE = ADD and Q(7) = '1' then

NA <= A + M;

NQ <= Q;

NM <= M;

NF <= (M(0) and Q(7)) or F;

Page 109: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

NCOUNT <= COUNT;

elsif STATE = RSHIFT then

NQ(1 to 7) <= Q(0 to 6); NQ(0)<=A(7);

NA(1 to 7) <= A(0 to 6); NA(0) <= F;

NM <= M;

NF <= F;

NCOUNT <= COUNT;

elsif STATE= TEST then

NA <= A;

NQ <= Q;

NF <= F;

NM <= M;

NCOUNT<=COUNT + 1 ;

elsif STATE = CORRECTION and Q(7) = '1' then

NQ(0 to 6) <= Q(0 to 6);

NQ(7) <= '0';

NA <= A - M;

NM <= M;

NF <= F;

NCOUNT <= COUNT;

elsif STATE = OVER then

NQ <= Q;

NA <= A;

NM <= M;

NF <= F;

NCOUNT <= COUNT;

OUTBUSHI <= A;

OUTBUSLO <= Q;

else NQ<=Q;NA<=A;NF<=F;NM<=M;NCOUNT <= COUNT; end if;

end process A_proc;

end RTL;

Page 110: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

5.7 TEST BENCH

Earlier, we have seen how to test the entities in the simulator by giving

stimulus either by console commands or by invoking a command file. This

procedure is suitable for simple entities. But for testing complex entities, we need

long test sequences, which should be generated by a program. Sometimes we need to

generate handshake responses. In such cases we use VHDL itself for generating

stimulus and capturing the response. Such an arrangement is called a TEST

BENCH. Fig 5.3 shows the general architecture of a test bench.

FIG 5.3

The test bench is written as an overall entity in which, the DUT is described as

a “component”. The stimulus is generated by one process and the response is

captured by another process. In simple cases, we can do away with the response

capture process and observe the waveform straightaway in the simulator. For

complex entities, the response capture process is made sensitive to the DUT output

and it records the current time and the status of the output to a disk file. In

synchronous designs, we are mostly interested in the status of various signals at the

rising edge of the clock. In such case, the response capture process can be made

sensitive to clock. In a typical design flow, we first simulate the RTL architecture of

a device and record the responses. Then we synthesize and compare the responses

with the old ones. This process is called “verification”. For this, we need two types of

STIMULUS

GENERATOR

DEVICE UNDER TEST

RESPONSE CAPTURE AND

COMPARISON

Page 111: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

test benches, one for recording and the other for comparing. The entity block of a

test bench is usually empty because it has no external ports.

EXAMPLE- TEST BENCH FOR A PRIORITY ENCODER

In this example, we will first design a priority encoder, which encodes four

input signals I1, I2, I3, I4 into two output signals MSB and LSB as shown in FIG

5.4. For simplicity, we will assume that at least one of the inputs is always active and

if all inputs happen to be low, then it should flash a warning message. Then we will

design a test bench for it.

I1

I2 MSB

I3

LSB

I4

FIG 5.4

We start by defining the entity and architecture of the encoder. Then we define a

package to declare general utilities and use it in the entity TB(Test Bench). The

APPLY_VECTOR process generates the stimulus and the

TWO_CHANNEL_RECORDER process captures all changes in the output

variables OUT1 and OUT2. Two files are made. One file is written in ASCII for

manual checking and the other is written in binary for display in waves or for

comparison.

--TEST BENCH

use std.textio.all;

entity ENCODER is

generic(DELAY : time := 5 ns);

port(I1, I2, I3, I4 : in BIT; MSB, LSB : out BIT);

PRIORITY

ENCODER

Page 112: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

end ENCODER;

architecture BEHAV of ENCODER is

begin

process(I1,I2,I3,I4)

variable BIT1,BIT0 : BIT;

begin

if((I1 or I2 or I3 or I4) = '0') then

assert false report "ALL LOW";

else

if I4='1' then BIT1 := '1';BIT0 := '1';

elsif I3='1' then BIT1 := '1';BIT0 := '0';

elsif I2='1' then BIT1 := '0';BIT0 := '1';

else BIT1 := '0';BIT0 := '0';

end if;

MSB <= BIT1 after DELAY;

LSB <= BIT0 after DELAY;

end if;

end process;

end BEHAV;

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

package TB is

type TWO_CHANNEL_TRACE_ELEMENT is record

CH1:BIT;

CH0:BIT;

AT :time;

end record;

type TWO_CHANNEL_TRACE_FILE is file of

TWO_CHANNEL_TRACE_ELEMENT;

component ENCODER port(I1,I2,I3,I4: in BIT; MSB,LSB:out BIT);

end component;

constant BITS_IN_VECTOR:integer := 4;

subtype TEST_VECTOR is BIT_VECTOR(BITS_IN_VECTOR-1 downto 0);

Page 113: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

end TB;

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

use std.textio.all;

entity TBENCH is

end TBENCH;

use work.tb.all;

architecture TB1 of TBENCH is

constant NO_OF_VECTORS:integer :=5;

type VECTOR_MEMORY is array(1 to NO_OF_VECTORS) of TEST_VECTOR;

constant INPUT_VECTORS:VECTOR_MEMORY:=

("1010","0010","1100","0110","1111");

constant VECTOR_PERIOD:time := 100 ns;

signal IN1,IN2,IN3,IN4:BIT;

SIGNAL OUT1,OUT2:BIT;

begin

ENCODER1:ENCODER port map(IN1,IN2,IN3,IN4,OUT2,OUT1);

APPLY_VECTORS:process

begin

for J in 1 to NO_OF_VECTORS loop

IN1<=INPUT_VECTORS(J)(0);

IN2<=INPUT_VECTORS(J)(1);

IN3<=INPUT_VECTORS(J)(2);

IN4<=INPUT_VECTORS(J)(3);

wait for VECTOR_PERIOD;

end loop;

assert false report "TEST COMPLETED";

wait;

end process APPLY_VECTORS;

process(OUT1,OUT2)

file TRACE_OF_OUT12:TWO_CHANNEL_TRACE_FILE is out

"NEW_TRACE.DAT";

file ASCII_OF_OUT12: TEXT is out "NEW_TRACE.TXT";

Page 114: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

variable SAMPLE:TWO_CHANNEL_TRACE_ELEMENT;

variable ASCII_LINE:LINE;

begin

SAMPLE.CH1 := OUT2;

SAMPLE.CH0 := OUT1;

SAMPLE.AT := NOW;

write(TRACE_OF_OUT12,SAMPLE);

write(ASCII_LINE,OUT2,LEFT,10);

write(ASCII_LINE,OUT1,LEFT,10);

write(ASCII_LINE,NOW,LEFT,10);

writeline(ASCII_OF_OUT12,ASCII_LINE);

end process TWO_CHANNEL_RECORDER;

end TB1;

DATA FILE NEW_TRACE.TXT

0 0 0 NS

1 1 5 NS

0 1 105 NS

1 1 205 NS

1 0 305 NS

1 1 405 NS

EXERCICES

5.1 Write a function PARITY, which returns the even parity for the bit vector, passed to

it.

5.2 Following statement in the architecture body would obviously give a syntax error.

Signal A, B, C:BIT;

- - - - -

- - - - -

A <= B<= C;

Write something in the entity block such that the syntax error will be removed. (Hint:

overload the “<=” operator)

5.3 Write a function to return the number of 1’s in a vector.

Page 115: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

5.4 Write a overloaded “or” operator for the LOGIC4 data type defined in sec 5.4. The

truth table should be as follows.

A\B 0 1 Z X

0 0 1 1 X

1 1 1 1 1

Z 1 1 1 1

X X 1 1 X

5.5 Write a procedure COMP that compares the magnitudes of two bit-vectors A and B

and returns three outputs A_GT_B, A_LT_B and A_EQ_B.

5.6 Consider the following program. Plot the waveforms of the stimulus signal

FUTURELOOK and the output signals VAR_FLAG and SIG_FLAG. Note that when a

parameter is passed as a “signal”, its driver is passed along with it and when an

assignment is made after some delay, its current value is assigned rather than the value

prevalent at the time of the procedure call.

entity TEST isport(VAR_FLAG,SIG_FLAG:out bit);

procedure SIG_PROC(signal PASSED:in bit;signal FLAG:out bit)isbegin

wait for 15 ns;flag<= PASSED;end SIG_PROC;procedure VAR_PROC( PASSED:in bit;signal FLAG:out bit)isbegin

wait for 15 ns;flag<= PASSED;end VAR_PROC;end TEST;architecture A of TEST is

signal FUTURELOOK:bit:='0';begin

FUTURELOOK<= '1' after 10 ns,'0' after 20 ns, '1' after 40 ns,'0' after 60 ns,'1' after 70 ns;

SIG_PROC(FUTURELOOK,SIG_FLAG);VAR_PROC(FUTURELOOK,VAR_FLAG);

end A;

ANSWERS

5.1

function PARITY(a:STD_LOGIC_VECTOR) return STD_LOGIC is

variable temp:std_logic:='0';

Page 116: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

begin

for i in a'range loop

temp:=temp xor a(i);

end loop;

return temp;

end PARITY;

5.2

Function "<=" (a,b:BIT) return BIT is

begin

return a or b;

end "<=";

5.3

function COUNT1(a:STD_LOGIC_VECTOR) return integer is

variable temp:integer:=0;

begin

for i in a'range loop

if a(i)='1' then temp:=temp +1;end if;

end loop;

return temp;

end COUNT1;

5.4

Function "or" (a,b:LOGIC4) return LOGIC4 is

Type LOGIC4 is (‘0’,’1’,’Z’,’X’);

Type L4_TWO_DIM_ARR is array(LOGIC4,LOGIC4) of LOGIC4;

Constant or_table: L4_TWO_DIM_ARR:=

(('0','1','1','X'),('1','1','1','1'),('1','1','1','1'),('X','1','1','X'));

begin

return or_table(a,b);

end "or";

5.5

procedure COMP(a,b:STD_LOGIC_VECTOR(3 DOWNTO 0);

signal A_GT_B,A_EQ_B,A_LT_B:out STD_LOGIC) is

Page 117: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

begin

if (a>b) then A_GT_B<='1'; A_EQ_B<='0'; A_LT_B<='0';

elsif(a<b) then A_GT_B<='0'; A_EQ_B<='0'; A_LT_B<='1';

else A_GT_B<='0'; A_EQ_B<='1'; A_LT_B<='0';

end if;

end COMP;

Page 118: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

5.6

FUTURE

LOOK

VAR

FLAG

SIG

FLAG | | | | | | | | |

TIME(ns) 00 10 20 30 40 50 60 70 80 90

Explanation: Both procedures are called once at t=0 ns. A value of ‘0’ is passed to the

VAR_PROC while the signal driver is passed to SIG_PROC. Thus, when an assignment

is made at t=15 ns, VAR_FLAG remains at ‘0’ but SIG_FLAG is set to its current value

of ‘1’. The transition on FUTURE_LOOK at t=10 ns is ignored as both processes are

suspended in the “wait” command. The processes are again triggered at t=20 ns. After

waiting for 15 ns, ie. at t= 35ns, SIG_FLAG is assigned the current value of ‘0’ and

VAR_FLAG is assigned the passed value of ‘0’. The processes are again triggered at t=

40 ns. At t=55 ns, SIG_FLAG and VAR_FLAG are assigned ‘1’. The next triggering is at

t=60 ns. At t=75, VAR_FLAG is assigned the passed value of ‘0’ and SIG_FLAG is

assigned the current value of ‘1’. The transition at t= 70 ns is ignored.

Page 119: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

CHAPTER 6PROJECTS

6.1 Serial transmitterDesign a serial transmitter, which accepts an 8 bit parallel data on its “data_in”

bus along with an asynchronous “valid” signal. The data should be stored with the rising

edge of “valid” and shifted out serially on the “data_out” line with the rising edge of the

transmit clock, “clk”. The “data_out” signal should be high in the idle state. A low start

bit and a high stop bit should be inserted by the transmitter. A “hold” signal should be

provided as long as the shifter is busy.

SYSTEM BLOCK DIAGRAM

‘0’ Q0Data_in data_out

SHIFT‘1’ REG

valid LATCH CLK

COUNT=’0’ CLK LD

HOLD

RUN H dao_valid D Q D Q CLR_BAR

COUNTER CLK CLK CLK

R R_BARCLK

RST COUNT=11

entity SERIAL_XMT is

port (data_in:in bit_vector(7 downto 0);valid,clk,rst:in bit;

Page 120: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

data_out,hold:out bit );

end SERIAL_XMT;

architecture BEH of SERIAL_XMT is

signal SHIFT_REG: bit_vector(9 downto 0);

signal count:integer range 0 to 11;

signal in_buffer:bit_vector(7 downto 0);

signal run,dao_valid:bit;

begin

RUN_PROC:process(rst,valid,count)

begin

if rst='1' or count=11 then run<= '0' ;

elsif valid'event and valid='1' then run<='1';

end if;

end process RUN_PROC;

hold<=run;

data_out_proc:process(clk,run)

begin

if run='0' then dao_valid<='0';

elsif clk'event and clk ='1' then

dao_valid <= run;

end if;

end process data_out_proc;

COUNT_PROC:process(run,clk,count)

begin

if run= '0' then count<= 0;

elsif clk'event and clk='1' then count<=count+1;

end if;

end process COUNT_PROC;

REG_PROC:process(clk,run,in_buffer)

begin

Page 121: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

if clk'event and clk='1' then

if run='1' then

if count=0 then

SHIFT_REG(8 downto 1)<=in_buffer;

SHIFT_REG(0)<='0';

SHIFT_REG(9)<='1';

else SHIFT_REG<='1' & SHIFT_REG(9 downto 1);

end if;

end if;

end if;

end process REG_PROC;

BUFF_PROC:process(valid,data_in)

begin

if valid'event and valid='1' then in_buffer<=data_in;

end if;

end process BUFF_PROC;

data_out<= (not dao_valid) or SHIFT_REG(0);

end BEH;

Page 122: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

6.2 Matrix keyboard scanner

Design a scanner for a 4X4 key matrix. When a key is pressed, it should send a 4 bit key

code along with a valid signal.

SYSTEM BLOCK DIAGRAM

KEY_CODE S0

KEY S1SCANNER

S2 valid

S3 CLK R0 R1 R2 R3

DESIGN HIGHLIGHTS

For scanning the 4X4 matrix, we have 4 scan lines S[3:0] and 4 returnlines R[3:0]. The scan lines are generated by decoding a 2 bit counter “cnt”.When all keys are open, the return lines should be high. When a low state isdetected on any return line, the counter is disabled. The return lines are encodedin two bits and combined with the scan counter to form the 4 bit key code. The“valid” signal is asserted. When the key is released, “valid” is de-asserted and thecounter is again enabled.

library ieee;

use ieee.std_logic_1164.all;

use ieee.std_logic_unsigned.all;

entity KEY_SCAN is

port (CLK,RST:in STD_LOGIC;S:out STD_LOGIC_VECTOR(3 downto 0);

R:in STD_LOGIC_VECTOR(3 downto 0);valid:out STD_LOGIC;

KEY_CODE:out STD_LOGIC_VECTOR(3 downto 0));

Page 123: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

end KEY_SCAN;

architecture DF of KEY_SCAN is

signal cnt,RET_CODE: std_logic_vector (1 downto 0 );

signal cnt_enable: std_logic;

begin

CNT_PROC: process (CLK,RST )

begin

if RST= '1' then cnt<="00";

elsif CLK'event and CLK='1' then

if cnt_enable='1' then cnt<=cnt+1;end if;

end if;

end process CNT_PROC;

S<= "1110" when cnt ="00" else

"1101" when cnt ="01" else

"1011" when cnt ="10" else

"0111" ;

cnt_enable<= R(0) and R(1) and R(2) and R(3);

RET_CODE<= "00" when R(0)='0' else

"01" when R(1)='0' else

"10" when R(2)='0' else

"11" ;

KEY_CODE<= cnt & RET_CODE;

valid<= not cnt_enable;

end DF;

--TEST BENCH for key scanner

library ieee;

use ieee.std_logic_1164.all;

use ieee.std_logic_unsigned.all;

Page 124: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

entity TB_KEY is

end TB_KEY;

architecture BEH of TB_KEY is

signal clk,rst,V:std_logic:='0';

signal SCAN,K_CODE,RET: std_logic_vector ( 3 downto 0 );

component KEY_SCAN

port (CLK,RST:in STD_LOGIC;S:out STD_LOGIC_VECTOR(3 downto 0);

R:in STD_LOGIC_VECTOR(3 downto 0);valid:out STD_LOGIC;

KEY_CODE:out STD_LOGIC_VECTOR(3 downto 0));

end component;

begin

K1:KEY_SCAN port map(clk,rst,SCAN,RET,V,K_CODE);

rst<='1','0' after 25 ns;

clk<= not clk after 50 ns;

RET<="1111","1110" after 400 ns,"1111" after 500 ns,"1101" after 600 ns,

"1111" after 700 ns,"1011" after 800 ns,"1111" after 1000 ns,

"0111" after 1100 ns,"1111" after 1300 ns;

end BEH;

6.3 3 X 3 Crossbar switch controller

Design a controller for a 3X3 crossbar switch that has three input busesand three output buses. Each input bus is associated with a two-bit destinationcode and a bus request signal. Each channel should get a BUS GRANT signalfrom the controller. Priority logic should be followed for granting the buses suchthat channel 0 gets the highest priority. However, once a bus is granted to achannel, it will not be given to any other channel till the original request comesdown.

Before designing the crossbar controller, we first design a three-line bus arbiter

and the use it as a component in the crossbar controller. The bus arbiter is designed as a

finite state machine.

REQ1 GRANT1

Page 125: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

REQ2 BUS ARBITER GRANT2

REQ3 GRANT3

CLK RST

library ieee;

use ieee.std_logic_1164.all;

entity BUS_ARB is

port ( REQ1,REQ2,REQ3,CLK,RST:in

STD_LOGIC;GRANT1,GRANT2,GRANT3:out STD_LOGIC);

end BUS_ARB;

architecture BEH of BUS_ARB is

type STATE_TABLE is(IDLE,G1,G2,G3);

signal STATE,N_STATE:STATE_TABLE;

begin

STATE_PROC:process(REQ1,REQ2,REQ3,CLK,RST)

begin

if RST = '1' then STATE<= IDLE;

elsif CLK'event and CLK = '1' then STATE<=N_STATE;

end if;

end process STATE_PROC;

N_STATE<= G1 when (state=idle and REQ1='1')else

G1 when (state= G1 and REQ1='1')else

G1 when (state= G2 and REQ1='1' and REQ2='0') else

G1 when (state= G3 and REQ1='1' and REQ3='0') else

G2 when (state=idle and REQ2='1' and REQ1='0') else

G2 when (state= G1 and REQ2='1' and REQ1='0') else

G2 when (state= G2 and REQ2='1')else

G2 when (state= G3 and REQ2='1' and REQ1='0' and REQ3='0') else

G3 when (state=idle and REQ3='1' and REQ1='0' and REQ2='0') else

G3 when (state= G1 and REQ3='1' and REQ1='0' and REQ2='0') else

Page 126: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

G3 when (state= G2 and REQ3='1' and REQ1='0' and REQ2='0') else

G3 when (state= G3 and REQ3='1')else

IDLE;

GRANT1<= '1' when STATE = G1 else '0';

GRANT2<= '1' when STATE = G2 else '0';

GRANT3<= '1' when STATE = G3 else '0';

end BEH;

CROSSBAR BLOCK DIAGRAM

Data1 Dout1

Dest1

Req1

Data2 Dout2

Dest2

Req2

Data3 Dout3

Dest3

Req3

gr1 gr2 gr3

Three copies of the BUS_ARB are used in the crossbar controller, one for each

output bus. The destination codes, together with the bus requests generate the individual

bus requests. The bus arbiters grant the requests according to the priority logic.

library ieee;

use ieee.std_logic_1164.all;

entity CROSSBAR is

port ( data1,data2,data3:in std_logic_vector(7 downto 0);

dout1,dout2,dout3:out std_logic_vector(7 downto 0);

dest1,dest2,dest3:in std_logic_vector(7 downto 0);

req1,req2,req3,CLK,RST:in std_logic;

Page 127: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

gr1,gr2,gr3:out std_logic

);

end CROSSBAR;

architecture STRUCT of CROSSBAR is

signal R1,R2,R3,G1,G2,G3:std_logic_vector(3 downto 1);

component BUS_ARB

port (REQ1,REQ2,REQ3,CLK,RST:in STD_LOGIC;

GRANT1,GRANT2,GRANT3:out STD_LOGIC);

end component;

begin

GENBA:for i in 1 to 3 generate

GBA:BUS_ARB port map(R1(i),R2(i),R3(i),CLK,RST,G1(i),G2(i),G3(i));

end generate;

R1(1)<= '1' when req1='1' and dest1(1)='0' and dest1(0)='0' else '0';

R1(2)<= '1' when req1='1' and dest1(1)='0' and dest1(0)='1' else '0';

R1(3)<= '1' when req1='1' and dest1(1)='1' and dest1(0)='0' else '0';

R2(1)<= '1' when req2='1' and dest2(1)='0' and dest2(0)='0' else '0';

R2(2)<= '1' when req2='1' and dest2(1)='0' and dest2(0)='1' else '0';

R2(3)<= '1' when req2='1' and dest2(1)='1' and dest2(0)='0' else '0';

R3(1)<= '1' when req3='1' and dest3(1)='0' and dest3(0)='0' else '0';

R3(2)<= '1' when req3='1' and dest3(1)='0' and dest3(0)='1' else '0';

R3(3)<= '1' when req3='1' and dest3(1)='1' and dest3(0)='0' else '0';

dout1<=data1 when G1(1) = '1' else "ZZZZZZZZ";

dout1<=data2 when G2(1) = '1' else "ZZZZZZZZ";

dout1<=data3 when G3(1) = '1' else "ZZZZZZZZ";

dout2<=data1 when G1(2) = '1' else "ZZZZZZZZ";

dout2<=data2 when G2(2) = '1' else "ZZZZZZZZ";

dout2<=data3 when G3(2) = '1' else "ZZZZZZZZ";

dout3<=data1 when G1(3) = '1' else "ZZZZZZZZ";

dout3<=data2 when G2(3) = '1' else "ZZZZZZZZ";

Page 128: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

dout3<=data3 when G3(3) = '1' else "ZZZZZZZZ";

gr1<=G1(1) or G1(2) or G1(3);

gr2<=G2(1) or G2(2) or G2(3);

gr3<=G3(1) or G3(2) or G3(3);

end STRUCT;

6.4 8 TAP FIR FILTER

Design an 8 tap FIR filter.

X

CA0 CA1 CA2 CA3 CA4 CA5 CA6 CA7

Y

library ieee;

use ieee.std_logic_1164.all;

use ieee.std_logic_unsigned.all;

entity FIRFILT8 is

port(X: in std_logic_vector(7 downto 0);

Y: out std_logic_vector(7 downto 0);

CLK,RST:in std_logic);

type F_ARRAY is array(1 to 7) of std_logic_vector(7 downto 0);

signal XA:F_ARRAY;

constant CA0:std_logic_vector(7 downto 0):= ("10000000");

constant CA:F_ARRAY := ("10000000","10000000",

"10000000","10000000",

D Q

CLK

RST

D Q

CLK

RST

D Q

CLK

RST

D Q

CLK

RST

D Q

CLK

RST

D Q

CLK

RST

D Q

CLK

RST

ADDER

Page 129: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

"10000000","10000000",

"10000000");

end FIRFILT8;

architecture RTL of FIRFILT8 is

type P_ARRAY is array(0 to 7) of std_logic_vector(15 downto 0);

signal Yint:std_logic_vector(18 downto 0);

signal P :P_ARRAY;

begin

CLK_PROC:process(CLK,RST,XA,X)

begin

if RST='1' then XA<= (others=>"00000000");

elsif CLK'event and CLK = '1' then

XA(1)<=X;

for i in 1 to XA'high-1 loop

XA(i+1)<=XA(i);

end loop;

end if;

end process CLK_PROC;

SUM_PROC:process(XA)

begin

P(0)<=X*CA0;

for i in XA'range loop

p(i)<= XA(i) * CA(i);

end loop;

Yint<=("000"& P(0))+p(1)+p(2)+p(3)+p(4)+p(5)+p(6)+p(7);

end process SUM_PROC;

Y<=Yint(18 downto 11);

end RTL;

Page 130: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

6.5 HAMMING ERROR CORRECTION FOR SRAMDesign a chip for single error correction for a byte wide static RAM. Use

Hamming code for error correction.SYSTEM BLOCK DIAGRAM

MEMW_BAR

CPU_BUS RAM BUS

MEMR_BAR

--HAMMING ERROR CORRECTION CHIPlibrary ieee;use ieee.std_logic_1164.all;entity HAM_CHIP is

port (CPU_BUS: inout std_logic_vector(8 downto 1);RAM_BUS: inout std_logic_vector(8 downto 1);PRAM_BUS: inout std_logic_vector(3 downto 0);MEMR_BAR,MEMW_BAR:in std_logic);

end HAM_CHIP;architecture STRUCT of HAM_CHIP is

signal CORR_BUS: STD_LOGIC_VECTOR(8 DOWNTO 1);signal SYNDROME,PARITY: STD_LOGIC_VECTOR(3 DOWNTO 0);

EN_BAR

INPUTBUFFER

PARITYGENERATOR

WE_BAR

MAINRAM

RE_BAR

PARITYRAM

RE_BAR

EN_BAR

INPUTBUFFER

EN_BAR

OUTPUTBUFFER

CORRECTIONUNIT

SYNDROMEGENERATOR

Page 131: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

beginRAM_BUS<=CPU_BUS when MEMW_BAR='0' else "ZZZZZZZZ";

-- PARITY GENERATORPARITY(0)<= CPU_BUS(1) xor CPU_BUS(2) xor

CPU_BUS(4) xor CPU_BUS(5) xorCPU_BUS(7) ;

PARITY(1)<= CPU_BUS(1) xor CPU_BUS(3) xorCPU_BUS(4) xor CPU_BUS(6) xorCPU_BUS(7) ;

PARITY(2)<= CPU_BUS(2) xor CPU_BUS(3) xorCPU_BUS(4) xor CPU_BUS(8) ;

PARITY(3)<= CPU_BUS(5) xor CPU_BUS(6) xorCPU_BUS(7) xor CPU_BUS(8) ;

PRAM_BUS<=PARITY when MEMW_BAR='0' else "ZZZZ";

-- SYNDROME GENERATOR

SYNDROME(0)<= RAM_BUS(1) xor RAM_BUS(2) xorRAM_BUS(4) xor RAM_BUS(5) xorRAM_BUS(7) xor PRAM_BUS(0);

SYNDROME(1)<= RAM_BUS(1) xor RAM_BUS(3) xorRAM_BUS(4) xor RAM_BUS(6) xorRAM_BUS(7) xor PRAM_BUS(1);

SYNDROME(2)<= RAM_BUS(2) xor RAM_BUS(3) xorRAM_BUS(4) xor RAM_BUS(8) xor PRAM_BUS(2);

SYNDROME(3)<= RAM_BUS(5) xor RAM_BUS(6) xorRAM_BUS(7) xor RAM_BUS(8) xor PRAM_BUS(3);

-- CORRECTION UNIT

CORR_PROC:process(RAM_BUS,SYNDROME)variable temp: STD_LOGIC_VECTOR(8 DOWNTO 1 );

begintemp:=RAM_BUS;case SYNDROME is

when "0000"=>null;when "0001"=>null;when "0010"=>null;when "0100"=>null;when "1000"=>null;when "0011"=>temp(1):=not temp(1);when "0101"=>temp(2):=not temp(2);when "0110"=>temp(3):=not temp(3);when "0111"=>temp(4):=not temp(4);when "1001"=>temp(5):=not temp(5);

Page 132: Ss Limay Vhdl Book

Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman ,

This manual specially created for EFY & IT Magazine CD

when "1010"=>temp(6):=not temp(6);when "1011"=>temp(7):=not temp(7);when "1100"=>temp(8):=not temp(8);when others=>temp:="XXXXXXXX";

assert false report "Unknown syndrome";end case;CORR_BUS<=temp;

end process CORR_PROC;CPU_BUS<=CORR_BUS when MEMR_BAR='0' else "ZZZZZZZZ";

end STRUCT;