Главная » Просмотр файлов » Donald E. Thomas - The Verilog Hardware Description Language, Fifth Edition

Donald E. Thomas - The Verilog Hardware Description Language, Fifth Edition (798541), страница 31

Файл №798541 Donald E. Thomas - The Verilog Hardware Description Language, Fifth Edition (Donald E. Thomas - The Verilog Hardware Description Language, Fifth Edition) 31 страницаDonald E. Thomas - The Verilog Hardware Description Language, Fifth Edition (798541) страница 312019-09-20СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 31)

Those not listed at the instantiation will retain their generic values.The general form of specifying parameter values at instantiation time is seen in thefollowing syntax specification:module instantiationmodule _identifier [ parameter_value_assignment ] module_instance {,module_instance };parameter_value_assignment# (list_of_parameter_assignments})list_of_parameter_assignmentsordered_parameter_assignment {, ordered_parameter_assignment}named_parameter_assignment {, named_parameter_assignment}ordered_parameter_assignmentexpressionnamed_parameter_assignment. parameter_identifier ([expression])This shows the syntax for either the ordered or named parameter lists.Module HierarchyAnother approach to overriding theparameters in a module definition is touse the defparam statement and the hierarchical naming conventions of Verilog.This approach is shown in Example 5.4.149module xorsAreUs(output [3:0]reg[3:0]xorxUsing the defparam statement, all ofthe respecifications of parameters can begrouped into one place within thedescription.

In this example, the delayparameter of instance b of module xorxinstantiated within module xorsAreUshas been changed so that its delay is five.Module annotate uses hierarchical naming to affect the change. Thus, theparameters may be respecified on an individual basis. The general form of the defparam statement is:parameter_overridedefparamlist_of_param_assignments;a1, a2);b1, c1, b2, c2;a(al, bl, cl),b(a2, b2, c2);endmodulemodule xorx#(parameter width = 4,delay =10)(output [1:width] xout,input [1:width] xin1, xin2);assign #delay xout = xin1 ^ xin2;endmodulemodule annotate;defparamxorsAreUs.b.delay = 5;endmoduleThe choice of using the defparam or Example 5.4 Overriding Parametermodule instance method of modifyingSpecification With defparamparameters is a matter of personal styleand modeling needs. Using the module instance method makes it clear at the instantiation site that new values are overriding defaults.

Using the defparam method allowsfor grouping the respecifications in specific locations. Indeed, the defparams can becollected in a separate file and compiled with the rest of the simulation model. Thesystem can be changed by compiling with a different defparam file rather than by reediting the entire description. Further, a separate program could generate the defparam file for back annotation of delays.The Verilog Hardware Description Language1505.3 Arrays of InstancesThe definition of the xor8 module inmodule xor8Example 5.1 was rather tedious because each(output [1:8]xout,XOR instance had to be individually numxin1, xin2);input [1:8]bered with the appropriate bit.

Verilog has ashorthand method of specifying an array ofxor a[l:8] (xout, xinl, xin2);instances where the bit numbering of eachendmodulesuccessive instance differ in a controlled way.Example 5.5 shows the equivalent redefini- Example 5.5 Equivalent xor8 UsingArray of Instancestion of module xor8 using arrays ofinstances. This is equivalent to the originalmodule xor8 in Example 5.1.The array of instances specification uses the optionalrange specifier to provide the numbering of the instance names.There are no requirements onthe absolute values or the relationship of the msb or lsb of the rangespecifier (the [1:8} in this example) — both must be integers andone is not required to be largerthan the other.

Indeed, they canbe equal in which case only oneinstance will be generated. Givenmsb and lsb, 1 + abs(msb-lsb)instances will be generated.module reggae(output [7:0]input [7:0]inputdffendmoduleD,clock, clear);r[7:0] (D, clear, clock);module regExpanded(output [7:0]input [7:0] D,inputclock, clear);This example showed the casewhere each instance was condffr7D[7], clear, clock),nected to a bit-select of the outr6D[6], clear, clock),puts and inputs. When ther5D[5], clear, clock),instances are generated and ther4D[4], clear, clock),connections are made, there mustr3D[3], clear, clock),be an equal number of bits pror2D[2], clear, clock),vided by the terminals (ports,r1D[l], clear, clock),wires, registers) and needed by ther0D[0], clear, clock);instances.

In this, eight instancesendmoduleneeded eight bits in each of theoutput and input ports. (It is anExample 5.6 A Register Using Arrays oferror if the numbers are notInstancesequal.) However, instances are notlimited to bit-select connections. If a terminal has only one bit (it is scalar) but thereare n instances, then each instance will be connected to the one-bit terminal.Example 5.6 shows D flip flops connected to form a register. The equivalent moduleModule Hierarchy151with the instances expanded is shown at the bottom.

Note that clock and clear, beingone-bit scalars, are connected to each instance.5.4 Generate BlocksUsing arrays of instances is limited to fairly simple repetitive structures. Generateblocks provide a far more powerful capability to create multiple instances of an object.The primary objects that can be generated are: module and primitive instances, initialand always procedural blocks, continuous assignments, net and variable declarations,task and function definitions, and parameter redefinitions.Continuing with the xorxexamplesof thechapter,Example 5.7 illustrates using agenerate statement to re-describethe module.

