You are on page 1of 132

DIGITAL DESIGN WITH

VHDL
Dr. S. S. Limaye Professor of Electronics, RKN Engg College

CMR Design Automation P. Ltd. Salesdel@cmr-da.com Salesblr@cmr-da.com

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

About the author


Dr. S. S. Limaye passed B.E. (Electrical Engineering) exam with a gold medal From Visvesvaraya Regional College of engineering, Nagpur in 1971. He passed M. Tech. (Electrical Engineering) from Indian Institute of Technology, Kanpur in 1973 with a specialization in electronics. He started his career as an assistant design engineer in the R&D department of DCM Data products, New Delhi. Initially he worked on a TTL MSI based minicomputer named Galaxy 11. Later, he worked on several microprocessor based designs. In 1978 he was made Manufacturing Support Services Manager. Here, he designed various test jigs and diagnostic software for computer manufacturing. He later worked as a Works manager at Eiko Computers Bangalore, Development manager (Process control) at PSI data systems at Bangalore and Vice President (Technical) at Cherry Computronics, Srinagar. He joined Shri Ramdevbaba Kamla Nehru Engineering college, Nagpur in 1989 as an Assistant Professor. In 1997, he was awarded a Ph.D. degree by the Nagpur University and subsequently he was promoted as a Professor. He has published several papers in national and international journals. He has guided several VHDL based projects at the undergraduate level and conducted VHDL training programs in collaboration with M/S CMR design automation P. Ltd.

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

FOREWORD
This book is the result of a series of training courses we conducted for electronics design professionals. Interaction with customers in Microelectronics Design for over a Decade has given a clear idea about the typical design projects undertaken in India. We saw that HDL based design methodology was fast gaining ground there was a great need for training working design engineers who may not have had a chance to learn this design methodology while at College. We at CMR formulated a four days intensive training package in collaboration with academicians. This program was immensely popular. In a span of 1 year, we ended up training nearly 120 professionals from 30 different organizations. We went on upgrading the contents of the package based on the feedback received from each training batch. Now we are enlarging the contents and making them available in a book form so that it will also be useful to the students undergoing a VLSI design course and to the professionals who can do self-study. To facilitate hands on experience, we have based our practical exercises based on VIEWLOGIC software suit. I hope that this book will be well received by the readers.

Mahesh Chandra
Director, CMR Design Automation P. Ltd. New Delhi

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

PREFACE
VHDL (VHSIC Hardware Description Language) is a relatively new language. VHDL is mainly used for simulation, synthesis and testing of digital circuits. VHDL user base has been sky rocketing in the recent years. Although many books have appeared on the subject, I feel that the readers bookshelves have space for another book written with a different perspective. We have given equal emphasis on digital design and VHDL. Thus it is not just a dull language reference manual but a lively text which introduces the language in a step by step way, provides many tips and tricks, gives plenty of examples and also gives review questions to reinforce your learning. Care has been taken to ensure a smooth transition from popular undergraduate textbooks on digital design to VHDL. Practical exercises based on Viewlogic software suit have also been given. I hope that university 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 called GALAXY 11. It was a proprietary design that inherited many useful features from HP21MX and PDP 11, which were popular those days. It was built from scratch using 74XX series TTL SSI and MSI parts. Then in 80s we witnessed a wave of microprocessor based designs in which the role of hardware design engineer underwent a radical change. The digital design was divided into two distinct areas. The first area was design of chips and the second was design of equipment and systems. With the increasingly sophisticated fabrication technology the chip designers included more and more functionality in the chips. The system designer selected a collection of LSI chips suitable for his application bound them together through glue logic made from TTL MSI ICs. The glue logic mostly consisted of chip select decoders and tristate bus drivers. As far as general-purpose computers are concerned, the world was swamped with IBM PC wave. For the sake of compatibility, the clone makers made the chip addresses and bus architecture 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 standard glue chips were built from Programmable Gate Arrays. Electronics system designers services were required mainly for the design of special purpose dedicated computers and random interface logic. The use of standard chips for a given application was not always optimal. If a chip could be designed starting from scratch, then the resulting design would be most optimal. Such chips were called Application Specific ICs or ASICs. However, the cost economics those days did not permit a custom chip design unless the production volume
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

was very large. Custom design for medium volume was done with the help of Programmable Gate Arrays and the design for small volume was done with the help of Field Programmable Gate Arrays (FPGAs). Today, with the help of sophisticated Computer aided design tools, the set up costs have dramatically reduced and the ASIC option is cheaper for a production volume as low as 1000 pieces. PGAs and FPGAs are economical at even lower volumes. Apart from cost reduction, custom chips offer other advantages such as less time to market, more reliability and compactness. There is no doubt 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 the state of 70s. We are back to the drawing board with diagrams of gates, registers and decoders. There is one significant difference however, that the complexity of the circuits that we design today is 10 to 50 times higher. This necessitates a total change in the design methodology. Earlier, we followed a schematic based methodology in which we designed smaller blocks by interconnecting available chips and then compounded these blocks 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 upto 10000 basic gates. Beyond this, we must switch over to a hardware description language with a top down approach. Imagine that you are designing a chip as big as a Pentium with 2 million transistors. It is meaningless to draw its schematics. In such cases it is more convenient to describe the design functionality at a higher level and leave the task of converting it to silicon to an automaton. This is where hardware description languages come into picture. Organization of the book. The learning curve of VHDL is quite steep. Some people describe VHDL as a Very Hard Description Language. But it is possible to start with a small subset of the language and then gradually enlarge the scope of learning. Therefore, although the preferred design methodology is top down, the preferred sequence of learning in my opinion 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 and operators are described. Then in chapter 3, we come to the design of simple entities at the data flow level. Once a set of primary entities is built, in chapter 4 we build composite components at the structural level. In chapter 5, we design bigger components at the behavioral level. Design of test benches is also covered here. In chapter 6, some design examples are given.
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

The exercises at the end of each chapter will stimulate your thinking and reinforce your learning. The suggested lab experiments will give you hands on training. The companion CD that comes with this book contains the source code for the examples and also a large number of design projects collected from the field. You could use these examples as templates for starting a similar project. In the end, I hope that this book will be useful for university students undergoing a VLSI design course and also to practicing design professionals for self-study.

Dr.S.S.Limaye. Professor of electronics, Ramdevbaba Kamla Nehru Engg. College Nagpur

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

CONTENTS
Chap Title
1 Introduction 1.1 History 1.2 Design Methodology 1.3 Hardware modeling issues 1.4 Overview of VHDL Language fundamentals 2.1 Data types 2.2 Assignment statements and Operators 2.3 Objects 2.4 Attributes of objects 2.5 Simple logic examples 2.6 Practical session on simulator DATAFLOW style of description 3.1 Conditional concurrent assignment 3.2 Selected concurrent assignment 3.3 Block statement 3.4 If and Wait statements 3.5 Examples of simple sequential circuits 3.6 Finite State Machines 3.7 Designing for synthesizability 3.8 Practical session on FPGA express STRUCTURAL style of description 4.1 Component declaration and instantiation 4.2 Configuration statement 4.3 Configuration declaration 4.4 Generate statement 4.5 Generic statement 4.6 Package statement 4.7 Examples of structural style 4.8 Practical session with ACTEL backend tool BEHAVIORAL style of description 5.1 Case statement 5.2 Loop and exit statements 5.3 Null statement 5.4 Assert and Report statements 5.5 Functions 5.6 Procedures 5.7 File I/O operations 5.8 Test Benches Design examples 6.1 Digital Filters 6.2 Simple CPU

Page No
1

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

CHAPTER 1

INTRODUCTION
1.1 HISTORY VHDL (VHSIC Hardware Description Language) is a language for describing hardware. Its requirement emerged during the VHSIC development program of the US Department of Defense. The department organized a work shop in 1981 to lay down the specifications of a language which could describe hardware at various levels of abstractions, could generate test signals and record responses, and could act as a medium of information exchange between the chip foundries and the CAD tool operators. However, due to military restrictions, it remained classified till 1985. There was a large participation 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 DOD granted a permission to hand over the specs to IEEE. Subsequently IEEE released the IEEE 1076/A standard in 1987. It was later revised in 1993. The 1993 revisions are minor 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 similar to ADA. It is an object-oriented language and therefore people familiar with C++ or PASCAL 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 not synthesized. At the moment, what can be synthesized is vague and very much tool dependant. 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 sequential instructions.

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

When a designer is handed over the specifications of a new product, he can start the design using one of the following approaches. TOP DOWN. In this approach, first the top-level behavior is designed and then it is partitioned it into smaller 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 suitable for large designs, typically involving more than 10000 basic gates. Many FPGA based designs follow this approach. BOTTOM UP. This is the traditional schematic based approach. It is used when a library of known low level components such as 74XX TTL is available. You build medium subsystems from them and then finally interconnect them to realize the overall system. This approach is suitable 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 dont go right up to the component level. You can stop when you can find suitable medium level entities for realizing the design. A library of medium level components is prepared for this purpose, using the bottom up approach. This approach is suitable for ASIC design where vendor supplied cell libraries are available.

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

BEHAVIOURIAL DESCRIPTION (VHDL) MORE Copyright CMR Design Automation P Ltd, E 534 Greater Kailash II, New Delhi 110048 ABSTRACT Suppliers of ExcelVHDL, Speedwave VHDL, Fintronic Verilog, Specman , LEVEL This manual specially created for EFY & IT Magazine CD REG. TRANSFER DESCRIPTION (VHDL)

GATE LEVEL NET LIST (FPGA EXPRESS, AMBIT)

ANALYSIS

SYNTHESIS

Fig 1.1 A typical design process First, we need to design the system architecture, identify major blocks and define their interface signals. This is a job, which requires the creative abilities of the right hemisphere of the human brain. We cant expect any computer support at this stage apart from some drawing tools. Having done this, the circuit behavior can be transcribed into a machine-readable form using the behavioral description style of VHDL. At this stage, the emphasis is on obtaining the terminal behavior without bothering about how the circuit will be realized. This description serves as a test environment for part by part testing of individual subsystem realizations at lower levels of abstractions. Then each subsystem is rewritten in Register Transfer Level (RTL) form. In this form, the system is described as a set of registers and ALUs interconnected by set of data buses. The selection of registers on data buses, function selection of ALU and storage of bus contents into selected registers is done in a sequential manner using the control signals generated by a control unit. Todays synthesis tools can understand VHDL code written in RTL style. From this point onwards, it is only the mechanical work of optimization and mapping. If done manually, it is done with the left hemisphere of the brain. This is the area that is most suitable for computerization. The synthesis tool translates the RTL description to a structural description using the components available in the target
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

system. In case of CPLDs, these devices are AND-OR arrays, in case of SRAM based FPGAs they are configurable logic modules and in case of ASICs they are standard cell libraries. The synthesis tool must be aware of the target devices component repertory. The FPGA express from Viewlogic supports a large family of FPGAs from popular FPGA vendors. While FPGA express is available on PCs, the synthesis tools for ASICs like ambit are available only on workstations. Having obtained the structural description, our next job is to physically place the logic blocks on the target device and interconnect them using the available interconnection resources. We also need to assign I/O pads and buffers for the port signals and assign pin numbers. This job is done with the help of back end software tools supplied by the chip manufacturers.

1.3HARDWARE MODELLING ISSUES Since VHDL describes hardware, it has to address many tricky issues, which are not present 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 the circuit of fig 1.2 and corresponding VHDL code.

B C E

A D

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

Fig 1.2 Typical circuit (Note that <= is the assignment operator in VHDL. The syntax details are covered later.) To simulate the above circuit properly, the order of execution of statements in a VHDL program can not be same as the order in which the statements have been
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

typed. All statements in VHDL are considered to be Concurrent. I.e. a statement is executed whenever any variable in its RHS changes state. In the above example, the second statement (D<= A and E;) will execute earlier than the first statement if E changes earlier than B or C. The list of variables in the RHS of a statement is called its sensitivity list. Whenever a state change occurs on any of the variables in the sensitivity list, the statement is fired. b. Sequential blocks: - It is not possible to describe complicated operations in a single statement as shown above. To take care of such cases, process, procedure and function blocks are used. The statements in these blocks execute in a sequential manner like a normal programming language. The process statement can be optionally assigned a sensitivity list. It then gets triggered whenever any variable in the process sensitivity list changes. Thus a process as a whole operates concurrently with 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-level description. c. Delays: - In actual hardware, when an input to a gate changes, the output appears after a delay. The language must have an easy way to describe a delay. VHDL provides delay statements like B<=A after 10ns; If the signal A changes state in the current simulation cycle, nothing is done immediately. Only a change is scheduled to occur on B after 10 ns. When the simulation time will advance by 10 ns, the change will take effect. The delay can be of two types. Transport or inertial. In most practical situations, RC low pass circuits cause the delay. These circuits typically introduce an inertial type of delay. An important property of the inertial delay is that, if a narrow pulse (having width less than the delay time) appears at the input of an inertial delay element, then the pulse is not passed to the output. The transport delay on the other hand faithfully repeats the input waveform after the specified delay irrespective of the pulse width. It represents delay lines. A delay can be specified to be of transport type by 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 and outputs, the concept of delta time is introduced. If a delay is not mentioned in an assignment statement, then a delta time delay is assigned to it. Physically, delta time is zero but logically, it represents a delay of one evaluation cycle. The simulation
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

process goes in two phases, namely evaluate and propagate. In the evaluation phase, all inputs those have changed state trigger corresponding statements. But the values are not assigned to the target variables of these statements unless the entire evaluation process is over. The propagate phase starts after all statements are evaluated,. In this phase, the changed values are assigned to the LHS variables. Since these variables may be appearing on right hand side of some other statements, these assignments may again trigger some more statements. This cycle continues till the circuit reaches a steady state and no further triggering occurs. Then the simulation clock is advanced by an amount known as tick and signal changes scheduled to occur due to earlier statements are checked. The tick period should be set to a value that is less than the smallest delay you want to simulate. However, making the tick value too small makes the 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 an indefinite evaluation cycle and hang. If the statement is modified as A<= not A after 5 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 as the are dependent on the target technology and routing. The delays mentioned in VHDL programs are for simulation only. The synthesis tool ignores them and acts on only the logical part of the statement. After realizing the circuit and routing, the back end tool calculates the delays and pastes them back to the higher level for a realistic simulation. This is called back annotation. IEEE has evolved a standard called VITAL for this purpose. Note that it is not possible to synthesize a delay line by a statement like B<=A after 20 ns. For synthesizing delays, one has to instantiate a delay line component on the target device if it exists. f. Free mix: - To allow flexibility, VHDL allows structural and behavioral styles to be freely mixed. g. Hierarchical structure: - For managing large projects, it is necessary to split it into several levels of hierarchy. VHDL allows a hierarchical design by making use of libraries and packages.

1.4 Overview of VHDL

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

VHDL syntax is very close to that of ADA. The VHDL literature uses terms like objects and classes but VHDL is not a fully object oriented language. It incorporates some features of object oriented languages like C++ or Object Pascal, namely functions with default parameters, function overloading and operator overloading. The classes in VHDL are more like structures of C++ because they are not allowed to have function members. In VHDL, anything that occupies memory is called an Object. These objects have to be derived from some predefined classes. However, for defining classes, the keyword TYPE is used instead of CLASS. This is similar to the Object Pascal convention. Inheritance, which is an important OOPS feature, is not supported by VHDL as it complicates synthesis. There are three types of objects in VHDL, namely variables, constants and signals. While variables and constants have same meaning as in other languages, signal is a special type of object. Every signal has an associated driver that maintains a history of its past transactions and a list of future transactions scheduled for it. The most unusual aspect of VHDL is that the order in which VHDL statements are typed is immaterial because all statements are evaluated concurrently. It also has provision for sequential blocks that can be enclosed in process, procedure or function bodies. Functions and procedures are called by other statements but a process is automatically triggered when an object in its sensitivity list changes state. VHDL has totally different sets of statements for the sequential and concurrent parts of the program. One of the often-committed mistakes by new designers is to use a sequential instruction 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 a smallest compilable piece of code. A statement must be enclosed inside a design unit to get compiled. Isolated statements cannot be compiled. There are 5 types of design units namely entity, architecture, configuration, package declaration and package body. One can have a meaningful program with entity and architecture units only. The other units are used for additional information. A) Entity Each component or subsystem that we want to design is identified by its entity name. The entity unit defines the components name and its port signals. The syntax of entity declaration is: Entity ENTITY_NAME is Port (SIGNAL_NAME: mode DATA_TYPE, more signals); End ENTITY_NAME;
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

Where mode can be in, out, inout or buffer. The inout mode is used for bi-directional signals and buffer mode is used for outputs whose values also sensed inside the entity. If a signal is defined as out instead of buffer, then it can not appear on the RHS of any assignment statement. Similarly, a signal with in mode can not appear as a target of an assignment statement. Physically the inputs and outputs of an entity will be bunches of wires carrying binary data. However, we can specify composite data types such as bit vectors, records or integers in the port statement. In the final synthesis, they get converted into individual bits. The data types are covered in chapter 2. A typical entity unit looks like this: Entity ANDGATE is Port (in1, in2: in BIT; output: out BIT); End ANDGATE; The entity unit may also define additional objects, generic parameters, functions and procedures as explained in the later chapters. The port objects are automatically treated as signals and not variables. B) Architecture The architecture unit describes the implementation of the port behavior declared in the entity unit. In high level behavioral description, it consists of several process statements. In the Data flow description style (Generally used for describing basic gates or simple logic blocks), it consists of a set of concurrent statements. In the structural style, various components i.e. other smaller entities, are instantiated and their interconnections are specified by the port map statements. 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 the structural modeling style. Of course VHDL allows all modeling styles to be mixed. The architecture for the above entity will look like this.
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

Architecture DATAFLOW of ANDGATE is Begin Output<= in1 and in2 after 10 ns; End DATAFLOW; There can be any number of architecture units for a single entity unit. All the architecture names referring to a single entity must be distinct. Usually the architecture name denotes its description style. Objects, functions etc. that are defined in the entity unit are passed on to all its architectures. C) Configuration The component declaration in a structural description only defines a socket where some component will be plugged in. If there exits a component by the same name in the design library, then it is automatically chosen to be plugged in. Otherwise the configuration unit is used to specify the entity and the architecture that will be used for instantiating the components. The configuration unit is optional. Its job can also be done by means of configuration statement inside the architecture as explained later. D) Package declaration The Package and Package body units are used for declaring a set of useful type declarations, functions and procedures. Other programs can easily use the package contents with the use statement. E) Package body The package declaration gives only the prototype declarations of the functions. The implementation 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 primary design unit.

Libraries: - A set of utility packages can be put inside a library. Library is basically a
subdirectory in the host environment. The present working library is identified by the keyword work in VHDL. A package named STANDARD containing some basic definitions is automatically included in every program. The STANDARD package defines a data type BIT for representing binary numbers. In many situations we need to use multivalued logic to represent dont care values and tristate buses. In such cases, it is recommended that one should use a package called std_logic_1164 from the IEEE
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

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 next design unit. Thus if we have 5 design units, then the library and use statements must be repeated before each unit. However, the definitions used by a primary unit are automatically passed on to its secondary unit. So if we have IEEE library statement before an entity unit, we dont 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 to have the same name repeated in different libraries. The compiler searches for the names in various libraries in a user defined search order. The work library is always the first in 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 and therefore, the semicolon is put after end. The language is not case sensitive. So entity, ENTITY and ENtity have same meaning. In this book, we have followed the C convention of using the small letters for the key words and capital letters for the user defined identifiers. Some people like to use the exactly opposite convention. Indentation should be used to clearly identify various statement blocks. However, it is not mandatory. A pair of dashes denotes the beginning of comment. All matter on the line after - - is ignored.

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

REVIEW QUESTIONS Q1.1 Fill in the blanks a) 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 false a) 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 primary units. Q1.5 Suppose you have designed an entity ANDGATE having architecture named DATAFLOW. Can we design another entity ORGATE and name its architecture as DATAFLOW? Q1.5 Suppose you have defined a function PARITY in your source program and a function having the same name exists in one of the libraries used by you. Which version of the function will be selected?

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

CHAPTER 2 Language fundamentals


1.1 Data types
Interestingly, 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 a package called STANDARD, which is automatically included with every program. In addition to the standard types, the user is free to define an unlimited number of custom data types for meeting his requirement. The VHDL data types are categorized into 4 major 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 and constants. A signal type object maintains a time history of its value changes while a variable type object can store only its current value. A constant can be assigned value only at the time of its definition. Scalar types: Scalar data types consist of a single data element. Objects belonging to scalar data types have an ordering relation defined for them. I.e. if A and B are two objects of a scalar type, 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 is as 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 class and type are often used interchangeably. The type declaration statement describes only the internal structure of an object. It does not have any physical existence. The objects derived from the above classes have a physical existence in the sense that memory is allocated for them. Defining an object of a class is called 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 derived from. In the enumeration identifier list, the value of a symbol increases from left to right. E.g. in the FOUR_VALUED_LOGIC enumeration given above, X is the smallest
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

element and 1 is the largest element. So, an expression like Z < 0 will evaluate to TRUE. The STANDARD package starts from scratch to define the basic data types using the enumeration method. Some basic declarations are given below..
type type type type type BOOLEAN is (FALSE, TRUE); BIT is ('0', '1'); INTEGER is range -2147483648 to +2147483647;-- 32 bits signed REAL is range -0.179769313486231e+309 to +0.179769313486231e+309; 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 integer Type MY_REAL is range 7.5 to 12.5; --custom real Type TTL_VCC is range 4.75 to 5.25; --custom real Note that the above user defined types are completely new types. Only numerical operations are permitted on them. Mixing them with standard integers or any other user defined numerical types is not permitted. Also, the operators and functions, which are overloaded for integers or real numbers, are not applicable to the user defined numeric types. If we want the new type to inherit all the overloading properties of the base type, then we must declare them as subtypes of integer or real as explained later. VHDL does not allow mixed mode arithmetic. The type of all objects in an arithmetic operation and the type of the target object must be same. If we want to perform mixed mode arithmetic, then all the operands must be converted to one type by suitable conversion functions. Various numeric types can be converted into 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);
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

X <= MY_REAL(5.3)+7.1; The STANDARD package, which was a part of the original release of the IEEE standard, declares only one data-type for representing binary numbers, namely BIT. Unfortunately, this data type does not adequately represent many practical situations where we need to consider the strength of the driver, unknown state, dont care state and high Impedance State. To tackle this problem, many tool developers defined their own multi valued logic types, which made portability a big problem. To solve these difficulties, IEEE later released the STD_LOGIC_1164 package, which declares a data type STD_ULOGIC having 9 values 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 function to take care of two outputs driving a single signal. Such functions are required for describing tri- state buses and wired-or logic. For this purpose, the package declares 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 and strength of all its drivers. For new designs, it is recommended to use either BIT or std_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 type called 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 base unit. E.g. a time of 5 ns is equivalent to 5,000,000 fs and so, it is stored as 5,000,000. Since it is basically an integer type, it can be multiplied by another integer giving a result in physical units. Similarly, when a physical data-type is divided by the base unit, the result is an integer. E.g.
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

Signal IntTime: integer; Signal PhyTime: time:= 5 ns; IntTime <= PhyTime/ 1 fs;-- The value of IntTime will be 5,000,000 Subtypes: Subtype is a type with a range constraint. The set of values that a subtype can have is a subset of the values of the base type. The arithmetic and logical operations that are defined for the base type are valid for the subtype also because they inherit all properties of the base type. Subtypes are basically used for 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 impose a range constraint. In that case, it just becomes an another name for the base type 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 an attribute of the integer data type. Attributes are discussed in detail later. Numeric literals: Numeric values in an expression are called literals. Underscore characters may be freely inserted in a number to improve its readability. Following are the examples of valid integer literals. 5 , 55E4, 0, 5_657_554, -70 Real 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 2 We 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 exponent The base value and the exponent are given in decimal notation. e.g. 2#1101_0011# 16#1_B3# 16#A#E2 (Binary) (Hex,1*256+11*16+3) (Hex,10*256)

Composite types:
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

As opposed to scalars, the composite type contains a collection of data elements. If the type of all the elements in a composite data type is identical, then it is called an ARRAY, otherwise it is called a RECORD. The syntax of array declaration is as follows. Type ARRAY_NAME is array (index range) of ELEMENT_TYPE; The range may be either ascending or descending. For declaring multi dimensional 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 also give a data-type name in its place. The index range then becomes the range of that 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 type range <> 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 to specify the range. E.g. Signal MyFloatArray: FloatArray(0 to 31); The STANDARD package declares two unconstrained array types namely STRING 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 whose elements 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 most synthesis tools do not support more than 2 dimensions. We can access the elements of an array by giving the object name followed by the index 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.
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

An important subset of string literals is the Bit string literal. Bit string literals are 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)<=XFF; Note that a string like 1101 is treated either as a bit string or a std_logic string depending the type of the target object. However, the X and O prefixes always convert the string into a bit string and therefore its target object must be a BIT_VECTOR. If the target is std_logic_vector, then the bit string literal must be converted into a std_logic string literal by using the To_StdLogicVector function defined in the std_logic_1164 package. E.g. Signal S1, S2, S3: std_logic_vector (7 downto 0); Signal B1, B2, B3: bit_vector (7 downto 0); B1<= 11001100; B2<= XFF; B3<= 11 & O77;-- Match the length by concatenating 2 bits with two octal digits S1<= 11001100; S2<= To_StdLogicVector (XFF); S3<= To_StdLogicVector (O377);-- 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 a strongly typed language it treats them quite differently. The arithmetic operations are defined only for the integers and the concatenation operation is defined only for bit vectors. The ieee.std_logic_arith package overloads the arithmetic operators on std_logic_vectors so that we can perform arithmetic operations on them. But if you want to assign an integer value to a std_logic_vector or vice versa, then you have to explicitly use conversion functions CONV_STD_LOGIC_VECTOR and CONV_INTEGER. The prototype of CONV_STD_LOGIC_VECTOR in std_logic_arith package is as
follows. 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 conversion Consider 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.
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

A<="00001111";--OK A<=X"0F";--OK A<=O377;--not OK as length of RHS string is 3*3=9 and LHS=8 A<="11"&O"77";--OK version of above B<="00001111"; --OK B<= X"0F"; -- not OK as B is std_logic_vector B<=To_StdLogicVector (X"0F");--OK version of above B<= O"377";" -- not OK as B is std_logic_vector B<=To_StdLogicVector (O"377");--OK version of above I2<=B; -- not OK as I2 is integer and B is std_logic_vector I2<=conv_integer (B);--OK version of above B<=CONV_STD_LOGIC_VECTOR (I,8);--OK I2<=conv_integer (A); -- not OK as conv_integer is not defined for bit_vector I2<=conv_integer (To_stdLogicVector(A)) ;--OK version of above A4<=A4+1; -- not OK as + operator is not overloaded for bit_vector B4<=B4+1; --OK as + operator is overloaded for std_logic_vector I1<=I1+1;--OK I2<=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;
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

Access types: Values belonging to access types are memory addresses of dynamically
created 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 a mechanism by which a VHDL design communicates with the host environment. The syntax 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 STATEMENTS


The 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 statements end 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, the process 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 a sensitivity list is given, then after coming to the first statement, the process remains suspended till an event occurs on any signal in the sensitivity list. The process can also be suspended due to a wait statement anywhere in the statement-body. If the sensitivity list is omitted, then the process is always active. In such processes, it is necessary to include wait statements otherwise they will cause the simulator to hang. Wait:
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

The wait statement is used to suspend a process until some condition is met. There are three 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 will come out of wait state when the Boolean condition changes from false to true. If the condition remains permanently high thereafter, it does not wake up the process again and again. 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, otherwise operator := is used. For initializing an object, assignment should be made during its definition. These initializing assignments always use the := operator irrespective of the type of the object. Constants can be assigned value only during their definition. The only exception being that a constant can be declared in the package declaration and given a value in the package body. Expression is either a single object or a literal or a combination of objects and literals connected by suitable operators. Delay specifier can be given only if the target of the assignment is a signal. Types of assignments: Concurrent and sequential An assignment statement in concurrent portion of the program is called a concurrent assignment and an assignment statement in sequential portion of the program is called a sequential assignment. Every concurrent assignment produces a DRIVER for the signal, which contains the schedule for its future assignments. A sequential body like a process may contain several assignments to the same signal, but they are all added to a single driver. The time, when an assignment becomes effective, is different for signals and variables. If a process makes an assignment to a variable, then it takes effect immediately but if it makes an assignment to a signal, then it takes effect in the next simulation cycle. In other words, during one invocation of a process, the signals retain their old values till the end of the process while the variables change their values as the program progresses. Another interesting property of concurrent assignment statements is that all concurrent statements get fired at t=0 irrespective of their sensitivity lists and they operate on the initialized data. All processes also get fired once at t=0. Following are some examples of assignment statements.
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

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 string D := 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 type declarations 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 is as follows. ARRAY_OBJ_NAME (RANGE) The direction of the slice range must be same as the direction of the parent array. SLICE EXAMPLES Let 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
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

n1 <= BL(7 downto 4);-- upper nibble of B is copied to n1 n2 <= n1;-- whole array is copied B <= n2(2);-- single bit B receives a bit from an array n2 n1(2 downto 0 ) <= W(13 downto 11 );--both source and target are slices n3<=n1(0) & n1(1) & n1(2) & n1(3); -- copy in reverse order Remember that the direction of the slice range must be same as the direction of the parent array. 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 in parenthesis. 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 elements in 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. If you 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 you want to assign 0 and 1 respectively to bits 7 and 13 of W without affecting the remaining 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 to all the bits. This property is very useful to reset all bits of an array, especially if the length of 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 data register that receives data from memory. The bits 15-13 are op code, bits 12-11 are addressing mode and bits 10-0 are address. We could declare following convenient aliases 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
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

3. Shift operators 4. Adding operators 5. 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 is evaluated from left to right. Parenthesis may be used to clarify the order of evaluation. 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 is TRUE or FALSE. The relational operators are valid for all scalars including enumerated variables. E.g. consider the statementtype 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 types provided that the array elements are scalars. The comparison is made one element at a time starting from left to right. The operators = and /= are valid for all objects except FILE 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, shift right 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 same result by using the slice and concatenation operator. Adding operators: +, -, & The + and operators are valid for all numeric types. The concatenation operator & is valid 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;
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

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 operators mod 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 N e.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 the exponent is of integer type.

1.4 Objects in VHDL: Signals


Anything that stores information is called an object in VHDL. For signal objects, the simulator maintains a data structure called driver of the signal that records the time and a value of each assignment to the signal (called transaction). When a new transaction is added, certain old transactions have to be dropped from the driver in order to be consistent with the delay model used. The rules for adding transaction are explained in the next section. Each concurrent statement produces one driver for the target signal. If more then one concurrent statement assign values to the same target signal, then it becomes a multiwriter signal and it must be declared as a resolved signal type. A signal can be declared as resolved signal type by specifying a resolution function in the declaration of the signal. The resolution function takes all values that the individual drivers wish to assign to the signal and resolves them to produce a single value that is actually assigned to the signal. 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. The procedure for writing resolution functions is described in chapter 5. If we want to declare many resolved type signals, it is more convenient to declare a resolved 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 of the 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 architecture body, but not outside it.

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

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 the architecture 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 waveforms We can conveniently generate waveforms by using assignment statements with multiple transactions. Suppose we want to create a waveform on the signal phase as shown in fig 2.1. Phase:

E) T T+8 T+13
Fig 2.1 Wave 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 drivers A 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

T+50 ns

Effect of transport delay on signal drivers Recall that a transport delay faithfully reproduces the input waveform at the output after a specified delay. Consider following multiple assignments in a process to the signal RX_DATA. Entity TEST is end TEST;-- this entity does not have any ports Architecture T of TEST is
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

Signal RX_DATA: integer; begin process begin 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 the new 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 looks like 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 process begin 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 new transaction are deleted (as in the transport case).
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

2. If the value of the new transaction is the same as the value of the transaction on the driver, 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 more transactions on the driver, these transactions are deleted from the driver and the new transaction is added. 4. For a single signal assignment statement, if the first waveform element is added to the driver, all subsequent waveform elements of that signal assignment are also added to the driver. The driver of the TX_DATA signal looks like this at the end of the process. TX_DATA TX_DATA curr@now curr@now 11 @ 10ns 33@15ns 22 @ 20 ns

Let us consider another example, which clearly demonstrates how the above rules filter out 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 width B<= A after 15 ns;-- large inertial delay C<= 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 A places a transaction (0,15) on B and (0,5) on C. By this time, the driver of C is empty and the driver of B contains the old transaction which now looks as (1,7). Since the value of the new transaction (i.e. 0) is different from the old transaction (i.e.1), the old transaction is 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 used as intermediate storage locations and for passing parameters to functions in the sequential bodies. Variables can not be defined in the concurrent portion of the code. Although 1993 standard has introduced shared variables, most tools dont support them. They can be declared 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 it is declared. Hence variables can not be used to transmit information from one process to another. Process variables retain their values between two invocations but Procedure and function variables are initialized each time the procedure is called. Sometimes the programmer has a choice to choose the object type as a signal or a variable. In that case, it is preferable to choose variable because the synthesis
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

tool does not distinguish between a variable and a signal but a simulation tool assigns a driver only to the signals. Unnecessarily defining too many signals slows down the simulation. Assignment to variables: Assignment to a variable can be made only within a sequential portion of the code. The assignment operator := is used for variables. The target variable immediately assumes the value of the RHS expression. In contrast, recall that an assignment to a signal, made in 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 additional restriction 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 be declared in the package declarations and package bodies.

1.4 ATTRIBUTES OF OBJECTS


The VHDL objects have various properties apart from their value. These properties are called attributes. There are several predefined attributes in the language. The programmer can add his own attributes to objects if desired. Such attributes are used to either convey some additional information to the synthesis tool or for documentation purpose. 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. qvectleft(1) = 3 qvectright(1) = 0

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

qvecthigh(2) = 7 qvectrange(1)= 3 downto 0 qvectlength= 4 qrange = 3 downto 0

qvectlow(2) = 0 qvectrange(2) = 0 to 7 qvectlength(1)=4 qreverse_range = 0 to 3

Since qvect is a multi dimensional array, we need to specify which index we are talking about. The index number (1 or 2) should be given in bracket after the attribute name. In absence of the index specification, the compiler automatically assumes the index to be 1. Thus qvectlength is same as qvectlength(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 with these examples. subtype bit_position is integer range 15 downto 0; Type fraction is range -.999 to .999; Bit_positionlow= 0 Bit_positionhigh= 15 Bit_positionbase= integer Fractionright = .999 Bit_positionleft=15 Bit_positionright=0 Bit_positionbasehigh=2147483647 Fractionleft = -.999

Additional attributes for integers and enumerated data types: pos, val, succ, pred, leftof, rightof Attribute pos is zero based index of the given symbol in the enumeration list. Val is the value at the given index in the enumeration list. Pred is predecessor and succ is successor. Consider the type declarations Type T1 is (A, B, C, D); T1Pos (B) = 1 T1val (3) = D T1succ (C)=D T1pred (C)=B T1leftof (B)=A T1rightof (A)=B T1rightof (D)=error

Attributes of signals: event, stable, last_event, last_value, delayed, quiet, active, last_active, transaction Consider the statement Signal A:BIT; The meanings of the attributes become clear with following illustration. Aevent = TRUE if A has changed state at current simulation cycle Astable = TRUE if A has not changed state at current simulation cycle
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

Astable(5 ns) = TRUE if A has not changed within last 5 ns Alast_event = time elapsed since last event on A (FALSE If Aevent is true) Alast_value = value of A before the most recent event Adelayed(10 ns) = another copy of A but delayed by 10ns Aquiet(10 ns) = TRUE if no transaction has been placed on A in last 10 ns Aactive = TRUE if a transaction has been placed on A in the current simulation cycle Alast_active= time elapsed since last transaction on A (FALSE If Aactive is true) Notice the similarity between event and active attributes. Event is true only if the value 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 ATTRIBUTES In addition to the above attributes, the user can define his own attributes to various entity class elements. The entity class includes not only the entity design unit but also architecture, configuration, procedure, package, type, subtype, constant, signal, variable, component and label. The user-defined attribute has to be defined in two steps. In the first step, the attribute name and its 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 is Port (-------); 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 dont have any computational significance. They can be used for various purposes. Some synthesis tools use these attributes to convey some additional parameters of the objects being described. They can also be used for documentation.

1.5 EXAMPLES OF SIMPLE CIRCUITS


--TWO INPUT AND GATE
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

entity AND2 is port (A, B: in BIT; Y: out BIT); end AND2; architecture DATAFLOW of AND2 is begin Y <= A and B after 10 ns; end DATAFLOW;

--HALF ADDER entity HADD is port (A,B: in BIT; S,C: out BIT);-- S = sum, C= Carry end HADD; architecture DATAFLOW of HADD is begin S<= A xor B after 10 ns; C<= A and B after 10 ns; end DATAFLOW;

--FULL ADDER entity FADD is port (A, B, Ci: in BIT; S, Co: out BIT);-- S = sum, Ci = Carry in, Co = Carry out end FADD; architecture DATAFLOW of FADD is begin 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 MUX entity MUX2 is port (A, B, S: in BIT; Y: out BIT);-- A, B are inputs, S is select control, Y= out end MUX2; architecture DATAFLOW of MUX2 is begin 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
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

Y: out BIT_VECTOR( 3 downto 0));-- Y is output end AND2_4; architecture DATAFLOW of AND2_4 is begin Y <= A and B after 10 ns; end DATAFLOW; -- 2:4 DECODER entity DECODER2_4 is port (A1, A0: in BIT; Y0,Y1,Y2,Y3: out BIT); end DECODER2_4; architecture DATAFLOW of DECODER2_4 is begin 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 SIMULATOR


For simulating the above examples, we can use ViewLogics Workview Office suite that supports digital, analog, and mixed digital/analog design and simulation. It also supports synthesis through FPGA express. For installation of the package, refer to the Workview Office documentation. Before starting anything, we need to create a project through the Project Manager program. The project manager creates a subdirectory in the project name. All relevant files for the project are stored here. We use HDL manager for source code entry and analysis and SpeedWave for simulation.

Creating a new project


First, create a folder named VHDL using windows explorer. We will create a subfolder for each project in this folder. The installation program would have put the Workview office toolbar on the desktop. If the Workview office toolbar is not visible for some 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 a dialog box appears which asks you whether you want to copy the current library paths to 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 may use the BROWSE button to locate the parent directory, i.e. VHDL. Since the GATES subdirectory is non-existent, the project manager will automatically create it. e. Enter project name as SIMPLE_GATES and click NEXT.
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

f. For instantiating components from FPGA or ASIC cell libraries, we need to include the corresponding configured libraries. For the time being, we dont need them, so click NEXT. g. If we need to include previously designed libraries, we can specify them. For the time being, we dont need them, so click FINISH. h. A dialog box appears which summarizes your choices. Click OK to confirm. Since the GATES subdirectory does not exist, a dialog box appears to ask whether it should be 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. Whenever speedwave is invoked in future, the project settings will be automatically taken from this file. The default settings will change only when another project is opened or another new project is created. Suppose somebody has changed the active project and you want to restore the SIMPLE_GATES as the active project. Open project manager from the main toolbar and click File>open. Navigate to the SIMPLE_GATES.vpj file and double click it. Once the active project is set, we dont need the project managers window. It is better to close it. Entering VHDL code a. VHDL code can be conveniently entered through the HDLPAD editor. HDLPAD is a modified version of WORDPAD having a facility of automatic color coding of the key words. However the HDLPAD package does not have a facility to save a new file in plain text format. So, you should create a startup file with only one line entered on it using Notepad or any other plain text editor. Save the file as AND.VHD in C:\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 it gates saved as AND.VHD. Otherwise it gets saved as AND.VHD.TXT. Click on the SpeedWave icon. The SpeedWave dialog box pops up. The speedwave dialog box may be considered as the parent window for all other windows. From this dialog box, we can either click the Analyze design tool button for invoking the HDL manager or the load design tool button for invoking the simulator. 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 invoke the HDL manager. For the first invocation in a project, the Jumpstart wizard opens up. You can answer the wizard queries as follows. c. For using previously defined libraries we need to tick Yes please use existing libraries, 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. By default, the windows user name is selected as the library name. If the session was started using administrator as the user name, then library is named as administrator.lib. It is desirable to change the name to a self-explanatory name. This will help in including useful files of this library in other projects. Inside the current project, the library is identified as work. Rename the library as GATES and Click NEXT.
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

e. Tick the Add source files option and navigate to the AND.VHD file that you generated in step a. Click NEXT. f. A dialog box for selection of Standard libraries pops up. IEEE and synopsis libraries are automatically selected. At this stage, we dont 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 user library symbol in the left pane so that a source-file list is presented. RIGHT CLICK on AND.VHD. This will pop up a dialog box with options for analyze, edit etc. Click on the Edit option. h. HDLPAD gets invoked. Enter the complete program and save it. i. Close HDLPAD. Analyzing the VHDL design a. 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. The source file gets analyzed and the results of analysis are presented in the message window at the bottom. b. If there are errors, double click on the error so that HDLPAD gets invoked with the erroneous line highlighted. Edit and make corrections for the mistakes. Again analyze till you get an error free compilation. Simulating a VHDL design a. 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. Since our design is in the GATES.lib library, double click on it so that all entities in the library are displayed. Click on the entity AND2. Click OK. b. Now the simulator window opens up. The screen now has four areas. The top left corner 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 into two vertical panes. The left pane displays the design hierarchically. You should click on 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 thje AND2 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 important commands 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 value SIM simulate for one step (100ns by default) STEP <time period> set step size SIM <time period> simulate for the specified time period. For the AND design, first enter the commands HA SIM Note that the new value of A is reflected in the right pane. Y is still at 0. Now type: HB SIM
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

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

OTHER EXAMPLES
For simulating other examples, you may either add them to the same source file or create a separate source file for each one of them. Repeat the above steps for each one. 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. The commands can be given as follows: A A 0101 or A A 5\h A B 0011 or A B 3\h SIM VIEWING SIGNAL WAVEFORMS When a design is loaded the port signals and internal signals are displayed in the right pane. 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 all other desired signal names. Then right click. A quick menu pops up. Click Display in Vwaves option. The Vwaves window opens up and shows the selected signals. Apply stimulus using command line interface. The corresponding waveforms are displayed in the Vwaves window. If a design has too many signals, then it becomes difficult to watch them in the right pane. In such case, you can watch selected signals in a separate monitor window. For this, use the same procedure as described above but after right clicking, choose the Add to monitor window option instead of Display in Vwaves option. CREATING A COMMAND FILE FOR STIMULUS GENERATION We have seen how to give stimulus to ports by A, H and L commands. In case of large circuits, too many commands have to be given to test the circuit fully. To avoid the trouble of retyping the commands for each test run, we can make a command file and run it. The command file is a simple text file, which can be created through HDLPAD or NOTEPAD. To invoke the command file, click FILE>Run command file menu options. 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 1 Cycle Apply one clock cycle. Monitor object1 object2Add to objects to the monitor window Wave filename.vwf object1 object2Add objects to the Vwaves window e.g. wave fusion.vwf a b c Following command file will be appropriate for testing the 2:4 decoder. Restart Wave decoder.vwf A1 A0 Y0 Y1 Y2 Y3 Sim H A0 Sim
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

H A1 L A0 Sim H A0 Sim

EXERCIZES
E2.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 vowel characters. 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 bit std_logic_vector. 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 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 MSBs 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. a) Declare a record called MY_REC having two bytes B0 and B1, two integers I0 and 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: XFF, X00, 5, 6, .2, 4.5. d) Transfer the contents of B0 and R1 of REC1 to B1 and R0 of REC2. a) Using a single concurrent statement, generate a symmetrical 1 MHz clock. Can it be synthesized? b) Using process and wait statements, generate a 1 MHz clock that is high for 600 ns and low for 400ns. a) Write a single concurrent statement that produces a 10 ns wide pulse on a signal called EDGE_PULSE whenever a signal called INPUT_SIG changes state. Hint: Use Delayed attribute and XOR b) Repeat above so that EDGE_PULSE is generated only for the positive transitions of INPUT_SIG.
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

E2.2

E2.3

E2.4

E2.5

E2.6

E2.7

E2.8

a) Write the description of a CMOS inverter entity INV with a propagation delay of 10 ns. b) Rewrite architecture of INV such that the propagation delay PD is first defined as a constant with a value of 3RC where R is output impedance and C is load capacitance. 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 type RES with ohm as the base unit. Write another architecture for INV where R and C are defined in physical units. 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.1 type 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.2 signal 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.3 subtype nibble is std_logic_vector(3 downto 0); subtype byte is std_logic_vector(7 downto 0);
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

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.4 type 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 is Signal Clock: BIT; begin Clock_proc: process Begin 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_SIGdelayed (10 ns); (b) EDGE_PULSE <= INPUT_SIG and (not INPUT_SIGdelayed (10 ns)); E2.7 (a)
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

entity INV is port (A: in BIT; B: out BIT); end INV; architecture A1 of INV is begin 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 in femto seconds and then convert it into integer. Finally we multiply the product by 3 femto 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; begin B <= not A after PD; end A2; ( c) In this case, the product of 1 ff and 1 ohm is 1 femto second. So we dont have to multiply it by any scaling constant as above. architecture A3 of INV is type CAP is range 1 to 1E18 units ff; pf=1000 ff; nf=1000 pf; uf=1000 nf; mf=1000 uf; f =1000 mf; end units; type RES is range 1 to 1E9 units 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; begin B <= not A after PD; end A3; E2.8
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

X 0 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 and places the same transactions on the driver. Before the first transaction can take effect at t=120, the process is again triggered at t=110. It causes the old transactions to be deleted and new transactions to be placed. Y goes low at t=150. Y would have gone high at t=190 but the process is again triggered at t=175. It deletes the old transactions and places a new trio which takes effect at t=175, 215 and 255. 80 110 175

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

CHAPTER 3

DATAFLOW style of description


Dataflow description is a middle ground between behavioral and structural descriptions. This description consists of concurrent assignment statements that specify the flow of data through various gates, registers or buses in the system. We have discussed realization of simple gates using unconditional signal assignments in chapter 2. More complex logic blocks can be described using conditional and selected signal assignments. Synchronous Sequential circuits can be described either by using guarded assignments, or by using clock edge expression as an enabling condition.

3.1 Concurrent conditional assignments


A 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 else Expression2 when condition2 else ----------------------ExpressionN when conditionN else ExpressionN+1; The conditions need not be mutually exclusive. During the execution of the statement, the conditions are evaluated one by one and when a true condition is detected, the corresponding expression is evaluated and assigned to the target signal. This method of evaluation forces a priority encoding structure for the conditions. This statement is similar to the ifelse if ladder structure which is used in sequential blocks. A 4:1 mux with select inputs S1, S0, data inputs I0, I1, I2, I3 and out put can be described as follows. --4:1 MUX Y <= I0 after 5ns when (S1 & S0) = 00 else I1 after 5ns when (S1 & S0) = 01 else I2 after 5ns when (S1 & S0) = 10 else I3 after 5ns;

3.2 Concurrent Selected signal assignment


The concurrent selected signal assignment statement is similar to the CASE statement of a sequential block. The choices are not evaluated in a sequence like the conditional statement. All possible values of the selecting 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,
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

------------------expressionN when valueN, expressionN+1 when others; The 4:1 mux example can also be written using a selected signal assignment statement as follows. -- 4:1 MUX --s has been declared as a bit_vector(1 downto 0)) with s select Y <= 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 values should be separated by the symbol |. Eg 00|01. The following example of a 3:1 mux shows the use of oring condition. -- 3:1 MUX --s has been declared as a bit_vector(1 downto 0)) with s select Y <= 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 us build a 3:8 decoder using a selected signal assignment statement. --3:8 decoder entity 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 is Begin With ADR select Y<= 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 ADR from 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
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

binary value i.e. Z , X etc. Another thing to be noted here is that although VHDL is not a case sensitive language, the enumerated literals are case sensitive. So, in the above example, if X is replaced by x, then it will not work. The use of Z state for describing a tristate bus is illustrated in the following example. --OCTAL BIDIRECTIONAL TRISTATE BUFFER (74LS245) library IEEE; use IEEE.std_logic_1164.all; entity BIDIBUF8 is port ( 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 is begin 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 logic library IEEE; use IEEE.std_logic_1164.all; entity MUX4 is port(I0,I1,I2,I3,S0,S1:in std_logic; Y :out std_logic); end MUX4; architecture DF2 of MUX4 is begin 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_logic resolution function. It is important to remember that the conditions in the selected conditional assignment statement must be mutually exclusive. E.g. consider following statements. -- c is bit vector with c select e<= "01" when "10" , "10" when "11" , "11" when "00"|"10" ,
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

"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 used only for non-synthesizable programs like test benches. The guard expression must evaluate to a Boolean value. The statements within the block can use the guard condition by using the guarded keyword. Following examples will clarify the use of BLOCK statement. --Transparent Latch entity TLATCH is port(D,CLK: in BIT; Q: out BIT); end TLATCH; architecture DF of TLATCH is begin B:block(CLK=1 ) Begin Q<= guarded D; End block B; End DF; --+ve edge triggered Quad D flipflop entity DFF is port(D1,D2,D3D4,CLK: in BIT; Q1,Q2,Q3,Q4: out BIT); end DFF; architecture DF of DFF is begin B:block(CLK=1 and CLKevent ) Begin Q1<= guarded D1; Q2<= guarded D2; Q3<= guarded D3; Q4<= guarded D4; End block B; End DF;

3.4 IF statement
IF is a sequential statement and hence it can not be used in the concurrent part of a program. IF statement has following three forms:
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

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 second form, if the Boolean expression does not evaluate to TRUE, then the second set of statements is executed. In the third form, the Boolean expressions are evaluated sequentially and when a first TRUE expression is found, the corresponding set of statements is executed. The same job could also be done by using nested if statements but the advantage of using the third form is that it requires a single end if clause. This form results 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 a high level language without bothering about its actual implementation. Accordingly, there is no explicit instruction to indicate whether a given signal is latched or not. The synthesis tool automatically infers a latch when we specify an enabling condition in an assignment statement. If the condition refers to a clocks edge then it implies an edgetriggered flipflop. If the condition refers to a clocks level then it implies a transparent latch. 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 be mixed with other conditions. The modeling techniques for sequential circuits will be clear from the following examples. Gated SR Latch S S_BAR Q 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 is signal S_BAR,R_BAR,INT_Q,INT_Q_BAR:BIT; begin S_BAR <= S nand CLK ;
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

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 program works 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 the initial values of Q and Q_BAR are both low, the two nand gates at the output latch form an 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 because initialization has no hardware counterpart. Instead of initialization, an asynchronous reset should be used. If we introduce a delay in the assignment statements as follows then there is no hanging problem but the Q and Q_BAR waveforms show a square wave of 10 ns period. 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

Q D FLIP FLOP

CLK RST_BAR

Fig 3.2 D 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
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

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. Since Q is an output port signal, it can not be read, so it is necessary to create an intermediate signal INT_Q, which can be both read and written to. A concurrent statement at the end transfers the value of INT_Q to Q. Instead of creating an intermediate signal, we could have 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-directional tristate buffer, which is not our intention here. Declaring it as inout has two disadvantages. 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 client program must specify the matching port mode. Declaring an output signal as buffer increases the chances of mistakes and confusion. Therefore the method of creating intermediate signals is quite popular. The above program runs all right on a simulator but does not work with a synthesizer. The reason being that the synthesis tool does not accept any assignments in the else part of a clock edge expression. The best way to describe a flipflop is to embed it in a process as shown below. entity DFF is port (D,CLK,RESET_BAR:in BIT;Q:out BIT); end DFF ; architecture PROC of DFF is begin 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 flop The following program is a synthesizable model of a T (toggle) flipflop. entity TFF is port (T,CLK,RESET_BAR:in BIT;Q:out BIT); end TFF ; architecture BEH of TFF is signal INT_Q:BIT; begin process(CLK,RESET_BAR) begin
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

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 flop The following program is a synthesizable model of a master-slave JK flipflop. entity JKFF is port (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 Q begin 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. It has an asynchronous reset input and two count-enable inputs namely EN_P and EN_T. It also has one terminal count output TC that goes high when all the four flip flops are in a high state. The following program shows a dataflow type modeling of this IC. The data type 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

CLK RESET_BAR LOAD_BAR EN_P EN_T

COUNTER 74163

TC

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

Q3

Q2 Q1 Q0

Fig 3.3 4 bit presettable synchronous counter library IEEE; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; --COUNTER 74163 entity 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 is signal INT_COUNT:std_logic_vector(3 downto 0); begin INT_COUNT<= "0000" when RESET_BAR='0' else P when CLK'event and CLK='1' and LOAD_BAR='0' else INT_COUNT+1 when CLK'event and CLK='1' and EN_P='1' and EN_T='1' else INT_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 because we 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 edge expression. 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 74163 entity 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 is signal INT_COUNT:std_logic_vector(3 downto 0);
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

begin process(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+1 ; end if; end if; end process; TC <= '1' when INT_COUNT= "1111" else '0'; Q <= INT_COUNT; end BEH;

INT_COUNT<=

1K X 8 RAM 1K X 8 RAM can be easily implemented as an array of std_logic_vectors. The address input acts as the index of the array. The address must be converted into integer by the conv_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 the start of simulation. Remember that all concurrent statements are executed once at t=0 using the initialized values. If we do not specify default for ADR, then conv_integer function is called with X values on ADR, which results in assertion error. This initialization 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; --RAM 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' OE_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;

and

3.6 MODELING OF FINITE STATE MACHINES


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

Finite-state machine (FSM) is an important area in digital logic design. FSMs are commonly used as controllers or sequence detectors in a digital system. A finite state machine can be described in terms of following structures. 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 DETECTOR Consider a single input single output FSM which gives an output=1 when a sequence 1011 is received on its input. Overlapping sequences are allowed. The state transition diagram for implementing this sequence detector is given in fig 3.4. 0/0 0/0
RESET GOT101

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

GOT1

GOT10

1/0

0/0

Fig 3.4 State 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, one hot or one cold. Define signals PRESENT_STATE and NEXT_STATE belonging to the enumerated state class. 2. Define one process for the memory elements which makes PRESENT_STATE as the initial state if RESET is active else with the rising edge of the clock, it assigns the NEXT_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 present input 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
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

present state and the present input X. In case of a moore machine, Z depends only on the present state. VHDL code for modeling the above FSM is given below. --FINITE STATE MACHINE TO DETECT 1011 SEQUENCE entity 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; begin process(CLK,RST,X) begin if(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. restart wave fusion.vwf rst clk x z state next_state clock clk 0 1 h rst sim l rst sim hx cycle lx cycle hx cycle
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

cycle

3.7 GUIDELINES FOR SYNTHESIS


As 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 this standard is released and adopted by the synthesis tool vendors we have to go by certain rules 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 be avoided. Instead of initialization, the memory elements should be initialized with asynchronous reset or preset signals. 2. Completely specify all possibilities. In conditional assignments if all possibilities are not specified, it means that the old value should 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 tool infers a latch in this case. If you dont want a latch, then you must specify all the possibilities. 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. Dont use physical data types like time. Synthesis tools do not support physical types. Delay specs are generated by the synthesizers 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 a warning message if this rule is violated. 5. Dont mix edge expression with other conditions. A synthesis tool infers a synchronous flip flop from an edge expression likeClkevent and clk=1 Clkevent and clk=0 Clk=1 and not clkstable Following statement is likely to give trouble. If(clkevent and clk=1 and Y=0) then Q <= D; end if;

6.Dont combine positive and negative edge triggered flip-flops in a single process or a block. Following code will give trouble. Process(clock, X,Y) Begin If(clockevent and clock=1) then Q1 <= X ; end if; If(clockevent and clock=0) then Q2 <= Y ; end if; End process; Separate them out into two different processes. Also dont use more than one edge-expressions in a single process. 7. Dont assign a value in the FALSE branch of an edge expression Consider the statement.
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

If(clkevent 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 CLKevent 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 CLKevent and CLK=1 then Q<=D;end if; End process Q_PROC; 8. Dont use edge expression as an operand Following is invalid. If ( not (clkevent and clk=1)) then

3.8 PRACTICAL SESSION WITH FPGA EXPPRESS


The ultimate aim of any VHDL design process is synthesis. Some synthesis tools are tailored to a particular device family. Some tools like FPGA Express can take care of a wide range of FPGAs. Ambit is suitable for ASIC design. A synthesis tool converts a VHDL source code into another VHDL code but described in a structural style using components available in the target device. It also produces some files for use by the back end tool, which actually does layout and routing. For small designs, one may blindly choose any FPGA and still produce successful design. But for larger designs, it is necessary to be familiar with the architecture of the target FPGA. PROCEDURE a. b. c. d. e. f. g. h. i. j. First create a simulation project called DECODER using the code given above. Debug and simulate it on VWaves. Close speedwave. Click on FPGA Express icon to open FPGA screen. Click File New to open Create FPGA project window. Enter project directory as FPGA within DECODER directory. Browse and identify the source file decoder.vhd. The work window with two panes opens up. Right click on decoder.vhd to invoke pop up box and select create implementation. The create implementation dialog box opens up. Select vendor as XILINX, Family as XC3000, Device as 3020ACB100 and leave the other items at their default values. Click OK. An entry appears in the chips pane. Right click on it and select optimize chip. 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\fpga directory. Click OK.
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

k. Right click and select chip report option. Specify chip.txt as filename in the decoder\fpga directory. Click OK. Open the report in any text editor and see the results. l. Open SpeedWave and start VHD manager. Click on add source file icon and add the new 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 is end try; architecture DATAFLOW of try is signal 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 bit 0 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 0 and 1 are XORed and fed to the D input of the bit 7. Verify by simulation that the counter 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

11

01

00

11

00

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

E3.4
-- 4 bit Look ahead adder entity 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 P3 and Cin) ; S(0)<= P0 xor Cin; S(1)<= P1 xor C1; S(2)<= P2 xor C2; S(3)<= P3 xor C3; end DF;

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

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

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

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.

c HALF ADDER

a HA1
s

S1 a s s

HA2 c b c
c2 c1 co

c1

Figure 4.1 Full adder from half adders

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

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

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

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;

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

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

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

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


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

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

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 ifgenerate. The ifgenerate 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
FA

a6 b6
FA

a5 b5
FA

a4 b4
FA

a3 b3
FA

a2 b2
FA

a1 b1
FA

a0 b0 cin
FA

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

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

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

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

The ifgenerate 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 ifgenerate 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 9th 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 XORed with a signal X. The circuit to achieve this is

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

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

a3 X

b3

a2

b2

a1

b1

a0

b0

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;

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

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

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

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

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

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

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

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

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 TFFs to realize a divide by 8 ripple counter. Connect output of this counter to a 3:8 decoder. Simulate the circuit. First give

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

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 2s 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 FA

X1Y1 FA

X0Y1

X2Y2 FA

X1Y2 FA

X0Y2

FA

FA

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

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

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(i1),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


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

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;

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

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

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

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

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 is port(HOUR:in integer;RATE:out real); end GetRate; architecture DATAFLOW of GetRate is begin process(HOUR) begin Case HOUR is When 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];

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

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

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

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

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 isReturn [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 isPROC_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

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

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

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 BYTErange 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 bitvectors. Function ADD (A, B: BIT_VECTOR) return BIT_VECTOR is Variable SUM: integer;
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

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

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.

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

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

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

next step. Thus the hardware architecture consists of a set of registers whose contents can be routed to combinational processing elements like ALUs, 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

TRI_BUS

EN_C

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

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 INPUTSRANGE loop if INPUTS(J) = 1 then return 1; end if return 0; end WIRED_OR;

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

RTL EXAMPLE - SIGNED 8 BIT MULTIPLIER As an exercise in RTL design, consider the design of a signed 8 bit twos complement multiplier. The hardware arrangement is as follows.

F
Q(7) M(0)

COUNT

ADDER/SUBTRACTOR

C) CONTROL

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

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

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


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

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

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

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 process A_proc; end if;

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

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.

STIMULUS

DEVICE

GENERATOR

UNDER TEST

RESPONSE CAPTURE AND COMPARISON

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

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

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

PRIORITY ENCODER

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

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

BIT1 := '0';BIT0 := '0';

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

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

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 1 0 1 1 1 0 1 1 1 0 1 0 NS 5 NS 105 NS 205 NS 305 NS 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 1s in a vector.

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

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 is port(VAR_FLAG,SIG_FLAG:out bit); procedure SIG_PROC(signal PASSED:in bit;signal FLAG:out bit)is begin wait for 15 ns;flag<= PASSED; end SIG_PROC; procedure VAR_PROC( PASSED:in bit;signal FLAG:out bit)is begin 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';
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

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

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 end if; end COMP; A_GT_B<='0'; A_EQ_B<='1'; A_LT_B<='0';

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

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.

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

CHAPTER 6
PROJECTS

6.1 Serial transmitter


Design 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 Data_in SHIFT REG

Q0 data_out

1 valid LATCH CLK

COUNT=0 CLK LD HOLD RUN H D CLK R CLK Q D Q dao_valid CLR_BAR COUNTER CLK

CLK R_BAR

RST

COUNT=11

entity SERIAL_XMT is port (data_in:in bit_vector(7 downto 0);valid,clk,rst:in bit;


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

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

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 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; SHIFT_REG<='1' & SHIFT_REG(9 downto 1);

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

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

S1 S2

CLK

S3 R0 R1 R2 R3

DESIGN HIGHLIGHTS For scanning the 4X4 matrix, we have 4 scan lines S[3:0] and 4 return lines 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 is detected on any return line, the counter is disabled. The return lines are encoded in 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 the counter 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));
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

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

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 buses and three output buses. Each input bus is associated with a two-bit destination code and a bus request signal. Each channel should get a BUS GRANT signal from the controller. Priority logic should be followed for granting the buses such that channel 0 gets the highest priority. However, once a bus is granted to a channel, it will not be given to any other channel till the original request comes down. 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

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

REQ2 REQ3

BUS ARBITER

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

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 Dest1 Req1 Data2 Dest2 Req2 Data3 Dest3 Req3 Dout3 Dout2 Dout1

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

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

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
X
D Q

8 TAP FIR FILTER Design an 8 tap FIR filter.


D Q D Q D Q D Q D Q D Q

CLK RST

CLK RST

CLK RST

CLK RST

CLK RST

CLK RST

CLK RST

CA0

CA1

CA2

CA3

CA4

CA5

CA6

CA7

ADDER

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

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

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

6.5 HAMMING ERROR CORRECTION FOR SRAM Design 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

EN_BAR

RAM BUS

WE_BAR MAIN RAM

INPUT BUFFER PARITY GENERATOR EN_BAR PARITY RAM RE_BAR RE_BAR

INPUT BUFFER

MEMR_BAR
EN_BAR CORRECTION UNIT OUTPUT BUFFER SYNDROME GENERATOR

--HAMMING ERROR CORRECTION CHIP library 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);
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

begin RAM_BUS<=CPU_BUS when MEMW_BAR='0' else "ZZZZZZZZ"; -- PARITY GENERATOR PARITY(0)<= CPU_BUS(1) xor CPU_BUS(2) xor CPU_BUS(4) xor CPU_BUS(5) xor CPU_BUS(7) ; PARITY(1)<= CPU_BUS(1) xor CPU_BUS(3) xor CPU_BUS(4) xor CPU_BUS(6) xor CPU_BUS(7) ; PARITY(2)<= CPU_BUS(2) xor CPU_BUS(3) xor CPU_BUS(4) xor CPU_BUS(8) ; PARITY(3)<= CPU_BUS(5) xor CPU_BUS(6) xor CPU_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) xor RAM_BUS(4) xor RAM_BUS(5) xor RAM_BUS(7) xor PRAM_BUS(0); SYNDROME(1)<= RAM_BUS(1) xor RAM_BUS(3) xor RAM_BUS(4) xor RAM_BUS(6) xor RAM_BUS(7) xor PRAM_BUS(1); SYNDROME(2)<= RAM_BUS(2) xor RAM_BUS(3) xor RAM_BUS(4) xor RAM_BUS(8) xor PRAM_BUS(2); SYNDROME(3)<= RAM_BUS(5) xor RAM_BUS(6) xor RAM_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 ); begin temp:=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);
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

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;

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

You might also like