The generate…endgenerate block specifies how anobject is going to be repeated.Variables for use in specifying therepetition are defined to be genvars. Then a for loop is used toincrement (or decrement) thegenvars over a range. The use ofthe genvars in the object to berepeated then specify such information as bit-selects.module xorGen#(parameter width = 4,delay =10)(output [1:width] xout,input [l:width] xinl, xin2);generategenvar i;for (i = 1; i <= width; i=i+l) begin: xiassign #delayxout[i] = xin1[i] ^ xin2[i];endendgenerateendmoduleExample 5.7 A Generate BlockIn this example, the genvar is i.The following four copies of the assign statement are generated:assign #delayassign #delayassign #delayassign #delayxout[l] = xinl[l] ^ xin2[l];xout[2] = xinl[2] ^ xin2[2];xout[3] = xinl[3] ^ xin2[3];xout[4] = xinl[4] ^ xin2[4];Since the generate statement is executed at elaboration time, these four statementsbecome part of module xorGen replacing the generate…endgenerate statement.The statements controlling the generation of objects within a generate…endgenerate block are limited to for, if-then-else, and case.

The index of the for loop must be agenvar and both assignments in the for must be to the same genvar. The genvar canonly be assigned a value as part of the for loop and it can only take on the values of 0and positive integers. The genvar declaration may be outside of the generate…end-152The Verilog Hardware Description Languagegenerate block, making it available to other generate blocks.

A named begin…endblock must be used to specify the contents of the for loop; this provides hierarchicalnaming to the generated items.The generate block of Example 5.7 could also have been written to instantiateprimitive gate instances or always blocks. Shown below is the gate primitive version.In this case four XOR gates would be instantiated.

The gates would have hierarchicalnames of xi[1] … xi[4], assuming that the generic instantiation of the module wasspecified.generategenvar i;for (i = 1; i <= width; i=i+1) begin: xixor #delay a (xout[i], xin1[i], xin2[i]);endendgenerateThe always block version is shown below. The result would be four always blockswith the indicies replaced by 1 through 4.generategenvar i;for (i = 1; i <= width; i=i+1) begin: xialways @(*)xout[i] = xin1[i] ^ xin2[i];endendgenerateConsider modeling an n-bit adder (where n is greater than 1) that also has condition code outputs to indicate if the result was negative, produced a carry, or produceda two’s complement overflow. In this case, not all generated instances of the adder areconnected the same.

if-then-else and case statements in the for loop may be used togenerate these differences. Example 5.8 shows a module using a case statement in thegenerate to produce different adder logic depending on which bit is being generated.Three different situations are broken out for separate handling. For most of thestages, the carry in of a stage is connect to the carry out of the previous stage. For theleast significant bit (bit 0), the carry in is connected to the module’s carry in (cIn).

Forthe most significant bit (which is parameterized as width), the carry out (cOut), overFlow and negative (neg) outputs must be connected.Module Hierarchy153module adderWithConditionCodes#(parameterwidth = 1)(output reg [width-1:0] sum,output regcOut, neg, overFlow,input[width-1:0] a, b,inputcIn);reg[width -1:0]c;generategenvar i;for (i = 0; 1<= width-1; i=i+l) begin: stagecase(i)0: beginalways @(*) beginsum[i] = a[i] ^ b[i] ^ cIn;c[i] = a[i]&b[i] | b[i]&cIn | a[i] & c I n ;endendwidth-1: beginalways @(*) beginsum[i] = a[i] ^ b[i] ^ c[i-1];cOut = a[i]&b[i] | b[i]&c[i-1] | a[i] & c[i-1];neg = sum[i];overFlow = cOut^ c[i-1];endenddefault: beginalways @(*) beginsum[i] = a[i] ^ b[i] ^ c[i-l];c[i] = a[i]&b[i] | b[i]&c[i-1] | a[i] &c[i-l];endendendcaseendendgenerateendmoduleExample 5.8 Generating an AdderThe Verilog Hardware Description Language1545.5 Exercises5.1 Write a module with the structure:module progBidirect (ioA, ioB, selectA, selectB, enable);inout [3:0] ioA, ioB;input[1:0] selectA, selectB;inputenable;endmodulesuch that selectA controls the driving of ioA in the following way:selectA0123ioAno drivedrive all 0'sdrive all 1'sdrive ioBand selectB controls the driving of ioB in the same way.

The drivers are only to be ineffect if enable is 1. If enable is 0 the state of the ioA and ioB drivers must be highimpedance.A. Write this module using gate level primitives only.B. Write this module using continuous assignments only.Module Hierarchy1555.2 The following combinational logic block has three inputs and an output. Thecircuit was built in some screwy technology and then analyzed. We now want toinsert the correct input-to-output timing information into the circuit (internalnode timings need not be correct).Here are the circuit timings that must be represented in the circuit.The delay of a rising or falling edge on a or b to output f: 15 time unitsThe delay of a rising or falling edge on c to output f: 10 time unitsYes, those times are rather strange given the logic diagram. However, this is ascrewy technology and the transistor implementation made for some strange,but actual, time delays.Assume a, b, and c are outputs of synchronously clocked flip flops.

Характеристики

Тип файла
PDF-файл
Размер
7,95 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6510
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее